Passed
Push — master ( 25fe32...0fb74a )
by Morris
13:02 queued 10s
created
apps/dav/appinfo/app.php 1 patch
Indentation   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -31,59 +31,59 @@  discard block
 block discarded – undo
31 31
 $app->registerHooks();
32 32
 
33 33
 \OC::$server->registerService('CardDAVSyncService', function() use ($app) {
34
-	return $app->getSyncService();
34
+    return $app->getSyncService();
35 35
 });
36 36
 
37 37
 $eventDispatcher = \OC::$server->getEventDispatcher();
38 38
 
39 39
 $eventDispatcher->addListener('OCP\Federation\TrustedServerEvent::remove',
40
-	function(GenericEvent $event) use ($app) {
41
-		/** @var CardDavBackend $cardDavBackend */
42
-		$cardDavBackend = $app->getContainer()->query(CardDavBackend::class);
43
-		$addressBookUri = $event->getSubject();
44
-		$addressBook = $cardDavBackend->getAddressBooksByUri('principals/system/system', $addressBookUri);
45
-		if (!is_null($addressBook)) {
46
-			$cardDavBackend->deleteAddressBook($addressBook['id']);
47
-		}
48
-	}
40
+    function(GenericEvent $event) use ($app) {
41
+        /** @var CardDavBackend $cardDavBackend */
42
+        $cardDavBackend = $app->getContainer()->query(CardDavBackend::class);
43
+        $addressBookUri = $event->getSubject();
44
+        $addressBook = $cardDavBackend->getAddressBooksByUri('principals/system/system', $addressBookUri);
45
+        if (!is_null($addressBook)) {
46
+            $cardDavBackend->deleteAddressBook($addressBook['id']);
47
+        }
48
+    }
49 49
 );
50 50
 
51 51
 $eventDispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::createSubscription',
52
-	function(GenericEvent $event) use ($app) {
53
-		$jobList = $app->getContainer()->getServer()->getJobList();
54
-		$subscriptionData = $event->getArgument('subscriptionData');
52
+    function(GenericEvent $event) use ($app) {
53
+        $jobList = $app->getContainer()->getServer()->getJobList();
54
+        $subscriptionData = $event->getArgument('subscriptionData');
55 55
 
56
-		$jobList->add(\OCA\DAV\BackgroundJob\RefreshWebcalJob::class, [
57
-			'principaluri' => $subscriptionData['principaluri'],
58
-			'uri' => $subscriptionData['uri']
59
-		]);
60
-	}
56
+        $jobList->add(\OCA\DAV\BackgroundJob\RefreshWebcalJob::class, [
57
+            'principaluri' => $subscriptionData['principaluri'],
58
+            'uri' => $subscriptionData['uri']
59
+        ]);
60
+    }
61 61
 );
62 62
 
63 63
 $eventDispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription',
64
-	function(GenericEvent $event) use ($app) {
65
-		$jobList = $app->getContainer()->getServer()->getJobList();
66
-		$subscriptionData = $event->getArgument('subscriptionData');
64
+    function(GenericEvent $event) use ($app) {
65
+        $jobList = $app->getContainer()->getServer()->getJobList();
66
+        $subscriptionData = $event->getArgument('subscriptionData');
67 67
 
68
-		$jobList->remove(\OCA\DAV\BackgroundJob\RefreshWebcalJob::class, [
69
-			'principaluri' => $subscriptionData['principaluri'],
70
-			'uri' => $subscriptionData['uri']
71
-		]);
68
+        $jobList->remove(\OCA\DAV\BackgroundJob\RefreshWebcalJob::class, [
69
+            'principaluri' => $subscriptionData['principaluri'],
70
+            'uri' => $subscriptionData['uri']
71
+        ]);
72 72
 
73
-		/** @var \OCA\DAV\CalDAV\CalDavBackend $calDavBackend */
74
-		$calDavBackend = $app->getContainer()->query(\OCA\DAV\CalDAV\CalDavBackend::class);
75
-		$calDavBackend->purgeAllCachedEventsForSubscription($subscriptionData['id']);
76
-	}
73
+        /** @var \OCA\DAV\CalDAV\CalDavBackend $calDavBackend */
74
+        $calDavBackend = $app->getContainer()->query(\OCA\DAV\CalDAV\CalDavBackend::class);
75
+        $calDavBackend->purgeAllCachedEventsForSubscription($subscriptionData['id']);
76
+    }
77 77
 );
78 78
 
79 79
 $eventHandler = function() use ($app) {
80
-	try {
81
-		$job = $app->getContainer()->query(\OCA\DAV\BackgroundJob\UpdateCalendarResourcesRoomsBackgroundJob::class);
82
-		$job->run([]);
83
-		$app->getContainer()->getServer()->getJobList()->setLastRun($job);
84
-	} catch(\Exception $ex) {
85
-		$app->getContainer()->getServer()->getLogger()->logException($ex);
86
-	}
80
+    try {
81
+        $job = $app->getContainer()->query(\OCA\DAV\BackgroundJob\UpdateCalendarResourcesRoomsBackgroundJob::class);
82
+        $job->run([]);
83
+        $app->getContainer()->getServer()->getJobList()->setLastRun($job);
84
+    } catch(\Exception $ex) {
85
+        $app->getContainer()->getServer()->getLogger()->logException($ex);
86
+    }
87 87
 };
88 88
 
89 89
 $eventDispatcher->addListener('\OCP\Calendar\Resource\ForceRefreshEvent', $eventHandler);
@@ -91,18 +91,18 @@  discard block
 block discarded – undo
91 91
 
92 92
 $cm = \OC::$server->getContactsManager();
93 93
 $cm->register(function() use ($cm, $app) {
94
-	$user = \OC::$server->getUserSession()->getUser();
95
-	if (!is_null($user)) {
96
-		$app->setupContactsProvider($cm, $user->getUID());
97
-	} else {
98
-		$app->setupSystemContactsProvider($cm);
99
-	}
94
+    $user = \OC::$server->getUserSession()->getUser();
95
+    if (!is_null($user)) {
96
+        $app->setupContactsProvider($cm, $user->getUID());
97
+    } else {
98
+        $app->setupSystemContactsProvider($cm);
99
+    }
100 100
 });
101 101
 
102 102
 $calendarManager = \OC::$server->getCalendarManager();
103 103
 $calendarManager->register(function() use ($calendarManager, $app) {
104
-	$user = \OC::$server->getUserSession()->getUser();
105
-	if ($user !== null) {
106
-		$app->setupCalendarProvider($calendarManager, $user->getUID());
107
-	}
104
+    $user = \OC::$server->getUserSession()->getUser();
105
+    if ($user !== null) {
106
+        $app->setupCalendarProvider($calendarManager, $user->getUID());
107
+    }
108 108
 });
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/WebcalCaching/Plugin.php 2 patches
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -49,7 +49,7 @@  discard block
 block discarded – undo
49 49
 	/**
50 50
 	 * @var bool
51 51
 	 */
52
-	private $enabled=false;
52
+	private $enabled = false;
53 53
 
54 54
 	/**
55 55
 	 * @var Server
@@ -103,7 +103,7 @@  discard block
 block discarded – undo
103 103
 		}
104 104
 
105 105
 		// $calendarHomePath will look like: calendars/username
106
-		$calendarHomePath = $pathParts[0] . '/' . $pathParts[1];
106
+		$calendarHomePath = $pathParts[0].'/'.$pathParts[1];
107 107
 		try {
108 108
 			$calendarHome = $this->server->tree->getNodeForPath($calendarHomePath);
109 109
 			if (!($calendarHome instanceof CalendarHome)) {
@@ -112,7 +112,7 @@  discard block
 block discarded – undo
112 112
 			}
113 113
 
114 114
 			$calendarHome->enableCachedSubscriptionsForThisRequest();
115
-		} catch(NotFound $ex) {
115
+		} catch (NotFound $ex) {
116 116
 			return;
117 117
 		}
118 118
 	}
Please login to merge, or discard this patch.
Indentation   +97 added lines, -97 removed lines patch added patch discarded remove patch
@@ -33,113 +33,113 @@
 block discarded – undo
33 33
 
34 34
 class Plugin extends ServerPlugin {
35 35
 
36
-	/**
37
-	 * list of regular expressions for calendar user agents,
38
-	 * that do not support subscriptions on their own
39
-	 *
40
-	 * @var string[]
41
-	 */
42
-	const ENABLE_FOR_CLIENTS = [];
36
+    /**
37
+     * list of regular expressions for calendar user agents,
38
+     * that do not support subscriptions on their own
39
+     *
40
+     * @var string[]
41
+     */
42
+    const ENABLE_FOR_CLIENTS = [];
43 43
 
44
-	/**
45
-	 * @var bool
46
-	 */
47
-	private $enabled=false;
44
+    /**
45
+     * @var bool
46
+     */
47
+    private $enabled=false;
48 48
 
49
-	/**
50
-	 * @var Server
51
-	 */
52
-	private $server;
49
+    /**
50
+     * @var Server
51
+     */
52
+    private $server;
53 53
 
54
-	/**
55
-	 * Plugin constructor.
56
-	 *
57
-	 * @param IRequest $request
58
-	 */
59
-	public function __construct(IRequest $request) {
60
-		if ($request->isUserAgent(self::ENABLE_FOR_CLIENTS)) {
61
-			$this->enabled = true;
62
-		}
54
+    /**
55
+     * Plugin constructor.
56
+     *
57
+     * @param IRequest $request
58
+     */
59
+    public function __construct(IRequest $request) {
60
+        if ($request->isUserAgent(self::ENABLE_FOR_CLIENTS)) {
61
+            $this->enabled = true;
62
+        }
63 63
 
64
-		$magicHeader = $request->getHeader('X-NC-CalDAV-Webcal-Caching');
65
-		if ($magicHeader === 'On') {
66
-			$this->enabled = true;
67
-		}
68
-	}
64
+        $magicHeader = $request->getHeader('X-NC-CalDAV-Webcal-Caching');
65
+        if ($magicHeader === 'On') {
66
+            $this->enabled = true;
67
+        }
68
+    }
69 69
 
70
-	/**
71
-	 * This initializes the plugin.
72
-	 *
73
-	 * This function is called by Sabre\DAV\Server, after
74
-	 * addPlugin is called.
75
-	 *
76
-	 * This method should set up the required event subscriptions.
77
-	 *
78
-	 * @param Server $server
79
-	 */
80
-	public function initialize(Server $server) {
81
-		$this->server = $server;
82
-		$server->on('beforeMethod', [$this, 'beforeMethod']);
83
-	}
70
+    /**
71
+     * This initializes the plugin.
72
+     *
73
+     * This function is called by Sabre\DAV\Server, after
74
+     * addPlugin is called.
75
+     *
76
+     * This method should set up the required event subscriptions.
77
+     *
78
+     * @param Server $server
79
+     */
80
+    public function initialize(Server $server) {
81
+        $this->server = $server;
82
+        $server->on('beforeMethod', [$this, 'beforeMethod']);
83
+    }
84 84
 
85
-	/**
86
-	 * @param RequestInterface $request
87
-	 * @param ResponseInterface $response
88
-	 */
89
-	public function beforeMethod(RequestInterface $request, ResponseInterface $response) {
90
-		if (!$this->enabled) {
91
-			return;
92
-		}
85
+    /**
86
+     * @param RequestInterface $request
87
+     * @param ResponseInterface $response
88
+     */
89
+    public function beforeMethod(RequestInterface $request, ResponseInterface $response) {
90
+        if (!$this->enabled) {
91
+            return;
92
+        }
93 93
 
94
-		$path = $request->getPath();
95
-		$pathParts = explode('/', ltrim($path, '/'));
96
-		if (\count($pathParts) < 2) {
97
-			return;
98
-		}
94
+        $path = $request->getPath();
95
+        $pathParts = explode('/', ltrim($path, '/'));
96
+        if (\count($pathParts) < 2) {
97
+            return;
98
+        }
99 99
 
100
-		// $calendarHomePath will look like: calendars/username
101
-		$calendarHomePath = $pathParts[0] . '/' . $pathParts[1];
102
-		try {
103
-			$calendarHome = $this->server->tree->getNodeForPath($calendarHomePath);
104
-			if (!($calendarHome instanceof CalendarHome)) {
105
-				//how did we end up here?
106
-				return;
107
-			}
100
+        // $calendarHomePath will look like: calendars/username
101
+        $calendarHomePath = $pathParts[0] . '/' . $pathParts[1];
102
+        try {
103
+            $calendarHome = $this->server->tree->getNodeForPath($calendarHomePath);
104
+            if (!($calendarHome instanceof CalendarHome)) {
105
+                //how did we end up here?
106
+                return;
107
+            }
108 108
 
109
-			$calendarHome->enableCachedSubscriptionsForThisRequest();
110
-		} catch(NotFound $ex) {
111
-			return;
112
-		}
113
-	}
109
+            $calendarHome->enableCachedSubscriptionsForThisRequest();
110
+        } catch(NotFound $ex) {
111
+            return;
112
+        }
113
+    }
114 114
 
115
-	/**
116
-	 * @return bool
117
-	 */
118
-	public function isCachingEnabledForThisRequest():bool {
119
-		return $this->enabled;
120
-	}
115
+    /**
116
+     * @return bool
117
+     */
118
+    public function isCachingEnabledForThisRequest():bool {
119
+        return $this->enabled;
120
+    }
121 121
 
122
-	/**
123
-	 * This method should return a list of server-features.
124
-	 *
125
-	 * This is for example 'versioning' and is added to the DAV: header
126
-	 * in an OPTIONS response.
127
-	 *
128
-	 * @return string[]
129
-	 */
130
-	public function getFeatures():array {
131
-		return ['nc-calendar-webcal-cache'];
132
-	}
122
+    /**
123
+     * This method should return a list of server-features.
124
+     *
125
+     * This is for example 'versioning' and is added to the DAV: header
126
+     * in an OPTIONS response.
127
+     *
128
+     * @return string[]
129
+     */
130
+    public function getFeatures():array {
131
+        return ['nc-calendar-webcal-cache'];
132
+    }
133 133
 
134
-	/**
135
-	 * Returns a plugin name.
136
-	 *
137
-	 * Using this name other plugins will be able to access other plugins
138
-	 * using Sabre\DAV\Server::getPlugin
139
-	 *
140
-	 * @return string
141
-	 */
142
-	public function getPluginName():string {
143
-		return 'nc-calendar-webcal-cache';
144
-	}
134
+    /**
135
+     * Returns a plugin name.
136
+     *
137
+     * Using this name other plugins will be able to access other plugins
138
+     * using Sabre\DAV\Server::getPlugin
139
+     *
140
+     * @return string
141
+     */
142
+    public function getPluginName():string {
143
+        return 'nc-calendar-webcal-cache';
144
+    }
145 145
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/CalendarHome.php 2 patches
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -44,7 +44,7 @@  discard block
 block discarded – undo
44 44
 	private $config;
45 45
 
46 46
 	/** @var bool */
47
-	private $returnCachedSubscriptions=false;
47
+	private $returnCachedSubscriptions = false;
48 48
 
49 49
 	public function __construct(BackendInterface $caldavBackend, $principalInfo) {
50 50
 		parent::__construct($caldavBackend, $principalInfo);
@@ -141,7 +141,7 @@  discard block
 block discarded – undo
141 141
 
142 142
 		}
143 143
 
144
-		throw new NotFound('Node with name \'' . $name . '\' could not be found');
144
+		throw new NotFound('Node with name \''.$name.'\' could not be found');
145 145
 	}
146 146
 
147 147
 	/**
@@ -149,7 +149,7 @@  discard block
 block discarded – undo
149 149
 	 * @param integer|null $limit
150 150
 	 * @param integer|null $offset
151 151
 	 */
152
-	function calendarSearch(array $filters, $limit=null, $offset=null) {
152
+	function calendarSearch(array $filters, $limit = null, $offset = null) {
153 153
 		$principalUri = $this->principalInfo['uri'];
154 154
 		return $this->caldavBackend->calendarSearch($principalUri, $filters, $limit, $offset);
155 155
 	}
Please login to merge, or discard this patch.
Indentation   +123 added lines, -123 removed lines patch added patch discarded remove patch
@@ -36,127 +36,127 @@
 block discarded – undo
36 36
 
37 37
 class CalendarHome extends \Sabre\CalDAV\CalendarHome {
38 38
 
39
-	/** @var \OCP\IL10N */
40
-	private $l10n;
41
-
42
-	/** @var \OCP\IConfig */
43
-	private $config;
44
-
45
-	/** @var bool */
46
-	private $returnCachedSubscriptions=false;
47
-
48
-	public function __construct(BackendInterface $caldavBackend, $principalInfo) {
49
-		parent::__construct($caldavBackend, $principalInfo);
50
-		$this->l10n = \OC::$server->getL10N('dav');
51
-		$this->config = \OC::$server->getConfig();
52
-	}
53
-
54
-	/**
55
-	 * @return BackendInterface
56
-	 */
57
-	public function getCalDAVBackend() {
58
-		return $this->caldavBackend;
59
-	}
60
-
61
-	/**
62
-	 * @inheritdoc
63
-	 */
64
-	function createExtendedCollection($name, MkCol $mkCol) {
65
-		$reservedNames = [BirthdayService::BIRTHDAY_CALENDAR_URI];
66
-
67
-		if (in_array($name, $reservedNames)) {
68
-			throw new MethodNotAllowed('The resource you tried to create has a reserved name');
69
-		}
70
-
71
-		parent::createExtendedCollection($name, $mkCol);
72
-	}
73
-
74
-	/**
75
-	 * @inheritdoc
76
-	 */
77
-	function getChildren() {
78
-		$calendars = $this->caldavBackend->getCalendarsForUser($this->principalInfo['uri']);
79
-		$objects = [];
80
-		foreach ($calendars as $calendar) {
81
-			$objects[] = new Calendar($this->caldavBackend, $calendar, $this->l10n, $this->config);
82
-		}
83
-
84
-		if ($this->caldavBackend instanceof SchedulingSupport) {
85
-			$objects[] = new Inbox($this->caldavBackend, $this->principalInfo['uri']);
86
-			$objects[] = new Outbox($this->config, $this->principalInfo['uri']);
87
-		}
88
-
89
-		// We're adding a notifications node, if it's supported by the backend.
90
-		if ($this->caldavBackend instanceof NotificationSupport) {
91
-			$objects[] = new \Sabre\CalDAV\Notifications\Collection($this->caldavBackend, $this->principalInfo['uri']);
92
-		}
93
-
94
-		// If the backend supports subscriptions, we'll add those as well,
95
-		if ($this->caldavBackend instanceof SubscriptionSupport) {
96
-			foreach ($this->caldavBackend->getSubscriptionsForUser($this->principalInfo['uri']) as $subscription) {
97
-				if ($this->returnCachedSubscriptions) {
98
-					$objects[] = new CachedSubscription($this->caldavBackend, $subscription);
99
-				} else {
100
-					$objects[] = new Subscription($this->caldavBackend, $subscription);
101
-				}
102
-			}
103
-		}
104
-
105
-		return $objects;
106
-	}
107
-
108
-	/**
109
-	 * @inheritdoc
110
-	 */
111
-	function getChild($name) {
112
-		// Special nodes
113
-		if ($name === 'inbox' && $this->caldavBackend instanceof SchedulingSupport) {
114
-			return new Inbox($this->caldavBackend, $this->principalInfo['uri']);
115
-		}
116
-		if ($name === 'outbox' && $this->caldavBackend instanceof SchedulingSupport) {
117
-			return new Outbox($this->config, $this->principalInfo['uri']);
118
-		}
119
-		if ($name === 'notifications' && $this->caldavBackend instanceof NotificationSupport) {
120
-			return new \Sabre\CalDAv\Notifications\Collection($this->caldavBackend, $this->principalInfo['uri']);
121
-		}
122
-
123
-		// Calendars
124
-		foreach ($this->caldavBackend->getCalendarsForUser($this->principalInfo['uri']) as $calendar) {
125
-			if ($calendar['uri'] === $name) {
126
-				return new Calendar($this->caldavBackend, $calendar, $this->l10n, $this->config);
127
-			}
128
-		}
129
-
130
-		if ($this->caldavBackend instanceof SubscriptionSupport) {
131
-			foreach ($this->caldavBackend->getSubscriptionsForUser($this->principalInfo['uri']) as $subscription) {
132
-				if ($subscription['uri'] === $name) {
133
-					if ($this->returnCachedSubscriptions) {
134
-						return new CachedSubscription($this->caldavBackend, $subscription);
135
-					}
136
-
137
-					return new Subscription($this->caldavBackend, $subscription);
138
-				}
139
-			}
140
-
141
-		}
142
-
143
-		throw new NotFound('Node with name \'' . $name . '\' could not be found');
144
-	}
145
-
146
-	/**
147
-	 * @param array $filters
148
-	 * @param integer|null $limit
149
-	 * @param integer|null $offset
150
-	 */
151
-	function calendarSearch(array $filters, $limit=null, $offset=null) {
152
-		$principalUri = $this->principalInfo['uri'];
153
-		return $this->caldavBackend->calendarSearch($principalUri, $filters, $limit, $offset);
154
-	}
155
-
156
-	/**
157
-	 *
158
-	 */
159
-	public function enableCachedSubscriptionsForThisRequest() {
160
-		$this->returnCachedSubscriptions = true;
161
-	}
39
+    /** @var \OCP\IL10N */
40
+    private $l10n;
41
+
42
+    /** @var \OCP\IConfig */
43
+    private $config;
44
+
45
+    /** @var bool */
46
+    private $returnCachedSubscriptions=false;
47
+
48
+    public function __construct(BackendInterface $caldavBackend, $principalInfo) {
49
+        parent::__construct($caldavBackend, $principalInfo);
50
+        $this->l10n = \OC::$server->getL10N('dav');
51
+        $this->config = \OC::$server->getConfig();
52
+    }
53
+
54
+    /**
55
+     * @return BackendInterface
56
+     */
57
+    public function getCalDAVBackend() {
58
+        return $this->caldavBackend;
59
+    }
60
+
61
+    /**
62
+     * @inheritdoc
63
+     */
64
+    function createExtendedCollection($name, MkCol $mkCol) {
65
+        $reservedNames = [BirthdayService::BIRTHDAY_CALENDAR_URI];
66
+
67
+        if (in_array($name, $reservedNames)) {
68
+            throw new MethodNotAllowed('The resource you tried to create has a reserved name');
69
+        }
70
+
71
+        parent::createExtendedCollection($name, $mkCol);
72
+    }
73
+
74
+    /**
75
+     * @inheritdoc
76
+     */
77
+    function getChildren() {
78
+        $calendars = $this->caldavBackend->getCalendarsForUser($this->principalInfo['uri']);
79
+        $objects = [];
80
+        foreach ($calendars as $calendar) {
81
+            $objects[] = new Calendar($this->caldavBackend, $calendar, $this->l10n, $this->config);
82
+        }
83
+
84
+        if ($this->caldavBackend instanceof SchedulingSupport) {
85
+            $objects[] = new Inbox($this->caldavBackend, $this->principalInfo['uri']);
86
+            $objects[] = new Outbox($this->config, $this->principalInfo['uri']);
87
+        }
88
+
89
+        // We're adding a notifications node, if it's supported by the backend.
90
+        if ($this->caldavBackend instanceof NotificationSupport) {
91
+            $objects[] = new \Sabre\CalDAV\Notifications\Collection($this->caldavBackend, $this->principalInfo['uri']);
92
+        }
93
+
94
+        // If the backend supports subscriptions, we'll add those as well,
95
+        if ($this->caldavBackend instanceof SubscriptionSupport) {
96
+            foreach ($this->caldavBackend->getSubscriptionsForUser($this->principalInfo['uri']) as $subscription) {
97
+                if ($this->returnCachedSubscriptions) {
98
+                    $objects[] = new CachedSubscription($this->caldavBackend, $subscription);
99
+                } else {
100
+                    $objects[] = new Subscription($this->caldavBackend, $subscription);
101
+                }
102
+            }
103
+        }
104
+
105
+        return $objects;
106
+    }
107
+
108
+    /**
109
+     * @inheritdoc
110
+     */
111
+    function getChild($name) {
112
+        // Special nodes
113
+        if ($name === 'inbox' && $this->caldavBackend instanceof SchedulingSupport) {
114
+            return new Inbox($this->caldavBackend, $this->principalInfo['uri']);
115
+        }
116
+        if ($name === 'outbox' && $this->caldavBackend instanceof SchedulingSupport) {
117
+            return new Outbox($this->config, $this->principalInfo['uri']);
118
+        }
119
+        if ($name === 'notifications' && $this->caldavBackend instanceof NotificationSupport) {
120
+            return new \Sabre\CalDAv\Notifications\Collection($this->caldavBackend, $this->principalInfo['uri']);
121
+        }
122
+
123
+        // Calendars
124
+        foreach ($this->caldavBackend->getCalendarsForUser($this->principalInfo['uri']) as $calendar) {
125
+            if ($calendar['uri'] === $name) {
126
+                return new Calendar($this->caldavBackend, $calendar, $this->l10n, $this->config);
127
+            }
128
+        }
129
+
130
+        if ($this->caldavBackend instanceof SubscriptionSupport) {
131
+            foreach ($this->caldavBackend->getSubscriptionsForUser($this->principalInfo['uri']) as $subscription) {
132
+                if ($subscription['uri'] === $name) {
133
+                    if ($this->returnCachedSubscriptions) {
134
+                        return new CachedSubscription($this->caldavBackend, $subscription);
135
+                    }
136
+
137
+                    return new Subscription($this->caldavBackend, $subscription);
138
+                }
139
+            }
140
+
141
+        }
142
+
143
+        throw new NotFound('Node with name \'' . $name . '\' could not be found');
144
+    }
145
+
146
+    /**
147
+     * @param array $filters
148
+     * @param integer|null $limit
149
+     * @param integer|null $offset
150
+     */
151
+    function calendarSearch(array $filters, $limit=null, $offset=null) {
152
+        $principalUri = $this->principalInfo['uri'];
153
+        return $this->caldavBackend->calendarSearch($principalUri, $filters, $limit, $offset);
154
+    }
155
+
156
+    /**
157
+     *
158
+     */
159
+    public function enableCachedSubscriptionsForThisRequest() {
160
+        $this->returnCachedSubscriptions = true;
161
+    }
162 162
 }
Please login to merge, or discard this patch.
apps/dav/lib/Migration/RefreshWebcalJobRegistrar.php 2 patches
Indentation   +41 added lines, -41 removed lines patch added patch discarded remove patch
@@ -32,52 +32,52 @@
 block discarded – undo
32 32
 
33 33
 class RefreshWebcalJobRegistrar implements IRepairStep {
34 34
 
35
-	/** @var IDBConnection */
36
-	private $connection;
35
+    /** @var IDBConnection */
36
+    private $connection;
37 37
 
38
-	/** @var IJobList */
39
-	private $jobList;
38
+    /** @var IJobList */
39
+    private $jobList;
40 40
 
41
-	/**
42
-	 * FixBirthdayCalendarComponent constructor.
43
-	 *
44
-	 * @param IDBConnection $connection
45
-	 * @param IJobList $jobList
46
-	 */
47
-	public function __construct(IDBConnection $connection, IJobList $jobList) {
48
-		$this->connection = $connection;
49
-		$this->jobList = $jobList;
50
-	}
41
+    /**
42
+     * FixBirthdayCalendarComponent constructor.
43
+     *
44
+     * @param IDBConnection $connection
45
+     * @param IJobList $jobList
46
+     */
47
+    public function __construct(IDBConnection $connection, IJobList $jobList) {
48
+        $this->connection = $connection;
49
+        $this->jobList = $jobList;
50
+    }
51 51
 
52
-	/**
53
-	 * @inheritdoc
54
-	 */
55
-	public function getName() {
56
-		return 'Registering background jobs to update cache for webcal calendars';
57
-	}
52
+    /**
53
+     * @inheritdoc
54
+     */
55
+    public function getName() {
56
+        return 'Registering background jobs to update cache for webcal calendars';
57
+    }
58 58
 
59
-	/**
60
-	 * @inheritdoc
61
-	 */
62
-	public function run(IOutput $output) {
63
-		$query = $this->connection->getQueryBuilder();
64
-		$query->select(['principaluri', 'uri'])
65
-			->from('calendarsubscriptions');
66
-		$stmt = $query->execute();
59
+    /**
60
+     * @inheritdoc
61
+     */
62
+    public function run(IOutput $output) {
63
+        $query = $this->connection->getQueryBuilder();
64
+        $query->select(['principaluri', 'uri'])
65
+            ->from('calendarsubscriptions');
66
+        $stmt = $query->execute();
67 67
 
68
-		$count = 0;
69
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
70
-			$args = [
71
-				'principaluri' => $row['principaluri'],
72
-				'uri' => $row['uri'],
73
-			];
68
+        $count = 0;
69
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
70
+            $args = [
71
+                'principaluri' => $row['principaluri'],
72
+                'uri' => $row['uri'],
73
+            ];
74 74
 
75
-			if (!$this->jobList->has(RefreshWebcalJob::class, $args)) {
76
-				$this->jobList->add(RefreshWebcalJob::class, $args);
77
-				$count++;
78
-			}
79
-		}
75
+            if (!$this->jobList->has(RefreshWebcalJob::class, $args)) {
76
+                $this->jobList->add(RefreshWebcalJob::class, $args);
77
+                $count++;
78
+            }
79
+        }
80 80
 
81
-		$output->info("Added $count background jobs to update webcal calendars");
82
-	}
81
+        $output->info("Added $count background jobs to update webcal calendars");
82
+    }
83 83
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -66,7 +66,7 @@
 block discarded – undo
66 66
 		$stmt = $query->execute();
67 67
 
68 68
 		$count = 0;
69
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
69
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
70 70
 			$args = [
71 71
 				'principaluri' => $row['principaluri'],
72 72
 				'uri' => $row['uri'],
Please login to merge, or discard this patch.
apps/dav/lib/Migration/Version1006Date20180628111625.php 1 patch
Indentation   +61 added lines, -61 removed lines patch added patch discarded remove patch
@@ -31,75 +31,75 @@
 block discarded – undo
31 31
 
32 32
 class Version1006Date20180628111625 extends SimpleMigrationStep {
33 33
 
34
-	/**
35
-	 * @param IOutput $output
36
-	 * @param \Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
37
-	 * @param array $options
38
-	 * @return null|ISchemaWrapper
39
-	 */
40
-	public function changeSchema(IOutput $output, \Closure $schemaClosure, array $options) {
41
-		/** @var ISchemaWrapper $schema */
42
-		$schema = $schemaClosure();
34
+    /**
35
+     * @param IOutput $output
36
+     * @param \Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
37
+     * @param array $options
38
+     * @return null|ISchemaWrapper
39
+     */
40
+    public function changeSchema(IOutput $output, \Closure $schemaClosure, array $options) {
41
+        /** @var ISchemaWrapper $schema */
42
+        $schema = $schemaClosure();
43 43
 
44
-		if ($schema->hasTable('calendarchanges')) {
45
-			$calendarChangesTable = $schema->getTable('calendarchanges');
46
-			$calendarChangesTable->addColumn('calendartype', Type::INTEGER, [
47
-				'notnull' => true,
48
-				'default' => 0,
49
-			]);
44
+        if ($schema->hasTable('calendarchanges')) {
45
+            $calendarChangesTable = $schema->getTable('calendarchanges');
46
+            $calendarChangesTable->addColumn('calendartype', Type::INTEGER, [
47
+                'notnull' => true,
48
+                'default' => 0,
49
+            ]);
50 50
 
51
-			if ($calendarChangesTable->hasIndex('calendarid_synctoken')) {
52
-				$calendarChangesTable->dropIndex('calendarid_synctoken');
53
-			}
54
-			$calendarChangesTable->addIndex(['calendarid', 'calendartype', 'synctoken'], 'calendarid_calendartype_synctoken');
55
-		}
51
+            if ($calendarChangesTable->hasIndex('calendarid_synctoken')) {
52
+                $calendarChangesTable->dropIndex('calendarid_synctoken');
53
+            }
54
+            $calendarChangesTable->addIndex(['calendarid', 'calendartype', 'synctoken'], 'calendarid_calendartype_synctoken');
55
+        }
56 56
 
57
-		if ($schema->hasTable('calendarobjects')) {
58
-			$calendarObjectsTable = $schema->getTable('calendarobjects');
59
-			$calendarObjectsTable->addColumn('calendartype', Type::INTEGER, [
60
-				'notnull' => true,
61
-				'default' => 0,
62
-			]);
57
+        if ($schema->hasTable('calendarobjects')) {
58
+            $calendarObjectsTable = $schema->getTable('calendarobjects');
59
+            $calendarObjectsTable->addColumn('calendartype', Type::INTEGER, [
60
+                'notnull' => true,
61
+                'default' => 0,
62
+            ]);
63 63
 
64
-			if ($calendarObjectsTable->hasIndex('calobjects_index')) {
65
-				$calendarObjectsTable->dropIndex('calobjects_index');
66
-			}
67
-			$calendarObjectsTable->addUniqueIndex(['calendarid', 'calendartype', 'uri'], 'calobjects_index');
68
-		}
64
+            if ($calendarObjectsTable->hasIndex('calobjects_index')) {
65
+                $calendarObjectsTable->dropIndex('calobjects_index');
66
+            }
67
+            $calendarObjectsTable->addUniqueIndex(['calendarid', 'calendartype', 'uri'], 'calobjects_index');
68
+        }
69 69
 
70
-		if ($schema->hasTable('calendarobjects_props')) {
71
-			$calendarObjectsPropsTable = $schema->getTable('calendarobjects_props');
72
-			$calendarObjectsPropsTable->addColumn('calendartype', Type::INTEGER, [
73
-				'notnull' => true,
74
-				'default' => 0,
75
-			]);
70
+        if ($schema->hasTable('calendarobjects_props')) {
71
+            $calendarObjectsPropsTable = $schema->getTable('calendarobjects_props');
72
+            $calendarObjectsPropsTable->addColumn('calendartype', Type::INTEGER, [
73
+                'notnull' => true,
74
+                'default' => 0,
75
+            ]);
76 76
 
77 77
 
78
-			if ($calendarObjectsPropsTable->hasIndex('calendarobject_index')) {
79
-				$calendarObjectsPropsTable->dropIndex('calendarobject_index');
80
-			}
81
-			if ($calendarObjectsPropsTable->hasIndex('calendarobject_name_index')) {
82
-				$calendarObjectsPropsTable->dropIndex('calendarobject_name_index');
83
-			}
84
-			if ($calendarObjectsPropsTable->hasIndex('calendarobject_value_index')) {
85
-				$calendarObjectsPropsTable->dropIndex('calendarobject_value_index');
86
-			}
78
+            if ($calendarObjectsPropsTable->hasIndex('calendarobject_index')) {
79
+                $calendarObjectsPropsTable->dropIndex('calendarobject_index');
80
+            }
81
+            if ($calendarObjectsPropsTable->hasIndex('calendarobject_name_index')) {
82
+                $calendarObjectsPropsTable->dropIndex('calendarobject_name_index');
83
+            }
84
+            if ($calendarObjectsPropsTable->hasIndex('calendarobject_value_index')) {
85
+                $calendarObjectsPropsTable->dropIndex('calendarobject_value_index');
86
+            }
87 87
 
88
-			$calendarObjectsPropsTable->addIndex(['objectid', 'calendartype'], 'calendarobject_index');
89
-			$calendarObjectsPropsTable->addIndex(['name', 'calendartype'], 'calendarobject_name_index');
90
-			$calendarObjectsPropsTable->addIndex(['value', 'calendartype'], 'calendarobject_value_index');
91
-		}
88
+            $calendarObjectsPropsTable->addIndex(['objectid', 'calendartype'], 'calendarobject_index');
89
+            $calendarObjectsPropsTable->addIndex(['name', 'calendartype'], 'calendarobject_name_index');
90
+            $calendarObjectsPropsTable->addIndex(['value', 'calendartype'], 'calendarobject_value_index');
91
+        }
92 92
 
93
-		if ($schema->hasTable('calendarsubscriptions')) {
94
-			$calendarSubscriptionsTable = $schema->getTable('calendarsubscriptions');
95
-			$calendarSubscriptionsTable->addColumn('synctoken', 'integer', [
96
-				'notnull' => true,
97
-				'default' => 1,
98
-				'length' => 10,
99
-				'unsigned' => true,
100
-			]);
101
-		}
93
+        if ($schema->hasTable('calendarsubscriptions')) {
94
+            $calendarSubscriptionsTable = $schema->getTable('calendarsubscriptions');
95
+            $calendarSubscriptionsTable->addColumn('synctoken', 'integer', [
96
+                'notnull' => true,
97
+                'default' => 1,
98
+                'length' => 10,
99
+                'unsigned' => true,
100
+            ]);
101
+        }
102 102
 
103
-		return $schema;
104
-	}
103
+        return $schema;
104
+    }
105 105
 }
Please login to merge, or discard this patch.
apps/dav/lib/BackgroundJob/RefreshWebcalJob.php 2 patches
Indentation   +390 added lines, -390 removed lines patch added patch discarded remove patch
@@ -45,394 +45,394 @@
 block discarded – undo
45 45
 
46 46
 class RefreshWebcalJob extends Job {
47 47
 
48
-	/** @var CalDavBackend */
49
-	private $calDavBackend;
50
-
51
-	/** @var IClientService */
52
-	private $clientService;
53
-
54
-	/** @var IConfig */
55
-	private $config;
56
-
57
-	/** @var ILogger */
58
-	private $logger;
59
-
60
-	/** @var ITimeFactory */
61
-	private $timeFactory;
62
-
63
-	/** @var array */
64
-	private $subscription;
65
-
66
-	/**
67
-	 * RefreshWebcalJob constructor.
68
-	 *
69
-	 * @param CalDavBackend $calDavBackend
70
-	 * @param IClientService $clientService
71
-	 * @param IConfig $config
72
-	 * @param ILogger $logger
73
-	 * @param ITimeFactory $timeFactory
74
-	 */
75
-	public function __construct(CalDavBackend $calDavBackend, IClientService $clientService, IConfig $config, ILogger $logger, ITimeFactory $timeFactory) {
76
-		$this->calDavBackend = $calDavBackend;
77
-		$this->clientService = $clientService;
78
-		$this->config = $config;
79
-		$this->logger = $logger;
80
-		$this->timeFactory = $timeFactory;
81
-	}
82
-
83
-	/**
84
-	 * this function is called at most every hour
85
-	 *
86
-	 * @inheritdoc
87
-	 */
88
-	public function execute($jobList, ILogger $logger = null) {
89
-		$subscription = $this->getSubscription($this->argument['principaluri'], $this->argument['uri']);
90
-		if (!$subscription) {
91
-			return;
92
-		}
93
-
94
-		// if no refresh rate was configured, just refresh once a week
95
-		$subscriptionId = $subscription['id'];
96
-		$refreshrate = $subscription['refreshrate'] ?? 'P1W';
97
-
98
-		try {
99
-			/** @var \DateInterval $dateInterval */
100
-			$dateInterval = DateTimeParser::parseDuration($refreshrate);
101
-		} catch(InvalidDataException $ex) {
102
-			$this->logger->logException($ex);
103
-			$this->logger->warning("Subscription $subscriptionId could not be refreshed, refreshrate in database is invalid");
104
-			return;
105
-		}
106
-
107
-		$interval = $this->getIntervalFromDateInterval($dateInterval);
108
-		if (($this->timeFactory->getTime() - $this->lastRun) <= $interval) {
109
-			return;
110
-		}
111
-
112
-		parent::execute($jobList, $logger);
113
-	}
114
-
115
-	/**
116
-	 * @param array $argument
117
-	 */
118
-	protected function run($argument) {
119
-		$subscription = $this->getSubscription($argument['principaluri'], $argument['uri']);
120
-		$mutations = [];
121
-		if (!$subscription) {
122
-			return;
123
-		}
124
-
125
-		$webcalData = $this->queryWebcalFeed($subscription, $mutations);
126
-		if (!$webcalData) {
127
-			return;
128
-		}
129
-
130
-		$stripTodos = $subscription['striptodos'] ?? 1;
131
-		$stripAlarms = $subscription['stripalarms'] ?? 1;
132
-		$stripAttachments = $subscription['stripattachments'] ?? 1;
133
-
134
-		try {
135
-			$splitter = new ICalendar($webcalData, Reader::OPTION_FORGIVING);
136
-
137
-			// we wait with deleting all outdated events till we parsed the new ones
138
-			// in case the new calendar is broken and `new ICalendar` throws a ParseException
139
-			// the user will still see the old data
140
-			$this->calDavBackend->purgeAllCachedEventsForSubscription($subscription['id']);
141
-
142
-			while ($vObject = $splitter->getNext()) {
143
-				/** @var Component $vObject */
144
-				$uid = null;
145
-				$compName = null;
146
-
147
-				foreach ($vObject->getComponents() as $component) {
148
-					if ($component->name === 'VTIMEZONE') {
149
-						continue;
150
-					}
151
-
152
-					$uid = $component->{'UID'}->getValue();
153
-					$compName = $component->name;
154
-
155
-					if ($stripAlarms) {
156
-						unset($component->{'VALARM'});
157
-					}
158
-					if ($stripAttachments) {
159
-						unset($component->{'ATTACH'});
160
-					}
161
-				}
162
-
163
-				if ($stripTodos && $compName === 'VTODO') {
164
-					continue;
165
-				}
166
-
167
-				$uri = $uid . '.ics';
168
-				$calendarData = $vObject->serialize();
169
-				try {
170
-					$this->calDavBackend->createCalendarObject($subscription['id'], $uri, $calendarData, CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION);
171
-				} catch(BadRequest $ex) {
172
-					$this->logger->logException($ex);
173
-				}
174
-			}
175
-
176
-			$newRefreshRate = $this->checkWebcalDataForRefreshRate($subscription, $webcalData);
177
-			if ($newRefreshRate) {
178
-				$mutations['{http://apple.com/ns/ical/}refreshrate'] = $newRefreshRate;
179
-			}
180
-
181
-			$this->updateSubscription($subscription, $mutations);
182
-		} catch(ParseException $ex) {
183
-			$subscriptionId = $subscription['id'];
184
-
185
-			$this->logger->logException($ex);
186
-			$this->logger->warning("Subscription $subscriptionId could not be refreshed due to a parsing error");
187
-		}
188
-	}
189
-
190
-	/**
191
-	 * gets webcal feed from remote server
192
-	 *
193
-	 * @param array $subscription
194
-	 * @param array &$mutations
195
-	 * @return null|string
196
-	 */
197
-	private function queryWebcalFeed(array $subscription, array &$mutations) {
198
-		$client = $this->clientService->newClient();
199
-
200
-		$didBreak301Chain = false;
201
-		$latestLocation = null;
202
-
203
-		$handlerStack = HandlerStack::create();
204
-		$handlerStack->push(Middleware::mapRequest(function (RequestInterface $request) {
205
-			return $request
206
-				->withHeader('Accept', 'text/calendar, application/calendar+json, application/calendar+xml')
207
-				->withHeader('User-Agent', 'Nextcloud Webcal Crawler');
208
-		}));
209
-		$handlerStack->push(Middleware::mapResponse(function(ResponseInterface $response) use (&$didBreak301Chain, &$latestLocation) {
210
-			if (!$didBreak301Chain) {
211
-				if ($response->getStatusCode() !== 301) {
212
-					$didBreak301Chain = true;
213
-				} else {
214
-					$latestLocation = $response->getHeader('Location');
215
-				}
216
-			}
217
-			return $response;
218
-		}));
219
-
220
-		$allowLocalAccess = $this->config->getAppValue('dav', 'webcalAllowLocalAccess', 'no');
221
-		$subscriptionId = $subscription['id'];
222
-		$url = $this->cleanURL($subscription['source']);
223
-		if ($url === null) {
224
-			return null;
225
-		}
226
-
227
-		if ($allowLocalAccess !== 'yes') {
228
-			$host = parse_url($url, PHP_URL_HOST);
229
-			// remove brackets from IPv6 addresses
230
-			if (strpos($host, '[') === 0 && substr($host, -1) === ']') {
231
-				$host = substr($host, 1, -1);
232
-			}
233
-
234
-			if ($host === 'localhost' || substr($host, -6) === '.local' || substr($host, -10) === '.localhost' ||
235
-				preg_match('/(^127\.)|(^192\.168\.)|(^10\.)|(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)|(^::1$)|(^[fF][cCdD])/', $host)) {
236
-				$this->logger->warning("Subscription $subscriptionId was not refreshed because it violates local access rules");
237
-				return null;
238
-			}
239
-		}
240
-
241
-		try {
242
-			$params = [
243
-				'allow_redirects' => [
244
-					'redirects' => 10
245
-				],
246
-				'handler' => $handlerStack,
247
-			];
248
-
249
-			$user = parse_url($subscription['source'], PHP_URL_USER);
250
-			$pass = parse_url($subscription['source'], PHP_URL_PASS);
251
-			if ($user !== null && $pass !== null) {
252
-				$params['auth'] = [$user, $pass];
253
-			}
254
-
255
-			$response = $client->get($url, $params);
256
-			$body = $response->getBody();
257
-
258
-			if ($latestLocation) {
259
-				$mutations['{http://calendarserver.org/ns/}source'] = new Href($latestLocation);
260
-			}
261
-
262
-			$contentType = $response->getHeader('Content-Type');
263
-			$contentType = explode(';', $contentType, 2)[0];
264
-			switch($contentType) {
265
-				case 'application/calendar+json':
266
-					try {
267
-						$jCalendar = Reader::readJson($body, Reader::OPTION_FORGIVING);
268
-					} catch(\Exception $ex) {
269
-						// In case of a parsing error return null
270
-						$this->logger->debug("Subscription $subscriptionId could not be parsed");
271
-						return null;
272
-					}
273
-					return $jCalendar->serialize();
274
-
275
-				case 'application/calendar+xml':
276
-					try {
277
-						$xCalendar = Reader::readXML($body);
278
-					} catch(\Exception $ex) {
279
-						// In case of a parsing error return null
280
-						$this->logger->debug("Subscription $subscriptionId could not be parsed");
281
-						return null;
282
-					}
283
-					return $xCalendar->serialize();
284
-
285
-				case 'text/calendar':
286
-				default:
287
-					try {
288
-						$vCalendar = Reader::read($body);
289
-					} catch(\Exception $ex) {
290
-						// In case of a parsing error return null
291
-						$this->logger->debug("Subscription $subscriptionId could not be parsed");
292
-						return null;
293
-					}
294
-					return $vCalendar->serialize();
295
-			}
296
-		} catch(\Exception $ex) {
297
-			$this->logger->logException($ex);
298
-			$this->logger->warning("Subscription $subscriptionId could not be refreshed due to a network error");
299
-
300
-			return null;
301
-		}
302
-	}
303
-
304
-	/**
305
-	 * loads subscription from backend
306
-	 *
307
-	 * @param string $principalUri
308
-	 * @param string $uri
309
-	 * @return array|null
310
-	 */
311
-	private function getSubscription(string $principalUri, string $uri) {
312
-		$subscriptions = array_values(array_filter(
313
-			$this->calDavBackend->getSubscriptionsForUser($principalUri),
314
-			function($sub) use ($uri) {
315
-				return $sub['uri'] === $uri;
316
-			}
317
-		));
318
-
319
-		if (\count($subscriptions) === 0) {
320
-			return null;
321
-		}
322
-
323
-		$this->subscription = $subscriptions[0];
324
-		return $this->subscription;
325
-	}
326
-
327
-	/**
328
-	 * get total number of seconds from DateInterval object
329
-	 *
330
-	 * @param \DateInterval $interval
331
-	 * @return int
332
-	 */
333
-	private function getIntervalFromDateInterval(\DateInterval $interval):int {
334
-		return $interval->s
335
-			+ ($interval->i * 60)
336
-			+ ($interval->h * 60 * 60)
337
-			+ ($interval->d * 60 * 60 * 24)
338
-			+ ($interval->m * 60 * 60 * 24 * 30)
339
-			+ ($interval->y * 60 * 60 * 24 * 365);
340
-	}
341
-
342
-	/**
343
-	 * check if:
344
-	 *  - current subscription stores a refreshrate
345
-	 *  - the webcal feed suggests a refreshrate
346
-	 *  - return suggested refreshrate if user didn't set a custom one
347
-	 *
348
-	 * @param array $subscription
349
-	 * @param string $webcalData
350
-	 * @return string|null
351
-	 */
352
-	private function checkWebcalDataForRefreshRate($subscription, $webcalData) {
353
-		// if there is no refreshrate stored in the database, check the webcal feed
354
-		// whether it suggests any refresh rate and store that in the database
355
-		if (isset($subscription['refreshrate']) && $subscription['refreshrate'] !== null) {
356
-			return null;
357
-		}
358
-
359
-		/** @var Component\VCalendar $vCalendar */
360
-		$vCalendar = Reader::read($webcalData);
361
-
362
-		$newRefreshrate = null;
363
-		if (isset($vCalendar->{'X-PUBLISHED-TTL'})) {
364
-			$newRefreshrate = $vCalendar->{'X-PUBLISHED-TTL'}->getValue();
365
-		}
366
-		if (isset($vCalendar->{'REFRESH-INTERVAL'})) {
367
-			$newRefreshrate = $vCalendar->{'REFRESH-INTERVAL'}->getValue();
368
-		}
369
-
370
-		if (!$newRefreshrate) {
371
-			return null;
372
-		}
373
-
374
-		// check if new refresh rate is even valid
375
-		try {
376
-			DateTimeParser::parseDuration($newRefreshrate);
377
-		} catch(InvalidDataException $ex) {
378
-			return null;
379
-		}
380
-
381
-		return $newRefreshrate;
382
-	}
383
-
384
-	/**
385
-	 * update subscription stored in database
386
-	 * used to set:
387
-	 *  - refreshrate
388
-	 *  - source
389
-	 *
390
-	 * @param array $subscription
391
-	 * @param array $mutations
392
-	 */
393
-	private function updateSubscription(array $subscription, array $mutations) {
394
-		if (empty($mutations)) {
395
-			return;
396
-		}
397
-
398
-		$propPatch = new PropPatch($mutations);
399
-		$this->calDavBackend->updateSubscription($subscription['id'], $propPatch);
400
-		$propPatch->commit();
401
-	}
402
-
403
-	/**
404
-	 * This method will strip authentication information and replace the
405
-	 * 'webcal' or 'webcals' protocol scheme
406
-	 *
407
-	 * @param string $url
408
-	 * @return string|null
409
-	 */
410
-	private function cleanURL(string $url) {
411
-		$parsed = parse_url($url);
412
-		if ($parsed === false) {
413
-			return null;
414
-		}
415
-
416
-		if (isset($parsed['scheme']) && $parsed['scheme'] === 'http') {
417
-			$scheme = 'http';
418
-		} else {
419
-			$scheme = 'https';
420
-		}
421
-
422
-		$host = $parsed['host'] ?? '';
423
-		$port = isset($parsed['port']) ? ':' . $parsed['port'] : '';
424
-		$path = $parsed['path'] ?? '';
425
-		$query = isset($parsed['query']) ? '?' . $parsed['query'] : '';
426
-		$fragment = isset($parsed['fragment']) ? '#' . $parsed['fragment'] : '';
427
-
428
-		$cleanURL = "$scheme://$host$port$path$query$fragment";
429
-		// parse_url is giving some weird results if no url and no :// is given,
430
-		// so let's test the url again
431
-		$parsedClean = parse_url($cleanURL);
432
-		if ($parsedClean === false || !isset($parsedClean['host'])) {
433
-			return null;
434
-		}
435
-
436
-		return $cleanURL;
437
-	}
48
+    /** @var CalDavBackend */
49
+    private $calDavBackend;
50
+
51
+    /** @var IClientService */
52
+    private $clientService;
53
+
54
+    /** @var IConfig */
55
+    private $config;
56
+
57
+    /** @var ILogger */
58
+    private $logger;
59
+
60
+    /** @var ITimeFactory */
61
+    private $timeFactory;
62
+
63
+    /** @var array */
64
+    private $subscription;
65
+
66
+    /**
67
+     * RefreshWebcalJob constructor.
68
+     *
69
+     * @param CalDavBackend $calDavBackend
70
+     * @param IClientService $clientService
71
+     * @param IConfig $config
72
+     * @param ILogger $logger
73
+     * @param ITimeFactory $timeFactory
74
+     */
75
+    public function __construct(CalDavBackend $calDavBackend, IClientService $clientService, IConfig $config, ILogger $logger, ITimeFactory $timeFactory) {
76
+        $this->calDavBackend = $calDavBackend;
77
+        $this->clientService = $clientService;
78
+        $this->config = $config;
79
+        $this->logger = $logger;
80
+        $this->timeFactory = $timeFactory;
81
+    }
82
+
83
+    /**
84
+     * this function is called at most every hour
85
+     *
86
+     * @inheritdoc
87
+     */
88
+    public function execute($jobList, ILogger $logger = null) {
89
+        $subscription = $this->getSubscription($this->argument['principaluri'], $this->argument['uri']);
90
+        if (!$subscription) {
91
+            return;
92
+        }
93
+
94
+        // if no refresh rate was configured, just refresh once a week
95
+        $subscriptionId = $subscription['id'];
96
+        $refreshrate = $subscription['refreshrate'] ?? 'P1W';
97
+
98
+        try {
99
+            /** @var \DateInterval $dateInterval */
100
+            $dateInterval = DateTimeParser::parseDuration($refreshrate);
101
+        } catch(InvalidDataException $ex) {
102
+            $this->logger->logException($ex);
103
+            $this->logger->warning("Subscription $subscriptionId could not be refreshed, refreshrate in database is invalid");
104
+            return;
105
+        }
106
+
107
+        $interval = $this->getIntervalFromDateInterval($dateInterval);
108
+        if (($this->timeFactory->getTime() - $this->lastRun) <= $interval) {
109
+            return;
110
+        }
111
+
112
+        parent::execute($jobList, $logger);
113
+    }
114
+
115
+    /**
116
+     * @param array $argument
117
+     */
118
+    protected function run($argument) {
119
+        $subscription = $this->getSubscription($argument['principaluri'], $argument['uri']);
120
+        $mutations = [];
121
+        if (!$subscription) {
122
+            return;
123
+        }
124
+
125
+        $webcalData = $this->queryWebcalFeed($subscription, $mutations);
126
+        if (!$webcalData) {
127
+            return;
128
+        }
129
+
130
+        $stripTodos = $subscription['striptodos'] ?? 1;
131
+        $stripAlarms = $subscription['stripalarms'] ?? 1;
132
+        $stripAttachments = $subscription['stripattachments'] ?? 1;
133
+
134
+        try {
135
+            $splitter = new ICalendar($webcalData, Reader::OPTION_FORGIVING);
136
+
137
+            // we wait with deleting all outdated events till we parsed the new ones
138
+            // in case the new calendar is broken and `new ICalendar` throws a ParseException
139
+            // the user will still see the old data
140
+            $this->calDavBackend->purgeAllCachedEventsForSubscription($subscription['id']);
141
+
142
+            while ($vObject = $splitter->getNext()) {
143
+                /** @var Component $vObject */
144
+                $uid = null;
145
+                $compName = null;
146
+
147
+                foreach ($vObject->getComponents() as $component) {
148
+                    if ($component->name === 'VTIMEZONE') {
149
+                        continue;
150
+                    }
151
+
152
+                    $uid = $component->{'UID'}->getValue();
153
+                    $compName = $component->name;
154
+
155
+                    if ($stripAlarms) {
156
+                        unset($component->{'VALARM'});
157
+                    }
158
+                    if ($stripAttachments) {
159
+                        unset($component->{'ATTACH'});
160
+                    }
161
+                }
162
+
163
+                if ($stripTodos && $compName === 'VTODO') {
164
+                    continue;
165
+                }
166
+
167
+                $uri = $uid . '.ics';
168
+                $calendarData = $vObject->serialize();
169
+                try {
170
+                    $this->calDavBackend->createCalendarObject($subscription['id'], $uri, $calendarData, CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION);
171
+                } catch(BadRequest $ex) {
172
+                    $this->logger->logException($ex);
173
+                }
174
+            }
175
+
176
+            $newRefreshRate = $this->checkWebcalDataForRefreshRate($subscription, $webcalData);
177
+            if ($newRefreshRate) {
178
+                $mutations['{http://apple.com/ns/ical/}refreshrate'] = $newRefreshRate;
179
+            }
180
+
181
+            $this->updateSubscription($subscription, $mutations);
182
+        } catch(ParseException $ex) {
183
+            $subscriptionId = $subscription['id'];
184
+
185
+            $this->logger->logException($ex);
186
+            $this->logger->warning("Subscription $subscriptionId could not be refreshed due to a parsing error");
187
+        }
188
+    }
189
+
190
+    /**
191
+     * gets webcal feed from remote server
192
+     *
193
+     * @param array $subscription
194
+     * @param array &$mutations
195
+     * @return null|string
196
+     */
197
+    private function queryWebcalFeed(array $subscription, array &$mutations) {
198
+        $client = $this->clientService->newClient();
199
+
200
+        $didBreak301Chain = false;
201
+        $latestLocation = null;
202
+
203
+        $handlerStack = HandlerStack::create();
204
+        $handlerStack->push(Middleware::mapRequest(function (RequestInterface $request) {
205
+            return $request
206
+                ->withHeader('Accept', 'text/calendar, application/calendar+json, application/calendar+xml')
207
+                ->withHeader('User-Agent', 'Nextcloud Webcal Crawler');
208
+        }));
209
+        $handlerStack->push(Middleware::mapResponse(function(ResponseInterface $response) use (&$didBreak301Chain, &$latestLocation) {
210
+            if (!$didBreak301Chain) {
211
+                if ($response->getStatusCode() !== 301) {
212
+                    $didBreak301Chain = true;
213
+                } else {
214
+                    $latestLocation = $response->getHeader('Location');
215
+                }
216
+            }
217
+            return $response;
218
+        }));
219
+
220
+        $allowLocalAccess = $this->config->getAppValue('dav', 'webcalAllowLocalAccess', 'no');
221
+        $subscriptionId = $subscription['id'];
222
+        $url = $this->cleanURL($subscription['source']);
223
+        if ($url === null) {
224
+            return null;
225
+        }
226
+
227
+        if ($allowLocalAccess !== 'yes') {
228
+            $host = parse_url($url, PHP_URL_HOST);
229
+            // remove brackets from IPv6 addresses
230
+            if (strpos($host, '[') === 0 && substr($host, -1) === ']') {
231
+                $host = substr($host, 1, -1);
232
+            }
233
+
234
+            if ($host === 'localhost' || substr($host, -6) === '.local' || substr($host, -10) === '.localhost' ||
235
+                preg_match('/(^127\.)|(^192\.168\.)|(^10\.)|(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)|(^::1$)|(^[fF][cCdD])/', $host)) {
236
+                $this->logger->warning("Subscription $subscriptionId was not refreshed because it violates local access rules");
237
+                return null;
238
+            }
239
+        }
240
+
241
+        try {
242
+            $params = [
243
+                'allow_redirects' => [
244
+                    'redirects' => 10
245
+                ],
246
+                'handler' => $handlerStack,
247
+            ];
248
+
249
+            $user = parse_url($subscription['source'], PHP_URL_USER);
250
+            $pass = parse_url($subscription['source'], PHP_URL_PASS);
251
+            if ($user !== null && $pass !== null) {
252
+                $params['auth'] = [$user, $pass];
253
+            }
254
+
255
+            $response = $client->get($url, $params);
256
+            $body = $response->getBody();
257
+
258
+            if ($latestLocation) {
259
+                $mutations['{http://calendarserver.org/ns/}source'] = new Href($latestLocation);
260
+            }
261
+
262
+            $contentType = $response->getHeader('Content-Type');
263
+            $contentType = explode(';', $contentType, 2)[0];
264
+            switch($contentType) {
265
+                case 'application/calendar+json':
266
+                    try {
267
+                        $jCalendar = Reader::readJson($body, Reader::OPTION_FORGIVING);
268
+                    } catch(\Exception $ex) {
269
+                        // In case of a parsing error return null
270
+                        $this->logger->debug("Subscription $subscriptionId could not be parsed");
271
+                        return null;
272
+                    }
273
+                    return $jCalendar->serialize();
274
+
275
+                case 'application/calendar+xml':
276
+                    try {
277
+                        $xCalendar = Reader::readXML($body);
278
+                    } catch(\Exception $ex) {
279
+                        // In case of a parsing error return null
280
+                        $this->logger->debug("Subscription $subscriptionId could not be parsed");
281
+                        return null;
282
+                    }
283
+                    return $xCalendar->serialize();
284
+
285
+                case 'text/calendar':
286
+                default:
287
+                    try {
288
+                        $vCalendar = Reader::read($body);
289
+                    } catch(\Exception $ex) {
290
+                        // In case of a parsing error return null
291
+                        $this->logger->debug("Subscription $subscriptionId could not be parsed");
292
+                        return null;
293
+                    }
294
+                    return $vCalendar->serialize();
295
+            }
296
+        } catch(\Exception $ex) {
297
+            $this->logger->logException($ex);
298
+            $this->logger->warning("Subscription $subscriptionId could not be refreshed due to a network error");
299
+
300
+            return null;
301
+        }
302
+    }
303
+
304
+    /**
305
+     * loads subscription from backend
306
+     *
307
+     * @param string $principalUri
308
+     * @param string $uri
309
+     * @return array|null
310
+     */
311
+    private function getSubscription(string $principalUri, string $uri) {
312
+        $subscriptions = array_values(array_filter(
313
+            $this->calDavBackend->getSubscriptionsForUser($principalUri),
314
+            function($sub) use ($uri) {
315
+                return $sub['uri'] === $uri;
316
+            }
317
+        ));
318
+
319
+        if (\count($subscriptions) === 0) {
320
+            return null;
321
+        }
322
+
323
+        $this->subscription = $subscriptions[0];
324
+        return $this->subscription;
325
+    }
326
+
327
+    /**
328
+     * get total number of seconds from DateInterval object
329
+     *
330
+     * @param \DateInterval $interval
331
+     * @return int
332
+     */
333
+    private function getIntervalFromDateInterval(\DateInterval $interval):int {
334
+        return $interval->s
335
+            + ($interval->i * 60)
336
+            + ($interval->h * 60 * 60)
337
+            + ($interval->d * 60 * 60 * 24)
338
+            + ($interval->m * 60 * 60 * 24 * 30)
339
+            + ($interval->y * 60 * 60 * 24 * 365);
340
+    }
341
+
342
+    /**
343
+     * check if:
344
+     *  - current subscription stores a refreshrate
345
+     *  - the webcal feed suggests a refreshrate
346
+     *  - return suggested refreshrate if user didn't set a custom one
347
+     *
348
+     * @param array $subscription
349
+     * @param string $webcalData
350
+     * @return string|null
351
+     */
352
+    private function checkWebcalDataForRefreshRate($subscription, $webcalData) {
353
+        // if there is no refreshrate stored in the database, check the webcal feed
354
+        // whether it suggests any refresh rate and store that in the database
355
+        if (isset($subscription['refreshrate']) && $subscription['refreshrate'] !== null) {
356
+            return null;
357
+        }
358
+
359
+        /** @var Component\VCalendar $vCalendar */
360
+        $vCalendar = Reader::read($webcalData);
361
+
362
+        $newRefreshrate = null;
363
+        if (isset($vCalendar->{'X-PUBLISHED-TTL'})) {
364
+            $newRefreshrate = $vCalendar->{'X-PUBLISHED-TTL'}->getValue();
365
+        }
366
+        if (isset($vCalendar->{'REFRESH-INTERVAL'})) {
367
+            $newRefreshrate = $vCalendar->{'REFRESH-INTERVAL'}->getValue();
368
+        }
369
+
370
+        if (!$newRefreshrate) {
371
+            return null;
372
+        }
373
+
374
+        // check if new refresh rate is even valid
375
+        try {
376
+            DateTimeParser::parseDuration($newRefreshrate);
377
+        } catch(InvalidDataException $ex) {
378
+            return null;
379
+        }
380
+
381
+        return $newRefreshrate;
382
+    }
383
+
384
+    /**
385
+     * update subscription stored in database
386
+     * used to set:
387
+     *  - refreshrate
388
+     *  - source
389
+     *
390
+     * @param array $subscription
391
+     * @param array $mutations
392
+     */
393
+    private function updateSubscription(array $subscription, array $mutations) {
394
+        if (empty($mutations)) {
395
+            return;
396
+        }
397
+
398
+        $propPatch = new PropPatch($mutations);
399
+        $this->calDavBackend->updateSubscription($subscription['id'], $propPatch);
400
+        $propPatch->commit();
401
+    }
402
+
403
+    /**
404
+     * This method will strip authentication information and replace the
405
+     * 'webcal' or 'webcals' protocol scheme
406
+     *
407
+     * @param string $url
408
+     * @return string|null
409
+     */
410
+    private function cleanURL(string $url) {
411
+        $parsed = parse_url($url);
412
+        if ($parsed === false) {
413
+            return null;
414
+        }
415
+
416
+        if (isset($parsed['scheme']) && $parsed['scheme'] === 'http') {
417
+            $scheme = 'http';
418
+        } else {
419
+            $scheme = 'https';
420
+        }
421
+
422
+        $host = $parsed['host'] ?? '';
423
+        $port = isset($parsed['port']) ? ':' . $parsed['port'] : '';
424
+        $path = $parsed['path'] ?? '';
425
+        $query = isset($parsed['query']) ? '?' . $parsed['query'] : '';
426
+        $fragment = isset($parsed['fragment']) ? '#' . $parsed['fragment'] : '';
427
+
428
+        $cleanURL = "$scheme://$host$port$path$query$fragment";
429
+        // parse_url is giving some weird results if no url and no :// is given,
430
+        // so let's test the url again
431
+        $parsedClean = parse_url($cleanURL);
432
+        if ($parsedClean === false || !isset($parsedClean['host'])) {
433
+            return null;
434
+        }
435
+
436
+        return $cleanURL;
437
+    }
438 438
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -98,7 +98,7 @@  discard block
 block discarded – undo
98 98
 		try {
99 99
 			/** @var \DateInterval $dateInterval */
100 100
 			$dateInterval = DateTimeParser::parseDuration($refreshrate);
101
-		} catch(InvalidDataException $ex) {
101
+		} catch (InvalidDataException $ex) {
102 102
 			$this->logger->logException($ex);
103 103
 			$this->logger->warning("Subscription $subscriptionId could not be refreshed, refreshrate in database is invalid");
104 104
 			return;
@@ -164,11 +164,11 @@  discard block
 block discarded – undo
164 164
 					continue;
165 165
 				}
166 166
 
167
-				$uri = $uid . '.ics';
167
+				$uri = $uid.'.ics';
168 168
 				$calendarData = $vObject->serialize();
169 169
 				try {
170 170
 					$this->calDavBackend->createCalendarObject($subscription['id'], $uri, $calendarData, CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION);
171
-				} catch(BadRequest $ex) {
171
+				} catch (BadRequest $ex) {
172 172
 					$this->logger->logException($ex);
173 173
 				}
174 174
 			}
@@ -179,7 +179,7 @@  discard block
 block discarded – undo
179 179
 			}
180 180
 
181 181
 			$this->updateSubscription($subscription, $mutations);
182
-		} catch(ParseException $ex) {
182
+		} catch (ParseException $ex) {
183 183
 			$subscriptionId = $subscription['id'];
184 184
 
185 185
 			$this->logger->logException($ex);
@@ -201,7 +201,7 @@  discard block
 block discarded – undo
201 201
 		$latestLocation = null;
202 202
 
203 203
 		$handlerStack = HandlerStack::create();
204
-		$handlerStack->push(Middleware::mapRequest(function (RequestInterface $request) {
204
+		$handlerStack->push(Middleware::mapRequest(function(RequestInterface $request) {
205 205
 			return $request
206 206
 				->withHeader('Accept', 'text/calendar, application/calendar+json, application/calendar+xml')
207 207
 				->withHeader('User-Agent', 'Nextcloud Webcal Crawler');
@@ -261,11 +261,11 @@  discard block
 block discarded – undo
261 261
 
262 262
 			$contentType = $response->getHeader('Content-Type');
263 263
 			$contentType = explode(';', $contentType, 2)[0];
264
-			switch($contentType) {
264
+			switch ($contentType) {
265 265
 				case 'application/calendar+json':
266 266
 					try {
267 267
 						$jCalendar = Reader::readJson($body, Reader::OPTION_FORGIVING);
268
-					} catch(\Exception $ex) {
268
+					} catch (\Exception $ex) {
269 269
 						// In case of a parsing error return null
270 270
 						$this->logger->debug("Subscription $subscriptionId could not be parsed");
271 271
 						return null;
@@ -275,7 +275,7 @@  discard block
 block discarded – undo
275 275
 				case 'application/calendar+xml':
276 276
 					try {
277 277
 						$xCalendar = Reader::readXML($body);
278
-					} catch(\Exception $ex) {
278
+					} catch (\Exception $ex) {
279 279
 						// In case of a parsing error return null
280 280
 						$this->logger->debug("Subscription $subscriptionId could not be parsed");
281 281
 						return null;
@@ -286,14 +286,14 @@  discard block
 block discarded – undo
286 286
 				default:
287 287
 					try {
288 288
 						$vCalendar = Reader::read($body);
289
-					} catch(\Exception $ex) {
289
+					} catch (\Exception $ex) {
290 290
 						// In case of a parsing error return null
291 291
 						$this->logger->debug("Subscription $subscriptionId could not be parsed");
292 292
 						return null;
293 293
 					}
294 294
 					return $vCalendar->serialize();
295 295
 			}
296
-		} catch(\Exception $ex) {
296
+		} catch (\Exception $ex) {
297 297
 			$this->logger->logException($ex);
298 298
 			$this->logger->warning("Subscription $subscriptionId could not be refreshed due to a network error");
299 299
 
@@ -374,7 +374,7 @@  discard block
 block discarded – undo
374 374
 		// check if new refresh rate is even valid
375 375
 		try {
376 376
 			DateTimeParser::parseDuration($newRefreshrate);
377
-		} catch(InvalidDataException $ex) {
377
+		} catch (InvalidDataException $ex) {
378 378
 			return null;
379 379
 		}
380 380
 
@@ -420,10 +420,10 @@  discard block
 block discarded – undo
420 420
 		}
421 421
 
422 422
 		$host = $parsed['host'] ?? '';
423
-		$port = isset($parsed['port']) ? ':' . $parsed['port'] : '';
423
+		$port = isset($parsed['port']) ? ':'.$parsed['port'] : '';
424 424
 		$path = $parsed['path'] ?? '';
425
-		$query = isset($parsed['query']) ? '?' . $parsed['query'] : '';
426
-		$fragment = isset($parsed['fragment']) ? '#' . $parsed['fragment'] : '';
425
+		$query = isset($parsed['query']) ? '?'.$parsed['query'] : '';
426
+		$fragment = isset($parsed['fragment']) ? '#'.$parsed['fragment'] : '';
427 427
 
428 428
 		$cleanURL = "$scheme://$host$port$path$query$fragment";
429 429
 		// parse_url is giving some weird results if no url and no :// is given,
Please login to merge, or discard this patch.
apps/dav/lib/Server.php 1 patch
Indentation   +240 added lines, -240 removed lines patch added patch discarded remove patch
@@ -67,244 +67,244 @@
 block discarded – undo
67 67
 
68 68
 class Server {
69 69
 
70
-	/** @var IRequest */
71
-	private $request;
72
-
73
-	/** @var  string */
74
-	private $baseUri;
75
-
76
-	/** @var Connector\Sabre\Server  */
77
-	public $server;
78
-
79
-	public function __construct(IRequest $request, $baseUri) {
80
-		$this->request = $request;
81
-		$this->baseUri = $baseUri;
82
-		$logger = \OC::$server->getLogger();
83
-		$dispatcher = \OC::$server->getEventDispatcher();
84
-
85
-		$root = new RootCollection();
86
-		$this->server = new \OCA\DAV\Connector\Sabre\Server(new CachingTree($root));
87
-
88
-		// Add maintenance plugin
89
-		$this->server->addPlugin(new \OCA\DAV\Connector\Sabre\MaintenancePlugin(\OC::$server->getConfig()));
90
-
91
-		// Backends
92
-		$authBackend = new Auth(
93
-			\OC::$server->getSession(),
94
-			\OC::$server->getUserSession(),
95
-			\OC::$server->getRequest(),
96
-			\OC::$server->getTwoFactorAuthManager(),
97
-			\OC::$server->getBruteForceThrottler()
98
-		);
99
-
100
-		// Set URL explicitly due to reverse-proxy situations
101
-		$this->server->httpRequest->setUrl($this->request->getRequestUri());
102
-		$this->server->setBaseUri($this->baseUri);
103
-
104
-		$this->server->addPlugin(new BlockLegacyClientPlugin(\OC::$server->getConfig()));
105
-		$this->server->addPlugin(new AnonymousOptionsPlugin());
106
-		$authPlugin = new Plugin();
107
-		$authPlugin->addBackend(new PublicAuth());
108
-		$this->server->addPlugin($authPlugin);
109
-
110
-		// allow setup of additional auth backends
111
-		$event = new SabrePluginEvent($this->server);
112
-		$dispatcher->dispatch('OCA\DAV\Connector\Sabre::authInit', $event);
113
-
114
-		$bearerAuthBackend = new BearerAuth(
115
-			\OC::$server->getUserSession(),
116
-			\OC::$server->getSession(),
117
-			\OC::$server->getRequest()
118
-		);
119
-		$authPlugin->addBackend($bearerAuthBackend);
120
-		// because we are throwing exceptions this plugin has to be the last one
121
-		$authPlugin->addBackend($authBackend);
122
-
123
-		// debugging
124
-		if(\OC::$server->getConfig()->getSystemValue('debug', false)) {
125
-			$this->server->addPlugin(new \Sabre\DAV\Browser\Plugin());
126
-		} else {
127
-			$this->server->addPlugin(new DummyGetResponsePlugin());
128
-		}
129
-
130
-		$this->server->addPlugin(new \OCA\DAV\Connector\Sabre\ExceptionLoggerPlugin('webdav', $logger));
131
-		$this->server->addPlugin(new \OCA\DAV\Connector\Sabre\LockPlugin());
132
-		$this->server->addPlugin(new \Sabre\DAV\Sync\Plugin());
133
-
134
-		// acl
135
-		$acl = new DavAclPlugin();
136
-		$acl->principalCollectionSet = [
137
-			'principals/users', 'principals/groups',
138
-			'principals/calendar-resources',
139
-			'principals/calendar-rooms',
140
-		];
141
-		$acl->defaultUsernamePath = 'principals/users';
142
-		$this->server->addPlugin($acl);
143
-
144
-		// calendar plugins
145
-		if ($this->requestIsForSubtree(['calendars', 'public-calendars', 'system-calendars', 'principals'])) {
146
-			$this->server->addPlugin(new \OCA\DAV\CalDAV\Plugin());
147
-			$this->server->addPlugin(new \Sabre\CalDAV\ICSExportPlugin());
148
-			$this->server->addPlugin(new \OCA\DAV\CalDAV\Schedule\Plugin());
149
-			if (\OC::$server->getConfig()->getAppValue('dav', 'sendInvitations', 'yes') === 'yes') {
150
-				$this->server->addPlugin(\OC::$server->query(\OCA\DAV\CalDAV\Schedule\IMipPlugin::class));
151
-			}
152
-
153
-			$this->server->addPlugin(new CalDAV\WebcalCaching\Plugin($request));
154
-			$this->server->addPlugin(new \Sabre\CalDAV\Subscriptions\Plugin());
155
-
156
-			$this->server->addPlugin(new \Sabre\CalDAV\Notifications\Plugin());
157
-			$this->server->addPlugin(new DAV\Sharing\Plugin($authBackend, \OC::$server->getRequest()));
158
-			$this->server->addPlugin(new \OCA\DAV\CalDAV\Publishing\PublishPlugin(
159
-				\OC::$server->getConfig(),
160
-				\OC::$server->getURLGenerator()
161
-			));
162
-		}
163
-
164
-		// addressbook plugins
165
-		if ($this->requestIsForSubtree(['addressbooks', 'principals'])) {
166
-			$this->server->addPlugin(new DAV\Sharing\Plugin($authBackend, \OC::$server->getRequest()));
167
-			$this->server->addPlugin(new \OCA\DAV\CardDAV\Plugin());
168
-			$this->server->addPlugin(new VCFExportPlugin());
169
-			$this->server->addPlugin(new MultiGetExportPlugin());
170
-			$this->server->addPlugin(new ImageExportPlugin(new PhotoCache(\OC::$server->getAppDataDir('dav-photocache'))));
171
-		}
172
-
173
-		// system tags plugins
174
-		$this->server->addPlugin(new SystemTagPlugin(
175
-			\OC::$server->getSystemTagManager(),
176
-			\OC::$server->getGroupManager(),
177
-			\OC::$server->getUserSession()
178
-		));
179
-
180
-		// comments plugin
181
-		$this->server->addPlugin(new CommentsPlugin(
182
-			\OC::$server->getCommentsManager(),
183
-			\OC::$server->getUserSession()
184
-		));
185
-
186
-		$this->server->addPlugin(new CopyEtagHeaderPlugin());
187
-		$this->server->addPlugin(new ChunkingPlugin());
188
-
189
-		// allow setup of additional plugins
190
-		$dispatcher->dispatch('OCA\DAV\Connector\Sabre::addPlugin', $event);
191
-
192
-		// Some WebDAV clients do require Class 2 WebDAV support (locking), since
193
-		// we do not provide locking we emulate it using a fake locking plugin.
194
-		if($request->isUserAgent([
195
-			'/WebDAVFS/',
196
-			'/OneNote/',
197
-			'/^Microsoft-WebDAV/',// Microsoft-WebDAV-MiniRedir/6.1.7601
198
-		])) {
199
-			$this->server->addPlugin(new FakeLockerPlugin());
200
-		}
201
-
202
-		if (BrowserErrorPagePlugin::isBrowserRequest($request)) {
203
-			$this->server->addPlugin(new BrowserErrorPagePlugin());
204
-		}
205
-
206
-		$lazySearchBackend = new LazySearchBackend();
207
-		$this->server->addPlugin(new SearchPlugin($lazySearchBackend));
208
-
209
-		// wait with registering these until auth is handled and the filesystem is setup
210
-		$this->server->on('beforeMethod', function () use ($root, $lazySearchBackend) {
211
-			// custom properties plugin must be the last one
212
-			$userSession = \OC::$server->getUserSession();
213
-			$user = $userSession->getUser();
214
-			if ($user !== null) {
215
-				$view = \OC\Files\Filesystem::getView();
216
-				$this->server->addPlugin(
217
-					new FilesPlugin(
218
-						$this->server->tree,
219
-						\OC::$server->getConfig(),
220
-						$this->request,
221
-						\OC::$server->getPreviewManager(),
222
-						false,
223
-						!\OC::$server->getConfig()->getSystemValue('debug', false)
224
-					)
225
-				);
226
-
227
-				$this->server->addPlugin(
228
-					new \Sabre\DAV\PropertyStorage\Plugin(
229
-						new CustomPropertiesBackend(
230
-							$this->server->tree,
231
-							\OC::$server->getDatabaseConnection(),
232
-							\OC::$server->getUserSession()->getUser()
233
-						)
234
-					)
235
-				);
236
-				if ($view !== null) {
237
-					$this->server->addPlugin(
238
-						new QuotaPlugin($view, false));
239
-				}
240
-				$this->server->addPlugin(
241
-					new TagsPlugin(
242
-						$this->server->tree, \OC::$server->getTagManager()
243
-					)
244
-				);
245
-				// TODO: switch to LazyUserFolder
246
-				$userFolder = \OC::$server->getUserFolder();
247
-				$this->server->addPlugin(new SharesPlugin(
248
-					$this->server->tree,
249
-					$userSession,
250
-					$userFolder,
251
-					\OC::$server->getShareManager()
252
-				));
253
-				$this->server->addPlugin(new CommentPropertiesPlugin(
254
-					\OC::$server->getCommentsManager(),
255
-					$userSession
256
-				));
257
-				$this->server->addPlugin(new \OCA\DAV\CalDAV\Search\SearchPlugin());
258
-				if ($view !== null) {
259
-					$this->server->addPlugin(new FilesReportPlugin(
260
-						$this->server->tree,
261
-						$view,
262
-						\OC::$server->getSystemTagManager(),
263
-						\OC::$server->getSystemTagObjectMapper(),
264
-						\OC::$server->getTagManager(),
265
-						$userSession,
266
-						\OC::$server->getGroupManager(),
267
-						$userFolder
268
-					));
269
-					$lazySearchBackend->setBackend(new \OCA\DAV\Files\FileSearchBackend(
270
-						$this->server->tree,
271
-						$user,
272
-						\OC::$server->getRootFolder(),
273
-						\OC::$server->getShareManager(),
274
-						$view
275
-					));
276
-				}
277
-				$this->server->addPlugin(new \OCA\DAV\CalDAV\BirthdayCalendar\EnablePlugin(
278
-					\OC::$server->getConfig(),
279
-					\OC::$server->query(BirthdayService::class)
280
-				));
281
-			}
282
-
283
-			// register plugins from apps
284
-			$pluginManager = new PluginManager(
285
-				\OC::$server,
286
-				\OC::$server->getAppManager()
287
-			);
288
-			foreach ($pluginManager->getAppPlugins() as $appPlugin) {
289
-				$this->server->addPlugin($appPlugin);
290
-			}
291
-			foreach ($pluginManager->getAppCollections() as $appCollection) {
292
-				$root->addChild($appCollection);
293
-			}
294
-		});
295
-	}
296
-
297
-	public function exec() {
298
-		$this->server->exec();
299
-	}
300
-
301
-	private function requestIsForSubtree(array $subTrees): bool {
302
-		foreach ($subTrees as $subTree) {
303
-			$subTree = trim($subTree, ' /');
304
-			if (strpos($this->server->getRequestUri(), $subTree.'/') === 0) {
305
-				return true;
306
-			}
307
-		}
308
-		return false;
309
-	}
70
+    /** @var IRequest */
71
+    private $request;
72
+
73
+    /** @var  string */
74
+    private $baseUri;
75
+
76
+    /** @var Connector\Sabre\Server  */
77
+    public $server;
78
+
79
+    public function __construct(IRequest $request, $baseUri) {
80
+        $this->request = $request;
81
+        $this->baseUri = $baseUri;
82
+        $logger = \OC::$server->getLogger();
83
+        $dispatcher = \OC::$server->getEventDispatcher();
84
+
85
+        $root = new RootCollection();
86
+        $this->server = new \OCA\DAV\Connector\Sabre\Server(new CachingTree($root));
87
+
88
+        // Add maintenance plugin
89
+        $this->server->addPlugin(new \OCA\DAV\Connector\Sabre\MaintenancePlugin(\OC::$server->getConfig()));
90
+
91
+        // Backends
92
+        $authBackend = new Auth(
93
+            \OC::$server->getSession(),
94
+            \OC::$server->getUserSession(),
95
+            \OC::$server->getRequest(),
96
+            \OC::$server->getTwoFactorAuthManager(),
97
+            \OC::$server->getBruteForceThrottler()
98
+        );
99
+
100
+        // Set URL explicitly due to reverse-proxy situations
101
+        $this->server->httpRequest->setUrl($this->request->getRequestUri());
102
+        $this->server->setBaseUri($this->baseUri);
103
+
104
+        $this->server->addPlugin(new BlockLegacyClientPlugin(\OC::$server->getConfig()));
105
+        $this->server->addPlugin(new AnonymousOptionsPlugin());
106
+        $authPlugin = new Plugin();
107
+        $authPlugin->addBackend(new PublicAuth());
108
+        $this->server->addPlugin($authPlugin);
109
+
110
+        // allow setup of additional auth backends
111
+        $event = new SabrePluginEvent($this->server);
112
+        $dispatcher->dispatch('OCA\DAV\Connector\Sabre::authInit', $event);
113
+
114
+        $bearerAuthBackend = new BearerAuth(
115
+            \OC::$server->getUserSession(),
116
+            \OC::$server->getSession(),
117
+            \OC::$server->getRequest()
118
+        );
119
+        $authPlugin->addBackend($bearerAuthBackend);
120
+        // because we are throwing exceptions this plugin has to be the last one
121
+        $authPlugin->addBackend($authBackend);
122
+
123
+        // debugging
124
+        if(\OC::$server->getConfig()->getSystemValue('debug', false)) {
125
+            $this->server->addPlugin(new \Sabre\DAV\Browser\Plugin());
126
+        } else {
127
+            $this->server->addPlugin(new DummyGetResponsePlugin());
128
+        }
129
+
130
+        $this->server->addPlugin(new \OCA\DAV\Connector\Sabre\ExceptionLoggerPlugin('webdav', $logger));
131
+        $this->server->addPlugin(new \OCA\DAV\Connector\Sabre\LockPlugin());
132
+        $this->server->addPlugin(new \Sabre\DAV\Sync\Plugin());
133
+
134
+        // acl
135
+        $acl = new DavAclPlugin();
136
+        $acl->principalCollectionSet = [
137
+            'principals/users', 'principals/groups',
138
+            'principals/calendar-resources',
139
+            'principals/calendar-rooms',
140
+        ];
141
+        $acl->defaultUsernamePath = 'principals/users';
142
+        $this->server->addPlugin($acl);
143
+
144
+        // calendar plugins
145
+        if ($this->requestIsForSubtree(['calendars', 'public-calendars', 'system-calendars', 'principals'])) {
146
+            $this->server->addPlugin(new \OCA\DAV\CalDAV\Plugin());
147
+            $this->server->addPlugin(new \Sabre\CalDAV\ICSExportPlugin());
148
+            $this->server->addPlugin(new \OCA\DAV\CalDAV\Schedule\Plugin());
149
+            if (\OC::$server->getConfig()->getAppValue('dav', 'sendInvitations', 'yes') === 'yes') {
150
+                $this->server->addPlugin(\OC::$server->query(\OCA\DAV\CalDAV\Schedule\IMipPlugin::class));
151
+            }
152
+
153
+            $this->server->addPlugin(new CalDAV\WebcalCaching\Plugin($request));
154
+            $this->server->addPlugin(new \Sabre\CalDAV\Subscriptions\Plugin());
155
+
156
+            $this->server->addPlugin(new \Sabre\CalDAV\Notifications\Plugin());
157
+            $this->server->addPlugin(new DAV\Sharing\Plugin($authBackend, \OC::$server->getRequest()));
158
+            $this->server->addPlugin(new \OCA\DAV\CalDAV\Publishing\PublishPlugin(
159
+                \OC::$server->getConfig(),
160
+                \OC::$server->getURLGenerator()
161
+            ));
162
+        }
163
+
164
+        // addressbook plugins
165
+        if ($this->requestIsForSubtree(['addressbooks', 'principals'])) {
166
+            $this->server->addPlugin(new DAV\Sharing\Plugin($authBackend, \OC::$server->getRequest()));
167
+            $this->server->addPlugin(new \OCA\DAV\CardDAV\Plugin());
168
+            $this->server->addPlugin(new VCFExportPlugin());
169
+            $this->server->addPlugin(new MultiGetExportPlugin());
170
+            $this->server->addPlugin(new ImageExportPlugin(new PhotoCache(\OC::$server->getAppDataDir('dav-photocache'))));
171
+        }
172
+
173
+        // system tags plugins
174
+        $this->server->addPlugin(new SystemTagPlugin(
175
+            \OC::$server->getSystemTagManager(),
176
+            \OC::$server->getGroupManager(),
177
+            \OC::$server->getUserSession()
178
+        ));
179
+
180
+        // comments plugin
181
+        $this->server->addPlugin(new CommentsPlugin(
182
+            \OC::$server->getCommentsManager(),
183
+            \OC::$server->getUserSession()
184
+        ));
185
+
186
+        $this->server->addPlugin(new CopyEtagHeaderPlugin());
187
+        $this->server->addPlugin(new ChunkingPlugin());
188
+
189
+        // allow setup of additional plugins
190
+        $dispatcher->dispatch('OCA\DAV\Connector\Sabre::addPlugin', $event);
191
+
192
+        // Some WebDAV clients do require Class 2 WebDAV support (locking), since
193
+        // we do not provide locking we emulate it using a fake locking plugin.
194
+        if($request->isUserAgent([
195
+            '/WebDAVFS/',
196
+            '/OneNote/',
197
+            '/^Microsoft-WebDAV/',// Microsoft-WebDAV-MiniRedir/6.1.7601
198
+        ])) {
199
+            $this->server->addPlugin(new FakeLockerPlugin());
200
+        }
201
+
202
+        if (BrowserErrorPagePlugin::isBrowserRequest($request)) {
203
+            $this->server->addPlugin(new BrowserErrorPagePlugin());
204
+        }
205
+
206
+        $lazySearchBackend = new LazySearchBackend();
207
+        $this->server->addPlugin(new SearchPlugin($lazySearchBackend));
208
+
209
+        // wait with registering these until auth is handled and the filesystem is setup
210
+        $this->server->on('beforeMethod', function () use ($root, $lazySearchBackend) {
211
+            // custom properties plugin must be the last one
212
+            $userSession = \OC::$server->getUserSession();
213
+            $user = $userSession->getUser();
214
+            if ($user !== null) {
215
+                $view = \OC\Files\Filesystem::getView();
216
+                $this->server->addPlugin(
217
+                    new FilesPlugin(
218
+                        $this->server->tree,
219
+                        \OC::$server->getConfig(),
220
+                        $this->request,
221
+                        \OC::$server->getPreviewManager(),
222
+                        false,
223
+                        !\OC::$server->getConfig()->getSystemValue('debug', false)
224
+                    )
225
+                );
226
+
227
+                $this->server->addPlugin(
228
+                    new \Sabre\DAV\PropertyStorage\Plugin(
229
+                        new CustomPropertiesBackend(
230
+                            $this->server->tree,
231
+                            \OC::$server->getDatabaseConnection(),
232
+                            \OC::$server->getUserSession()->getUser()
233
+                        )
234
+                    )
235
+                );
236
+                if ($view !== null) {
237
+                    $this->server->addPlugin(
238
+                        new QuotaPlugin($view, false));
239
+                }
240
+                $this->server->addPlugin(
241
+                    new TagsPlugin(
242
+                        $this->server->tree, \OC::$server->getTagManager()
243
+                    )
244
+                );
245
+                // TODO: switch to LazyUserFolder
246
+                $userFolder = \OC::$server->getUserFolder();
247
+                $this->server->addPlugin(new SharesPlugin(
248
+                    $this->server->tree,
249
+                    $userSession,
250
+                    $userFolder,
251
+                    \OC::$server->getShareManager()
252
+                ));
253
+                $this->server->addPlugin(new CommentPropertiesPlugin(
254
+                    \OC::$server->getCommentsManager(),
255
+                    $userSession
256
+                ));
257
+                $this->server->addPlugin(new \OCA\DAV\CalDAV\Search\SearchPlugin());
258
+                if ($view !== null) {
259
+                    $this->server->addPlugin(new FilesReportPlugin(
260
+                        $this->server->tree,
261
+                        $view,
262
+                        \OC::$server->getSystemTagManager(),
263
+                        \OC::$server->getSystemTagObjectMapper(),
264
+                        \OC::$server->getTagManager(),
265
+                        $userSession,
266
+                        \OC::$server->getGroupManager(),
267
+                        $userFolder
268
+                    ));
269
+                    $lazySearchBackend->setBackend(new \OCA\DAV\Files\FileSearchBackend(
270
+                        $this->server->tree,
271
+                        $user,
272
+                        \OC::$server->getRootFolder(),
273
+                        \OC::$server->getShareManager(),
274
+                        $view
275
+                    ));
276
+                }
277
+                $this->server->addPlugin(new \OCA\DAV\CalDAV\BirthdayCalendar\EnablePlugin(
278
+                    \OC::$server->getConfig(),
279
+                    \OC::$server->query(BirthdayService::class)
280
+                ));
281
+            }
282
+
283
+            // register plugins from apps
284
+            $pluginManager = new PluginManager(
285
+                \OC::$server,
286
+                \OC::$server->getAppManager()
287
+            );
288
+            foreach ($pluginManager->getAppPlugins() as $appPlugin) {
289
+                $this->server->addPlugin($appPlugin);
290
+            }
291
+            foreach ($pluginManager->getAppCollections() as $appCollection) {
292
+                $root->addChild($appCollection);
293
+            }
294
+        });
295
+    }
296
+
297
+    public function exec() {
298
+        $this->server->exec();
299
+    }
300
+
301
+    private function requestIsForSubtree(array $subTrees): bool {
302
+        foreach ($subTrees as $subTree) {
303
+            $subTree = trim($subTree, ' /');
304
+            if (strpos($this->server->getRequestUri(), $subTree.'/') === 0) {
305
+                return true;
306
+            }
307
+        }
308
+        return false;
309
+    }
310 310
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/CachedSubscriptionObject.php 1 patch
Indentation   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -33,32 +33,32 @@
 block discarded – undo
33 33
  */
34 34
 class CachedSubscriptionObject extends \Sabre\CalDAV\CalendarObject {
35 35
 
36
-	/**
37
-	 * @inheritdoc
38
-	 */
39
-	public function get() {
40
-		// Pre-populating the 'calendardata' is optional, if we don't have it
41
-		// already we fetch it from the backend.
42
-		if (!isset($this->objectData['calendardata'])) {
43
-			$this->objectData = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'], $this->objectData['uri'], CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION);
44
-		}
36
+    /**
37
+     * @inheritdoc
38
+     */
39
+    public function get() {
40
+        // Pre-populating the 'calendardata' is optional, if we don't have it
41
+        // already we fetch it from the backend.
42
+        if (!isset($this->objectData['calendardata'])) {
43
+            $this->objectData = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'], $this->objectData['uri'], CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION);
44
+        }
45 45
 
46
-		return $this->objectData['calendardata'];
47
-	}
46
+        return $this->objectData['calendardata'];
47
+    }
48 48
 
49
-	/**
50
-	 * @param resource|string $calendarData
51
-	 * @return string|void
52
-	 * @throws MethodNotAllowed
53
-	 */
54
-	public function put($calendarData) {
55
-		throw new MethodNotAllowed('Creating objects in a cached subscription is not allowed');
56
-	}
49
+    /**
50
+     * @param resource|string $calendarData
51
+     * @return string|void
52
+     * @throws MethodNotAllowed
53
+     */
54
+    public function put($calendarData) {
55
+        throw new MethodNotAllowed('Creating objects in a cached subscription is not allowed');
56
+    }
57 57
 
58
-	/**
59
-	 * @throws MethodNotAllowed
60
-	 */
61
-	public function delete() {
62
-		throw new MethodNotAllowed('Deleting objects in a cached subscription is not allowed');
63
-	}
58
+    /**
59
+     * @throws MethodNotAllowed
60
+     */
61
+    public function delete() {
62
+        throw new MethodNotAllowed('Deleting objects in a cached subscription is not allowed');
63
+    }
64 64
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/CalDavBackend.php 2 patches
Indentation   +2535 added lines, -2535 removed lines patch added patch discarded remove patch
@@ -73,2540 +73,2540 @@
 block discarded – undo
73 73
  */
74 74
 class CalDavBackend extends AbstractBackend implements SyncSupport, SubscriptionSupport, SchedulingSupport {
75 75
 
76
-	const CALENDAR_TYPE_CALENDAR = 0;
77
-	const CALENDAR_TYPE_SUBSCRIPTION = 1;
78
-
79
-	const PERSONAL_CALENDAR_URI = 'personal';
80
-	const PERSONAL_CALENDAR_NAME = 'Personal';
81
-
82
-	const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
83
-	const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
84
-
85
-	/**
86
-	 * We need to specify a max date, because we need to stop *somewhere*
87
-	 *
88
-	 * On 32 bit system the maximum for a signed integer is 2147483647, so
89
-	 * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
90
-	 * in 2038-01-19 to avoid problems when the date is converted
91
-	 * to a unix timestamp.
92
-	 */
93
-	const MAX_DATE = '2038-01-01';
94
-
95
-	const ACCESS_PUBLIC = 4;
96
-	const CLASSIFICATION_PUBLIC = 0;
97
-	const CLASSIFICATION_PRIVATE = 1;
98
-	const CLASSIFICATION_CONFIDENTIAL = 2;
99
-
100
-	/**
101
-	 * List of CalDAV properties, and how they map to database field names
102
-	 * Add your own properties by simply adding on to this array.
103
-	 *
104
-	 * Note that only string-based properties are supported here.
105
-	 *
106
-	 * @var array
107
-	 */
108
-	public $propertyMap = [
109
-		'{DAV:}displayname'                          => 'displayname',
110
-		'{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
111
-		'{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
112
-		'{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
113
-		'{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
114
-	];
115
-
116
-	/**
117
-	 * List of subscription properties, and how they map to database field names.
118
-	 *
119
-	 * @var array
120
-	 */
121
-	public $subscriptionPropertyMap = [
122
-		'{DAV:}displayname'                                           => 'displayname',
123
-		'{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
124
-		'{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
125
-		'{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
126
-		'{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
127
-		'{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
128
-		'{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
129
-	];
130
-
131
-	/** @var array properties to index */
132
-	public static $indexProperties = ['CATEGORIES', 'COMMENT', 'DESCRIPTION',
133
-		'LOCATION', 'RESOURCES', 'STATUS', 'SUMMARY', 'ATTENDEE', 'CONTACT',
134
-		'ORGANIZER'];
135
-
136
-	/** @var array parameters to index */
137
-	public static $indexParameters = [
138
-		'ATTENDEE' => ['CN'],
139
-		'ORGANIZER' => ['CN'],
140
-	];
141
-
142
-	/**
143
-	 * @var string[] Map of uid => display name
144
-	 */
145
-	protected $userDisplayNames;
146
-
147
-	/** @var IDBConnection */
148
-	private $db;
149
-
150
-	/** @var Backend */
151
-	private $calendarSharingBackend;
152
-
153
-	/** @var Principal */
154
-	private $principalBackend;
155
-
156
-	/** @var IUserManager */
157
-	private $userManager;
158
-
159
-	/** @var ISecureRandom */
160
-	private $random;
161
-
162
-	/** @var ILogger */
163
-	private $logger;
164
-
165
-	/** @var EventDispatcherInterface */
166
-	private $dispatcher;
167
-
168
-	/** @var bool */
169
-	private $legacyEndpoint;
170
-
171
-	/** @var string */
172
-	private $dbObjectPropertiesTable = 'calendarobjects_props';
173
-
174
-	/**
175
-	 * CalDavBackend constructor.
176
-	 *
177
-	 * @param IDBConnection $db
178
-	 * @param Principal $principalBackend
179
-	 * @param IUserManager $userManager
180
-	 * @param IGroupManager $groupManager
181
-	 * @param ISecureRandom $random
182
-	 * @param ILogger $logger
183
-	 * @param EventDispatcherInterface $dispatcher
184
-	 * @param bool $legacyEndpoint
185
-	 */
186
-	public function __construct(IDBConnection $db,
187
-								Principal $principalBackend,
188
-								IUserManager $userManager,
189
-								IGroupManager $groupManager,
190
-								ISecureRandom $random,
191
-								ILogger $logger,
192
-								EventDispatcherInterface $dispatcher,
193
-								$legacyEndpoint = false) {
194
-		$this->db = $db;
195
-		$this->principalBackend = $principalBackend;
196
-		$this->userManager = $userManager;
197
-		$this->calendarSharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'calendar');
198
-		$this->random = $random;
199
-		$this->logger = $logger;
200
-		$this->dispatcher = $dispatcher;
201
-		$this->legacyEndpoint = $legacyEndpoint;
202
-	}
203
-
204
-	/**
205
-	 * Return the number of calendars for a principal
206
-	 *
207
-	 * By default this excludes the automatically generated birthday calendar
208
-	 *
209
-	 * @param $principalUri
210
-	 * @param bool $excludeBirthday
211
-	 * @return int
212
-	 */
213
-	public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
214
-		$principalUri = $this->convertPrincipal($principalUri, true);
215
-		$query = $this->db->getQueryBuilder();
216
-		$query->select($query->createFunction('COUNT(*)'))
217
-			->from('calendars')
218
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
219
-
220
-		if ($excludeBirthday) {
221
-			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
222
-		}
223
-
224
-		return (int)$query->execute()->fetchColumn();
225
-	}
226
-
227
-	/**
228
-	 * Returns a list of calendars for a principal.
229
-	 *
230
-	 * Every project is an array with the following keys:
231
-	 *  * id, a unique id that will be used by other functions to modify the
232
-	 *    calendar. This can be the same as the uri or a database key.
233
-	 *  * uri, which the basename of the uri with which the calendar is
234
-	 *    accessed.
235
-	 *  * principaluri. The owner of the calendar. Almost always the same as
236
-	 *    principalUri passed to this method.
237
-	 *
238
-	 * Furthermore it can contain webdav properties in clark notation. A very
239
-	 * common one is '{DAV:}displayname'.
240
-	 *
241
-	 * Many clients also require:
242
-	 * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
243
-	 * For this property, you can just return an instance of
244
-	 * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
245
-	 *
246
-	 * If you return {http://sabredav.org/ns}read-only and set the value to 1,
247
-	 * ACL will automatically be put in read-only mode.
248
-	 *
249
-	 * @param string $principalUri
250
-	 * @return array
251
-	 */
252
-	function getCalendarsForUser($principalUri) {
253
-		$principalUriOriginal = $principalUri;
254
-		$principalUri = $this->convertPrincipal($principalUri, true);
255
-		$fields = array_values($this->propertyMap);
256
-		$fields[] = 'id';
257
-		$fields[] = 'uri';
258
-		$fields[] = 'synctoken';
259
-		$fields[] = 'components';
260
-		$fields[] = 'principaluri';
261
-		$fields[] = 'transparent';
262
-
263
-		// Making fields a comma-delimited list
264
-		$query = $this->db->getQueryBuilder();
265
-		$query->select($fields)->from('calendars')
266
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
267
-				->orderBy('calendarorder', 'ASC');
268
-		$stmt = $query->execute();
269
-
270
-		$calendars = [];
271
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
272
-
273
-			$components = [];
274
-			if ($row['components']) {
275
-				$components = explode(',',$row['components']);
276
-			}
277
-
278
-			$calendar = [
279
-				'id' => $row['id'],
280
-				'uri' => $row['uri'],
281
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
282
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
283
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
284
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
285
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
286
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
287
-			];
288
-
289
-			foreach($this->propertyMap as $xmlName=>$dbName) {
290
-				$calendar[$xmlName] = $row[$dbName];
291
-			}
292
-
293
-			$this->addOwnerPrincipal($calendar);
294
-
295
-			if (!isset($calendars[$calendar['id']])) {
296
-				$calendars[$calendar['id']] = $calendar;
297
-			}
298
-		}
299
-
300
-		$stmt->closeCursor();
301
-
302
-		// query for shared calendars
303
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
304
-		$principals = array_map(function($principal) {
305
-			return urldecode($principal);
306
-		}, $principals);
307
-		$principals[]= $principalUri;
308
-
309
-		$fields = array_values($this->propertyMap);
310
-		$fields[] = 'a.id';
311
-		$fields[] = 'a.uri';
312
-		$fields[] = 'a.synctoken';
313
-		$fields[] = 'a.components';
314
-		$fields[] = 'a.principaluri';
315
-		$fields[] = 'a.transparent';
316
-		$fields[] = 's.access';
317
-		$query = $this->db->getQueryBuilder();
318
-		$result = $query->select($fields)
319
-			->from('dav_shares', 's')
320
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
321
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
322
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
323
-			->setParameter('type', 'calendar')
324
-			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
325
-			->execute();
326
-
327
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
328
-		while($row = $result->fetch()) {
329
-			if ($row['principaluri'] === $principalUri) {
330
-				continue;
331
-			}
332
-
333
-			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
334
-			if (isset($calendars[$row['id']])) {
335
-				if ($readOnly) {
336
-					// New share can not have more permissions then the old one.
337
-					continue;
338
-				}
339
-				if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
340
-					$calendars[$row['id']][$readOnlyPropertyName] === 0) {
341
-					// Old share is already read-write, no more permissions can be gained
342
-					continue;
343
-				}
344
-			}
345
-
346
-			list(, $name) = Uri\split($row['principaluri']);
347
-			$uri = $row['uri'] . '_shared_by_' . $name;
348
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
349
-			$components = [];
350
-			if ($row['components']) {
351
-				$components = explode(',',$row['components']);
352
-			}
353
-			$calendar = [
354
-				'id' => $row['id'],
355
-				'uri' => $uri,
356
-				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
357
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
358
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
359
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
360
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
361
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
362
-				$readOnlyPropertyName => $readOnly,
363
-			];
364
-
365
-			foreach($this->propertyMap as $xmlName=>$dbName) {
366
-				$calendar[$xmlName] = $row[$dbName];
367
-			}
368
-
369
-			$this->addOwnerPrincipal($calendar);
370
-
371
-			$calendars[$calendar['id']] = $calendar;
372
-		}
373
-		$result->closeCursor();
374
-
375
-		return array_values($calendars);
376
-	}
377
-
378
-	/**
379
-	 * @param $principalUri
380
-	 * @return array
381
-	 */
382
-	public function getUsersOwnCalendars($principalUri) {
383
-		$principalUri = $this->convertPrincipal($principalUri, true);
384
-		$fields = array_values($this->propertyMap);
385
-		$fields[] = 'id';
386
-		$fields[] = 'uri';
387
-		$fields[] = 'synctoken';
388
-		$fields[] = 'components';
389
-		$fields[] = 'principaluri';
390
-		$fields[] = 'transparent';
391
-		// Making fields a comma-delimited list
392
-		$query = $this->db->getQueryBuilder();
393
-		$query->select($fields)->from('calendars')
394
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
395
-			->orderBy('calendarorder', 'ASC');
396
-		$stmt = $query->execute();
397
-		$calendars = [];
398
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
399
-			$components = [];
400
-			if ($row['components']) {
401
-				$components = explode(',',$row['components']);
402
-			}
403
-			$calendar = [
404
-				'id' => $row['id'],
405
-				'uri' => $row['uri'],
406
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
407
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
408
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
409
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
410
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
411
-			];
412
-			foreach($this->propertyMap as $xmlName=>$dbName) {
413
-				$calendar[$xmlName] = $row[$dbName];
414
-			}
415
-
416
-			$this->addOwnerPrincipal($calendar);
417
-
418
-			if (!isset($calendars[$calendar['id']])) {
419
-				$calendars[$calendar['id']] = $calendar;
420
-			}
421
-		}
422
-		$stmt->closeCursor();
423
-		return array_values($calendars);
424
-	}
425
-
426
-
427
-	/**
428
-	 * @param $uid
429
-	 * @return string
430
-	 */
431
-	private function getUserDisplayName($uid) {
432
-		if (!isset($this->userDisplayNames[$uid])) {
433
-			$user = $this->userManager->get($uid);
434
-
435
-			if ($user instanceof IUser) {
436
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
437
-			} else {
438
-				$this->userDisplayNames[$uid] = $uid;
439
-			}
440
-		}
441
-
442
-		return $this->userDisplayNames[$uid];
443
-	}
76
+    const CALENDAR_TYPE_CALENDAR = 0;
77
+    const CALENDAR_TYPE_SUBSCRIPTION = 1;
78
+
79
+    const PERSONAL_CALENDAR_URI = 'personal';
80
+    const PERSONAL_CALENDAR_NAME = 'Personal';
81
+
82
+    const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
83
+    const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
84
+
85
+    /**
86
+     * We need to specify a max date, because we need to stop *somewhere*
87
+     *
88
+     * On 32 bit system the maximum for a signed integer is 2147483647, so
89
+     * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
90
+     * in 2038-01-19 to avoid problems when the date is converted
91
+     * to a unix timestamp.
92
+     */
93
+    const MAX_DATE = '2038-01-01';
94
+
95
+    const ACCESS_PUBLIC = 4;
96
+    const CLASSIFICATION_PUBLIC = 0;
97
+    const CLASSIFICATION_PRIVATE = 1;
98
+    const CLASSIFICATION_CONFIDENTIAL = 2;
99
+
100
+    /**
101
+     * List of CalDAV properties, and how they map to database field names
102
+     * Add your own properties by simply adding on to this array.
103
+     *
104
+     * Note that only string-based properties are supported here.
105
+     *
106
+     * @var array
107
+     */
108
+    public $propertyMap = [
109
+        '{DAV:}displayname'                          => 'displayname',
110
+        '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
111
+        '{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
112
+        '{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
113
+        '{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
114
+    ];
115
+
116
+    /**
117
+     * List of subscription properties, and how they map to database field names.
118
+     *
119
+     * @var array
120
+     */
121
+    public $subscriptionPropertyMap = [
122
+        '{DAV:}displayname'                                           => 'displayname',
123
+        '{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
124
+        '{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
125
+        '{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
126
+        '{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
127
+        '{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
128
+        '{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
129
+    ];
130
+
131
+    /** @var array properties to index */
132
+    public static $indexProperties = ['CATEGORIES', 'COMMENT', 'DESCRIPTION',
133
+        'LOCATION', 'RESOURCES', 'STATUS', 'SUMMARY', 'ATTENDEE', 'CONTACT',
134
+        'ORGANIZER'];
135
+
136
+    /** @var array parameters to index */
137
+    public static $indexParameters = [
138
+        'ATTENDEE' => ['CN'],
139
+        'ORGANIZER' => ['CN'],
140
+    ];
141
+
142
+    /**
143
+     * @var string[] Map of uid => display name
144
+     */
145
+    protected $userDisplayNames;
146
+
147
+    /** @var IDBConnection */
148
+    private $db;
149
+
150
+    /** @var Backend */
151
+    private $calendarSharingBackend;
152
+
153
+    /** @var Principal */
154
+    private $principalBackend;
155
+
156
+    /** @var IUserManager */
157
+    private $userManager;
158
+
159
+    /** @var ISecureRandom */
160
+    private $random;
161
+
162
+    /** @var ILogger */
163
+    private $logger;
164
+
165
+    /** @var EventDispatcherInterface */
166
+    private $dispatcher;
167
+
168
+    /** @var bool */
169
+    private $legacyEndpoint;
170
+
171
+    /** @var string */
172
+    private $dbObjectPropertiesTable = 'calendarobjects_props';
173
+
174
+    /**
175
+     * CalDavBackend constructor.
176
+     *
177
+     * @param IDBConnection $db
178
+     * @param Principal $principalBackend
179
+     * @param IUserManager $userManager
180
+     * @param IGroupManager $groupManager
181
+     * @param ISecureRandom $random
182
+     * @param ILogger $logger
183
+     * @param EventDispatcherInterface $dispatcher
184
+     * @param bool $legacyEndpoint
185
+     */
186
+    public function __construct(IDBConnection $db,
187
+                                Principal $principalBackend,
188
+                                IUserManager $userManager,
189
+                                IGroupManager $groupManager,
190
+                                ISecureRandom $random,
191
+                                ILogger $logger,
192
+                                EventDispatcherInterface $dispatcher,
193
+                                $legacyEndpoint = false) {
194
+        $this->db = $db;
195
+        $this->principalBackend = $principalBackend;
196
+        $this->userManager = $userManager;
197
+        $this->calendarSharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'calendar');
198
+        $this->random = $random;
199
+        $this->logger = $logger;
200
+        $this->dispatcher = $dispatcher;
201
+        $this->legacyEndpoint = $legacyEndpoint;
202
+    }
203
+
204
+    /**
205
+     * Return the number of calendars for a principal
206
+     *
207
+     * By default this excludes the automatically generated birthday calendar
208
+     *
209
+     * @param $principalUri
210
+     * @param bool $excludeBirthday
211
+     * @return int
212
+     */
213
+    public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
214
+        $principalUri = $this->convertPrincipal($principalUri, true);
215
+        $query = $this->db->getQueryBuilder();
216
+        $query->select($query->createFunction('COUNT(*)'))
217
+            ->from('calendars')
218
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
219
+
220
+        if ($excludeBirthday) {
221
+            $query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
222
+        }
223
+
224
+        return (int)$query->execute()->fetchColumn();
225
+    }
226
+
227
+    /**
228
+     * Returns a list of calendars for a principal.
229
+     *
230
+     * Every project is an array with the following keys:
231
+     *  * id, a unique id that will be used by other functions to modify the
232
+     *    calendar. This can be the same as the uri or a database key.
233
+     *  * uri, which the basename of the uri with which the calendar is
234
+     *    accessed.
235
+     *  * principaluri. The owner of the calendar. Almost always the same as
236
+     *    principalUri passed to this method.
237
+     *
238
+     * Furthermore it can contain webdav properties in clark notation. A very
239
+     * common one is '{DAV:}displayname'.
240
+     *
241
+     * Many clients also require:
242
+     * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
243
+     * For this property, you can just return an instance of
244
+     * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
245
+     *
246
+     * If you return {http://sabredav.org/ns}read-only and set the value to 1,
247
+     * ACL will automatically be put in read-only mode.
248
+     *
249
+     * @param string $principalUri
250
+     * @return array
251
+     */
252
+    function getCalendarsForUser($principalUri) {
253
+        $principalUriOriginal = $principalUri;
254
+        $principalUri = $this->convertPrincipal($principalUri, true);
255
+        $fields = array_values($this->propertyMap);
256
+        $fields[] = 'id';
257
+        $fields[] = 'uri';
258
+        $fields[] = 'synctoken';
259
+        $fields[] = 'components';
260
+        $fields[] = 'principaluri';
261
+        $fields[] = 'transparent';
262
+
263
+        // Making fields a comma-delimited list
264
+        $query = $this->db->getQueryBuilder();
265
+        $query->select($fields)->from('calendars')
266
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
267
+                ->orderBy('calendarorder', 'ASC');
268
+        $stmt = $query->execute();
269
+
270
+        $calendars = [];
271
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
272
+
273
+            $components = [];
274
+            if ($row['components']) {
275
+                $components = explode(',',$row['components']);
276
+            }
277
+
278
+            $calendar = [
279
+                'id' => $row['id'],
280
+                'uri' => $row['uri'],
281
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
282
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
283
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
284
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
285
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
286
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
287
+            ];
288
+
289
+            foreach($this->propertyMap as $xmlName=>$dbName) {
290
+                $calendar[$xmlName] = $row[$dbName];
291
+            }
292
+
293
+            $this->addOwnerPrincipal($calendar);
294
+
295
+            if (!isset($calendars[$calendar['id']])) {
296
+                $calendars[$calendar['id']] = $calendar;
297
+            }
298
+        }
299
+
300
+        $stmt->closeCursor();
301
+
302
+        // query for shared calendars
303
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
304
+        $principals = array_map(function($principal) {
305
+            return urldecode($principal);
306
+        }, $principals);
307
+        $principals[]= $principalUri;
308
+
309
+        $fields = array_values($this->propertyMap);
310
+        $fields[] = 'a.id';
311
+        $fields[] = 'a.uri';
312
+        $fields[] = 'a.synctoken';
313
+        $fields[] = 'a.components';
314
+        $fields[] = 'a.principaluri';
315
+        $fields[] = 'a.transparent';
316
+        $fields[] = 's.access';
317
+        $query = $this->db->getQueryBuilder();
318
+        $result = $query->select($fields)
319
+            ->from('dav_shares', 's')
320
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
321
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
322
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
323
+            ->setParameter('type', 'calendar')
324
+            ->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
325
+            ->execute();
326
+
327
+        $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
328
+        while($row = $result->fetch()) {
329
+            if ($row['principaluri'] === $principalUri) {
330
+                continue;
331
+            }
332
+
333
+            $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
334
+            if (isset($calendars[$row['id']])) {
335
+                if ($readOnly) {
336
+                    // New share can not have more permissions then the old one.
337
+                    continue;
338
+                }
339
+                if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
340
+                    $calendars[$row['id']][$readOnlyPropertyName] === 0) {
341
+                    // Old share is already read-write, no more permissions can be gained
342
+                    continue;
343
+                }
344
+            }
345
+
346
+            list(, $name) = Uri\split($row['principaluri']);
347
+            $uri = $row['uri'] . '_shared_by_' . $name;
348
+            $row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
349
+            $components = [];
350
+            if ($row['components']) {
351
+                $components = explode(',',$row['components']);
352
+            }
353
+            $calendar = [
354
+                'id' => $row['id'],
355
+                'uri' => $uri,
356
+                'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
357
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
358
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
359
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
360
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
361
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
362
+                $readOnlyPropertyName => $readOnly,
363
+            ];
364
+
365
+            foreach($this->propertyMap as $xmlName=>$dbName) {
366
+                $calendar[$xmlName] = $row[$dbName];
367
+            }
368
+
369
+            $this->addOwnerPrincipal($calendar);
370
+
371
+            $calendars[$calendar['id']] = $calendar;
372
+        }
373
+        $result->closeCursor();
374
+
375
+        return array_values($calendars);
376
+    }
377
+
378
+    /**
379
+     * @param $principalUri
380
+     * @return array
381
+     */
382
+    public function getUsersOwnCalendars($principalUri) {
383
+        $principalUri = $this->convertPrincipal($principalUri, true);
384
+        $fields = array_values($this->propertyMap);
385
+        $fields[] = 'id';
386
+        $fields[] = 'uri';
387
+        $fields[] = 'synctoken';
388
+        $fields[] = 'components';
389
+        $fields[] = 'principaluri';
390
+        $fields[] = 'transparent';
391
+        // Making fields a comma-delimited list
392
+        $query = $this->db->getQueryBuilder();
393
+        $query->select($fields)->from('calendars')
394
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
395
+            ->orderBy('calendarorder', 'ASC');
396
+        $stmt = $query->execute();
397
+        $calendars = [];
398
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
399
+            $components = [];
400
+            if ($row['components']) {
401
+                $components = explode(',',$row['components']);
402
+            }
403
+            $calendar = [
404
+                'id' => $row['id'],
405
+                'uri' => $row['uri'],
406
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
407
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
408
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
409
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
410
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
411
+            ];
412
+            foreach($this->propertyMap as $xmlName=>$dbName) {
413
+                $calendar[$xmlName] = $row[$dbName];
414
+            }
415
+
416
+            $this->addOwnerPrincipal($calendar);
417
+
418
+            if (!isset($calendars[$calendar['id']])) {
419
+                $calendars[$calendar['id']] = $calendar;
420
+            }
421
+        }
422
+        $stmt->closeCursor();
423
+        return array_values($calendars);
424
+    }
425
+
426
+
427
+    /**
428
+     * @param $uid
429
+     * @return string
430
+     */
431
+    private function getUserDisplayName($uid) {
432
+        if (!isset($this->userDisplayNames[$uid])) {
433
+            $user = $this->userManager->get($uid);
434
+
435
+            if ($user instanceof IUser) {
436
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
437
+            } else {
438
+                $this->userDisplayNames[$uid] = $uid;
439
+            }
440
+        }
441
+
442
+        return $this->userDisplayNames[$uid];
443
+    }
444 444
 	
445
-	/**
446
-	 * @return array
447
-	 */
448
-	public function getPublicCalendars() {
449
-		$fields = array_values($this->propertyMap);
450
-		$fields[] = 'a.id';
451
-		$fields[] = 'a.uri';
452
-		$fields[] = 'a.synctoken';
453
-		$fields[] = 'a.components';
454
-		$fields[] = 'a.principaluri';
455
-		$fields[] = 'a.transparent';
456
-		$fields[] = 's.access';
457
-		$fields[] = 's.publicuri';
458
-		$calendars = [];
459
-		$query = $this->db->getQueryBuilder();
460
-		$result = $query->select($fields)
461
-			->from('dav_shares', 's')
462
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
463
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
464
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
465
-			->execute();
466
-
467
-		while($row = $result->fetch()) {
468
-			list(, $name) = Uri\split($row['principaluri']);
469
-			$row['displayname'] = $row['displayname'] . "($name)";
470
-			$components = [];
471
-			if ($row['components']) {
472
-				$components = explode(',',$row['components']);
473
-			}
474
-			$calendar = [
475
-				'id' => $row['id'],
476
-				'uri' => $row['publicuri'],
477
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
478
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
479
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
480
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
481
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
482
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
483
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
484
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
485
-			];
486
-
487
-			foreach($this->propertyMap as $xmlName=>$dbName) {
488
-				$calendar[$xmlName] = $row[$dbName];
489
-			}
490
-
491
-			$this->addOwnerPrincipal($calendar);
492
-
493
-			if (!isset($calendars[$calendar['id']])) {
494
-				$calendars[$calendar['id']] = $calendar;
495
-			}
496
-		}
497
-		$result->closeCursor();
498
-
499
-		return array_values($calendars);
500
-	}
501
-
502
-	/**
503
-	 * @param string $uri
504
-	 * @return array
505
-	 * @throws NotFound
506
-	 */
507
-	public function getPublicCalendar($uri) {
508
-		$fields = array_values($this->propertyMap);
509
-		$fields[] = 'a.id';
510
-		$fields[] = 'a.uri';
511
-		$fields[] = 'a.synctoken';
512
-		$fields[] = 'a.components';
513
-		$fields[] = 'a.principaluri';
514
-		$fields[] = 'a.transparent';
515
-		$fields[] = 's.access';
516
-		$fields[] = 's.publicuri';
517
-		$query = $this->db->getQueryBuilder();
518
-		$result = $query->select($fields)
519
-			->from('dav_shares', 's')
520
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
521
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
522
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
523
-			->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
524
-			->execute();
525
-
526
-		$row = $result->fetch(\PDO::FETCH_ASSOC);
527
-
528
-		$result->closeCursor();
529
-
530
-		if ($row === false) {
531
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
532
-		}
533
-
534
-		list(, $name) = Uri\split($row['principaluri']);
535
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
536
-		$components = [];
537
-		if ($row['components']) {
538
-			$components = explode(',',$row['components']);
539
-		}
540
-		$calendar = [
541
-			'id' => $row['id'],
542
-			'uri' => $row['publicuri'],
543
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
544
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
545
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
546
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
547
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
548
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
549
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
550
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
551
-		];
552
-
553
-		foreach($this->propertyMap as $xmlName=>$dbName) {
554
-			$calendar[$xmlName] = $row[$dbName];
555
-		}
556
-
557
-		$this->addOwnerPrincipal($calendar);
558
-
559
-		return $calendar;
560
-
561
-	}
562
-
563
-	/**
564
-	 * @param string $principal
565
-	 * @param string $uri
566
-	 * @return array|null
567
-	 */
568
-	public function getCalendarByUri($principal, $uri) {
569
-		$fields = array_values($this->propertyMap);
570
-		$fields[] = 'id';
571
-		$fields[] = 'uri';
572
-		$fields[] = 'synctoken';
573
-		$fields[] = 'components';
574
-		$fields[] = 'principaluri';
575
-		$fields[] = 'transparent';
576
-
577
-		// Making fields a comma-delimited list
578
-		$query = $this->db->getQueryBuilder();
579
-		$query->select($fields)->from('calendars')
580
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
581
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
582
-			->setMaxResults(1);
583
-		$stmt = $query->execute();
584
-
585
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
586
-		$stmt->closeCursor();
587
-		if ($row === false) {
588
-			return null;
589
-		}
590
-
591
-		$components = [];
592
-		if ($row['components']) {
593
-			$components = explode(',',$row['components']);
594
-		}
595
-
596
-		$calendar = [
597
-			'id' => $row['id'],
598
-			'uri' => $row['uri'],
599
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
600
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
601
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
602
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
603
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
604
-		];
605
-
606
-		foreach($this->propertyMap as $xmlName=>$dbName) {
607
-			$calendar[$xmlName] = $row[$dbName];
608
-		}
609
-
610
-		$this->addOwnerPrincipal($calendar);
611
-
612
-		return $calendar;
613
-	}
614
-
615
-	/**
616
-	 * @param $calendarId
617
-	 * @return array|null
618
-	 */
619
-	public function getCalendarById($calendarId) {
620
-		$fields = array_values($this->propertyMap);
621
-		$fields[] = 'id';
622
-		$fields[] = 'uri';
623
-		$fields[] = 'synctoken';
624
-		$fields[] = 'components';
625
-		$fields[] = 'principaluri';
626
-		$fields[] = 'transparent';
627
-
628
-		// Making fields a comma-delimited list
629
-		$query = $this->db->getQueryBuilder();
630
-		$query->select($fields)->from('calendars')
631
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
632
-			->setMaxResults(1);
633
-		$stmt = $query->execute();
634
-
635
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
636
-		$stmt->closeCursor();
637
-		if ($row === false) {
638
-			return null;
639
-		}
640
-
641
-		$components = [];
642
-		if ($row['components']) {
643
-			$components = explode(',',$row['components']);
644
-		}
645
-
646
-		$calendar = [
647
-			'id' => $row['id'],
648
-			'uri' => $row['uri'],
649
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
650
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
651
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
652
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
653
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
654
-		];
655
-
656
-		foreach($this->propertyMap as $xmlName=>$dbName) {
657
-			$calendar[$xmlName] = $row[$dbName];
658
-		}
659
-
660
-		$this->addOwnerPrincipal($calendar);
661
-
662
-		return $calendar;
663
-	}
664
-
665
-	/**
666
-	 * @param $subscriptionId
667
-	 */
668
-	public function getSubscriptionById($subscriptionId) {
669
-		$fields = array_values($this->subscriptionPropertyMap);
670
-		$fields[] = 'id';
671
-		$fields[] = 'uri';
672
-		$fields[] = 'source';
673
-		$fields[] = 'synctoken';
674
-		$fields[] = 'principaluri';
675
-		$fields[] = 'lastmodified';
676
-
677
-		$query = $this->db->getQueryBuilder();
678
-		$query->select($fields)
679
-			->from('calendarsubscriptions')
680
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
681
-			->orderBy('calendarorder', 'asc');
682
-		$stmt =$query->execute();
683
-
684
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
685
-		$stmt->closeCursor();
686
-		if ($row === false) {
687
-			return null;
688
-		}
689
-
690
-		$subscription = [
691
-			'id'           => $row['id'],
692
-			'uri'          => $row['uri'],
693
-			'principaluri' => $row['principaluri'],
694
-			'source'       => $row['source'],
695
-			'lastmodified' => $row['lastmodified'],
696
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
697
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
698
-		];
699
-
700
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
701
-			if (!is_null($row[$dbName])) {
702
-				$subscription[$xmlName] = $row[$dbName];
703
-			}
704
-		}
705
-
706
-		return $subscription;
707
-	}
708
-
709
-	/**
710
-	 * Creates a new calendar for a principal.
711
-	 *
712
-	 * If the creation was a success, an id must be returned that can be used to reference
713
-	 * this calendar in other methods, such as updateCalendar.
714
-	 *
715
-	 * @param string $principalUri
716
-	 * @param string $calendarUri
717
-	 * @param array $properties
718
-	 * @return int
719
-	 * @suppress SqlInjectionChecker
720
-	 */
721
-	function createCalendar($principalUri, $calendarUri, array $properties) {
722
-		$values = [
723
-			'principaluri' => $this->convertPrincipal($principalUri, true),
724
-			'uri'          => $calendarUri,
725
-			'synctoken'    => 1,
726
-			'transparent'  => 0,
727
-			'components'   => 'VEVENT,VTODO',
728
-			'displayname'  => $calendarUri
729
-		];
730
-
731
-		// Default value
732
-		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
733
-		if (isset($properties[$sccs])) {
734
-			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
735
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
736
-			}
737
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
738
-		}
739
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
740
-		if (isset($properties[$transp])) {
741
-			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
742
-		}
743
-
744
-		foreach($this->propertyMap as $xmlName=>$dbName) {
745
-			if (isset($properties[$xmlName])) {
746
-				$values[$dbName] = $properties[$xmlName];
747
-			}
748
-		}
749
-
750
-		$query = $this->db->getQueryBuilder();
751
-		$query->insert('calendars');
752
-		foreach($values as $column => $value) {
753
-			$query->setValue($column, $query->createNamedParameter($value));
754
-		}
755
-		$query->execute();
756
-		$calendarId = $query->getLastInsertId();
757
-
758
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
759
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
760
-			[
761
-				'calendarId' => $calendarId,
762
-				'calendarData' => $this->getCalendarById($calendarId),
763
-		]));
764
-
765
-		return $calendarId;
766
-	}
767
-
768
-	/**
769
-	 * Updates properties for a calendar.
770
-	 *
771
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
772
-	 * To do the actual updates, you must tell this object which properties
773
-	 * you're going to process with the handle() method.
774
-	 *
775
-	 * Calling the handle method is like telling the PropPatch object "I
776
-	 * promise I can handle updating this property".
777
-	 *
778
-	 * Read the PropPatch documentation for more info and examples.
779
-	 *
780
-	 * @param mixed $calendarId
781
-	 * @param PropPatch $propPatch
782
-	 * @return void
783
-	 */
784
-	function updateCalendar($calendarId, PropPatch $propPatch) {
785
-		$supportedProperties = array_keys($this->propertyMap);
786
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
787
-
788
-		/**
789
-		 * @suppress SqlInjectionChecker
790
-		 */
791
-		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
792
-			$newValues = [];
793
-			foreach ($mutations as $propertyName => $propertyValue) {
794
-
795
-				switch ($propertyName) {
796
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
797
-						$fieldName = 'transparent';
798
-						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
799
-						break;
800
-					default :
801
-						$fieldName = $this->propertyMap[$propertyName];
802
-						$newValues[$fieldName] = $propertyValue;
803
-						break;
804
-				}
805
-
806
-			}
807
-			$query = $this->db->getQueryBuilder();
808
-			$query->update('calendars');
809
-			foreach ($newValues as $fieldName => $value) {
810
-				$query->set($fieldName, $query->createNamedParameter($value));
811
-			}
812
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
813
-			$query->execute();
814
-
815
-			$this->addChange($calendarId, "", 2);
816
-
817
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
818
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
819
-				[
820
-					'calendarId' => $calendarId,
821
-					'calendarData' => $this->getCalendarById($calendarId),
822
-					'shares' => $this->getShares($calendarId),
823
-					'propertyMutations' => $mutations,
824
-			]));
825
-
826
-			return true;
827
-		});
828
-	}
829
-
830
-	/**
831
-	 * Delete a calendar and all it's objects
832
-	 *
833
-	 * @param mixed $calendarId
834
-	 * @return void
835
-	 */
836
-	function deleteCalendar($calendarId) {
837
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
838
-			'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
839
-			[
840
-				'calendarId' => $calendarId,
841
-				'calendarData' => $this->getCalendarById($calendarId),
842
-				'shares' => $this->getShares($calendarId),
843
-		]));
844
-
845
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?');
846
-		$stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
847
-
848
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
849
-		$stmt->execute([$calendarId]);
850
-
851
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ? AND `calendartype` = ?');
852
-		$stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
853
-
854
-		$this->calendarSharingBackend->deleteAllShares($calendarId);
855
-
856
-		$query = $this->db->getQueryBuilder();
857
-		$query->delete($this->dbObjectPropertiesTable)
858
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
859
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
860
-			->execute();
861
-	}
862
-
863
-	/**
864
-	 * Delete all of an user's shares
865
-	 *
866
-	 * @param string $principaluri
867
-	 * @return void
868
-	 */
869
-	function deleteAllSharesByUser($principaluri) {
870
-		$this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
871
-	}
872
-
873
-	/**
874
-	 * Returns all calendar objects within a calendar.
875
-	 *
876
-	 * Every item contains an array with the following keys:
877
-	 *   * calendardata - The iCalendar-compatible calendar data
878
-	 *   * uri - a unique key which will be used to construct the uri. This can
879
-	 *     be any arbitrary string, but making sure it ends with '.ics' is a
880
-	 *     good idea. This is only the basename, or filename, not the full
881
-	 *     path.
882
-	 *   * lastmodified - a timestamp of the last modification time
883
-	 *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
884
-	 *   '"abcdef"')
885
-	 *   * size - The size of the calendar objects, in bytes.
886
-	 *   * component - optional, a string containing the type of object, such
887
-	 *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
888
-	 *     the Content-Type header.
889
-	 *
890
-	 * Note that the etag is optional, but it's highly encouraged to return for
891
-	 * speed reasons.
892
-	 *
893
-	 * The calendardata is also optional. If it's not returned
894
-	 * 'getCalendarObject' will be called later, which *is* expected to return
895
-	 * calendardata.
896
-	 *
897
-	 * If neither etag or size are specified, the calendardata will be
898
-	 * used/fetched to determine these numbers. If both are specified the
899
-	 * amount of times this is needed is reduced by a great degree.
900
-	 *
901
-	 * @param mixed $id
902
-	 * @param int $calendarType
903
-	 * @return array
904
-	 */
905
-	public function getCalendarObjects($id, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
906
-		$query = $this->db->getQueryBuilder();
907
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
908
-			->from('calendarobjects')
909
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
910
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
911
-		$stmt = $query->execute();
912
-
913
-		$result = [];
914
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
915
-			$result[] = [
916
-				'id'           => $row['id'],
917
-				'uri'          => $row['uri'],
918
-				'lastmodified' => $row['lastmodified'],
919
-				'etag'         => '"' . $row['etag'] . '"',
920
-				'calendarid'   => $row['calendarid'],
921
-				'size'         => (int)$row['size'],
922
-				'component'    => strtolower($row['componenttype']),
923
-				'classification'=> (int)$row['classification']
924
-			];
925
-		}
926
-
927
-		return $result;
928
-	}
929
-
930
-	/**
931
-	 * Returns information from a single calendar object, based on it's object
932
-	 * uri.
933
-	 *
934
-	 * The object uri is only the basename, or filename and not a full path.
935
-	 *
936
-	 * The returned array must have the same keys as getCalendarObjects. The
937
-	 * 'calendardata' object is required here though, while it's not required
938
-	 * for getCalendarObjects.
939
-	 *
940
-	 * This method must return null if the object did not exist.
941
-	 *
942
-	 * @param mixed $id
943
-	 * @param string $objectUri
944
-	 * @param int $calendarType
945
-	 * @return array|null
946
-	 */
947
-	public function getCalendarObject($id, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
948
-		$query = $this->db->getQueryBuilder();
949
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
950
-			->from('calendarobjects')
951
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
952
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
953
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
954
-		$stmt = $query->execute();
955
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
956
-
957
-		if(!$row) {
958
-			return null;
959
-		}
960
-
961
-		return [
962
-			'id'            => $row['id'],
963
-			'uri'           => $row['uri'],
964
-			'lastmodified'  => $row['lastmodified'],
965
-			'etag'          => '"' . $row['etag'] . '"',
966
-			'calendarid'    => $row['calendarid'],
967
-			'size'          => (int)$row['size'],
968
-			'calendardata'  => $this->readBlob($row['calendardata']),
969
-			'component'     => strtolower($row['componenttype']),
970
-			'classification'=> (int)$row['classification']
971
-		];
972
-	}
973
-
974
-	/**
975
-	 * Returns a list of calendar objects.
976
-	 *
977
-	 * This method should work identical to getCalendarObject, but instead
978
-	 * return all the calendar objects in the list as an array.
979
-	 *
980
-	 * If the backend supports this, it may allow for some speed-ups.
981
-	 *
982
-	 * @param mixed $calendarId
983
-	 * @param string[] $uris
984
-	 * @param int $calendarType
985
-	 * @return array
986
-	 */
987
-	public function getMultipleCalendarObjects($id, array $uris, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
988
-		if (empty($uris)) {
989
-			return [];
990
-		}
991
-
992
-		$chunks = array_chunk($uris, 100);
993
-		$objects = [];
994
-
995
-		$query = $this->db->getQueryBuilder();
996
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
997
-			->from('calendarobjects')
998
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
999
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
1000
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1001
-
1002
-		foreach ($chunks as $uris) {
1003
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
1004
-			$result = $query->execute();
1005
-
1006
-			while ($row = $result->fetch()) {
1007
-				$objects[] = [
1008
-					'id'           => $row['id'],
1009
-					'uri'          => $row['uri'],
1010
-					'lastmodified' => $row['lastmodified'],
1011
-					'etag'         => '"' . $row['etag'] . '"',
1012
-					'calendarid'   => $row['calendarid'],
1013
-					'size'         => (int)$row['size'],
1014
-					'calendardata' => $this->readBlob($row['calendardata']),
1015
-					'component'    => strtolower($row['componenttype']),
1016
-					'classification' => (int)$row['classification']
1017
-				];
1018
-			}
1019
-			$result->closeCursor();
1020
-		}
1021
-
1022
-		return $objects;
1023
-	}
1024
-
1025
-	/**
1026
-	 * Creates a new calendar object.
1027
-	 *
1028
-	 * The object uri is only the basename, or filename and not a full path.
1029
-	 *
1030
-	 * It is possible return an etag from this function, which will be used in
1031
-	 * the response to this PUT request. Note that the ETag must be surrounded
1032
-	 * by double-quotes.
1033
-	 *
1034
-	 * However, you should only really return this ETag if you don't mangle the
1035
-	 * calendar-data. If the result of a subsequent GET to this object is not
1036
-	 * the exact same as this request body, you should omit the ETag.
1037
-	 *
1038
-	 * @param mixed $calendarId
1039
-	 * @param string $objectUri
1040
-	 * @param string $calendarData
1041
-	 * @param int $calendarType
1042
-	 * @return string
1043
-	 */
1044
-	function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1045
-		$extraData = $this->getDenormalizedData($calendarData);
1046
-
1047
-		$q = $this->db->getQueryBuilder();
1048
-		$q->select($q->createFunction('COUNT(*)'))
1049
-			->from('calendarobjects')
1050
-			->where($q->expr()->eq('calendarid', $q->createNamedParameter($calendarId)))
1051
-			->andWhere($q->expr()->eq('uid', $q->createNamedParameter($extraData['uid'])))
1052
-			->andWhere($q->expr()->eq('calendartype', $q->createNamedParameter($calendarType)));
1053
-
1054
-		$result = $q->execute();
1055
-		$count = (int) $result->fetchColumn();
1056
-		$result->closeCursor();
1057
-
1058
-		if ($count !== 0) {
1059
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar object with uid already exists in this calendar collection.');
1060
-		}
1061
-
1062
-		$query = $this->db->getQueryBuilder();
1063
-		$query->insert('calendarobjects')
1064
-			->values([
1065
-				'calendarid' => $query->createNamedParameter($calendarId),
1066
-				'uri' => $query->createNamedParameter($objectUri),
1067
-				'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
1068
-				'lastmodified' => $query->createNamedParameter(time()),
1069
-				'etag' => $query->createNamedParameter($extraData['etag']),
1070
-				'size' => $query->createNamedParameter($extraData['size']),
1071
-				'componenttype' => $query->createNamedParameter($extraData['componentType']),
1072
-				'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1073
-				'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1074
-				'classification' => $query->createNamedParameter($extraData['classification']),
1075
-				'uid' => $query->createNamedParameter($extraData['uid']),
1076
-				'calendartype' => $query->createNamedParameter($calendarType),
1077
-			])
1078
-			->execute();
1079
-
1080
-		$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1081
-
1082
-		if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1083
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
1084
-				'\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
1085
-				[
1086
-					'calendarId' => $calendarId,
1087
-					'calendarData' => $this->getCalendarById($calendarId),
1088
-					'shares' => $this->getShares($calendarId),
1089
-					'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1090
-				]
1091
-			));
1092
-		} else {
1093
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject', new GenericEvent(
1094
-				'\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject',
1095
-				[
1096
-					'subscriptionId' => $calendarId,
1097
-					'calendarData' => $this->getCalendarById($calendarId),
1098
-					'shares' => $this->getShares($calendarId),
1099
-					'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1100
-				]
1101
-			));
1102
-		}
1103
-		$this->addChange($calendarId, $objectUri, 1, $calendarType);
1104
-
1105
-		return '"' . $extraData['etag'] . '"';
1106
-	}
1107
-
1108
-	/**
1109
-	 * Updates an existing calendarobject, based on it's uri.
1110
-	 *
1111
-	 * The object uri is only the basename, or filename and not a full path.
1112
-	 *
1113
-	 * It is possible return an etag from this function, which will be used in
1114
-	 * the response to this PUT request. Note that the ETag must be surrounded
1115
-	 * by double-quotes.
1116
-	 *
1117
-	 * However, you should only really return this ETag if you don't mangle the
1118
-	 * calendar-data. If the result of a subsequent GET to this object is not
1119
-	 * the exact same as this request body, you should omit the ETag.
1120
-	 *
1121
-	 * @param mixed $calendarId
1122
-	 * @param string $objectUri
1123
-	 * @param string $calendarData
1124
-	 * @param int $calendarType
1125
-	 * @return string
1126
-	 */
1127
-	function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1128
-		$extraData = $this->getDenormalizedData($calendarData);
1129
-
1130
-		$query = $this->db->getQueryBuilder();
1131
-		$query->update('calendarobjects')
1132
-				->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1133
-				->set('lastmodified', $query->createNamedParameter(time()))
1134
-				->set('etag', $query->createNamedParameter($extraData['etag']))
1135
-				->set('size', $query->createNamedParameter($extraData['size']))
1136
-				->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1137
-				->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1138
-				->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1139
-				->set('classification', $query->createNamedParameter($extraData['classification']))
1140
-				->set('uid', $query->createNamedParameter($extraData['uid']))
1141
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1142
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1143
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1144
-			->execute();
1145
-
1146
-		$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1147
-
1148
-		$data = $this->getCalendarObject($calendarId, $objectUri);
1149
-		if (is_array($data)) {
1150
-			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1151
-				$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
1152
-					'\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
1153
-					[
1154
-						'calendarId' => $calendarId,
1155
-						'calendarData' => $this->getCalendarById($calendarId),
1156
-						'shares' => $this->getShares($calendarId),
1157
-						'objectData' => $data,
1158
-					]
1159
-				));
1160
-			} else {
1161
-				$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject', new GenericEvent(
1162
-					'\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject',
1163
-					[
1164
-						'subscriptionId' => $calendarId,
1165
-						'calendarData' => $this->getCalendarById($calendarId),
1166
-						'shares' => $this->getShares($calendarId),
1167
-						'objectData' => $data,
1168
-					]
1169
-				));
1170
-			}
1171
-		}
1172
-		$this->addChange($calendarId, $objectUri, 2, $calendarType);
1173
-
1174
-		return '"' . $extraData['etag'] . '"';
1175
-	}
1176
-
1177
-	/**
1178
-	 * @param int $calendarObjectId
1179
-	 * @param int $classification
1180
-	 */
1181
-	public function setClassification($calendarObjectId, $classification) {
1182
-		if (!in_array($classification, [
1183
-			self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1184
-		])) {
1185
-			throw new \InvalidArgumentException();
1186
-		}
1187
-		$query = $this->db->getQueryBuilder();
1188
-		$query->update('calendarobjects')
1189
-			->set('classification', $query->createNamedParameter($classification))
1190
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1191
-			->execute();
1192
-	}
1193
-
1194
-	/**
1195
-	 * Deletes an existing calendar object.
1196
-	 *
1197
-	 * The object uri is only the basename, or filename and not a full path.
1198
-	 *
1199
-	 * @param mixed $calendarId
1200
-	 * @param string $objectUri
1201
-	 * @param int $calendarType
1202
-	 * @return void
1203
-	 */
1204
-	function deleteCalendarObject($calendarId, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1205
-		$data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1206
-		if (is_array($data)) {
1207
-			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1208
-				$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1209
-					'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1210
-					[
1211
-						'calendarId' => $calendarId,
1212
-						'calendarData' => $this->getCalendarById($calendarId),
1213
-						'shares' => $this->getShares($calendarId),
1214
-						'objectData' => $data,
1215
-					]
1216
-				));
1217
-			} else {
1218
-				$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject', new GenericEvent(
1219
-					'\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject',
1220
-					[
1221
-						'subscriptionId' => $calendarId,
1222
-						'calendarData' => $this->getCalendarById($calendarId),
1223
-						'shares' => $this->getShares($calendarId),
1224
-						'objectData' => $data,
1225
-					]
1226
-				));
1227
-			}
1228
-		}
1229
-
1230
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
1231
-		$stmt->execute([$calendarId, $objectUri, $calendarType]);
1232
-
1233
-		$this->purgeProperties($calendarId, $data['id'], $calendarType);
1234
-
1235
-		$this->addChange($calendarId, $objectUri, 3, $calendarType);
1236
-	}
1237
-
1238
-	/**
1239
-	 * Performs a calendar-query on the contents of this calendar.
1240
-	 *
1241
-	 * The calendar-query is defined in RFC4791 : CalDAV. Using the
1242
-	 * calendar-query it is possible for a client to request a specific set of
1243
-	 * object, based on contents of iCalendar properties, date-ranges and
1244
-	 * iCalendar component types (VTODO, VEVENT).
1245
-	 *
1246
-	 * This method should just return a list of (relative) urls that match this
1247
-	 * query.
1248
-	 *
1249
-	 * The list of filters are specified as an array. The exact array is
1250
-	 * documented by Sabre\CalDAV\CalendarQueryParser.
1251
-	 *
1252
-	 * Note that it is extremely likely that getCalendarObject for every path
1253
-	 * returned from this method will be called almost immediately after. You
1254
-	 * may want to anticipate this to speed up these requests.
1255
-	 *
1256
-	 * This method provides a default implementation, which parses *all* the
1257
-	 * iCalendar objects in the specified calendar.
1258
-	 *
1259
-	 * This default may well be good enough for personal use, and calendars
1260
-	 * that aren't very large. But if you anticipate high usage, big calendars
1261
-	 * or high loads, you are strongly advised to optimize certain paths.
1262
-	 *
1263
-	 * The best way to do so is override this method and to optimize
1264
-	 * specifically for 'common filters'.
1265
-	 *
1266
-	 * Requests that are extremely common are:
1267
-	 *   * requests for just VEVENTS
1268
-	 *   * requests for just VTODO
1269
-	 *   * requests with a time-range-filter on either VEVENT or VTODO.
1270
-	 *
1271
-	 * ..and combinations of these requests. It may not be worth it to try to
1272
-	 * handle every possible situation and just rely on the (relatively
1273
-	 * easy to use) CalendarQueryValidator to handle the rest.
1274
-	 *
1275
-	 * Note that especially time-range-filters may be difficult to parse. A
1276
-	 * time-range filter specified on a VEVENT must for instance also handle
1277
-	 * recurrence rules correctly.
1278
-	 * A good example of how to interprete all these filters can also simply
1279
-	 * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1280
-	 * as possible, so it gives you a good idea on what type of stuff you need
1281
-	 * to think of.
1282
-	 *
1283
-	 * @param mixed $id
1284
-	 * @param array $filters
1285
-	 * @param int $calendarType
1286
-	 * @return array
1287
-	 */
1288
-	public function calendarQuery($id, array $filters, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
1289
-		$componentType = null;
1290
-		$requirePostFilter = true;
1291
-		$timeRange = null;
1292
-
1293
-		// if no filters were specified, we don't need to filter after a query
1294
-		if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1295
-			$requirePostFilter = false;
1296
-		}
1297
-
1298
-		// Figuring out if there's a component filter
1299
-		if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1300
-			$componentType = $filters['comp-filters'][0]['name'];
1301
-
1302
-			// Checking if we need post-filters
1303
-			if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1304
-				$requirePostFilter = false;
1305
-			}
1306
-			// There was a time-range filter
1307
-			if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1308
-				$timeRange = $filters['comp-filters'][0]['time-range'];
1309
-
1310
-				// If start time OR the end time is not specified, we can do a
1311
-				// 100% accurate mysql query.
1312
-				if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1313
-					$requirePostFilter = false;
1314
-				}
1315
-			}
1316
-
1317
-		}
1318
-		$columns = ['uri'];
1319
-		if ($requirePostFilter) {
1320
-			$columns = ['uri', 'calendardata'];
1321
-		}
1322
-		$query = $this->db->getQueryBuilder();
1323
-		$query->select($columns)
1324
-			->from('calendarobjects')
1325
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
1326
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1327
-
1328
-		if ($componentType) {
1329
-			$query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1330
-		}
1331
-
1332
-		if ($timeRange && $timeRange['start']) {
1333
-			$query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1334
-		}
1335
-		if ($timeRange && $timeRange['end']) {
1336
-			$query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1337
-		}
1338
-
1339
-		$stmt = $query->execute();
1340
-
1341
-		$result = [];
1342
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1343
-			if ($requirePostFilter) {
1344
-				// validateFilterForObject will parse the calendar data
1345
-				// catch parsing errors
1346
-				try {
1347
-					$matches = $this->validateFilterForObject($row, $filters);
1348
-				} catch(ParseException $ex) {
1349
-					$this->logger->logException($ex, [
1350
-						'app' => 'dav',
1351
-						'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
1352
-					]);
1353
-					continue;
1354
-				} catch (InvalidDataException $ex) {
1355
-					$this->logger->logException($ex, [
1356
-						'app' => 'dav',
1357
-						'message' => 'Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
1358
-					]);
1359
-					continue;
1360
-				}
1361
-
1362
-				if (!$matches) {
1363
-					continue;
1364
-				}
1365
-			}
1366
-			$result[] = $row['uri'];
1367
-		}
1368
-
1369
-		return $result;
1370
-	}
1371
-
1372
-	/**
1373
-	 * custom Nextcloud search extension for CalDAV
1374
-	 *
1375
-	 * TODO - this should optionally cover cached calendar objects as well
1376
-	 *
1377
-	 * @param string $principalUri
1378
-	 * @param array $filters
1379
-	 * @param integer|null $limit
1380
-	 * @param integer|null $offset
1381
-	 * @return array
1382
-	 */
1383
-	public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1384
-		$calendars = $this->getCalendarsForUser($principalUri);
1385
-		$ownCalendars = [];
1386
-		$sharedCalendars = [];
1387
-
1388
-		$uriMapper = [];
1389
-
1390
-		foreach($calendars as $calendar) {
1391
-			if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1392
-				$ownCalendars[] = $calendar['id'];
1393
-			} else {
1394
-				$sharedCalendars[] = $calendar['id'];
1395
-			}
1396
-			$uriMapper[$calendar['id']] = $calendar['uri'];
1397
-		}
1398
-		if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1399
-			return [];
1400
-		}
1401
-
1402
-		$query = $this->db->getQueryBuilder();
1403
-		// Calendar id expressions
1404
-		$calendarExpressions = [];
1405
-		foreach($ownCalendars as $id) {
1406
-			$calendarExpressions[] = $query->expr()->andX(
1407
-				$query->expr()->eq('c.calendarid',
1408
-					$query->createNamedParameter($id)),
1409
-				$query->expr()->eq('c.calendartype',
1410
-						$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1411
-		}
1412
-		foreach($sharedCalendars as $id) {
1413
-			$calendarExpressions[] = $query->expr()->andX(
1414
-				$query->expr()->eq('c.calendarid',
1415
-					$query->createNamedParameter($id)),
1416
-				$query->expr()->eq('c.classification',
1417
-					$query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
1418
-				$query->expr()->eq('c.calendartype',
1419
-					$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1420
-		}
1421
-
1422
-		if (count($calendarExpressions) === 1) {
1423
-			$calExpr = $calendarExpressions[0];
1424
-		} else {
1425
-			$calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1426
-		}
1427
-
1428
-		// Component expressions
1429
-		$compExpressions = [];
1430
-		foreach($filters['comps'] as $comp) {
1431
-			$compExpressions[] = $query->expr()
1432
-				->eq('c.componenttype', $query->createNamedParameter($comp));
1433
-		}
1434
-
1435
-		if (count($compExpressions) === 1) {
1436
-			$compExpr = $compExpressions[0];
1437
-		} else {
1438
-			$compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1439
-		}
1440
-
1441
-		if (!isset($filters['props'])) {
1442
-			$filters['props'] = [];
1443
-		}
1444
-		if (!isset($filters['params'])) {
1445
-			$filters['params'] = [];
1446
-		}
1447
-
1448
-		$propParamExpressions = [];
1449
-		foreach($filters['props'] as $prop) {
1450
-			$propParamExpressions[] = $query->expr()->andX(
1451
-				$query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1452
-				$query->expr()->isNull('i.parameter')
1453
-			);
1454
-		}
1455
-		foreach($filters['params'] as $param) {
1456
-			$propParamExpressions[] = $query->expr()->andX(
1457
-				$query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1458
-				$query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1459
-			);
1460
-		}
1461
-
1462
-		if (count($propParamExpressions) === 1) {
1463
-			$propParamExpr = $propParamExpressions[0];
1464
-		} else {
1465
-			$propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1466
-		}
1467
-
1468
-		$query->select(['c.calendarid', 'c.uri'])
1469
-			->from($this->dbObjectPropertiesTable, 'i')
1470
-			->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1471
-			->where($calExpr)
1472
-			->andWhere($compExpr)
1473
-			->andWhere($propParamExpr)
1474
-			->andWhere($query->expr()->iLike('i.value',
1475
-				$query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')));
1476
-
1477
-		if ($offset) {
1478
-			$query->setFirstResult($offset);
1479
-		}
1480
-		if ($limit) {
1481
-			$query->setMaxResults($limit);
1482
-		}
1483
-
1484
-		$stmt = $query->execute();
1485
-
1486
-		$result = [];
1487
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1488
-			$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1489
-			if (!in_array($path, $result)) {
1490
-				$result[] = $path;
1491
-			}
1492
-		}
1493
-
1494
-		return $result;
1495
-	}
1496
-
1497
-	/**
1498
-	 * used for Nextcloud's calendar API
1499
-	 *
1500
-	 * @param array $calendarInfo
1501
-	 * @param string $pattern
1502
-	 * @param array $searchProperties
1503
-	 * @param array $options
1504
-	 * @param integer|null $limit
1505
-	 * @param integer|null $offset
1506
-	 *
1507
-	 * @return array
1508
-	 */
1509
-	public function search(array $calendarInfo, $pattern, array $searchProperties,
1510
-						   array $options, $limit, $offset) {
1511
-		$outerQuery = $this->db->getQueryBuilder();
1512
-		$innerQuery = $this->db->getQueryBuilder();
1513
-
1514
-		$innerQuery->selectDistinct('op.objectid')
1515
-			->from($this->dbObjectPropertiesTable, 'op')
1516
-			->andWhere($innerQuery->expr()->eq('op.calendarid',
1517
-				$outerQuery->createNamedParameter($calendarInfo['id'])))
1518
-			->andWhere($innerQuery->expr()->eq('op.calendartype',
1519
-				$outerQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1520
-
1521
-		// only return public items for shared calendars for now
1522
-		if ($calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
1523
-			$innerQuery->andWhere($innerQuery->expr()->eq('c.classification',
1524
-				$outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1525
-		}
1526
-
1527
-		$or = $innerQuery->expr()->orX();
1528
-		foreach($searchProperties as $searchProperty) {
1529
-			$or->add($innerQuery->expr()->eq('op.name',
1530
-				$outerQuery->createNamedParameter($searchProperty)));
1531
-		}
1532
-		$innerQuery->andWhere($or);
1533
-
1534
-		if ($pattern !== '') {
1535
-			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1536
-				$outerQuery->createNamedParameter('%' .
1537
-					$this->db->escapeLikeParameter($pattern) . '%')));
1538
-		}
1539
-
1540
-		$outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1541
-			->from('calendarobjects', 'c');
1542
-
1543
-		if (isset($options['timerange'])) {
1544
-			if (isset($options['timerange']['start'])) {
1545
-				$outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence',
1546
-					$outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp)));
1547
-
1548
-			}
1549
-			if (isset($options['timerange']['end'])) {
1550
-				$outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence',
1551
-					$outerQuery->createNamedParameter($options['timerange']['end']->getTimeStamp)));
1552
-			}
1553
-		}
1554
-
1555
-		if (isset($options['types'])) {
1556
-			$or = $outerQuery->expr()->orX();
1557
-			foreach($options['types'] as $type) {
1558
-				$or->add($outerQuery->expr()->eq('componenttype',
1559
-					$outerQuery->createNamedParameter($type)));
1560
-			}
1561
-			$outerQuery->andWhere($or);
1562
-		}
1563
-
1564
-		$outerQuery->andWhere($outerQuery->expr()->in('c.id',
1565
-			$outerQuery->createFunction($innerQuery->getSQL())));
1566
-
1567
-		if ($offset) {
1568
-			$outerQuery->setFirstResult($offset);
1569
-		}
1570
-		if ($limit) {
1571
-			$outerQuery->setMaxResults($limit);
1572
-		}
1573
-
1574
-		$result = $outerQuery->execute();
1575
-		$calendarObjects = $result->fetchAll();
1576
-
1577
-		return array_map(function($o) {
1578
-			$calendarData = Reader::read($o['calendardata']);
1579
-			$comps = $calendarData->getComponents();
1580
-			$objects = [];
1581
-			$timezones = [];
1582
-			foreach($comps as $comp) {
1583
-				if ($comp instanceof VTimeZone) {
1584
-					$timezones[] = $comp;
1585
-				} else {
1586
-					$objects[] = $comp;
1587
-				}
1588
-			}
1589
-
1590
-			return [
1591
-				'id' => $o['id'],
1592
-				'type' => $o['componenttype'],
1593
-				'uid' => $o['uid'],
1594
-				'uri' => $o['uri'],
1595
-				'objects' => array_map(function($c) {
1596
-					return $this->transformSearchData($c);
1597
-				}, $objects),
1598
-				'timezones' => array_map(function($c) {
1599
-					return $this->transformSearchData($c);
1600
-				}, $timezones),
1601
-			];
1602
-		}, $calendarObjects);
1603
-	}
1604
-
1605
-	/**
1606
-	 * @param Component $comp
1607
-	 * @return array
1608
-	 */
1609
-	private function transformSearchData(Component $comp) {
1610
-		$data = [];
1611
-		/** @var Component[] $subComponents */
1612
-		$subComponents = $comp->getComponents();
1613
-		/** @var Property[] $properties */
1614
-		$properties = array_filter($comp->children(), function($c) {
1615
-			return $c instanceof Property;
1616
-		});
1617
-		$validationRules = $comp->getValidationRules();
1618
-
1619
-		foreach($subComponents as $subComponent) {
1620
-			$name = $subComponent->name;
1621
-			if (!isset($data[$name])) {
1622
-				$data[$name] = [];
1623
-			}
1624
-			$data[$name][] = $this->transformSearchData($subComponent);
1625
-		}
1626
-
1627
-		foreach($properties as $property) {
1628
-			$name = $property->name;
1629
-			if (!isset($validationRules[$name])) {
1630
-				$validationRules[$name] = '*';
1631
-			}
1632
-
1633
-			$rule = $validationRules[$property->name];
1634
-			if ($rule === '+' || $rule === '*') { // multiple
1635
-				if (!isset($data[$name])) {
1636
-					$data[$name] = [];
1637
-				}
1638
-
1639
-				$data[$name][] = $this->transformSearchProperty($property);
1640
-			} else { // once
1641
-				$data[$name] = $this->transformSearchProperty($property);
1642
-			}
1643
-		}
1644
-
1645
-		return $data;
1646
-	}
1647
-
1648
-	/**
1649
-	 * @param Property $prop
1650
-	 * @return array
1651
-	 */
1652
-	private function transformSearchProperty(Property $prop) {
1653
-		// No need to check Date, as it extends DateTime
1654
-		if ($prop instanceof Property\ICalendar\DateTime) {
1655
-			$value = $prop->getDateTime();
1656
-		} else {
1657
-			$value = $prop->getValue();
1658
-		}
1659
-
1660
-		return [
1661
-			$value,
1662
-			$prop->parameters()
1663
-		];
1664
-	}
1665
-
1666
-	/**
1667
-	 * Searches through all of a users calendars and calendar objects to find
1668
-	 * an object with a specific UID.
1669
-	 *
1670
-	 * This method should return the path to this object, relative to the
1671
-	 * calendar home, so this path usually only contains two parts:
1672
-	 *
1673
-	 * calendarpath/objectpath.ics
1674
-	 *
1675
-	 * If the uid is not found, return null.
1676
-	 *
1677
-	 * This method should only consider * objects that the principal owns, so
1678
-	 * any calendars owned by other principals that also appear in this
1679
-	 * collection should be ignored.
1680
-	 *
1681
-	 * @param string $principalUri
1682
-	 * @param string $uid
1683
-	 * @return string|null
1684
-	 */
1685
-	function getCalendarObjectByUID($principalUri, $uid) {
1686
-
1687
-		$query = $this->db->getQueryBuilder();
1688
-		$query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1689
-			->from('calendarobjects', 'co')
1690
-			->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1691
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1692
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)))
1693
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1694
-
1695
-		$stmt = $query->execute();
1696
-
1697
-		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1698
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1699
-		}
1700
-
1701
-		return null;
1702
-	}
1703
-
1704
-	/**
1705
-	 * The getChanges method returns all the changes that have happened, since
1706
-	 * the specified syncToken in the specified calendar.
1707
-	 *
1708
-	 * This function should return an array, such as the following:
1709
-	 *
1710
-	 * [
1711
-	 *   'syncToken' => 'The current synctoken',
1712
-	 *   'added'   => [
1713
-	 *      'new.txt',
1714
-	 *   ],
1715
-	 *   'modified'   => [
1716
-	 *      'modified.txt',
1717
-	 *   ],
1718
-	 *   'deleted' => [
1719
-	 *      'foo.php.bak',
1720
-	 *      'old.txt'
1721
-	 *   ]
1722
-	 * );
1723
-	 *
1724
-	 * The returned syncToken property should reflect the *current* syncToken
1725
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1726
-	 * property This is * needed here too, to ensure the operation is atomic.
1727
-	 *
1728
-	 * If the $syncToken argument is specified as null, this is an initial
1729
-	 * sync, and all members should be reported.
1730
-	 *
1731
-	 * The modified property is an array of nodenames that have changed since
1732
-	 * the last token.
1733
-	 *
1734
-	 * The deleted property is an array with nodenames, that have been deleted
1735
-	 * from collection.
1736
-	 *
1737
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
1738
-	 * 1, you only have to report changes that happened only directly in
1739
-	 * immediate descendants. If it's 2, it should also include changes from
1740
-	 * the nodes below the child collections. (grandchildren)
1741
-	 *
1742
-	 * The $limit argument allows a client to specify how many results should
1743
-	 * be returned at most. If the limit is not specified, it should be treated
1744
-	 * as infinite.
1745
-	 *
1746
-	 * If the limit (infinite or not) is higher than you're willing to return,
1747
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1748
-	 *
1749
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
1750
-	 * return null.
1751
-	 *
1752
-	 * The limit is 'suggestive'. You are free to ignore it.
1753
-	 *
1754
-	 * @param string $calendarId
1755
-	 * @param string $syncToken
1756
-	 * @param int $syncLevel
1757
-	 * @param int $limit
1758
-	 * @param int $calendarType
1759
-	 * @return array
1760
-	 */
1761
-	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1762
-		// Current synctoken
1763
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1764
-		$stmt->execute([ $calendarId ]);
1765
-		$currentToken = $stmt->fetchColumn(0);
1766
-
1767
-		if (is_null($currentToken)) {
1768
-			return null;
1769
-		}
1770
-
1771
-		$result = [
1772
-			'syncToken' => $currentToken,
1773
-			'added'     => [],
1774
-			'modified'  => [],
1775
-			'deleted'   => [],
1776
-		];
1777
-
1778
-		if ($syncToken) {
1779
-
1780
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? AND `calendartype` = ? ORDER BY `synctoken`";
1781
-			if ($limit>0) {
1782
-				$query.= " LIMIT " . (int)$limit;
1783
-			}
1784
-
1785
-			// Fetching all changes
1786
-			$stmt = $this->db->prepare($query);
1787
-			$stmt->execute([$syncToken, $currentToken, $calendarId, $calendarType]);
1788
-
1789
-			$changes = [];
1790
-
1791
-			// This loop ensures that any duplicates are overwritten, only the
1792
-			// last change on a node is relevant.
1793
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1794
-
1795
-				$changes[$row['uri']] = $row['operation'];
1796
-
1797
-			}
1798
-
1799
-			foreach($changes as $uri => $operation) {
1800
-
1801
-				switch($operation) {
1802
-					case 1 :
1803
-						$result['added'][] = $uri;
1804
-						break;
1805
-					case 2 :
1806
-						$result['modified'][] = $uri;
1807
-						break;
1808
-					case 3 :
1809
-						$result['deleted'][] = $uri;
1810
-						break;
1811
-				}
1812
-
1813
-			}
1814
-		} else {
1815
-			// No synctoken supplied, this is the initial sync.
1816
-			$query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?";
1817
-			$stmt = $this->db->prepare($query);
1818
-			$stmt->execute([$calendarId, $calendarType]);
1819
-
1820
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1821
-		}
1822
-		return $result;
1823
-
1824
-	}
1825
-
1826
-	/**
1827
-	 * Returns a list of subscriptions for a principal.
1828
-	 *
1829
-	 * Every subscription is an array with the following keys:
1830
-	 *  * id, a unique id that will be used by other functions to modify the
1831
-	 *    subscription. This can be the same as the uri or a database key.
1832
-	 *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1833
-	 *  * principaluri. The owner of the subscription. Almost always the same as
1834
-	 *    principalUri passed to this method.
1835
-	 *
1836
-	 * Furthermore, all the subscription info must be returned too:
1837
-	 *
1838
-	 * 1. {DAV:}displayname
1839
-	 * 2. {http://apple.com/ns/ical/}refreshrate
1840
-	 * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1841
-	 *    should not be stripped).
1842
-	 * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1843
-	 *    should not be stripped).
1844
-	 * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1845
-	 *    attachments should not be stripped).
1846
-	 * 6. {http://calendarserver.org/ns/}source (Must be a
1847
-	 *     Sabre\DAV\Property\Href).
1848
-	 * 7. {http://apple.com/ns/ical/}calendar-color
1849
-	 * 8. {http://apple.com/ns/ical/}calendar-order
1850
-	 * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1851
-	 *    (should just be an instance of
1852
-	 *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1853
-	 *    default components).
1854
-	 *
1855
-	 * @param string $principalUri
1856
-	 * @return array
1857
-	 */
1858
-	function getSubscriptionsForUser($principalUri) {
1859
-		$fields = array_values($this->subscriptionPropertyMap);
1860
-		$fields[] = 'id';
1861
-		$fields[] = 'uri';
1862
-		$fields[] = 'source';
1863
-		$fields[] = 'principaluri';
1864
-		$fields[] = 'lastmodified';
1865
-		$fields[] = 'synctoken';
1866
-
1867
-		$query = $this->db->getQueryBuilder();
1868
-		$query->select($fields)
1869
-			->from('calendarsubscriptions')
1870
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1871
-			->orderBy('calendarorder', 'asc');
1872
-		$stmt =$query->execute();
1873
-
1874
-		$subscriptions = [];
1875
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1876
-
1877
-			$subscription = [
1878
-				'id'           => $row['id'],
1879
-				'uri'          => $row['uri'],
1880
-				'principaluri' => $row['principaluri'],
1881
-				'source'       => $row['source'],
1882
-				'lastmodified' => $row['lastmodified'],
1883
-
1884
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1885
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
1886
-			];
1887
-
1888
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1889
-				if (!is_null($row[$dbName])) {
1890
-					$subscription[$xmlName] = $row[$dbName];
1891
-				}
1892
-			}
1893
-
1894
-			$subscriptions[] = $subscription;
1895
-
1896
-		}
1897
-
1898
-		return $subscriptions;
1899
-	}
1900
-
1901
-	/**
1902
-	 * Creates a new subscription for a principal.
1903
-	 *
1904
-	 * If the creation was a success, an id must be returned that can be used to reference
1905
-	 * this subscription in other methods, such as updateSubscription.
1906
-	 *
1907
-	 * @param string $principalUri
1908
-	 * @param string $uri
1909
-	 * @param array $properties
1910
-	 * @return mixed
1911
-	 */
1912
-	function createSubscription($principalUri, $uri, array $properties) {
1913
-
1914
-		if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1915
-			throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1916
-		}
1917
-
1918
-		$values = [
1919
-			'principaluri' => $principalUri,
1920
-			'uri'          => $uri,
1921
-			'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1922
-			'lastmodified' => time(),
1923
-		];
1924
-
1925
-		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1926
-
1927
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1928
-			if (array_key_exists($xmlName, $properties)) {
1929
-					$values[$dbName] = $properties[$xmlName];
1930
-					if (in_array($dbName, $propertiesBoolean)) {
1931
-						$values[$dbName] = true;
1932
-				}
1933
-			}
1934
-		}
1935
-
1936
-		$valuesToInsert = array();
1937
-
1938
-		$query = $this->db->getQueryBuilder();
1939
-
1940
-		foreach (array_keys($values) as $name) {
1941
-			$valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1942
-		}
1943
-
1944
-		$query->insert('calendarsubscriptions')
1945
-			->values($valuesToInsert)
1946
-			->execute();
1947
-
1948
-		$subscriptionId = $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1949
-
1950
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createSubscription', new GenericEvent(
1951
-			'\OCA\DAV\CalDAV\CalDavBackend::createSubscription',
1952
-			[
1953
-				'subscriptionId' => $subscriptionId,
1954
-				'subscriptionData' => $this->getSubscriptionById($subscriptionId),
1955
-			]));
1956
-
1957
-		return $subscriptionId;
1958
-	}
1959
-
1960
-	/**
1961
-	 * Updates a subscription
1962
-	 *
1963
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1964
-	 * To do the actual updates, you must tell this object which properties
1965
-	 * you're going to process with the handle() method.
1966
-	 *
1967
-	 * Calling the handle method is like telling the PropPatch object "I
1968
-	 * promise I can handle updating this property".
1969
-	 *
1970
-	 * Read the PropPatch documentation for more info and examples.
1971
-	 *
1972
-	 * @param mixed $subscriptionId
1973
-	 * @param PropPatch $propPatch
1974
-	 * @return void
1975
-	 */
1976
-	function updateSubscription($subscriptionId, PropPatch $propPatch) {
1977
-		$supportedProperties = array_keys($this->subscriptionPropertyMap);
1978
-		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
1979
-
1980
-		/**
1981
-		 * @suppress SqlInjectionChecker
1982
-		 */
1983
-		$propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1984
-
1985
-			$newValues = [];
1986
-
1987
-			foreach($mutations as $propertyName=>$propertyValue) {
1988
-				if ($propertyName === '{http://calendarserver.org/ns/}source') {
1989
-					$newValues['source'] = $propertyValue->getHref();
1990
-				} else {
1991
-					$fieldName = $this->subscriptionPropertyMap[$propertyName];
1992
-					$newValues[$fieldName] = $propertyValue;
1993
-				}
1994
-			}
1995
-
1996
-			$query = $this->db->getQueryBuilder();
1997
-			$query->update('calendarsubscriptions')
1998
-				->set('lastmodified', $query->createNamedParameter(time()));
1999
-			foreach($newValues as $fieldName=>$value) {
2000
-				$query->set($fieldName, $query->createNamedParameter($value));
2001
-			}
2002
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2003
-				->execute();
2004
-
2005
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateSubscription', new GenericEvent(
2006
-				'\OCA\DAV\CalDAV\CalDavBackend::updateSubscription',
2007
-				[
2008
-					'subscriptionId' => $subscriptionId,
2009
-					'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2010
-					'propertyMutations' => $mutations,
2011
-				]));
2012
-
2013
-			return true;
2014
-
2015
-		});
2016
-	}
2017
-
2018
-	/**
2019
-	 * Deletes a subscription.
2020
-	 *
2021
-	 * @param mixed $subscriptionId
2022
-	 * @return void
2023
-	 */
2024
-	function deleteSubscription($subscriptionId) {
2025
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription', new GenericEvent(
2026
-			'\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription',
2027
-			[
2028
-				'subscriptionId' => $subscriptionId,
2029
-				'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2030
-			]));
2031
-
2032
-		$query = $this->db->getQueryBuilder();
2033
-		$query->delete('calendarsubscriptions')
2034
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2035
-			->execute();
2036
-
2037
-		$query = $this->db->getQueryBuilder();
2038
-		$query->delete('calendarobjects')
2039
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2040
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2041
-			->execute();
2042
-
2043
-		$query->delete('calendarchanges')
2044
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2045
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2046
-			->execute();
2047
-
2048
-		$query->delete($this->dbObjectPropertiesTable)
2049
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2050
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2051
-			->execute();
2052
-	}
2053
-
2054
-	/**
2055
-	 * Returns a single scheduling object for the inbox collection.
2056
-	 *
2057
-	 * The returned array should contain the following elements:
2058
-	 *   * uri - A unique basename for the object. This will be used to
2059
-	 *           construct a full uri.
2060
-	 *   * calendardata - The iCalendar object
2061
-	 *   * lastmodified - The last modification date. Can be an int for a unix
2062
-	 *                    timestamp, or a PHP DateTime object.
2063
-	 *   * etag - A unique token that must change if the object changed.
2064
-	 *   * size - The size of the object, in bytes.
2065
-	 *
2066
-	 * @param string $principalUri
2067
-	 * @param string $objectUri
2068
-	 * @return array
2069
-	 */
2070
-	function getSchedulingObject($principalUri, $objectUri) {
2071
-		$query = $this->db->getQueryBuilder();
2072
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2073
-			->from('schedulingobjects')
2074
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2075
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2076
-			->execute();
2077
-
2078
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
2079
-
2080
-		if(!$row) {
2081
-			return null;
2082
-		}
2083
-
2084
-		return [
2085
-				'uri'          => $row['uri'],
2086
-				'calendardata' => $row['calendardata'],
2087
-				'lastmodified' => $row['lastmodified'],
2088
-				'etag'         => '"' . $row['etag'] . '"',
2089
-				'size'         => (int)$row['size'],
2090
-		];
2091
-	}
2092
-
2093
-	/**
2094
-	 * Returns all scheduling objects for the inbox collection.
2095
-	 *
2096
-	 * These objects should be returned as an array. Every item in the array
2097
-	 * should follow the same structure as returned from getSchedulingObject.
2098
-	 *
2099
-	 * The main difference is that 'calendardata' is optional.
2100
-	 *
2101
-	 * @param string $principalUri
2102
-	 * @return array
2103
-	 */
2104
-	function getSchedulingObjects($principalUri) {
2105
-		$query = $this->db->getQueryBuilder();
2106
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2107
-				->from('schedulingobjects')
2108
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2109
-				->execute();
2110
-
2111
-		$result = [];
2112
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2113
-			$result[] = [
2114
-					'calendardata' => $row['calendardata'],
2115
-					'uri'          => $row['uri'],
2116
-					'lastmodified' => $row['lastmodified'],
2117
-					'etag'         => '"' . $row['etag'] . '"',
2118
-					'size'         => (int)$row['size'],
2119
-			];
2120
-		}
2121
-
2122
-		return $result;
2123
-	}
2124
-
2125
-	/**
2126
-	 * Deletes a scheduling object from the inbox collection.
2127
-	 *
2128
-	 * @param string $principalUri
2129
-	 * @param string $objectUri
2130
-	 * @return void
2131
-	 */
2132
-	function deleteSchedulingObject($principalUri, $objectUri) {
2133
-		$query = $this->db->getQueryBuilder();
2134
-		$query->delete('schedulingobjects')
2135
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2136
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2137
-				->execute();
2138
-	}
2139
-
2140
-	/**
2141
-	 * Creates a new scheduling object. This should land in a users' inbox.
2142
-	 *
2143
-	 * @param string $principalUri
2144
-	 * @param string $objectUri
2145
-	 * @param string $objectData
2146
-	 * @return void
2147
-	 */
2148
-	function createSchedulingObject($principalUri, $objectUri, $objectData) {
2149
-		$query = $this->db->getQueryBuilder();
2150
-		$query->insert('schedulingobjects')
2151
-			->values([
2152
-				'principaluri' => $query->createNamedParameter($principalUri),
2153
-				'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
2154
-				'uri' => $query->createNamedParameter($objectUri),
2155
-				'lastmodified' => $query->createNamedParameter(time()),
2156
-				'etag' => $query->createNamedParameter(md5($objectData)),
2157
-				'size' => $query->createNamedParameter(strlen($objectData))
2158
-			])
2159
-			->execute();
2160
-	}
2161
-
2162
-	/**
2163
-	 * Adds a change record to the calendarchanges table.
2164
-	 *
2165
-	 * @param mixed $calendarId
2166
-	 * @param string $objectUri
2167
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete.
2168
-	 * @param int $calendarType
2169
-	 * @return void
2170
-	 */
2171
-	protected function addChange($calendarId, $objectUri, $operation, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2172
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2173
-
2174
-		$query = $this->db->getQueryBuilder();
2175
-		$query->select('synctoken')
2176
-			->from($table)
2177
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2178
-		$syncToken = (int)$query->execute()->fetchColumn();
2179
-
2180
-		$query = $this->db->getQueryBuilder();
2181
-		$query->insert('calendarchanges')
2182
-			->values([
2183
-				'uri' => $query->createNamedParameter($objectUri),
2184
-				'synctoken' => $query->createNamedParameter($syncToken),
2185
-				'calendarid' => $query->createNamedParameter($calendarId),
2186
-				'operation' => $query->createNamedParameter($operation),
2187
-				'calendartype' => $query->createNamedParameter($calendarType),
2188
-			])
2189
-			->execute();
2190
-
2191
-		$stmt = $this->db->prepare("UPDATE `*PREFIX*$table` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?");
2192
-		$stmt->execute([
2193
-			$calendarId
2194
-		]);
2195
-
2196
-	}
2197
-
2198
-	/**
2199
-	 * Parses some information from calendar objects, used for optimized
2200
-	 * calendar-queries.
2201
-	 *
2202
-	 * Returns an array with the following keys:
2203
-	 *   * etag - An md5 checksum of the object without the quotes.
2204
-	 *   * size - Size of the object in bytes
2205
-	 *   * componentType - VEVENT, VTODO or VJOURNAL
2206
-	 *   * firstOccurence
2207
-	 *   * lastOccurence
2208
-	 *   * uid - value of the UID property
2209
-	 *
2210
-	 * @param string $calendarData
2211
-	 * @return array
2212
-	 */
2213
-	public function getDenormalizedData($calendarData) {
2214
-
2215
-		$vObject = Reader::read($calendarData);
2216
-		$componentType = null;
2217
-		$component = null;
2218
-		$firstOccurrence = null;
2219
-		$lastOccurrence = null;
2220
-		$uid = null;
2221
-		$classification = self::CLASSIFICATION_PUBLIC;
2222
-		foreach($vObject->getComponents() as $component) {
2223
-			if ($component->name!=='VTIMEZONE') {
2224
-				$componentType = $component->name;
2225
-				$uid = (string)$component->UID;
2226
-				break;
2227
-			}
2228
-		}
2229
-		if (!$componentType) {
2230
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
2231
-		}
2232
-		if ($componentType === 'VEVENT' && $component->DTSTART) {
2233
-			$firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
2234
-			// Finding the last occurrence is a bit harder
2235
-			if (!isset($component->RRULE)) {
2236
-				if (isset($component->DTEND)) {
2237
-					$lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
2238
-				} elseif (isset($component->DURATION)) {
2239
-					$endDate = clone $component->DTSTART->getDateTime();
2240
-					$endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
2241
-					$lastOccurrence = $endDate->getTimeStamp();
2242
-				} elseif (!$component->DTSTART->hasTime()) {
2243
-					$endDate = clone $component->DTSTART->getDateTime();
2244
-					$endDate->modify('+1 day');
2245
-					$lastOccurrence = $endDate->getTimeStamp();
2246
-				} else {
2247
-					$lastOccurrence = $firstOccurrence;
2248
-				}
2249
-			} else {
2250
-				$it = new EventIterator($vObject, (string)$component->UID);
2251
-				$maxDate = new \DateTime(self::MAX_DATE);
2252
-				if ($it->isInfinite()) {
2253
-					$lastOccurrence = $maxDate->getTimestamp();
2254
-				} else {
2255
-					$end = $it->getDtEnd();
2256
-					while($it->valid() && $end < $maxDate) {
2257
-						$end = $it->getDtEnd();
2258
-						$it->next();
2259
-
2260
-					}
2261
-					$lastOccurrence = $end->getTimestamp();
2262
-				}
2263
-
2264
-			}
2265
-		}
2266
-
2267
-		if ($component->CLASS) {
2268
-			$classification = CalDavBackend::CLASSIFICATION_PRIVATE;
2269
-			switch ($component->CLASS->getValue()) {
2270
-				case 'PUBLIC':
2271
-					$classification = CalDavBackend::CLASSIFICATION_PUBLIC;
2272
-					break;
2273
-				case 'CONFIDENTIAL':
2274
-					$classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
2275
-					break;
2276
-			}
2277
-		}
2278
-		return [
2279
-			'etag' => md5($calendarData),
2280
-			'size' => strlen($calendarData),
2281
-			'componentType' => $componentType,
2282
-			'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
2283
-			'lastOccurence'  => $lastOccurrence,
2284
-			'uid' => $uid,
2285
-			'classification' => $classification
2286
-		];
2287
-
2288
-	}
2289
-
2290
-	/**
2291
-	 * @param $cardData
2292
-	 * @return bool|string
2293
-	 */
2294
-	private function readBlob($cardData) {
2295
-		if (is_resource($cardData)) {
2296
-			return stream_get_contents($cardData);
2297
-		}
2298
-
2299
-		return $cardData;
2300
-	}
2301
-
2302
-	/**
2303
-	 * @param IShareable $shareable
2304
-	 * @param array $add
2305
-	 * @param array $remove
2306
-	 */
2307
-	public function updateShares($shareable, $add, $remove) {
2308
-		$calendarId = $shareable->getResourceId();
2309
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
2310
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2311
-			[
2312
-				'calendarId' => $calendarId,
2313
-				'calendarData' => $this->getCalendarById($calendarId),
2314
-				'shares' => $this->getShares($calendarId),
2315
-				'add' => $add,
2316
-				'remove' => $remove,
2317
-			]));
2318
-		$this->calendarSharingBackend->updateShares($shareable, $add, $remove);
2319
-	}
2320
-
2321
-	/**
2322
-	 * @param int $resourceId
2323
-	 * @param int $calendarType
2324
-	 * @return array
2325
-	 */
2326
-	public function getShares($resourceId, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2327
-		return $this->calendarSharingBackend->getShares($resourceId);
2328
-	}
2329
-
2330
-	/**
2331
-	 * @param boolean $value
2332
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
2333
-	 * @return string|null
2334
-	 */
2335
-	public function setPublishStatus($value, $calendar) {
2336
-
2337
-		$calendarId = $calendar->getResourceId();
2338
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', new GenericEvent(
2339
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2340
-			[
2341
-				'calendarId' => $calendarId,
2342
-				'calendarData' => $this->getCalendarById($calendarId),
2343
-				'public' => $value,
2344
-			]));
2345
-
2346
-		$query = $this->db->getQueryBuilder();
2347
-		if ($value) {
2348
-			$publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
2349
-			$query->insert('dav_shares')
2350
-				->values([
2351
-					'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
2352
-					'type' => $query->createNamedParameter('calendar'),
2353
-					'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
2354
-					'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
2355
-					'publicuri' => $query->createNamedParameter($publicUri)
2356
-				]);
2357
-			$query->execute();
2358
-			return $publicUri;
2359
-		}
2360
-		$query->delete('dav_shares')
2361
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2362
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
2363
-		$query->execute();
2364
-		return null;
2365
-	}
2366
-
2367
-	/**
2368
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
2369
-	 * @return mixed
2370
-	 */
2371
-	public function getPublishStatus($calendar) {
2372
-		$query = $this->db->getQueryBuilder();
2373
-		$result = $query->select('publicuri')
2374
-			->from('dav_shares')
2375
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2376
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
2377
-			->execute();
2378
-
2379
-		$row = $result->fetch();
2380
-		$result->closeCursor();
2381
-		return $row ? reset($row) : false;
2382
-	}
2383
-
2384
-	/**
2385
-	 * @param int $resourceId
2386
-	 * @param array $acl
2387
-	 * @return array
2388
-	 */
2389
-	public function applyShareAcl($resourceId, $acl) {
2390
-		return $this->calendarSharingBackend->applyShareAcl($resourceId, $acl);
2391
-	}
2392
-
2393
-
2394
-
2395
-	/**
2396
-	 * update properties table
2397
-	 *
2398
-	 * @param int $calendarId
2399
-	 * @param string $objectUri
2400
-	 * @param string $calendarData
2401
-	 * @param int $calendarType
2402
-	 */
2403
-	public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2404
-		$objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
2405
-
2406
-		try {
2407
-			$vCalendar = $this->readCalendarData($calendarData);
2408
-		} catch (\Exception $ex) {
2409
-			return;
2410
-		}
2411
-
2412
-		$this->purgeProperties($calendarId, $objectId);
2413
-
2414
-		$query = $this->db->getQueryBuilder();
2415
-		$query->insert($this->dbObjectPropertiesTable)
2416
-			->values(
2417
-				[
2418
-					'calendarid' => $query->createNamedParameter($calendarId),
2419
-					'calendartype' => $query->createNamedParameter($calendarType),
2420
-					'objectid' => $query->createNamedParameter($objectId),
2421
-					'name' => $query->createParameter('name'),
2422
-					'parameter' => $query->createParameter('parameter'),
2423
-					'value' => $query->createParameter('value'),
2424
-				]
2425
-			);
2426
-
2427
-		$indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
2428
-		foreach ($vCalendar->getComponents() as $component) {
2429
-			if (!in_array($component->name, $indexComponents)) {
2430
-				continue;
2431
-			}
2432
-
2433
-			foreach ($component->children() as $property) {
2434
-				if (in_array($property->name, self::$indexProperties)) {
2435
-					$value = $property->getValue();
2436
-					// is this a shitty db?
2437
-					if (!$this->db->supports4ByteText()) {
2438
-						$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2439
-					}
2440
-					$value = mb_substr($value, 0, 254);
2441
-
2442
-					$query->setParameter('name', $property->name);
2443
-					$query->setParameter('parameter', null);
2444
-					$query->setParameter('value', $value);
2445
-					$query->execute();
2446
-				}
2447
-
2448
-				if (array_key_exists($property->name, self::$indexParameters)) {
2449
-					$parameters = $property->parameters();
2450
-					$indexedParametersForProperty = self::$indexParameters[$property->name];
2451
-
2452
-					foreach ($parameters as $key => $value) {
2453
-						if (in_array($key, $indexedParametersForProperty)) {
2454
-							// is this a shitty db?
2455
-							if ($this->db->supports4ByteText()) {
2456
-								$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2457
-							}
2458
-							$value = mb_substr($value, 0, 254);
2459
-
2460
-							$query->setParameter('name', $property->name);
2461
-							$query->setParameter('parameter', substr($key, 0, 254));
2462
-							$query->setParameter('value', substr($value, 0, 254));
2463
-							$query->execute();
2464
-						}
2465
-					}
2466
-				}
2467
-			}
2468
-		}
2469
-	}
2470
-
2471
-	/**
2472
-	 * deletes all birthday calendars
2473
-	 */
2474
-	public function deleteAllBirthdayCalendars() {
2475
-		$query = $this->db->getQueryBuilder();
2476
-		$result = $query->select(['id'])->from('calendars')
2477
-			->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
2478
-			->execute();
2479
-
2480
-		$ids = $result->fetchAll();
2481
-		foreach($ids as $id) {
2482
-			$this->deleteCalendar($id['id']);
2483
-		}
2484
-	}
2485
-
2486
-	/**
2487
-	 * @param $subscriptionId
2488
-	 */
2489
-	public function purgeAllCachedEventsForSubscription($subscriptionId) {
2490
-		$query = $this->db->getQueryBuilder();
2491
-		$query->select('uri')
2492
-			->from('calendarobjects')
2493
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2494
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
2495
-		$stmt = $query->execute();
2496
-
2497
-		$uris = [];
2498
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2499
-			$uris[] = $row['uri'];
2500
-		}
2501
-		$stmt->closeCursor();
2502
-
2503
-		$query = $this->db->getQueryBuilder();
2504
-		$query->delete('calendarobjects')
2505
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2506
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2507
-			->execute();
2508
-
2509
-		$query->delete('calendarchanges')
2510
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2511
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2512
-			->execute();
2513
-
2514
-		$query->delete($this->dbObjectPropertiesTable)
2515
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2516
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2517
-			->execute();
2518
-
2519
-		foreach($uris as $uri) {
2520
-			$this->addChange($subscriptionId, $uri, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
2521
-		}
2522
-	}
2523
-
2524
-	/**
2525
-	 * read VCalendar data into a VCalendar object
2526
-	 *
2527
-	 * @param string $objectData
2528
-	 * @return VCalendar
2529
-	 */
2530
-	protected function readCalendarData($objectData) {
2531
-		return Reader::read($objectData);
2532
-	}
2533
-
2534
-	/**
2535
-	 * delete all properties from a given calendar object
2536
-	 *
2537
-	 * @param int $calendarId
2538
-	 * @param int $objectId
2539
-	 */
2540
-	protected function purgeProperties($calendarId, $objectId) {
2541
-		$query = $this->db->getQueryBuilder();
2542
-		$query->delete($this->dbObjectPropertiesTable)
2543
-			->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
2544
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2545
-		$query->execute();
2546
-	}
2547
-
2548
-	/**
2549
-	 * get ID from a given calendar object
2550
-	 *
2551
-	 * @param int $calendarId
2552
-	 * @param string $uri
2553
-	 * @param int $calendarType
2554
-	 * @return int
2555
-	 */
2556
-	protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
2557
-		$query = $this->db->getQueryBuilder();
2558
-		$query->select('id')
2559
-			->from('calendarobjects')
2560
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2561
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
2562
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
2563
-
2564
-		$result = $query->execute();
2565
-		$objectIds = $result->fetch();
2566
-		$result->closeCursor();
2567
-
2568
-		if (!isset($objectIds['id'])) {
2569
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2570
-		}
2571
-
2572
-		return (int)$objectIds['id'];
2573
-	}
2574
-
2575
-	/**
2576
-	 * return legacy endpoint principal name to new principal name
2577
-	 *
2578
-	 * @param $principalUri
2579
-	 * @param $toV2
2580
-	 * @return string
2581
-	 */
2582
-	private function convertPrincipal($principalUri, $toV2) {
2583
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
2584
-			list(, $name) = Uri\split($principalUri);
2585
-			if ($toV2 === true) {
2586
-				return "principals/users/$name";
2587
-			}
2588
-			return "principals/$name";
2589
-		}
2590
-		return $principalUri;
2591
-	}
2592
-
2593
-	/**
2594
-	 * adds information about an owner to the calendar data
2595
-	 *
2596
-	 * @param $calendarInfo
2597
-	 */
2598
-	private function addOwnerPrincipal(&$calendarInfo) {
2599
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2600
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2601
-		if (isset($calendarInfo[$ownerPrincipalKey])) {
2602
-			$uri = $calendarInfo[$ownerPrincipalKey];
2603
-		} else {
2604
-			$uri = $calendarInfo['principaluri'];
2605
-		}
2606
-
2607
-		$principalInformation = $this->principalBackend->getPrincipalByPath($uri);
2608
-		if (isset($principalInformation['{DAV:}displayname'])) {
2609
-			$calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
2610
-		}
2611
-	}
445
+    /**
446
+     * @return array
447
+     */
448
+    public function getPublicCalendars() {
449
+        $fields = array_values($this->propertyMap);
450
+        $fields[] = 'a.id';
451
+        $fields[] = 'a.uri';
452
+        $fields[] = 'a.synctoken';
453
+        $fields[] = 'a.components';
454
+        $fields[] = 'a.principaluri';
455
+        $fields[] = 'a.transparent';
456
+        $fields[] = 's.access';
457
+        $fields[] = 's.publicuri';
458
+        $calendars = [];
459
+        $query = $this->db->getQueryBuilder();
460
+        $result = $query->select($fields)
461
+            ->from('dav_shares', 's')
462
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
463
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
464
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
465
+            ->execute();
466
+
467
+        while($row = $result->fetch()) {
468
+            list(, $name) = Uri\split($row['principaluri']);
469
+            $row['displayname'] = $row['displayname'] . "($name)";
470
+            $components = [];
471
+            if ($row['components']) {
472
+                $components = explode(',',$row['components']);
473
+            }
474
+            $calendar = [
475
+                'id' => $row['id'],
476
+                'uri' => $row['publicuri'],
477
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
478
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
479
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
480
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
481
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
482
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
483
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
484
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
485
+            ];
486
+
487
+            foreach($this->propertyMap as $xmlName=>$dbName) {
488
+                $calendar[$xmlName] = $row[$dbName];
489
+            }
490
+
491
+            $this->addOwnerPrincipal($calendar);
492
+
493
+            if (!isset($calendars[$calendar['id']])) {
494
+                $calendars[$calendar['id']] = $calendar;
495
+            }
496
+        }
497
+        $result->closeCursor();
498
+
499
+        return array_values($calendars);
500
+    }
501
+
502
+    /**
503
+     * @param string $uri
504
+     * @return array
505
+     * @throws NotFound
506
+     */
507
+    public function getPublicCalendar($uri) {
508
+        $fields = array_values($this->propertyMap);
509
+        $fields[] = 'a.id';
510
+        $fields[] = 'a.uri';
511
+        $fields[] = 'a.synctoken';
512
+        $fields[] = 'a.components';
513
+        $fields[] = 'a.principaluri';
514
+        $fields[] = 'a.transparent';
515
+        $fields[] = 's.access';
516
+        $fields[] = 's.publicuri';
517
+        $query = $this->db->getQueryBuilder();
518
+        $result = $query->select($fields)
519
+            ->from('dav_shares', 's')
520
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
521
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
522
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
523
+            ->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
524
+            ->execute();
525
+
526
+        $row = $result->fetch(\PDO::FETCH_ASSOC);
527
+
528
+        $result->closeCursor();
529
+
530
+        if ($row === false) {
531
+            throw new NotFound('Node with name \'' . $uri . '\' could not be found');
532
+        }
533
+
534
+        list(, $name) = Uri\split($row['principaluri']);
535
+        $row['displayname'] = $row['displayname'] . ' ' . "($name)";
536
+        $components = [];
537
+        if ($row['components']) {
538
+            $components = explode(',',$row['components']);
539
+        }
540
+        $calendar = [
541
+            'id' => $row['id'],
542
+            'uri' => $row['publicuri'],
543
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
544
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
545
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
546
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
547
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
548
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
549
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
550
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
551
+        ];
552
+
553
+        foreach($this->propertyMap as $xmlName=>$dbName) {
554
+            $calendar[$xmlName] = $row[$dbName];
555
+        }
556
+
557
+        $this->addOwnerPrincipal($calendar);
558
+
559
+        return $calendar;
560
+
561
+    }
562
+
563
+    /**
564
+     * @param string $principal
565
+     * @param string $uri
566
+     * @return array|null
567
+     */
568
+    public function getCalendarByUri($principal, $uri) {
569
+        $fields = array_values($this->propertyMap);
570
+        $fields[] = 'id';
571
+        $fields[] = 'uri';
572
+        $fields[] = 'synctoken';
573
+        $fields[] = 'components';
574
+        $fields[] = 'principaluri';
575
+        $fields[] = 'transparent';
576
+
577
+        // Making fields a comma-delimited list
578
+        $query = $this->db->getQueryBuilder();
579
+        $query->select($fields)->from('calendars')
580
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
581
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
582
+            ->setMaxResults(1);
583
+        $stmt = $query->execute();
584
+
585
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
586
+        $stmt->closeCursor();
587
+        if ($row === false) {
588
+            return null;
589
+        }
590
+
591
+        $components = [];
592
+        if ($row['components']) {
593
+            $components = explode(',',$row['components']);
594
+        }
595
+
596
+        $calendar = [
597
+            'id' => $row['id'],
598
+            'uri' => $row['uri'],
599
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
600
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
601
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
602
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
603
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
604
+        ];
605
+
606
+        foreach($this->propertyMap as $xmlName=>$dbName) {
607
+            $calendar[$xmlName] = $row[$dbName];
608
+        }
609
+
610
+        $this->addOwnerPrincipal($calendar);
611
+
612
+        return $calendar;
613
+    }
614
+
615
+    /**
616
+     * @param $calendarId
617
+     * @return array|null
618
+     */
619
+    public function getCalendarById($calendarId) {
620
+        $fields = array_values($this->propertyMap);
621
+        $fields[] = 'id';
622
+        $fields[] = 'uri';
623
+        $fields[] = 'synctoken';
624
+        $fields[] = 'components';
625
+        $fields[] = 'principaluri';
626
+        $fields[] = 'transparent';
627
+
628
+        // Making fields a comma-delimited list
629
+        $query = $this->db->getQueryBuilder();
630
+        $query->select($fields)->from('calendars')
631
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
632
+            ->setMaxResults(1);
633
+        $stmt = $query->execute();
634
+
635
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
636
+        $stmt->closeCursor();
637
+        if ($row === false) {
638
+            return null;
639
+        }
640
+
641
+        $components = [];
642
+        if ($row['components']) {
643
+            $components = explode(',',$row['components']);
644
+        }
645
+
646
+        $calendar = [
647
+            'id' => $row['id'],
648
+            'uri' => $row['uri'],
649
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
650
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
651
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
652
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
653
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
654
+        ];
655
+
656
+        foreach($this->propertyMap as $xmlName=>$dbName) {
657
+            $calendar[$xmlName] = $row[$dbName];
658
+        }
659
+
660
+        $this->addOwnerPrincipal($calendar);
661
+
662
+        return $calendar;
663
+    }
664
+
665
+    /**
666
+     * @param $subscriptionId
667
+     */
668
+    public function getSubscriptionById($subscriptionId) {
669
+        $fields = array_values($this->subscriptionPropertyMap);
670
+        $fields[] = 'id';
671
+        $fields[] = 'uri';
672
+        $fields[] = 'source';
673
+        $fields[] = 'synctoken';
674
+        $fields[] = 'principaluri';
675
+        $fields[] = 'lastmodified';
676
+
677
+        $query = $this->db->getQueryBuilder();
678
+        $query->select($fields)
679
+            ->from('calendarsubscriptions')
680
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
681
+            ->orderBy('calendarorder', 'asc');
682
+        $stmt =$query->execute();
683
+
684
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
685
+        $stmt->closeCursor();
686
+        if ($row === false) {
687
+            return null;
688
+        }
689
+
690
+        $subscription = [
691
+            'id'           => $row['id'],
692
+            'uri'          => $row['uri'],
693
+            'principaluri' => $row['principaluri'],
694
+            'source'       => $row['source'],
695
+            'lastmodified' => $row['lastmodified'],
696
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
697
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
698
+        ];
699
+
700
+        foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
701
+            if (!is_null($row[$dbName])) {
702
+                $subscription[$xmlName] = $row[$dbName];
703
+            }
704
+        }
705
+
706
+        return $subscription;
707
+    }
708
+
709
+    /**
710
+     * Creates a new calendar for a principal.
711
+     *
712
+     * If the creation was a success, an id must be returned that can be used to reference
713
+     * this calendar in other methods, such as updateCalendar.
714
+     *
715
+     * @param string $principalUri
716
+     * @param string $calendarUri
717
+     * @param array $properties
718
+     * @return int
719
+     * @suppress SqlInjectionChecker
720
+     */
721
+    function createCalendar($principalUri, $calendarUri, array $properties) {
722
+        $values = [
723
+            'principaluri' => $this->convertPrincipal($principalUri, true),
724
+            'uri'          => $calendarUri,
725
+            'synctoken'    => 1,
726
+            'transparent'  => 0,
727
+            'components'   => 'VEVENT,VTODO',
728
+            'displayname'  => $calendarUri
729
+        ];
730
+
731
+        // Default value
732
+        $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
733
+        if (isset($properties[$sccs])) {
734
+            if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
735
+                throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
736
+            }
737
+            $values['components'] = implode(',',$properties[$sccs]->getValue());
738
+        }
739
+        $transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
740
+        if (isset($properties[$transp])) {
741
+            $values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
742
+        }
743
+
744
+        foreach($this->propertyMap as $xmlName=>$dbName) {
745
+            if (isset($properties[$xmlName])) {
746
+                $values[$dbName] = $properties[$xmlName];
747
+            }
748
+        }
749
+
750
+        $query = $this->db->getQueryBuilder();
751
+        $query->insert('calendars');
752
+        foreach($values as $column => $value) {
753
+            $query->setValue($column, $query->createNamedParameter($value));
754
+        }
755
+        $query->execute();
756
+        $calendarId = $query->getLastInsertId();
757
+
758
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
759
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
760
+            [
761
+                'calendarId' => $calendarId,
762
+                'calendarData' => $this->getCalendarById($calendarId),
763
+        ]));
764
+
765
+        return $calendarId;
766
+    }
767
+
768
+    /**
769
+     * Updates properties for a calendar.
770
+     *
771
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
772
+     * To do the actual updates, you must tell this object which properties
773
+     * you're going to process with the handle() method.
774
+     *
775
+     * Calling the handle method is like telling the PropPatch object "I
776
+     * promise I can handle updating this property".
777
+     *
778
+     * Read the PropPatch documentation for more info and examples.
779
+     *
780
+     * @param mixed $calendarId
781
+     * @param PropPatch $propPatch
782
+     * @return void
783
+     */
784
+    function updateCalendar($calendarId, PropPatch $propPatch) {
785
+        $supportedProperties = array_keys($this->propertyMap);
786
+        $supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
787
+
788
+        /**
789
+         * @suppress SqlInjectionChecker
790
+         */
791
+        $propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
792
+            $newValues = [];
793
+            foreach ($mutations as $propertyName => $propertyValue) {
794
+
795
+                switch ($propertyName) {
796
+                    case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
797
+                        $fieldName = 'transparent';
798
+                        $newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
799
+                        break;
800
+                    default :
801
+                        $fieldName = $this->propertyMap[$propertyName];
802
+                        $newValues[$fieldName] = $propertyValue;
803
+                        break;
804
+                }
805
+
806
+            }
807
+            $query = $this->db->getQueryBuilder();
808
+            $query->update('calendars');
809
+            foreach ($newValues as $fieldName => $value) {
810
+                $query->set($fieldName, $query->createNamedParameter($value));
811
+            }
812
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
813
+            $query->execute();
814
+
815
+            $this->addChange($calendarId, "", 2);
816
+
817
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
818
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
819
+                [
820
+                    'calendarId' => $calendarId,
821
+                    'calendarData' => $this->getCalendarById($calendarId),
822
+                    'shares' => $this->getShares($calendarId),
823
+                    'propertyMutations' => $mutations,
824
+            ]));
825
+
826
+            return true;
827
+        });
828
+    }
829
+
830
+    /**
831
+     * Delete a calendar and all it's objects
832
+     *
833
+     * @param mixed $calendarId
834
+     * @return void
835
+     */
836
+    function deleteCalendar($calendarId) {
837
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
838
+            '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
839
+            [
840
+                'calendarId' => $calendarId,
841
+                'calendarData' => $this->getCalendarById($calendarId),
842
+                'shares' => $this->getShares($calendarId),
843
+        ]));
844
+
845
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?');
846
+        $stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
847
+
848
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
849
+        $stmt->execute([$calendarId]);
850
+
851
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ? AND `calendartype` = ?');
852
+        $stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
853
+
854
+        $this->calendarSharingBackend->deleteAllShares($calendarId);
855
+
856
+        $query = $this->db->getQueryBuilder();
857
+        $query->delete($this->dbObjectPropertiesTable)
858
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
859
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
860
+            ->execute();
861
+    }
862
+
863
+    /**
864
+     * Delete all of an user's shares
865
+     *
866
+     * @param string $principaluri
867
+     * @return void
868
+     */
869
+    function deleteAllSharesByUser($principaluri) {
870
+        $this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
871
+    }
872
+
873
+    /**
874
+     * Returns all calendar objects within a calendar.
875
+     *
876
+     * Every item contains an array with the following keys:
877
+     *   * calendardata - The iCalendar-compatible calendar data
878
+     *   * uri - a unique key which will be used to construct the uri. This can
879
+     *     be any arbitrary string, but making sure it ends with '.ics' is a
880
+     *     good idea. This is only the basename, or filename, not the full
881
+     *     path.
882
+     *   * lastmodified - a timestamp of the last modification time
883
+     *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
884
+     *   '"abcdef"')
885
+     *   * size - The size of the calendar objects, in bytes.
886
+     *   * component - optional, a string containing the type of object, such
887
+     *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
888
+     *     the Content-Type header.
889
+     *
890
+     * Note that the etag is optional, but it's highly encouraged to return for
891
+     * speed reasons.
892
+     *
893
+     * The calendardata is also optional. If it's not returned
894
+     * 'getCalendarObject' will be called later, which *is* expected to return
895
+     * calendardata.
896
+     *
897
+     * If neither etag or size are specified, the calendardata will be
898
+     * used/fetched to determine these numbers. If both are specified the
899
+     * amount of times this is needed is reduced by a great degree.
900
+     *
901
+     * @param mixed $id
902
+     * @param int $calendarType
903
+     * @return array
904
+     */
905
+    public function getCalendarObjects($id, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
906
+        $query = $this->db->getQueryBuilder();
907
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
908
+            ->from('calendarobjects')
909
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
910
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
911
+        $stmt = $query->execute();
912
+
913
+        $result = [];
914
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
915
+            $result[] = [
916
+                'id'           => $row['id'],
917
+                'uri'          => $row['uri'],
918
+                'lastmodified' => $row['lastmodified'],
919
+                'etag'         => '"' . $row['etag'] . '"',
920
+                'calendarid'   => $row['calendarid'],
921
+                'size'         => (int)$row['size'],
922
+                'component'    => strtolower($row['componenttype']),
923
+                'classification'=> (int)$row['classification']
924
+            ];
925
+        }
926
+
927
+        return $result;
928
+    }
929
+
930
+    /**
931
+     * Returns information from a single calendar object, based on it's object
932
+     * uri.
933
+     *
934
+     * The object uri is only the basename, or filename and not a full path.
935
+     *
936
+     * The returned array must have the same keys as getCalendarObjects. The
937
+     * 'calendardata' object is required here though, while it's not required
938
+     * for getCalendarObjects.
939
+     *
940
+     * This method must return null if the object did not exist.
941
+     *
942
+     * @param mixed $id
943
+     * @param string $objectUri
944
+     * @param int $calendarType
945
+     * @return array|null
946
+     */
947
+    public function getCalendarObject($id, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
948
+        $query = $this->db->getQueryBuilder();
949
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
950
+            ->from('calendarobjects')
951
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
952
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
953
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
954
+        $stmt = $query->execute();
955
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
956
+
957
+        if(!$row) {
958
+            return null;
959
+        }
960
+
961
+        return [
962
+            'id'            => $row['id'],
963
+            'uri'           => $row['uri'],
964
+            'lastmodified'  => $row['lastmodified'],
965
+            'etag'          => '"' . $row['etag'] . '"',
966
+            'calendarid'    => $row['calendarid'],
967
+            'size'          => (int)$row['size'],
968
+            'calendardata'  => $this->readBlob($row['calendardata']),
969
+            'component'     => strtolower($row['componenttype']),
970
+            'classification'=> (int)$row['classification']
971
+        ];
972
+    }
973
+
974
+    /**
975
+     * Returns a list of calendar objects.
976
+     *
977
+     * This method should work identical to getCalendarObject, but instead
978
+     * return all the calendar objects in the list as an array.
979
+     *
980
+     * If the backend supports this, it may allow for some speed-ups.
981
+     *
982
+     * @param mixed $calendarId
983
+     * @param string[] $uris
984
+     * @param int $calendarType
985
+     * @return array
986
+     */
987
+    public function getMultipleCalendarObjects($id, array $uris, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
988
+        if (empty($uris)) {
989
+            return [];
990
+        }
991
+
992
+        $chunks = array_chunk($uris, 100);
993
+        $objects = [];
994
+
995
+        $query = $this->db->getQueryBuilder();
996
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
997
+            ->from('calendarobjects')
998
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
999
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
1000
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1001
+
1002
+        foreach ($chunks as $uris) {
1003
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
1004
+            $result = $query->execute();
1005
+
1006
+            while ($row = $result->fetch()) {
1007
+                $objects[] = [
1008
+                    'id'           => $row['id'],
1009
+                    'uri'          => $row['uri'],
1010
+                    'lastmodified' => $row['lastmodified'],
1011
+                    'etag'         => '"' . $row['etag'] . '"',
1012
+                    'calendarid'   => $row['calendarid'],
1013
+                    'size'         => (int)$row['size'],
1014
+                    'calendardata' => $this->readBlob($row['calendardata']),
1015
+                    'component'    => strtolower($row['componenttype']),
1016
+                    'classification' => (int)$row['classification']
1017
+                ];
1018
+            }
1019
+            $result->closeCursor();
1020
+        }
1021
+
1022
+        return $objects;
1023
+    }
1024
+
1025
+    /**
1026
+     * Creates a new calendar object.
1027
+     *
1028
+     * The object uri is only the basename, or filename and not a full path.
1029
+     *
1030
+     * It is possible return an etag from this function, which will be used in
1031
+     * the response to this PUT request. Note that the ETag must be surrounded
1032
+     * by double-quotes.
1033
+     *
1034
+     * However, you should only really return this ETag if you don't mangle the
1035
+     * calendar-data. If the result of a subsequent GET to this object is not
1036
+     * the exact same as this request body, you should omit the ETag.
1037
+     *
1038
+     * @param mixed $calendarId
1039
+     * @param string $objectUri
1040
+     * @param string $calendarData
1041
+     * @param int $calendarType
1042
+     * @return string
1043
+     */
1044
+    function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1045
+        $extraData = $this->getDenormalizedData($calendarData);
1046
+
1047
+        $q = $this->db->getQueryBuilder();
1048
+        $q->select($q->createFunction('COUNT(*)'))
1049
+            ->from('calendarobjects')
1050
+            ->where($q->expr()->eq('calendarid', $q->createNamedParameter($calendarId)))
1051
+            ->andWhere($q->expr()->eq('uid', $q->createNamedParameter($extraData['uid'])))
1052
+            ->andWhere($q->expr()->eq('calendartype', $q->createNamedParameter($calendarType)));
1053
+
1054
+        $result = $q->execute();
1055
+        $count = (int) $result->fetchColumn();
1056
+        $result->closeCursor();
1057
+
1058
+        if ($count !== 0) {
1059
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar object with uid already exists in this calendar collection.');
1060
+        }
1061
+
1062
+        $query = $this->db->getQueryBuilder();
1063
+        $query->insert('calendarobjects')
1064
+            ->values([
1065
+                'calendarid' => $query->createNamedParameter($calendarId),
1066
+                'uri' => $query->createNamedParameter($objectUri),
1067
+                'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
1068
+                'lastmodified' => $query->createNamedParameter(time()),
1069
+                'etag' => $query->createNamedParameter($extraData['etag']),
1070
+                'size' => $query->createNamedParameter($extraData['size']),
1071
+                'componenttype' => $query->createNamedParameter($extraData['componentType']),
1072
+                'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1073
+                'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1074
+                'classification' => $query->createNamedParameter($extraData['classification']),
1075
+                'uid' => $query->createNamedParameter($extraData['uid']),
1076
+                'calendartype' => $query->createNamedParameter($calendarType),
1077
+            ])
1078
+            ->execute();
1079
+
1080
+        $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1081
+
1082
+        if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1083
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
1084
+                '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
1085
+                [
1086
+                    'calendarId' => $calendarId,
1087
+                    'calendarData' => $this->getCalendarById($calendarId),
1088
+                    'shares' => $this->getShares($calendarId),
1089
+                    'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1090
+                ]
1091
+            ));
1092
+        } else {
1093
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject', new GenericEvent(
1094
+                '\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject',
1095
+                [
1096
+                    'subscriptionId' => $calendarId,
1097
+                    'calendarData' => $this->getCalendarById($calendarId),
1098
+                    'shares' => $this->getShares($calendarId),
1099
+                    'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1100
+                ]
1101
+            ));
1102
+        }
1103
+        $this->addChange($calendarId, $objectUri, 1, $calendarType);
1104
+
1105
+        return '"' . $extraData['etag'] . '"';
1106
+    }
1107
+
1108
+    /**
1109
+     * Updates an existing calendarobject, based on it's uri.
1110
+     *
1111
+     * The object uri is only the basename, or filename and not a full path.
1112
+     *
1113
+     * It is possible return an etag from this function, which will be used in
1114
+     * the response to this PUT request. Note that the ETag must be surrounded
1115
+     * by double-quotes.
1116
+     *
1117
+     * However, you should only really return this ETag if you don't mangle the
1118
+     * calendar-data. If the result of a subsequent GET to this object is not
1119
+     * the exact same as this request body, you should omit the ETag.
1120
+     *
1121
+     * @param mixed $calendarId
1122
+     * @param string $objectUri
1123
+     * @param string $calendarData
1124
+     * @param int $calendarType
1125
+     * @return string
1126
+     */
1127
+    function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1128
+        $extraData = $this->getDenormalizedData($calendarData);
1129
+
1130
+        $query = $this->db->getQueryBuilder();
1131
+        $query->update('calendarobjects')
1132
+                ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1133
+                ->set('lastmodified', $query->createNamedParameter(time()))
1134
+                ->set('etag', $query->createNamedParameter($extraData['etag']))
1135
+                ->set('size', $query->createNamedParameter($extraData['size']))
1136
+                ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1137
+                ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1138
+                ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1139
+                ->set('classification', $query->createNamedParameter($extraData['classification']))
1140
+                ->set('uid', $query->createNamedParameter($extraData['uid']))
1141
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1142
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1143
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1144
+            ->execute();
1145
+
1146
+        $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1147
+
1148
+        $data = $this->getCalendarObject($calendarId, $objectUri);
1149
+        if (is_array($data)) {
1150
+            if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1151
+                $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
1152
+                    '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
1153
+                    [
1154
+                        'calendarId' => $calendarId,
1155
+                        'calendarData' => $this->getCalendarById($calendarId),
1156
+                        'shares' => $this->getShares($calendarId),
1157
+                        'objectData' => $data,
1158
+                    ]
1159
+                ));
1160
+            } else {
1161
+                $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject', new GenericEvent(
1162
+                    '\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject',
1163
+                    [
1164
+                        'subscriptionId' => $calendarId,
1165
+                        'calendarData' => $this->getCalendarById($calendarId),
1166
+                        'shares' => $this->getShares($calendarId),
1167
+                        'objectData' => $data,
1168
+                    ]
1169
+                ));
1170
+            }
1171
+        }
1172
+        $this->addChange($calendarId, $objectUri, 2, $calendarType);
1173
+
1174
+        return '"' . $extraData['etag'] . '"';
1175
+    }
1176
+
1177
+    /**
1178
+     * @param int $calendarObjectId
1179
+     * @param int $classification
1180
+     */
1181
+    public function setClassification($calendarObjectId, $classification) {
1182
+        if (!in_array($classification, [
1183
+            self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1184
+        ])) {
1185
+            throw new \InvalidArgumentException();
1186
+        }
1187
+        $query = $this->db->getQueryBuilder();
1188
+        $query->update('calendarobjects')
1189
+            ->set('classification', $query->createNamedParameter($classification))
1190
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1191
+            ->execute();
1192
+    }
1193
+
1194
+    /**
1195
+     * Deletes an existing calendar object.
1196
+     *
1197
+     * The object uri is only the basename, or filename and not a full path.
1198
+     *
1199
+     * @param mixed $calendarId
1200
+     * @param string $objectUri
1201
+     * @param int $calendarType
1202
+     * @return void
1203
+     */
1204
+    function deleteCalendarObject($calendarId, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1205
+        $data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1206
+        if (is_array($data)) {
1207
+            if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1208
+                $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1209
+                    '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1210
+                    [
1211
+                        'calendarId' => $calendarId,
1212
+                        'calendarData' => $this->getCalendarById($calendarId),
1213
+                        'shares' => $this->getShares($calendarId),
1214
+                        'objectData' => $data,
1215
+                    ]
1216
+                ));
1217
+            } else {
1218
+                $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject', new GenericEvent(
1219
+                    '\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject',
1220
+                    [
1221
+                        'subscriptionId' => $calendarId,
1222
+                        'calendarData' => $this->getCalendarById($calendarId),
1223
+                        'shares' => $this->getShares($calendarId),
1224
+                        'objectData' => $data,
1225
+                    ]
1226
+                ));
1227
+            }
1228
+        }
1229
+
1230
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
1231
+        $stmt->execute([$calendarId, $objectUri, $calendarType]);
1232
+
1233
+        $this->purgeProperties($calendarId, $data['id'], $calendarType);
1234
+
1235
+        $this->addChange($calendarId, $objectUri, 3, $calendarType);
1236
+    }
1237
+
1238
+    /**
1239
+     * Performs a calendar-query on the contents of this calendar.
1240
+     *
1241
+     * The calendar-query is defined in RFC4791 : CalDAV. Using the
1242
+     * calendar-query it is possible for a client to request a specific set of
1243
+     * object, based on contents of iCalendar properties, date-ranges and
1244
+     * iCalendar component types (VTODO, VEVENT).
1245
+     *
1246
+     * This method should just return a list of (relative) urls that match this
1247
+     * query.
1248
+     *
1249
+     * The list of filters are specified as an array. The exact array is
1250
+     * documented by Sabre\CalDAV\CalendarQueryParser.
1251
+     *
1252
+     * Note that it is extremely likely that getCalendarObject for every path
1253
+     * returned from this method will be called almost immediately after. You
1254
+     * may want to anticipate this to speed up these requests.
1255
+     *
1256
+     * This method provides a default implementation, which parses *all* the
1257
+     * iCalendar objects in the specified calendar.
1258
+     *
1259
+     * This default may well be good enough for personal use, and calendars
1260
+     * that aren't very large. But if you anticipate high usage, big calendars
1261
+     * or high loads, you are strongly advised to optimize certain paths.
1262
+     *
1263
+     * The best way to do so is override this method and to optimize
1264
+     * specifically for 'common filters'.
1265
+     *
1266
+     * Requests that are extremely common are:
1267
+     *   * requests for just VEVENTS
1268
+     *   * requests for just VTODO
1269
+     *   * requests with a time-range-filter on either VEVENT or VTODO.
1270
+     *
1271
+     * ..and combinations of these requests. It may not be worth it to try to
1272
+     * handle every possible situation and just rely on the (relatively
1273
+     * easy to use) CalendarQueryValidator to handle the rest.
1274
+     *
1275
+     * Note that especially time-range-filters may be difficult to parse. A
1276
+     * time-range filter specified on a VEVENT must for instance also handle
1277
+     * recurrence rules correctly.
1278
+     * A good example of how to interprete all these filters can also simply
1279
+     * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1280
+     * as possible, so it gives you a good idea on what type of stuff you need
1281
+     * to think of.
1282
+     *
1283
+     * @param mixed $id
1284
+     * @param array $filters
1285
+     * @param int $calendarType
1286
+     * @return array
1287
+     */
1288
+    public function calendarQuery($id, array $filters, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
1289
+        $componentType = null;
1290
+        $requirePostFilter = true;
1291
+        $timeRange = null;
1292
+
1293
+        // if no filters were specified, we don't need to filter after a query
1294
+        if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1295
+            $requirePostFilter = false;
1296
+        }
1297
+
1298
+        // Figuring out if there's a component filter
1299
+        if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1300
+            $componentType = $filters['comp-filters'][0]['name'];
1301
+
1302
+            // Checking if we need post-filters
1303
+            if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1304
+                $requirePostFilter = false;
1305
+            }
1306
+            // There was a time-range filter
1307
+            if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1308
+                $timeRange = $filters['comp-filters'][0]['time-range'];
1309
+
1310
+                // If start time OR the end time is not specified, we can do a
1311
+                // 100% accurate mysql query.
1312
+                if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1313
+                    $requirePostFilter = false;
1314
+                }
1315
+            }
1316
+
1317
+        }
1318
+        $columns = ['uri'];
1319
+        if ($requirePostFilter) {
1320
+            $columns = ['uri', 'calendardata'];
1321
+        }
1322
+        $query = $this->db->getQueryBuilder();
1323
+        $query->select($columns)
1324
+            ->from('calendarobjects')
1325
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
1326
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1327
+
1328
+        if ($componentType) {
1329
+            $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1330
+        }
1331
+
1332
+        if ($timeRange && $timeRange['start']) {
1333
+            $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1334
+        }
1335
+        if ($timeRange && $timeRange['end']) {
1336
+            $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1337
+        }
1338
+
1339
+        $stmt = $query->execute();
1340
+
1341
+        $result = [];
1342
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1343
+            if ($requirePostFilter) {
1344
+                // validateFilterForObject will parse the calendar data
1345
+                // catch parsing errors
1346
+                try {
1347
+                    $matches = $this->validateFilterForObject($row, $filters);
1348
+                } catch(ParseException $ex) {
1349
+                    $this->logger->logException($ex, [
1350
+                        'app' => 'dav',
1351
+                        'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
1352
+                    ]);
1353
+                    continue;
1354
+                } catch (InvalidDataException $ex) {
1355
+                    $this->logger->logException($ex, [
1356
+                        'app' => 'dav',
1357
+                        'message' => 'Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
1358
+                    ]);
1359
+                    continue;
1360
+                }
1361
+
1362
+                if (!$matches) {
1363
+                    continue;
1364
+                }
1365
+            }
1366
+            $result[] = $row['uri'];
1367
+        }
1368
+
1369
+        return $result;
1370
+    }
1371
+
1372
+    /**
1373
+     * custom Nextcloud search extension for CalDAV
1374
+     *
1375
+     * TODO - this should optionally cover cached calendar objects as well
1376
+     *
1377
+     * @param string $principalUri
1378
+     * @param array $filters
1379
+     * @param integer|null $limit
1380
+     * @param integer|null $offset
1381
+     * @return array
1382
+     */
1383
+    public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1384
+        $calendars = $this->getCalendarsForUser($principalUri);
1385
+        $ownCalendars = [];
1386
+        $sharedCalendars = [];
1387
+
1388
+        $uriMapper = [];
1389
+
1390
+        foreach($calendars as $calendar) {
1391
+            if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1392
+                $ownCalendars[] = $calendar['id'];
1393
+            } else {
1394
+                $sharedCalendars[] = $calendar['id'];
1395
+            }
1396
+            $uriMapper[$calendar['id']] = $calendar['uri'];
1397
+        }
1398
+        if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1399
+            return [];
1400
+        }
1401
+
1402
+        $query = $this->db->getQueryBuilder();
1403
+        // Calendar id expressions
1404
+        $calendarExpressions = [];
1405
+        foreach($ownCalendars as $id) {
1406
+            $calendarExpressions[] = $query->expr()->andX(
1407
+                $query->expr()->eq('c.calendarid',
1408
+                    $query->createNamedParameter($id)),
1409
+                $query->expr()->eq('c.calendartype',
1410
+                        $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1411
+        }
1412
+        foreach($sharedCalendars as $id) {
1413
+            $calendarExpressions[] = $query->expr()->andX(
1414
+                $query->expr()->eq('c.calendarid',
1415
+                    $query->createNamedParameter($id)),
1416
+                $query->expr()->eq('c.classification',
1417
+                    $query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
1418
+                $query->expr()->eq('c.calendartype',
1419
+                    $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1420
+        }
1421
+
1422
+        if (count($calendarExpressions) === 1) {
1423
+            $calExpr = $calendarExpressions[0];
1424
+        } else {
1425
+            $calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1426
+        }
1427
+
1428
+        // Component expressions
1429
+        $compExpressions = [];
1430
+        foreach($filters['comps'] as $comp) {
1431
+            $compExpressions[] = $query->expr()
1432
+                ->eq('c.componenttype', $query->createNamedParameter($comp));
1433
+        }
1434
+
1435
+        if (count($compExpressions) === 1) {
1436
+            $compExpr = $compExpressions[0];
1437
+        } else {
1438
+            $compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1439
+        }
1440
+
1441
+        if (!isset($filters['props'])) {
1442
+            $filters['props'] = [];
1443
+        }
1444
+        if (!isset($filters['params'])) {
1445
+            $filters['params'] = [];
1446
+        }
1447
+
1448
+        $propParamExpressions = [];
1449
+        foreach($filters['props'] as $prop) {
1450
+            $propParamExpressions[] = $query->expr()->andX(
1451
+                $query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1452
+                $query->expr()->isNull('i.parameter')
1453
+            );
1454
+        }
1455
+        foreach($filters['params'] as $param) {
1456
+            $propParamExpressions[] = $query->expr()->andX(
1457
+                $query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1458
+                $query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1459
+            );
1460
+        }
1461
+
1462
+        if (count($propParamExpressions) === 1) {
1463
+            $propParamExpr = $propParamExpressions[0];
1464
+        } else {
1465
+            $propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1466
+        }
1467
+
1468
+        $query->select(['c.calendarid', 'c.uri'])
1469
+            ->from($this->dbObjectPropertiesTable, 'i')
1470
+            ->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1471
+            ->where($calExpr)
1472
+            ->andWhere($compExpr)
1473
+            ->andWhere($propParamExpr)
1474
+            ->andWhere($query->expr()->iLike('i.value',
1475
+                $query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')));
1476
+
1477
+        if ($offset) {
1478
+            $query->setFirstResult($offset);
1479
+        }
1480
+        if ($limit) {
1481
+            $query->setMaxResults($limit);
1482
+        }
1483
+
1484
+        $stmt = $query->execute();
1485
+
1486
+        $result = [];
1487
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1488
+            $path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1489
+            if (!in_array($path, $result)) {
1490
+                $result[] = $path;
1491
+            }
1492
+        }
1493
+
1494
+        return $result;
1495
+    }
1496
+
1497
+    /**
1498
+     * used for Nextcloud's calendar API
1499
+     *
1500
+     * @param array $calendarInfo
1501
+     * @param string $pattern
1502
+     * @param array $searchProperties
1503
+     * @param array $options
1504
+     * @param integer|null $limit
1505
+     * @param integer|null $offset
1506
+     *
1507
+     * @return array
1508
+     */
1509
+    public function search(array $calendarInfo, $pattern, array $searchProperties,
1510
+                            array $options, $limit, $offset) {
1511
+        $outerQuery = $this->db->getQueryBuilder();
1512
+        $innerQuery = $this->db->getQueryBuilder();
1513
+
1514
+        $innerQuery->selectDistinct('op.objectid')
1515
+            ->from($this->dbObjectPropertiesTable, 'op')
1516
+            ->andWhere($innerQuery->expr()->eq('op.calendarid',
1517
+                $outerQuery->createNamedParameter($calendarInfo['id'])))
1518
+            ->andWhere($innerQuery->expr()->eq('op.calendartype',
1519
+                $outerQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1520
+
1521
+        // only return public items for shared calendars for now
1522
+        if ($calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
1523
+            $innerQuery->andWhere($innerQuery->expr()->eq('c.classification',
1524
+                $outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1525
+        }
1526
+
1527
+        $or = $innerQuery->expr()->orX();
1528
+        foreach($searchProperties as $searchProperty) {
1529
+            $or->add($innerQuery->expr()->eq('op.name',
1530
+                $outerQuery->createNamedParameter($searchProperty)));
1531
+        }
1532
+        $innerQuery->andWhere($or);
1533
+
1534
+        if ($pattern !== '') {
1535
+            $innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1536
+                $outerQuery->createNamedParameter('%' .
1537
+                    $this->db->escapeLikeParameter($pattern) . '%')));
1538
+        }
1539
+
1540
+        $outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1541
+            ->from('calendarobjects', 'c');
1542
+
1543
+        if (isset($options['timerange'])) {
1544
+            if (isset($options['timerange']['start'])) {
1545
+                $outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence',
1546
+                    $outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp)));
1547
+
1548
+            }
1549
+            if (isset($options['timerange']['end'])) {
1550
+                $outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence',
1551
+                    $outerQuery->createNamedParameter($options['timerange']['end']->getTimeStamp)));
1552
+            }
1553
+        }
1554
+
1555
+        if (isset($options['types'])) {
1556
+            $or = $outerQuery->expr()->orX();
1557
+            foreach($options['types'] as $type) {
1558
+                $or->add($outerQuery->expr()->eq('componenttype',
1559
+                    $outerQuery->createNamedParameter($type)));
1560
+            }
1561
+            $outerQuery->andWhere($or);
1562
+        }
1563
+
1564
+        $outerQuery->andWhere($outerQuery->expr()->in('c.id',
1565
+            $outerQuery->createFunction($innerQuery->getSQL())));
1566
+
1567
+        if ($offset) {
1568
+            $outerQuery->setFirstResult($offset);
1569
+        }
1570
+        if ($limit) {
1571
+            $outerQuery->setMaxResults($limit);
1572
+        }
1573
+
1574
+        $result = $outerQuery->execute();
1575
+        $calendarObjects = $result->fetchAll();
1576
+
1577
+        return array_map(function($o) {
1578
+            $calendarData = Reader::read($o['calendardata']);
1579
+            $comps = $calendarData->getComponents();
1580
+            $objects = [];
1581
+            $timezones = [];
1582
+            foreach($comps as $comp) {
1583
+                if ($comp instanceof VTimeZone) {
1584
+                    $timezones[] = $comp;
1585
+                } else {
1586
+                    $objects[] = $comp;
1587
+                }
1588
+            }
1589
+
1590
+            return [
1591
+                'id' => $o['id'],
1592
+                'type' => $o['componenttype'],
1593
+                'uid' => $o['uid'],
1594
+                'uri' => $o['uri'],
1595
+                'objects' => array_map(function($c) {
1596
+                    return $this->transformSearchData($c);
1597
+                }, $objects),
1598
+                'timezones' => array_map(function($c) {
1599
+                    return $this->transformSearchData($c);
1600
+                }, $timezones),
1601
+            ];
1602
+        }, $calendarObjects);
1603
+    }
1604
+
1605
+    /**
1606
+     * @param Component $comp
1607
+     * @return array
1608
+     */
1609
+    private function transformSearchData(Component $comp) {
1610
+        $data = [];
1611
+        /** @var Component[] $subComponents */
1612
+        $subComponents = $comp->getComponents();
1613
+        /** @var Property[] $properties */
1614
+        $properties = array_filter($comp->children(), function($c) {
1615
+            return $c instanceof Property;
1616
+        });
1617
+        $validationRules = $comp->getValidationRules();
1618
+
1619
+        foreach($subComponents as $subComponent) {
1620
+            $name = $subComponent->name;
1621
+            if (!isset($data[$name])) {
1622
+                $data[$name] = [];
1623
+            }
1624
+            $data[$name][] = $this->transformSearchData($subComponent);
1625
+        }
1626
+
1627
+        foreach($properties as $property) {
1628
+            $name = $property->name;
1629
+            if (!isset($validationRules[$name])) {
1630
+                $validationRules[$name] = '*';
1631
+            }
1632
+
1633
+            $rule = $validationRules[$property->name];
1634
+            if ($rule === '+' || $rule === '*') { // multiple
1635
+                if (!isset($data[$name])) {
1636
+                    $data[$name] = [];
1637
+                }
1638
+
1639
+                $data[$name][] = $this->transformSearchProperty($property);
1640
+            } else { // once
1641
+                $data[$name] = $this->transformSearchProperty($property);
1642
+            }
1643
+        }
1644
+
1645
+        return $data;
1646
+    }
1647
+
1648
+    /**
1649
+     * @param Property $prop
1650
+     * @return array
1651
+     */
1652
+    private function transformSearchProperty(Property $prop) {
1653
+        // No need to check Date, as it extends DateTime
1654
+        if ($prop instanceof Property\ICalendar\DateTime) {
1655
+            $value = $prop->getDateTime();
1656
+        } else {
1657
+            $value = $prop->getValue();
1658
+        }
1659
+
1660
+        return [
1661
+            $value,
1662
+            $prop->parameters()
1663
+        ];
1664
+    }
1665
+
1666
+    /**
1667
+     * Searches through all of a users calendars and calendar objects to find
1668
+     * an object with a specific UID.
1669
+     *
1670
+     * This method should return the path to this object, relative to the
1671
+     * calendar home, so this path usually only contains two parts:
1672
+     *
1673
+     * calendarpath/objectpath.ics
1674
+     *
1675
+     * If the uid is not found, return null.
1676
+     *
1677
+     * This method should only consider * objects that the principal owns, so
1678
+     * any calendars owned by other principals that also appear in this
1679
+     * collection should be ignored.
1680
+     *
1681
+     * @param string $principalUri
1682
+     * @param string $uid
1683
+     * @return string|null
1684
+     */
1685
+    function getCalendarObjectByUID($principalUri, $uid) {
1686
+
1687
+        $query = $this->db->getQueryBuilder();
1688
+        $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1689
+            ->from('calendarobjects', 'co')
1690
+            ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1691
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1692
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)))
1693
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1694
+
1695
+        $stmt = $query->execute();
1696
+
1697
+        if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1698
+            return $row['calendaruri'] . '/' . $row['objecturi'];
1699
+        }
1700
+
1701
+        return null;
1702
+    }
1703
+
1704
+    /**
1705
+     * The getChanges method returns all the changes that have happened, since
1706
+     * the specified syncToken in the specified calendar.
1707
+     *
1708
+     * This function should return an array, such as the following:
1709
+     *
1710
+     * [
1711
+     *   'syncToken' => 'The current synctoken',
1712
+     *   'added'   => [
1713
+     *      'new.txt',
1714
+     *   ],
1715
+     *   'modified'   => [
1716
+     *      'modified.txt',
1717
+     *   ],
1718
+     *   'deleted' => [
1719
+     *      'foo.php.bak',
1720
+     *      'old.txt'
1721
+     *   ]
1722
+     * );
1723
+     *
1724
+     * The returned syncToken property should reflect the *current* syncToken
1725
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1726
+     * property This is * needed here too, to ensure the operation is atomic.
1727
+     *
1728
+     * If the $syncToken argument is specified as null, this is an initial
1729
+     * sync, and all members should be reported.
1730
+     *
1731
+     * The modified property is an array of nodenames that have changed since
1732
+     * the last token.
1733
+     *
1734
+     * The deleted property is an array with nodenames, that have been deleted
1735
+     * from collection.
1736
+     *
1737
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
1738
+     * 1, you only have to report changes that happened only directly in
1739
+     * immediate descendants. If it's 2, it should also include changes from
1740
+     * the nodes below the child collections. (grandchildren)
1741
+     *
1742
+     * The $limit argument allows a client to specify how many results should
1743
+     * be returned at most. If the limit is not specified, it should be treated
1744
+     * as infinite.
1745
+     *
1746
+     * If the limit (infinite or not) is higher than you're willing to return,
1747
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1748
+     *
1749
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
1750
+     * return null.
1751
+     *
1752
+     * The limit is 'suggestive'. You are free to ignore it.
1753
+     *
1754
+     * @param string $calendarId
1755
+     * @param string $syncToken
1756
+     * @param int $syncLevel
1757
+     * @param int $limit
1758
+     * @param int $calendarType
1759
+     * @return array
1760
+     */
1761
+    function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1762
+        // Current synctoken
1763
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1764
+        $stmt->execute([ $calendarId ]);
1765
+        $currentToken = $stmt->fetchColumn(0);
1766
+
1767
+        if (is_null($currentToken)) {
1768
+            return null;
1769
+        }
1770
+
1771
+        $result = [
1772
+            'syncToken' => $currentToken,
1773
+            'added'     => [],
1774
+            'modified'  => [],
1775
+            'deleted'   => [],
1776
+        ];
1777
+
1778
+        if ($syncToken) {
1779
+
1780
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? AND `calendartype` = ? ORDER BY `synctoken`";
1781
+            if ($limit>0) {
1782
+                $query.= " LIMIT " . (int)$limit;
1783
+            }
1784
+
1785
+            // Fetching all changes
1786
+            $stmt = $this->db->prepare($query);
1787
+            $stmt->execute([$syncToken, $currentToken, $calendarId, $calendarType]);
1788
+
1789
+            $changes = [];
1790
+
1791
+            // This loop ensures that any duplicates are overwritten, only the
1792
+            // last change on a node is relevant.
1793
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1794
+
1795
+                $changes[$row['uri']] = $row['operation'];
1796
+
1797
+            }
1798
+
1799
+            foreach($changes as $uri => $operation) {
1800
+
1801
+                switch($operation) {
1802
+                    case 1 :
1803
+                        $result['added'][] = $uri;
1804
+                        break;
1805
+                    case 2 :
1806
+                        $result['modified'][] = $uri;
1807
+                        break;
1808
+                    case 3 :
1809
+                        $result['deleted'][] = $uri;
1810
+                        break;
1811
+                }
1812
+
1813
+            }
1814
+        } else {
1815
+            // No synctoken supplied, this is the initial sync.
1816
+            $query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?";
1817
+            $stmt = $this->db->prepare($query);
1818
+            $stmt->execute([$calendarId, $calendarType]);
1819
+
1820
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1821
+        }
1822
+        return $result;
1823
+
1824
+    }
1825
+
1826
+    /**
1827
+     * Returns a list of subscriptions for a principal.
1828
+     *
1829
+     * Every subscription is an array with the following keys:
1830
+     *  * id, a unique id that will be used by other functions to modify the
1831
+     *    subscription. This can be the same as the uri or a database key.
1832
+     *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1833
+     *  * principaluri. The owner of the subscription. Almost always the same as
1834
+     *    principalUri passed to this method.
1835
+     *
1836
+     * Furthermore, all the subscription info must be returned too:
1837
+     *
1838
+     * 1. {DAV:}displayname
1839
+     * 2. {http://apple.com/ns/ical/}refreshrate
1840
+     * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1841
+     *    should not be stripped).
1842
+     * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1843
+     *    should not be stripped).
1844
+     * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1845
+     *    attachments should not be stripped).
1846
+     * 6. {http://calendarserver.org/ns/}source (Must be a
1847
+     *     Sabre\DAV\Property\Href).
1848
+     * 7. {http://apple.com/ns/ical/}calendar-color
1849
+     * 8. {http://apple.com/ns/ical/}calendar-order
1850
+     * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1851
+     *    (should just be an instance of
1852
+     *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1853
+     *    default components).
1854
+     *
1855
+     * @param string $principalUri
1856
+     * @return array
1857
+     */
1858
+    function getSubscriptionsForUser($principalUri) {
1859
+        $fields = array_values($this->subscriptionPropertyMap);
1860
+        $fields[] = 'id';
1861
+        $fields[] = 'uri';
1862
+        $fields[] = 'source';
1863
+        $fields[] = 'principaluri';
1864
+        $fields[] = 'lastmodified';
1865
+        $fields[] = 'synctoken';
1866
+
1867
+        $query = $this->db->getQueryBuilder();
1868
+        $query->select($fields)
1869
+            ->from('calendarsubscriptions')
1870
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1871
+            ->orderBy('calendarorder', 'asc');
1872
+        $stmt =$query->execute();
1873
+
1874
+        $subscriptions = [];
1875
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1876
+
1877
+            $subscription = [
1878
+                'id'           => $row['id'],
1879
+                'uri'          => $row['uri'],
1880
+                'principaluri' => $row['principaluri'],
1881
+                'source'       => $row['source'],
1882
+                'lastmodified' => $row['lastmodified'],
1883
+
1884
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1885
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
1886
+            ];
1887
+
1888
+            foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1889
+                if (!is_null($row[$dbName])) {
1890
+                    $subscription[$xmlName] = $row[$dbName];
1891
+                }
1892
+            }
1893
+
1894
+            $subscriptions[] = $subscription;
1895
+
1896
+        }
1897
+
1898
+        return $subscriptions;
1899
+    }
1900
+
1901
+    /**
1902
+     * Creates a new subscription for a principal.
1903
+     *
1904
+     * If the creation was a success, an id must be returned that can be used to reference
1905
+     * this subscription in other methods, such as updateSubscription.
1906
+     *
1907
+     * @param string $principalUri
1908
+     * @param string $uri
1909
+     * @param array $properties
1910
+     * @return mixed
1911
+     */
1912
+    function createSubscription($principalUri, $uri, array $properties) {
1913
+
1914
+        if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1915
+            throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1916
+        }
1917
+
1918
+        $values = [
1919
+            'principaluri' => $principalUri,
1920
+            'uri'          => $uri,
1921
+            'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1922
+            'lastmodified' => time(),
1923
+        ];
1924
+
1925
+        $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1926
+
1927
+        foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1928
+            if (array_key_exists($xmlName, $properties)) {
1929
+                    $values[$dbName] = $properties[$xmlName];
1930
+                    if (in_array($dbName, $propertiesBoolean)) {
1931
+                        $values[$dbName] = true;
1932
+                }
1933
+            }
1934
+        }
1935
+
1936
+        $valuesToInsert = array();
1937
+
1938
+        $query = $this->db->getQueryBuilder();
1939
+
1940
+        foreach (array_keys($values) as $name) {
1941
+            $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1942
+        }
1943
+
1944
+        $query->insert('calendarsubscriptions')
1945
+            ->values($valuesToInsert)
1946
+            ->execute();
1947
+
1948
+        $subscriptionId = $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1949
+
1950
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createSubscription', new GenericEvent(
1951
+            '\OCA\DAV\CalDAV\CalDavBackend::createSubscription',
1952
+            [
1953
+                'subscriptionId' => $subscriptionId,
1954
+                'subscriptionData' => $this->getSubscriptionById($subscriptionId),
1955
+            ]));
1956
+
1957
+        return $subscriptionId;
1958
+    }
1959
+
1960
+    /**
1961
+     * Updates a subscription
1962
+     *
1963
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1964
+     * To do the actual updates, you must tell this object which properties
1965
+     * you're going to process with the handle() method.
1966
+     *
1967
+     * Calling the handle method is like telling the PropPatch object "I
1968
+     * promise I can handle updating this property".
1969
+     *
1970
+     * Read the PropPatch documentation for more info and examples.
1971
+     *
1972
+     * @param mixed $subscriptionId
1973
+     * @param PropPatch $propPatch
1974
+     * @return void
1975
+     */
1976
+    function updateSubscription($subscriptionId, PropPatch $propPatch) {
1977
+        $supportedProperties = array_keys($this->subscriptionPropertyMap);
1978
+        $supportedProperties[] = '{http://calendarserver.org/ns/}source';
1979
+
1980
+        /**
1981
+         * @suppress SqlInjectionChecker
1982
+         */
1983
+        $propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1984
+
1985
+            $newValues = [];
1986
+
1987
+            foreach($mutations as $propertyName=>$propertyValue) {
1988
+                if ($propertyName === '{http://calendarserver.org/ns/}source') {
1989
+                    $newValues['source'] = $propertyValue->getHref();
1990
+                } else {
1991
+                    $fieldName = $this->subscriptionPropertyMap[$propertyName];
1992
+                    $newValues[$fieldName] = $propertyValue;
1993
+                }
1994
+            }
1995
+
1996
+            $query = $this->db->getQueryBuilder();
1997
+            $query->update('calendarsubscriptions')
1998
+                ->set('lastmodified', $query->createNamedParameter(time()));
1999
+            foreach($newValues as $fieldName=>$value) {
2000
+                $query->set($fieldName, $query->createNamedParameter($value));
2001
+            }
2002
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2003
+                ->execute();
2004
+
2005
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateSubscription', new GenericEvent(
2006
+                '\OCA\DAV\CalDAV\CalDavBackend::updateSubscription',
2007
+                [
2008
+                    'subscriptionId' => $subscriptionId,
2009
+                    'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2010
+                    'propertyMutations' => $mutations,
2011
+                ]));
2012
+
2013
+            return true;
2014
+
2015
+        });
2016
+    }
2017
+
2018
+    /**
2019
+     * Deletes a subscription.
2020
+     *
2021
+     * @param mixed $subscriptionId
2022
+     * @return void
2023
+     */
2024
+    function deleteSubscription($subscriptionId) {
2025
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription', new GenericEvent(
2026
+            '\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription',
2027
+            [
2028
+                'subscriptionId' => $subscriptionId,
2029
+                'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2030
+            ]));
2031
+
2032
+        $query = $this->db->getQueryBuilder();
2033
+        $query->delete('calendarsubscriptions')
2034
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2035
+            ->execute();
2036
+
2037
+        $query = $this->db->getQueryBuilder();
2038
+        $query->delete('calendarobjects')
2039
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2040
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2041
+            ->execute();
2042
+
2043
+        $query->delete('calendarchanges')
2044
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2045
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2046
+            ->execute();
2047
+
2048
+        $query->delete($this->dbObjectPropertiesTable)
2049
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2050
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2051
+            ->execute();
2052
+    }
2053
+
2054
+    /**
2055
+     * Returns a single scheduling object for the inbox collection.
2056
+     *
2057
+     * The returned array should contain the following elements:
2058
+     *   * uri - A unique basename for the object. This will be used to
2059
+     *           construct a full uri.
2060
+     *   * calendardata - The iCalendar object
2061
+     *   * lastmodified - The last modification date. Can be an int for a unix
2062
+     *                    timestamp, or a PHP DateTime object.
2063
+     *   * etag - A unique token that must change if the object changed.
2064
+     *   * size - The size of the object, in bytes.
2065
+     *
2066
+     * @param string $principalUri
2067
+     * @param string $objectUri
2068
+     * @return array
2069
+     */
2070
+    function getSchedulingObject($principalUri, $objectUri) {
2071
+        $query = $this->db->getQueryBuilder();
2072
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2073
+            ->from('schedulingobjects')
2074
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2075
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2076
+            ->execute();
2077
+
2078
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
2079
+
2080
+        if(!$row) {
2081
+            return null;
2082
+        }
2083
+
2084
+        return [
2085
+                'uri'          => $row['uri'],
2086
+                'calendardata' => $row['calendardata'],
2087
+                'lastmodified' => $row['lastmodified'],
2088
+                'etag'         => '"' . $row['etag'] . '"',
2089
+                'size'         => (int)$row['size'],
2090
+        ];
2091
+    }
2092
+
2093
+    /**
2094
+     * Returns all scheduling objects for the inbox collection.
2095
+     *
2096
+     * These objects should be returned as an array. Every item in the array
2097
+     * should follow the same structure as returned from getSchedulingObject.
2098
+     *
2099
+     * The main difference is that 'calendardata' is optional.
2100
+     *
2101
+     * @param string $principalUri
2102
+     * @return array
2103
+     */
2104
+    function getSchedulingObjects($principalUri) {
2105
+        $query = $this->db->getQueryBuilder();
2106
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2107
+                ->from('schedulingobjects')
2108
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2109
+                ->execute();
2110
+
2111
+        $result = [];
2112
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2113
+            $result[] = [
2114
+                    'calendardata' => $row['calendardata'],
2115
+                    'uri'          => $row['uri'],
2116
+                    'lastmodified' => $row['lastmodified'],
2117
+                    'etag'         => '"' . $row['etag'] . '"',
2118
+                    'size'         => (int)$row['size'],
2119
+            ];
2120
+        }
2121
+
2122
+        return $result;
2123
+    }
2124
+
2125
+    /**
2126
+     * Deletes a scheduling object from the inbox collection.
2127
+     *
2128
+     * @param string $principalUri
2129
+     * @param string $objectUri
2130
+     * @return void
2131
+     */
2132
+    function deleteSchedulingObject($principalUri, $objectUri) {
2133
+        $query = $this->db->getQueryBuilder();
2134
+        $query->delete('schedulingobjects')
2135
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2136
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2137
+                ->execute();
2138
+    }
2139
+
2140
+    /**
2141
+     * Creates a new scheduling object. This should land in a users' inbox.
2142
+     *
2143
+     * @param string $principalUri
2144
+     * @param string $objectUri
2145
+     * @param string $objectData
2146
+     * @return void
2147
+     */
2148
+    function createSchedulingObject($principalUri, $objectUri, $objectData) {
2149
+        $query = $this->db->getQueryBuilder();
2150
+        $query->insert('schedulingobjects')
2151
+            ->values([
2152
+                'principaluri' => $query->createNamedParameter($principalUri),
2153
+                'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
2154
+                'uri' => $query->createNamedParameter($objectUri),
2155
+                'lastmodified' => $query->createNamedParameter(time()),
2156
+                'etag' => $query->createNamedParameter(md5($objectData)),
2157
+                'size' => $query->createNamedParameter(strlen($objectData))
2158
+            ])
2159
+            ->execute();
2160
+    }
2161
+
2162
+    /**
2163
+     * Adds a change record to the calendarchanges table.
2164
+     *
2165
+     * @param mixed $calendarId
2166
+     * @param string $objectUri
2167
+     * @param int $operation 1 = add, 2 = modify, 3 = delete.
2168
+     * @param int $calendarType
2169
+     * @return void
2170
+     */
2171
+    protected function addChange($calendarId, $objectUri, $operation, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2172
+        $table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2173
+
2174
+        $query = $this->db->getQueryBuilder();
2175
+        $query->select('synctoken')
2176
+            ->from($table)
2177
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2178
+        $syncToken = (int)$query->execute()->fetchColumn();
2179
+
2180
+        $query = $this->db->getQueryBuilder();
2181
+        $query->insert('calendarchanges')
2182
+            ->values([
2183
+                'uri' => $query->createNamedParameter($objectUri),
2184
+                'synctoken' => $query->createNamedParameter($syncToken),
2185
+                'calendarid' => $query->createNamedParameter($calendarId),
2186
+                'operation' => $query->createNamedParameter($operation),
2187
+                'calendartype' => $query->createNamedParameter($calendarType),
2188
+            ])
2189
+            ->execute();
2190
+
2191
+        $stmt = $this->db->prepare("UPDATE `*PREFIX*$table` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?");
2192
+        $stmt->execute([
2193
+            $calendarId
2194
+        ]);
2195
+
2196
+    }
2197
+
2198
+    /**
2199
+     * Parses some information from calendar objects, used for optimized
2200
+     * calendar-queries.
2201
+     *
2202
+     * Returns an array with the following keys:
2203
+     *   * etag - An md5 checksum of the object without the quotes.
2204
+     *   * size - Size of the object in bytes
2205
+     *   * componentType - VEVENT, VTODO or VJOURNAL
2206
+     *   * firstOccurence
2207
+     *   * lastOccurence
2208
+     *   * uid - value of the UID property
2209
+     *
2210
+     * @param string $calendarData
2211
+     * @return array
2212
+     */
2213
+    public function getDenormalizedData($calendarData) {
2214
+
2215
+        $vObject = Reader::read($calendarData);
2216
+        $componentType = null;
2217
+        $component = null;
2218
+        $firstOccurrence = null;
2219
+        $lastOccurrence = null;
2220
+        $uid = null;
2221
+        $classification = self::CLASSIFICATION_PUBLIC;
2222
+        foreach($vObject->getComponents() as $component) {
2223
+            if ($component->name!=='VTIMEZONE') {
2224
+                $componentType = $component->name;
2225
+                $uid = (string)$component->UID;
2226
+                break;
2227
+            }
2228
+        }
2229
+        if (!$componentType) {
2230
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
2231
+        }
2232
+        if ($componentType === 'VEVENT' && $component->DTSTART) {
2233
+            $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
2234
+            // Finding the last occurrence is a bit harder
2235
+            if (!isset($component->RRULE)) {
2236
+                if (isset($component->DTEND)) {
2237
+                    $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
2238
+                } elseif (isset($component->DURATION)) {
2239
+                    $endDate = clone $component->DTSTART->getDateTime();
2240
+                    $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
2241
+                    $lastOccurrence = $endDate->getTimeStamp();
2242
+                } elseif (!$component->DTSTART->hasTime()) {
2243
+                    $endDate = clone $component->DTSTART->getDateTime();
2244
+                    $endDate->modify('+1 day');
2245
+                    $lastOccurrence = $endDate->getTimeStamp();
2246
+                } else {
2247
+                    $lastOccurrence = $firstOccurrence;
2248
+                }
2249
+            } else {
2250
+                $it = new EventIterator($vObject, (string)$component->UID);
2251
+                $maxDate = new \DateTime(self::MAX_DATE);
2252
+                if ($it->isInfinite()) {
2253
+                    $lastOccurrence = $maxDate->getTimestamp();
2254
+                } else {
2255
+                    $end = $it->getDtEnd();
2256
+                    while($it->valid() && $end < $maxDate) {
2257
+                        $end = $it->getDtEnd();
2258
+                        $it->next();
2259
+
2260
+                    }
2261
+                    $lastOccurrence = $end->getTimestamp();
2262
+                }
2263
+
2264
+            }
2265
+        }
2266
+
2267
+        if ($component->CLASS) {
2268
+            $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
2269
+            switch ($component->CLASS->getValue()) {
2270
+                case 'PUBLIC':
2271
+                    $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
2272
+                    break;
2273
+                case 'CONFIDENTIAL':
2274
+                    $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
2275
+                    break;
2276
+            }
2277
+        }
2278
+        return [
2279
+            'etag' => md5($calendarData),
2280
+            'size' => strlen($calendarData),
2281
+            'componentType' => $componentType,
2282
+            'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
2283
+            'lastOccurence'  => $lastOccurrence,
2284
+            'uid' => $uid,
2285
+            'classification' => $classification
2286
+        ];
2287
+
2288
+    }
2289
+
2290
+    /**
2291
+     * @param $cardData
2292
+     * @return bool|string
2293
+     */
2294
+    private function readBlob($cardData) {
2295
+        if (is_resource($cardData)) {
2296
+            return stream_get_contents($cardData);
2297
+        }
2298
+
2299
+        return $cardData;
2300
+    }
2301
+
2302
+    /**
2303
+     * @param IShareable $shareable
2304
+     * @param array $add
2305
+     * @param array $remove
2306
+     */
2307
+    public function updateShares($shareable, $add, $remove) {
2308
+        $calendarId = $shareable->getResourceId();
2309
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
2310
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2311
+            [
2312
+                'calendarId' => $calendarId,
2313
+                'calendarData' => $this->getCalendarById($calendarId),
2314
+                'shares' => $this->getShares($calendarId),
2315
+                'add' => $add,
2316
+                'remove' => $remove,
2317
+            ]));
2318
+        $this->calendarSharingBackend->updateShares($shareable, $add, $remove);
2319
+    }
2320
+
2321
+    /**
2322
+     * @param int $resourceId
2323
+     * @param int $calendarType
2324
+     * @return array
2325
+     */
2326
+    public function getShares($resourceId, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2327
+        return $this->calendarSharingBackend->getShares($resourceId);
2328
+    }
2329
+
2330
+    /**
2331
+     * @param boolean $value
2332
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
2333
+     * @return string|null
2334
+     */
2335
+    public function setPublishStatus($value, $calendar) {
2336
+
2337
+        $calendarId = $calendar->getResourceId();
2338
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', new GenericEvent(
2339
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2340
+            [
2341
+                'calendarId' => $calendarId,
2342
+                'calendarData' => $this->getCalendarById($calendarId),
2343
+                'public' => $value,
2344
+            ]));
2345
+
2346
+        $query = $this->db->getQueryBuilder();
2347
+        if ($value) {
2348
+            $publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
2349
+            $query->insert('dav_shares')
2350
+                ->values([
2351
+                    'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
2352
+                    'type' => $query->createNamedParameter('calendar'),
2353
+                    'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
2354
+                    'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
2355
+                    'publicuri' => $query->createNamedParameter($publicUri)
2356
+                ]);
2357
+            $query->execute();
2358
+            return $publicUri;
2359
+        }
2360
+        $query->delete('dav_shares')
2361
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2362
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
2363
+        $query->execute();
2364
+        return null;
2365
+    }
2366
+
2367
+    /**
2368
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
2369
+     * @return mixed
2370
+     */
2371
+    public function getPublishStatus($calendar) {
2372
+        $query = $this->db->getQueryBuilder();
2373
+        $result = $query->select('publicuri')
2374
+            ->from('dav_shares')
2375
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2376
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
2377
+            ->execute();
2378
+
2379
+        $row = $result->fetch();
2380
+        $result->closeCursor();
2381
+        return $row ? reset($row) : false;
2382
+    }
2383
+
2384
+    /**
2385
+     * @param int $resourceId
2386
+     * @param array $acl
2387
+     * @return array
2388
+     */
2389
+    public function applyShareAcl($resourceId, $acl) {
2390
+        return $this->calendarSharingBackend->applyShareAcl($resourceId, $acl);
2391
+    }
2392
+
2393
+
2394
+
2395
+    /**
2396
+     * update properties table
2397
+     *
2398
+     * @param int $calendarId
2399
+     * @param string $objectUri
2400
+     * @param string $calendarData
2401
+     * @param int $calendarType
2402
+     */
2403
+    public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2404
+        $objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
2405
+
2406
+        try {
2407
+            $vCalendar = $this->readCalendarData($calendarData);
2408
+        } catch (\Exception $ex) {
2409
+            return;
2410
+        }
2411
+
2412
+        $this->purgeProperties($calendarId, $objectId);
2413
+
2414
+        $query = $this->db->getQueryBuilder();
2415
+        $query->insert($this->dbObjectPropertiesTable)
2416
+            ->values(
2417
+                [
2418
+                    'calendarid' => $query->createNamedParameter($calendarId),
2419
+                    'calendartype' => $query->createNamedParameter($calendarType),
2420
+                    'objectid' => $query->createNamedParameter($objectId),
2421
+                    'name' => $query->createParameter('name'),
2422
+                    'parameter' => $query->createParameter('parameter'),
2423
+                    'value' => $query->createParameter('value'),
2424
+                ]
2425
+            );
2426
+
2427
+        $indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
2428
+        foreach ($vCalendar->getComponents() as $component) {
2429
+            if (!in_array($component->name, $indexComponents)) {
2430
+                continue;
2431
+            }
2432
+
2433
+            foreach ($component->children() as $property) {
2434
+                if (in_array($property->name, self::$indexProperties)) {
2435
+                    $value = $property->getValue();
2436
+                    // is this a shitty db?
2437
+                    if (!$this->db->supports4ByteText()) {
2438
+                        $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2439
+                    }
2440
+                    $value = mb_substr($value, 0, 254);
2441
+
2442
+                    $query->setParameter('name', $property->name);
2443
+                    $query->setParameter('parameter', null);
2444
+                    $query->setParameter('value', $value);
2445
+                    $query->execute();
2446
+                }
2447
+
2448
+                if (array_key_exists($property->name, self::$indexParameters)) {
2449
+                    $parameters = $property->parameters();
2450
+                    $indexedParametersForProperty = self::$indexParameters[$property->name];
2451
+
2452
+                    foreach ($parameters as $key => $value) {
2453
+                        if (in_array($key, $indexedParametersForProperty)) {
2454
+                            // is this a shitty db?
2455
+                            if ($this->db->supports4ByteText()) {
2456
+                                $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2457
+                            }
2458
+                            $value = mb_substr($value, 0, 254);
2459
+
2460
+                            $query->setParameter('name', $property->name);
2461
+                            $query->setParameter('parameter', substr($key, 0, 254));
2462
+                            $query->setParameter('value', substr($value, 0, 254));
2463
+                            $query->execute();
2464
+                        }
2465
+                    }
2466
+                }
2467
+            }
2468
+        }
2469
+    }
2470
+
2471
+    /**
2472
+     * deletes all birthday calendars
2473
+     */
2474
+    public function deleteAllBirthdayCalendars() {
2475
+        $query = $this->db->getQueryBuilder();
2476
+        $result = $query->select(['id'])->from('calendars')
2477
+            ->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
2478
+            ->execute();
2479
+
2480
+        $ids = $result->fetchAll();
2481
+        foreach($ids as $id) {
2482
+            $this->deleteCalendar($id['id']);
2483
+        }
2484
+    }
2485
+
2486
+    /**
2487
+     * @param $subscriptionId
2488
+     */
2489
+    public function purgeAllCachedEventsForSubscription($subscriptionId) {
2490
+        $query = $this->db->getQueryBuilder();
2491
+        $query->select('uri')
2492
+            ->from('calendarobjects')
2493
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2494
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
2495
+        $stmt = $query->execute();
2496
+
2497
+        $uris = [];
2498
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2499
+            $uris[] = $row['uri'];
2500
+        }
2501
+        $stmt->closeCursor();
2502
+
2503
+        $query = $this->db->getQueryBuilder();
2504
+        $query->delete('calendarobjects')
2505
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2506
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2507
+            ->execute();
2508
+
2509
+        $query->delete('calendarchanges')
2510
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2511
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2512
+            ->execute();
2513
+
2514
+        $query->delete($this->dbObjectPropertiesTable)
2515
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2516
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2517
+            ->execute();
2518
+
2519
+        foreach($uris as $uri) {
2520
+            $this->addChange($subscriptionId, $uri, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
2521
+        }
2522
+    }
2523
+
2524
+    /**
2525
+     * read VCalendar data into a VCalendar object
2526
+     *
2527
+     * @param string $objectData
2528
+     * @return VCalendar
2529
+     */
2530
+    protected function readCalendarData($objectData) {
2531
+        return Reader::read($objectData);
2532
+    }
2533
+
2534
+    /**
2535
+     * delete all properties from a given calendar object
2536
+     *
2537
+     * @param int $calendarId
2538
+     * @param int $objectId
2539
+     */
2540
+    protected function purgeProperties($calendarId, $objectId) {
2541
+        $query = $this->db->getQueryBuilder();
2542
+        $query->delete($this->dbObjectPropertiesTable)
2543
+            ->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
2544
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2545
+        $query->execute();
2546
+    }
2547
+
2548
+    /**
2549
+     * get ID from a given calendar object
2550
+     *
2551
+     * @param int $calendarId
2552
+     * @param string $uri
2553
+     * @param int $calendarType
2554
+     * @return int
2555
+     */
2556
+    protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
2557
+        $query = $this->db->getQueryBuilder();
2558
+        $query->select('id')
2559
+            ->from('calendarobjects')
2560
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2561
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
2562
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
2563
+
2564
+        $result = $query->execute();
2565
+        $objectIds = $result->fetch();
2566
+        $result->closeCursor();
2567
+
2568
+        if (!isset($objectIds['id'])) {
2569
+            throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2570
+        }
2571
+
2572
+        return (int)$objectIds['id'];
2573
+    }
2574
+
2575
+    /**
2576
+     * return legacy endpoint principal name to new principal name
2577
+     *
2578
+     * @param $principalUri
2579
+     * @param $toV2
2580
+     * @return string
2581
+     */
2582
+    private function convertPrincipal($principalUri, $toV2) {
2583
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
2584
+            list(, $name) = Uri\split($principalUri);
2585
+            if ($toV2 === true) {
2586
+                return "principals/users/$name";
2587
+            }
2588
+            return "principals/$name";
2589
+        }
2590
+        return $principalUri;
2591
+    }
2592
+
2593
+    /**
2594
+     * adds information about an owner to the calendar data
2595
+     *
2596
+     * @param $calendarInfo
2597
+     */
2598
+    private function addOwnerPrincipal(&$calendarInfo) {
2599
+        $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2600
+        $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2601
+        if (isset($calendarInfo[$ownerPrincipalKey])) {
2602
+            $uri = $calendarInfo[$ownerPrincipalKey];
2603
+        } else {
2604
+            $uri = $calendarInfo['principaluri'];
2605
+        }
2606
+
2607
+        $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
2608
+        if (isset($principalInformation['{DAV:}displayname'])) {
2609
+            $calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
2610
+        }
2611
+    }
2612 2612
 }
Please login to merge, or discard this patch.
Spacing   +150 added lines, -150 removed lines patch added patch discarded remove patch
@@ -221,7 +221,7 @@  discard block
 block discarded – undo
221 221
 			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
222 222
 		}
223 223
 
224
-		return (int)$query->execute()->fetchColumn();
224
+		return (int) $query->execute()->fetchColumn();
225 225
 	}
226 226
 
227 227
 	/**
@@ -268,25 +268,25 @@  discard block
 block discarded – undo
268 268
 		$stmt = $query->execute();
269 269
 
270 270
 		$calendars = [];
271
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
271
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
272 272
 
273 273
 			$components = [];
274 274
 			if ($row['components']) {
275
-				$components = explode(',',$row['components']);
275
+				$components = explode(',', $row['components']);
276 276
 			}
277 277
 
278 278
 			$calendar = [
279 279
 				'id' => $row['id'],
280 280
 				'uri' => $row['uri'],
281 281
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
282
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
283
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
284
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
285
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
286
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
282
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
283
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
284
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
285
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
286
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
287 287
 			];
288 288
 
289
-			foreach($this->propertyMap as $xmlName=>$dbName) {
289
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
290 290
 				$calendar[$xmlName] = $row[$dbName];
291 291
 			}
292 292
 
@@ -304,7 +304,7 @@  discard block
 block discarded – undo
304 304
 		$principals = array_map(function($principal) {
305 305
 			return urldecode($principal);
306 306
 		}, $principals);
307
-		$principals[]= $principalUri;
307
+		$principals[] = $principalUri;
308 308
 
309 309
 		$fields = array_values($this->propertyMap);
310 310
 		$fields[] = 'a.id';
@@ -324,8 +324,8 @@  discard block
 block discarded – undo
324 324
 			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
325 325
 			->execute();
326 326
 
327
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
328
-		while($row = $result->fetch()) {
327
+		$readOnlyPropertyName = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only';
328
+		while ($row = $result->fetch()) {
329 329
 			if ($row['principaluri'] === $principalUri) {
330 330
 				continue;
331 331
 			}
@@ -344,25 +344,25 @@  discard block
 block discarded – undo
344 344
 			}
345 345
 
346 346
 			list(, $name) = Uri\split($row['principaluri']);
347
-			$uri = $row['uri'] . '_shared_by_' . $name;
348
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
347
+			$uri = $row['uri'].'_shared_by_'.$name;
348
+			$row['displayname'] = $row['displayname'].' ('.$this->getUserDisplayName($name).')';
349 349
 			$components = [];
350 350
 			if ($row['components']) {
351
-				$components = explode(',',$row['components']);
351
+				$components = explode(',', $row['components']);
352 352
 			}
353 353
 			$calendar = [
354 354
 				'id' => $row['id'],
355 355
 				'uri' => $uri,
356 356
 				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
357
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
358
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
359
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
360
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
361
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
357
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
358
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
359
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
360
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
361
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
362 362
 				$readOnlyPropertyName => $readOnly,
363 363
 			];
364 364
 
365
-			foreach($this->propertyMap as $xmlName=>$dbName) {
365
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
366 366
 				$calendar[$xmlName] = $row[$dbName];
367 367
 			}
368 368
 
@@ -395,21 +395,21 @@  discard block
 block discarded – undo
395 395
 			->orderBy('calendarorder', 'ASC');
396 396
 		$stmt = $query->execute();
397 397
 		$calendars = [];
398
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
398
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
399 399
 			$components = [];
400 400
 			if ($row['components']) {
401
-				$components = explode(',',$row['components']);
401
+				$components = explode(',', $row['components']);
402 402
 			}
403 403
 			$calendar = [
404 404
 				'id' => $row['id'],
405 405
 				'uri' => $row['uri'],
406 406
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
407
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
408
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
409
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
410
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
407
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
408
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
409
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
410
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
411 411
 			];
412
-			foreach($this->propertyMap as $xmlName=>$dbName) {
412
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
413 413
 				$calendar[$xmlName] = $row[$dbName];
414 414
 			}
415 415
 
@@ -464,27 +464,27 @@  discard block
 block discarded – undo
464 464
 			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
465 465
 			->execute();
466 466
 
467
-		while($row = $result->fetch()) {
467
+		while ($row = $result->fetch()) {
468 468
 			list(, $name) = Uri\split($row['principaluri']);
469
-			$row['displayname'] = $row['displayname'] . "($name)";
469
+			$row['displayname'] = $row['displayname']."($name)";
470 470
 			$components = [];
471 471
 			if ($row['components']) {
472
-				$components = explode(',',$row['components']);
472
+				$components = explode(',', $row['components']);
473 473
 			}
474 474
 			$calendar = [
475 475
 				'id' => $row['id'],
476 476
 				'uri' => $row['publicuri'],
477 477
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
478
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
479
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
480
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
481
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
482
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
483
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
484
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
478
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
479
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
480
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
481
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
482
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
483
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
484
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
485 485
 			];
486 486
 
487
-			foreach($this->propertyMap as $xmlName=>$dbName) {
487
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
488 488
 				$calendar[$xmlName] = $row[$dbName];
489 489
 			}
490 490
 
@@ -528,29 +528,29 @@  discard block
 block discarded – undo
528 528
 		$result->closeCursor();
529 529
 
530 530
 		if ($row === false) {
531
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
531
+			throw new NotFound('Node with name \''.$uri.'\' could not be found');
532 532
 		}
533 533
 
534 534
 		list(, $name) = Uri\split($row['principaluri']);
535
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
535
+		$row['displayname'] = $row['displayname'].' '."($name)";
536 536
 		$components = [];
537 537
 		if ($row['components']) {
538
-			$components = explode(',',$row['components']);
538
+			$components = explode(',', $row['components']);
539 539
 		}
540 540
 		$calendar = [
541 541
 			'id' => $row['id'],
542 542
 			'uri' => $row['publicuri'],
543 543
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
544
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
545
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
546
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
547
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
548
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
549
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
550
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
544
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
545
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
546
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
547
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
548
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
549
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
550
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
551 551
 		];
552 552
 
553
-		foreach($this->propertyMap as $xmlName=>$dbName) {
553
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
554 554
 			$calendar[$xmlName] = $row[$dbName];
555 555
 		}
556 556
 
@@ -590,20 +590,20 @@  discard block
 block discarded – undo
590 590
 
591 591
 		$components = [];
592 592
 		if ($row['components']) {
593
-			$components = explode(',',$row['components']);
593
+			$components = explode(',', $row['components']);
594 594
 		}
595 595
 
596 596
 		$calendar = [
597 597
 			'id' => $row['id'],
598 598
 			'uri' => $row['uri'],
599 599
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
600
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
601
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
602
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
603
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
600
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
601
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
602
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
603
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
604 604
 		];
605 605
 
606
-		foreach($this->propertyMap as $xmlName=>$dbName) {
606
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
607 607
 			$calendar[$xmlName] = $row[$dbName];
608 608
 		}
609 609
 
@@ -640,20 +640,20 @@  discard block
 block discarded – undo
640 640
 
641 641
 		$components = [];
642 642
 		if ($row['components']) {
643
-			$components = explode(',',$row['components']);
643
+			$components = explode(',', $row['components']);
644 644
 		}
645 645
 
646 646
 		$calendar = [
647 647
 			'id' => $row['id'],
648 648
 			'uri' => $row['uri'],
649 649
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
650
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
651
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
652
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
653
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
650
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
651
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
652
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
653
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
654 654
 		];
655 655
 
656
-		foreach($this->propertyMap as $xmlName=>$dbName) {
656
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
657 657
 			$calendar[$xmlName] = $row[$dbName];
658 658
 		}
659 659
 
@@ -679,7 +679,7 @@  discard block
 block discarded – undo
679 679
 			->from('calendarsubscriptions')
680 680
 			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
681 681
 			->orderBy('calendarorder', 'asc');
682
-		$stmt =$query->execute();
682
+		$stmt = $query->execute();
683 683
 
684 684
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
685 685
 		$stmt->closeCursor();
@@ -693,11 +693,11 @@  discard block
 block discarded – undo
693 693
 			'principaluri' => $row['principaluri'],
694 694
 			'source'       => $row['source'],
695 695
 			'lastmodified' => $row['lastmodified'],
696
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
697
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
696
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
697
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
698 698
 		];
699 699
 
700
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
700
+		foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
701 701
 			if (!is_null($row[$dbName])) {
702 702
 				$subscription[$xmlName] = $row[$dbName];
703 703
 			}
@@ -732,16 +732,16 @@  discard block
 block discarded – undo
732 732
 		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
733 733
 		if (isset($properties[$sccs])) {
734 734
 			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
735
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
735
+				throw new DAV\Exception('The '.$sccs.' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
736 736
 			}
737
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
737
+			$values['components'] = implode(',', $properties[$sccs]->getValue());
738 738
 		}
739
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
739
+		$transp = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
740 740
 		if (isset($properties[$transp])) {
741 741
 			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
742 742
 		}
743 743
 
744
-		foreach($this->propertyMap as $xmlName=>$dbName) {
744
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
745 745
 			if (isset($properties[$xmlName])) {
746 746
 				$values[$dbName] = $properties[$xmlName];
747 747
 			}
@@ -749,7 +749,7 @@  discard block
 block discarded – undo
749 749
 
750 750
 		$query = $this->db->getQueryBuilder();
751 751
 		$query->insert('calendars');
752
-		foreach($values as $column => $value) {
752
+		foreach ($values as $column => $value) {
753 753
 			$query->setValue($column, $query->createNamedParameter($value));
754 754
 		}
755 755
 		$query->execute();
@@ -783,7 +783,7 @@  discard block
 block discarded – undo
783 783
 	 */
784 784
 	function updateCalendar($calendarId, PropPatch $propPatch) {
785 785
 		$supportedProperties = array_keys($this->propertyMap);
786
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
786
+		$supportedProperties[] = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
787 787
 
788 788
 		/**
789 789
 		 * @suppress SqlInjectionChecker
@@ -793,7 +793,7 @@  discard block
 block discarded – undo
793 793
 			foreach ($mutations as $propertyName => $propertyValue) {
794 794
 
795 795
 				switch ($propertyName) {
796
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
796
+					case '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' :
797 797
 						$fieldName = 'transparent';
798 798
 						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
799 799
 						break;
@@ -902,7 +902,7 @@  discard block
 block discarded – undo
902 902
 	 * @param int $calendarType
903 903
 	 * @return array
904 904
 	 */
905
-	public function getCalendarObjects($id, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
905
+	public function getCalendarObjects($id, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
906 906
 		$query = $this->db->getQueryBuilder();
907 907
 		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
908 908
 			->from('calendarobjects')
@@ -911,16 +911,16 @@  discard block
 block discarded – undo
911 911
 		$stmt = $query->execute();
912 912
 
913 913
 		$result = [];
914
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
914
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
915 915
 			$result[] = [
916 916
 				'id'           => $row['id'],
917 917
 				'uri'          => $row['uri'],
918 918
 				'lastmodified' => $row['lastmodified'],
919
-				'etag'         => '"' . $row['etag'] . '"',
919
+				'etag'         => '"'.$row['etag'].'"',
920 920
 				'calendarid'   => $row['calendarid'],
921
-				'size'         => (int)$row['size'],
921
+				'size'         => (int) $row['size'],
922 922
 				'component'    => strtolower($row['componenttype']),
923
-				'classification'=> (int)$row['classification']
923
+				'classification'=> (int) $row['classification']
924 924
 			];
925 925
 		}
926 926
 
@@ -944,7 +944,7 @@  discard block
 block discarded – undo
944 944
 	 * @param int $calendarType
945 945
 	 * @return array|null
946 946
 	 */
947
-	public function getCalendarObject($id, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
947
+	public function getCalendarObject($id, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
948 948
 		$query = $this->db->getQueryBuilder();
949 949
 		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
950 950
 			->from('calendarobjects')
@@ -954,7 +954,7 @@  discard block
 block discarded – undo
954 954
 		$stmt = $query->execute();
955 955
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
956 956
 
957
-		if(!$row) {
957
+		if (!$row) {
958 958
 			return null;
959 959
 		}
960 960
 
@@ -962,12 +962,12 @@  discard block
 block discarded – undo
962 962
 			'id'            => $row['id'],
963 963
 			'uri'           => $row['uri'],
964 964
 			'lastmodified'  => $row['lastmodified'],
965
-			'etag'          => '"' . $row['etag'] . '"',
965
+			'etag'          => '"'.$row['etag'].'"',
966 966
 			'calendarid'    => $row['calendarid'],
967
-			'size'          => (int)$row['size'],
967
+			'size'          => (int) $row['size'],
968 968
 			'calendardata'  => $this->readBlob($row['calendardata']),
969 969
 			'component'     => strtolower($row['componenttype']),
970
-			'classification'=> (int)$row['classification']
970
+			'classification'=> (int) $row['classification']
971 971
 		];
972 972
 	}
973 973
 
@@ -984,7 +984,7 @@  discard block
 block discarded – undo
984 984
 	 * @param int $calendarType
985 985
 	 * @return array
986 986
 	 */
987
-	public function getMultipleCalendarObjects($id, array $uris, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
987
+	public function getMultipleCalendarObjects($id, array $uris, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
988 988
 		if (empty($uris)) {
989 989
 			return [];
990 990
 		}
@@ -1008,12 +1008,12 @@  discard block
 block discarded – undo
1008 1008
 					'id'           => $row['id'],
1009 1009
 					'uri'          => $row['uri'],
1010 1010
 					'lastmodified' => $row['lastmodified'],
1011
-					'etag'         => '"' . $row['etag'] . '"',
1011
+					'etag'         => '"'.$row['etag'].'"',
1012 1012
 					'calendarid'   => $row['calendarid'],
1013
-					'size'         => (int)$row['size'],
1013
+					'size'         => (int) $row['size'],
1014 1014
 					'calendardata' => $this->readBlob($row['calendardata']),
1015 1015
 					'component'    => strtolower($row['componenttype']),
1016
-					'classification' => (int)$row['classification']
1016
+					'classification' => (int) $row['classification']
1017 1017
 				];
1018 1018
 			}
1019 1019
 			$result->closeCursor();
@@ -1041,7 +1041,7 @@  discard block
 block discarded – undo
1041 1041
 	 * @param int $calendarType
1042 1042
 	 * @return string
1043 1043
 	 */
1044
-	function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1044
+	function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1045 1045
 		$extraData = $this->getDenormalizedData($calendarData);
1046 1046
 
1047 1047
 		$q = $this->db->getQueryBuilder();
@@ -1102,7 +1102,7 @@  discard block
 block discarded – undo
1102 1102
 		}
1103 1103
 		$this->addChange($calendarId, $objectUri, 1, $calendarType);
1104 1104
 
1105
-		return '"' . $extraData['etag'] . '"';
1105
+		return '"'.$extraData['etag'].'"';
1106 1106
 	}
1107 1107
 
1108 1108
 	/**
@@ -1124,7 +1124,7 @@  discard block
 block discarded – undo
1124 1124
 	 * @param int $calendarType
1125 1125
 	 * @return string
1126 1126
 	 */
1127
-	function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1127
+	function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1128 1128
 		$extraData = $this->getDenormalizedData($calendarData);
1129 1129
 
1130 1130
 		$query = $this->db->getQueryBuilder();
@@ -1171,7 +1171,7 @@  discard block
 block discarded – undo
1171 1171
 		}
1172 1172
 		$this->addChange($calendarId, $objectUri, 2, $calendarType);
1173 1173
 
1174
-		return '"' . $extraData['etag'] . '"';
1174
+		return '"'.$extraData['etag'].'"';
1175 1175
 	}
1176 1176
 
1177 1177
 	/**
@@ -1201,7 +1201,7 @@  discard block
 block discarded – undo
1201 1201
 	 * @param int $calendarType
1202 1202
 	 * @return void
1203 1203
 	 */
1204
-	function deleteCalendarObject($calendarId, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1204
+	function deleteCalendarObject($calendarId, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1205 1205
 		$data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1206 1206
 		if (is_array($data)) {
1207 1207
 			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
@@ -1285,7 +1285,7 @@  discard block
 block discarded – undo
1285 1285
 	 * @param int $calendarType
1286 1286
 	 * @return array
1287 1287
 	 */
1288
-	public function calendarQuery($id, array $filters, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
1288
+	public function calendarQuery($id, array $filters, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1289 1289
 		$componentType = null;
1290 1290
 		$requirePostFilter = true;
1291 1291
 		$timeRange = null;
@@ -1339,13 +1339,13 @@  discard block
 block discarded – undo
1339 1339
 		$stmt = $query->execute();
1340 1340
 
1341 1341
 		$result = [];
1342
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1342
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1343 1343
 			if ($requirePostFilter) {
1344 1344
 				// validateFilterForObject will parse the calendar data
1345 1345
 				// catch parsing errors
1346 1346
 				try {
1347 1347
 					$matches = $this->validateFilterForObject($row, $filters);
1348
-				} catch(ParseException $ex) {
1348
+				} catch (ParseException $ex) {
1349 1349
 					$this->logger->logException($ex, [
1350 1350
 						'app' => 'dav',
1351 1351
 						'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
@@ -1380,14 +1380,14 @@  discard block
 block discarded – undo
1380 1380
 	 * @param integer|null $offset
1381 1381
 	 * @return array
1382 1382
 	 */
1383
-	public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1383
+	public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) {
1384 1384
 		$calendars = $this->getCalendarsForUser($principalUri);
1385 1385
 		$ownCalendars = [];
1386 1386
 		$sharedCalendars = [];
1387 1387
 
1388 1388
 		$uriMapper = [];
1389 1389
 
1390
-		foreach($calendars as $calendar) {
1390
+		foreach ($calendars as $calendar) {
1391 1391
 			if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1392 1392
 				$ownCalendars[] = $calendar['id'];
1393 1393
 			} else {
@@ -1402,14 +1402,14 @@  discard block
 block discarded – undo
1402 1402
 		$query = $this->db->getQueryBuilder();
1403 1403
 		// Calendar id expressions
1404 1404
 		$calendarExpressions = [];
1405
-		foreach($ownCalendars as $id) {
1405
+		foreach ($ownCalendars as $id) {
1406 1406
 			$calendarExpressions[] = $query->expr()->andX(
1407 1407
 				$query->expr()->eq('c.calendarid',
1408 1408
 					$query->createNamedParameter($id)),
1409 1409
 				$query->expr()->eq('c.calendartype',
1410 1410
 						$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1411 1411
 		}
1412
-		foreach($sharedCalendars as $id) {
1412
+		foreach ($sharedCalendars as $id) {
1413 1413
 			$calendarExpressions[] = $query->expr()->andX(
1414 1414
 				$query->expr()->eq('c.calendarid',
1415 1415
 					$query->createNamedParameter($id)),
@@ -1427,7 +1427,7 @@  discard block
 block discarded – undo
1427 1427
 
1428 1428
 		// Component expressions
1429 1429
 		$compExpressions = [];
1430
-		foreach($filters['comps'] as $comp) {
1430
+		foreach ($filters['comps'] as $comp) {
1431 1431
 			$compExpressions[] = $query->expr()
1432 1432
 				->eq('c.componenttype', $query->createNamedParameter($comp));
1433 1433
 		}
@@ -1446,13 +1446,13 @@  discard block
 block discarded – undo
1446 1446
 		}
1447 1447
 
1448 1448
 		$propParamExpressions = [];
1449
-		foreach($filters['props'] as $prop) {
1449
+		foreach ($filters['props'] as $prop) {
1450 1450
 			$propParamExpressions[] = $query->expr()->andX(
1451 1451
 				$query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1452 1452
 				$query->expr()->isNull('i.parameter')
1453 1453
 			);
1454 1454
 		}
1455
-		foreach($filters['params'] as $param) {
1455
+		foreach ($filters['params'] as $param) {
1456 1456
 			$propParamExpressions[] = $query->expr()->andX(
1457 1457
 				$query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1458 1458
 				$query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
@@ -1484,8 +1484,8 @@  discard block
 block discarded – undo
1484 1484
 		$stmt = $query->execute();
1485 1485
 
1486 1486
 		$result = [];
1487
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1488
-			$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1487
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1488
+			$path = $uriMapper[$row['calendarid']].'/'.$row['uri'];
1489 1489
 			if (!in_array($path, $result)) {
1490 1490
 				$result[] = $path;
1491 1491
 			}
@@ -1525,7 +1525,7 @@  discard block
 block discarded – undo
1525 1525
 		}
1526 1526
 
1527 1527
 		$or = $innerQuery->expr()->orX();
1528
-		foreach($searchProperties as $searchProperty) {
1528
+		foreach ($searchProperties as $searchProperty) {
1529 1529
 			$or->add($innerQuery->expr()->eq('op.name',
1530 1530
 				$outerQuery->createNamedParameter($searchProperty)));
1531 1531
 		}
@@ -1533,8 +1533,8 @@  discard block
 block discarded – undo
1533 1533
 
1534 1534
 		if ($pattern !== '') {
1535 1535
 			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1536
-				$outerQuery->createNamedParameter('%' .
1537
-					$this->db->escapeLikeParameter($pattern) . '%')));
1536
+				$outerQuery->createNamedParameter('%'.
1537
+					$this->db->escapeLikeParameter($pattern).'%')));
1538 1538
 		}
1539 1539
 
1540 1540
 		$outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
@@ -1554,7 +1554,7 @@  discard block
 block discarded – undo
1554 1554
 
1555 1555
 		if (isset($options['types'])) {
1556 1556
 			$or = $outerQuery->expr()->orX();
1557
-			foreach($options['types'] as $type) {
1557
+			foreach ($options['types'] as $type) {
1558 1558
 				$or->add($outerQuery->expr()->eq('componenttype',
1559 1559
 					$outerQuery->createNamedParameter($type)));
1560 1560
 			}
@@ -1579,7 +1579,7 @@  discard block
 block discarded – undo
1579 1579
 			$comps = $calendarData->getComponents();
1580 1580
 			$objects = [];
1581 1581
 			$timezones = [];
1582
-			foreach($comps as $comp) {
1582
+			foreach ($comps as $comp) {
1583 1583
 				if ($comp instanceof VTimeZone) {
1584 1584
 					$timezones[] = $comp;
1585 1585
 				} else {
@@ -1616,7 +1616,7 @@  discard block
 block discarded – undo
1616 1616
 		});
1617 1617
 		$validationRules = $comp->getValidationRules();
1618 1618
 
1619
-		foreach($subComponents as $subComponent) {
1619
+		foreach ($subComponents as $subComponent) {
1620 1620
 			$name = $subComponent->name;
1621 1621
 			if (!isset($data[$name])) {
1622 1622
 				$data[$name] = [];
@@ -1624,7 +1624,7 @@  discard block
 block discarded – undo
1624 1624
 			$data[$name][] = $this->transformSearchData($subComponent);
1625 1625
 		}
1626 1626
 
1627
-		foreach($properties as $property) {
1627
+		foreach ($properties as $property) {
1628 1628
 			$name = $property->name;
1629 1629
 			if (!isset($validationRules[$name])) {
1630 1630
 				$validationRules[$name] = '*';
@@ -1695,7 +1695,7 @@  discard block
 block discarded – undo
1695 1695
 		$stmt = $query->execute();
1696 1696
 
1697 1697
 		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1698
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1698
+			return $row['calendaruri'].'/'.$row['objecturi'];
1699 1699
 		}
1700 1700
 
1701 1701
 		return null;
@@ -1758,10 +1758,10 @@  discard block
 block discarded – undo
1758 1758
 	 * @param int $calendarType
1759 1759
 	 * @return array
1760 1760
 	 */
1761
-	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1761
+	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1762 1762
 		// Current synctoken
1763 1763
 		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1764
-		$stmt->execute([ $calendarId ]);
1764
+		$stmt->execute([$calendarId]);
1765 1765
 		$currentToken = $stmt->fetchColumn(0);
1766 1766
 
1767 1767
 		if (is_null($currentToken)) {
@@ -1778,8 +1778,8 @@  discard block
 block discarded – undo
1778 1778
 		if ($syncToken) {
1779 1779
 
1780 1780
 			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? AND `calendartype` = ? ORDER BY `synctoken`";
1781
-			if ($limit>0) {
1782
-				$query.= " LIMIT " . (int)$limit;
1781
+			if ($limit > 0) {
1782
+				$query .= " LIMIT ".(int) $limit;
1783 1783
 			}
1784 1784
 
1785 1785
 			// Fetching all changes
@@ -1790,15 +1790,15 @@  discard block
 block discarded – undo
1790 1790
 
1791 1791
 			// This loop ensures that any duplicates are overwritten, only the
1792 1792
 			// last change on a node is relevant.
1793
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1793
+			while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1794 1794
 
1795 1795
 				$changes[$row['uri']] = $row['operation'];
1796 1796
 
1797 1797
 			}
1798 1798
 
1799
-			foreach($changes as $uri => $operation) {
1799
+			foreach ($changes as $uri => $operation) {
1800 1800
 
1801
-				switch($operation) {
1801
+				switch ($operation) {
1802 1802
 					case 1 :
1803 1803
 						$result['added'][] = $uri;
1804 1804
 						break;
@@ -1869,10 +1869,10 @@  discard block
 block discarded – undo
1869 1869
 			->from('calendarsubscriptions')
1870 1870
 			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1871 1871
 			->orderBy('calendarorder', 'asc');
1872
-		$stmt =$query->execute();
1872
+		$stmt = $query->execute();
1873 1873
 
1874 1874
 		$subscriptions = [];
1875
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1875
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1876 1876
 
1877 1877
 			$subscription = [
1878 1878
 				'id'           => $row['id'],
@@ -1881,11 +1881,11 @@  discard block
 block discarded – undo
1881 1881
 				'source'       => $row['source'],
1882 1882
 				'lastmodified' => $row['lastmodified'],
1883 1883
 
1884
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1885
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
1884
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1885
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
1886 1886
 			];
1887 1887
 
1888
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1888
+			foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1889 1889
 				if (!is_null($row[$dbName])) {
1890 1890
 					$subscription[$xmlName] = $row[$dbName];
1891 1891
 				}
@@ -1924,7 +1924,7 @@  discard block
 block discarded – undo
1924 1924
 
1925 1925
 		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1926 1926
 
1927
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1927
+		foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1928 1928
 			if (array_key_exists($xmlName, $properties)) {
1929 1929
 					$values[$dbName] = $properties[$xmlName];
1930 1930
 					if (in_array($dbName, $propertiesBoolean)) {
@@ -1984,7 +1984,7 @@  discard block
 block discarded – undo
1984 1984
 
1985 1985
 			$newValues = [];
1986 1986
 
1987
-			foreach($mutations as $propertyName=>$propertyValue) {
1987
+			foreach ($mutations as $propertyName=>$propertyValue) {
1988 1988
 				if ($propertyName === '{http://calendarserver.org/ns/}source') {
1989 1989
 					$newValues['source'] = $propertyValue->getHref();
1990 1990
 				} else {
@@ -1996,7 +1996,7 @@  discard block
 block discarded – undo
1996 1996
 			$query = $this->db->getQueryBuilder();
1997 1997
 			$query->update('calendarsubscriptions')
1998 1998
 				->set('lastmodified', $query->createNamedParameter(time()));
1999
-			foreach($newValues as $fieldName=>$value) {
1999
+			foreach ($newValues as $fieldName=>$value) {
2000 2000
 				$query->set($fieldName, $query->createNamedParameter($value));
2001 2001
 			}
2002 2002
 			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
@@ -2077,7 +2077,7 @@  discard block
 block discarded – undo
2077 2077
 
2078 2078
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
2079 2079
 
2080
-		if(!$row) {
2080
+		if (!$row) {
2081 2081
 			return null;
2082 2082
 		}
2083 2083
 
@@ -2085,8 +2085,8 @@  discard block
 block discarded – undo
2085 2085
 				'uri'          => $row['uri'],
2086 2086
 				'calendardata' => $row['calendardata'],
2087 2087
 				'lastmodified' => $row['lastmodified'],
2088
-				'etag'         => '"' . $row['etag'] . '"',
2089
-				'size'         => (int)$row['size'],
2088
+				'etag'         => '"'.$row['etag'].'"',
2089
+				'size'         => (int) $row['size'],
2090 2090
 		];
2091 2091
 	}
2092 2092
 
@@ -2109,13 +2109,13 @@  discard block
 block discarded – undo
2109 2109
 				->execute();
2110 2110
 
2111 2111
 		$result = [];
2112
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2112
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2113 2113
 			$result[] = [
2114 2114
 					'calendardata' => $row['calendardata'],
2115 2115
 					'uri'          => $row['uri'],
2116 2116
 					'lastmodified' => $row['lastmodified'],
2117
-					'etag'         => '"' . $row['etag'] . '"',
2118
-					'size'         => (int)$row['size'],
2117
+					'etag'         => '"'.$row['etag'].'"',
2118
+					'size'         => (int) $row['size'],
2119 2119
 			];
2120 2120
 		}
2121 2121
 
@@ -2168,14 +2168,14 @@  discard block
 block discarded – undo
2168 2168
 	 * @param int $calendarType
2169 2169
 	 * @return void
2170 2170
 	 */
2171
-	protected function addChange($calendarId, $objectUri, $operation, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2172
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2171
+	protected function addChange($calendarId, $objectUri, $operation, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2172
+		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars' : 'calendarsubscriptions';
2173 2173
 
2174 2174
 		$query = $this->db->getQueryBuilder();
2175 2175
 		$query->select('synctoken')
2176 2176
 			->from($table)
2177 2177
 			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2178
-		$syncToken = (int)$query->execute()->fetchColumn();
2178
+		$syncToken = (int) $query->execute()->fetchColumn();
2179 2179
 
2180 2180
 		$query = $this->db->getQueryBuilder();
2181 2181
 		$query->insert('calendarchanges')
@@ -2219,10 +2219,10 @@  discard block
 block discarded – undo
2219 2219
 		$lastOccurrence = null;
2220 2220
 		$uid = null;
2221 2221
 		$classification = self::CLASSIFICATION_PUBLIC;
2222
-		foreach($vObject->getComponents() as $component) {
2223
-			if ($component->name!=='VTIMEZONE') {
2222
+		foreach ($vObject->getComponents() as $component) {
2223
+			if ($component->name !== 'VTIMEZONE') {
2224 2224
 				$componentType = $component->name;
2225
-				$uid = (string)$component->UID;
2225
+				$uid = (string) $component->UID;
2226 2226
 				break;
2227 2227
 			}
2228 2228
 		}
@@ -2247,13 +2247,13 @@  discard block
 block discarded – undo
2247 2247
 					$lastOccurrence = $firstOccurrence;
2248 2248
 				}
2249 2249
 			} else {
2250
-				$it = new EventIterator($vObject, (string)$component->UID);
2250
+				$it = new EventIterator($vObject, (string) $component->UID);
2251 2251
 				$maxDate = new \DateTime(self::MAX_DATE);
2252 2252
 				if ($it->isInfinite()) {
2253 2253
 					$lastOccurrence = $maxDate->getTimestamp();
2254 2254
 				} else {
2255 2255
 					$end = $it->getDtEnd();
2256
-					while($it->valid() && $end < $maxDate) {
2256
+					while ($it->valid() && $end < $maxDate) {
2257 2257
 						$end = $it->getDtEnd();
2258 2258
 						$it->next();
2259 2259
 
@@ -2323,7 +2323,7 @@  discard block
 block discarded – undo
2323 2323
 	 * @param int $calendarType
2324 2324
 	 * @return array
2325 2325
 	 */
2326
-	public function getShares($resourceId, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2326
+	public function getShares($resourceId, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2327 2327
 		return $this->calendarSharingBackend->getShares($resourceId);
2328 2328
 	}
2329 2329
 
@@ -2400,7 +2400,7 @@  discard block
 block discarded – undo
2400 2400
 	 * @param string $calendarData
2401 2401
 	 * @param int $calendarType
2402 2402
 	 */
2403
-	public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2403
+	public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2404 2404
 		$objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
2405 2405
 
2406 2406
 		try {
@@ -2478,7 +2478,7 @@  discard block
 block discarded – undo
2478 2478
 			->execute();
2479 2479
 
2480 2480
 		$ids = $result->fetchAll();
2481
-		foreach($ids as $id) {
2481
+		foreach ($ids as $id) {
2482 2482
 			$this->deleteCalendar($id['id']);
2483 2483
 		}
2484 2484
 	}
@@ -2495,7 +2495,7 @@  discard block
 block discarded – undo
2495 2495
 		$stmt = $query->execute();
2496 2496
 
2497 2497
 		$uris = [];
2498
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2498
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2499 2499
 			$uris[] = $row['uri'];
2500 2500
 		}
2501 2501
 		$stmt->closeCursor();
@@ -2516,7 +2516,7 @@  discard block
 block discarded – undo
2516 2516
 			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2517 2517
 			->execute();
2518 2518
 
2519
-		foreach($uris as $uri) {
2519
+		foreach ($uris as $uri) {
2520 2520
 			$this->addChange($subscriptionId, $uri, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
2521 2521
 		}
2522 2522
 	}
@@ -2566,10 +2566,10 @@  discard block
 block discarded – undo
2566 2566
 		$result->closeCursor();
2567 2567
 
2568 2568
 		if (!isset($objectIds['id'])) {
2569
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2569
+			throw new \InvalidArgumentException('Calendarobject does not exists: '.$uri);
2570 2570
 		}
2571 2571
 
2572
-		return (int)$objectIds['id'];
2572
+		return (int) $objectIds['id'];
2573 2573
 	}
2574 2574
 
2575 2575
 	/**
@@ -2596,8 +2596,8 @@  discard block
 block discarded – undo
2596 2596
 	 * @param $calendarInfo
2597 2597
 	 */
2598 2598
 	private function addOwnerPrincipal(&$calendarInfo) {
2599
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2600
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2599
+		$ownerPrincipalKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal';
2600
+		$displaynameKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}owner-displayname';
2601 2601
 		if (isset($calendarInfo[$ownerPrincipalKey])) {
2602 2602
 			$uri = $calendarInfo[$ownerPrincipalKey];
2603 2603
 		} else {
Please login to merge, or discard this patch.