Completed
Pull Request — master (#9895)
by Björn
43:43 queued 13:05
created
apps/dav/lib/CalDAV/Activity/Provider/Base.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -49,7 +49,7 @@
 block discarded – undo
49 49
 	protected function setSubjects(IEvent $event, $subject, array $parameters) {
50 50
 		$placeholders = $replacements = [];
51 51
 		foreach ($parameters as $placeholder => $parameter) {
52
-			$placeholders[] = '{' . $placeholder . '}';
52
+			$placeholders[] = '{'.$placeholder.'}';
53 53
 			$replacements[] = $parameter['name'];
54 54
 		}
55 55
 
Please login to merge, or discard this patch.
Indentation   +143 added lines, -143 removed lines patch added patch discarded remove patch
@@ -34,147 +34,147 @@
 block discarded – undo
34 34
 
35 35
 abstract class Base implements IProvider {
36 36
 
37
-	/** @var IUserManager */
38
-	protected $userManager;
39
-
40
-	/** @var string[]  */
41
-	protected $userDisplayNames = [];
42
-
43
-	/** @var IGroupManager */
44
-	protected $groupManager;
45
-
46
-	/** @var string[] */
47
-	protected $groupDisplayNames = [];
48
-
49
-	/**
50
-	 * @param IUserManager $userManager
51
-	 * @param IGroupManager $groupManager
52
-	 */
53
-	public function __construct(IUserManager $userManager, IGroupManager $groupManager) {
54
-		$this->userManager = $userManager;
55
-		$this->groupManager = $groupManager;
56
-	}
57
-
58
-	/**
59
-	 * @param IEvent $event
60
-	 * @param string $subject
61
-	 * @param array $parameters
62
-	 */
63
-	protected function setSubjects(IEvent $event, $subject, array $parameters) {
64
-		$placeholders = $replacements = [];
65
-		foreach ($parameters as $placeholder => $parameter) {
66
-			$placeholders[] = '{' . $placeholder . '}';
67
-			$replacements[] = $parameter['name'];
68
-		}
69
-
70
-		$event->setParsedSubject(str_replace($placeholders, $replacements, $subject))
71
-			->setRichSubject($subject, $parameters);
72
-	}
73
-
74
-	/**
75
-	 * @param array $eventData
76
-	 * @return array
77
-	 */
78
-	protected function generateObjectParameter($eventData) {
79
-		if (!is_array($eventData) || !isset($eventData['id']) || !isset($eventData['name'])) {
80
-			throw new \InvalidArgumentException();
81
-		}
82
-
83
-		return [
84
-			'type' => 'calendar-event',
85
-			'id' => $eventData['id'],
86
-			'name' => $eventData['name'],
87
-		];
88
-	}
89
-
90
-	/**
91
-	 * @param array $data
92
-	 * @param IL10N $l
93
-	 * @return array
94
-	 */
95
-	protected function generateCalendarParameter($data, IL10N $l) {
96
-		if ($data['uri'] === CalDavBackend::PERSONAL_CALENDAR_URI &&
97
-			$data['name'] === CalDavBackend::PERSONAL_CALENDAR_NAME) {
98
-			return [
99
-				'type' => 'calendar',
100
-				'id' => $data['id'],
101
-				'name' => $l->t('Personal'),
102
-			];
103
-		}
104
-
105
-		return [
106
-			'type' => 'calendar',
107
-			'id' => $data['id'],
108
-			'name' => $data['name'],
109
-		];
110
-	}
111
-
112
-	/**
113
-	 * @param int $id
114
-	 * @param string $name
115
-	 * @return array
116
-	 */
117
-	protected function generateLegacyCalendarParameter($id, $name) {
118
-		return [
119
-			'type' => 'calendar',
120
-			'id' => $id,
121
-			'name' => $name,
122
-		];
123
-	}
124
-
125
-	/**
126
-	 * @param string $uid
127
-	 * @return array
128
-	 */
129
-	protected function generateUserParameter($uid) {
130
-		if (!isset($this->userDisplayNames[$uid])) {
131
-			$this->userDisplayNames[$uid] = $this->getUserDisplayName($uid);
132
-		}
133
-
134
-		return [
135
-			'type' => 'user',
136
-			'id' => $uid,
137
-			'name' => $this->userDisplayNames[$uid],
138
-		];
139
-	}
140
-
141
-	/**
142
-	 * @param string $uid
143
-	 * @return string
144
-	 */
145
-	protected function getUserDisplayName($uid) {
146
-		$user = $this->userManager->get($uid);
147
-		if ($user instanceof IUser) {
148
-			return $user->getDisplayName();
149
-		}
150
-		return $uid;
151
-	}
152
-
153
-	/**
154
-	 * @param string $gid
155
-	 * @return array
156
-	 */
157
-	protected function generateGroupParameter($gid) {
158
-		if (!isset($this->groupDisplayNames[$gid])) {
159
-			$this->groupDisplayNames[$gid] = $this->getGroupDisplayName($gid);
160
-		}
161
-
162
-		return [
163
-			'type' => 'group',
164
-			'id' => $gid,
165
-			'name' => $this->groupDisplayNames[$gid],
166
-		];
167
-	}
168
-
169
-	/**
170
-	 * @param string $gid
171
-	 * @return string
172
-	 */
173
-	protected function getGroupDisplayName($gid) {
174
-		$group = $this->groupManager->get($gid);
175
-		if ($group instanceof IGroup) {
176
-			return $group->getDisplayName();
177
-		}
178
-		return $gid;
179
-	}
37
+    /** @var IUserManager */
38
+    protected $userManager;
39
+
40
+    /** @var string[]  */
41
+    protected $userDisplayNames = [];
42
+
43
+    /** @var IGroupManager */
44
+    protected $groupManager;
45
+
46
+    /** @var string[] */
47
+    protected $groupDisplayNames = [];
48
+
49
+    /**
50
+     * @param IUserManager $userManager
51
+     * @param IGroupManager $groupManager
52
+     */
53
+    public function __construct(IUserManager $userManager, IGroupManager $groupManager) {
54
+        $this->userManager = $userManager;
55
+        $this->groupManager = $groupManager;
56
+    }
57
+
58
+    /**
59
+     * @param IEvent $event
60
+     * @param string $subject
61
+     * @param array $parameters
62
+     */
63
+    protected function setSubjects(IEvent $event, $subject, array $parameters) {
64
+        $placeholders = $replacements = [];
65
+        foreach ($parameters as $placeholder => $parameter) {
66
+            $placeholders[] = '{' . $placeholder . '}';
67
+            $replacements[] = $parameter['name'];
68
+        }
69
+
70
+        $event->setParsedSubject(str_replace($placeholders, $replacements, $subject))
71
+            ->setRichSubject($subject, $parameters);
72
+    }
73
+
74
+    /**
75
+     * @param array $eventData
76
+     * @return array
77
+     */
78
+    protected function generateObjectParameter($eventData) {
79
+        if (!is_array($eventData) || !isset($eventData['id']) || !isset($eventData['name'])) {
80
+            throw new \InvalidArgumentException();
81
+        }
82
+
83
+        return [
84
+            'type' => 'calendar-event',
85
+            'id' => $eventData['id'],
86
+            'name' => $eventData['name'],
87
+        ];
88
+    }
89
+
90
+    /**
91
+     * @param array $data
92
+     * @param IL10N $l
93
+     * @return array
94
+     */
95
+    protected function generateCalendarParameter($data, IL10N $l) {
96
+        if ($data['uri'] === CalDavBackend::PERSONAL_CALENDAR_URI &&
97
+            $data['name'] === CalDavBackend::PERSONAL_CALENDAR_NAME) {
98
+            return [
99
+                'type' => 'calendar',
100
+                'id' => $data['id'],
101
+                'name' => $l->t('Personal'),
102
+            ];
103
+        }
104
+
105
+        return [
106
+            'type' => 'calendar',
107
+            'id' => $data['id'],
108
+            'name' => $data['name'],
109
+        ];
110
+    }
111
+
112
+    /**
113
+     * @param int $id
114
+     * @param string $name
115
+     * @return array
116
+     */
117
+    protected function generateLegacyCalendarParameter($id, $name) {
118
+        return [
119
+            'type' => 'calendar',
120
+            'id' => $id,
121
+            'name' => $name,
122
+        ];
123
+    }
124
+
125
+    /**
126
+     * @param string $uid
127
+     * @return array
128
+     */
129
+    protected function generateUserParameter($uid) {
130
+        if (!isset($this->userDisplayNames[$uid])) {
131
+            $this->userDisplayNames[$uid] = $this->getUserDisplayName($uid);
132
+        }
133
+
134
+        return [
135
+            'type' => 'user',
136
+            'id' => $uid,
137
+            'name' => $this->userDisplayNames[$uid],
138
+        ];
139
+    }
140
+
141
+    /**
142
+     * @param string $uid
143
+     * @return string
144
+     */
145
+    protected function getUserDisplayName($uid) {
146
+        $user = $this->userManager->get($uid);
147
+        if ($user instanceof IUser) {
148
+            return $user->getDisplayName();
149
+        }
150
+        return $uid;
151
+    }
152
+
153
+    /**
154
+     * @param string $gid
155
+     * @return array
156
+     */
157
+    protected function generateGroupParameter($gid) {
158
+        if (!isset($this->groupDisplayNames[$gid])) {
159
+            $this->groupDisplayNames[$gid] = $this->getGroupDisplayName($gid);
160
+        }
161
+
162
+        return [
163
+            'type' => 'group',
164
+            'id' => $gid,
165
+            'name' => $this->groupDisplayNames[$gid],
166
+        ];
167
+    }
168
+
169
+    /**
170
+     * @param string $gid
171
+     * @return string
172
+     */
173
+    protected function getGroupDisplayName($gid) {
174
+        $group = $this->groupManager->get($gid);
175
+        if ($group instanceof IGroup) {
176
+            return $group->getDisplayName();
177
+        }
178
+        return $gid;
179
+    }
180 180
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Activity/Filter/Calendar.php 1 patch
Indentation   +53 added lines, -53 removed lines patch added patch discarded remove patch
@@ -28,65 +28,65 @@
 block discarded – undo
28 28
 
29 29
 class Calendar implements IFilter {
30 30
 
31
-	/** @var IL10N */
32
-	protected $l;
31
+    /** @var IL10N */
32
+    protected $l;
33 33
 
34
-	/** @var IURLGenerator */
35
-	protected $url;
34
+    /** @var IURLGenerator */
35
+    protected $url;
36 36
 
37
-	public function __construct(IL10N $l, IURLGenerator $url) {
38
-		$this->l = $l;
39
-		$this->url = $url;
40
-	}
37
+    public function __construct(IL10N $l, IURLGenerator $url) {
38
+        $this->l = $l;
39
+        $this->url = $url;
40
+    }
41 41
 
42
-	/**
43
-	 * @return string Lowercase a-z and underscore only identifier
44
-	 * @since 11.0.0
45
-	 */
46
-	public function getIdentifier() {
47
-		return 'calendar';
48
-	}
42
+    /**
43
+     * @return string Lowercase a-z and underscore only identifier
44
+     * @since 11.0.0
45
+     */
46
+    public function getIdentifier() {
47
+        return 'calendar';
48
+    }
49 49
 
50
-	/**
51
-	 * @return string A translated string
52
-	 * @since 11.0.0
53
-	 */
54
-	public function getName() {
55
-		return $this->l->t('Calendar');
56
-	}
50
+    /**
51
+     * @return string A translated string
52
+     * @since 11.0.0
53
+     */
54
+    public function getName() {
55
+        return $this->l->t('Calendar');
56
+    }
57 57
 
58
-	/**
59
-	 * @return int whether the filter should be rather on the top or bottom of
60
-	 * the admin section. The filters are arranged in ascending order of the
61
-	 * priority values. It is required to return a value between 0 and 100.
62
-	 * @since 11.0.0
63
-	 */
64
-	public function getPriority() {
65
-		return 40;
66
-	}
58
+    /**
59
+     * @return int whether the filter should be rather on the top or bottom of
60
+     * the admin section. The filters are arranged in ascending order of the
61
+     * priority values. It is required to return a value between 0 and 100.
62
+     * @since 11.0.0
63
+     */
64
+    public function getPriority() {
65
+        return 40;
66
+    }
67 67
 
68
-	/**
69
-	 * @return string Full URL to an icon, empty string when none is given
70
-	 * @since 11.0.0
71
-	 */
72
-	public function getIcon() {
73
-		return $this->url->getAbsoluteURL($this->url->imagePath('core', 'places/calendar-dark.svg'));
74
-	}
68
+    /**
69
+     * @return string Full URL to an icon, empty string when none is given
70
+     * @since 11.0.0
71
+     */
72
+    public function getIcon() {
73
+        return $this->url->getAbsoluteURL($this->url->imagePath('core', 'places/calendar-dark.svg'));
74
+    }
75 75
 
76
-	/**
77
-	 * @param string[] $types
78
-	 * @return string[] An array of allowed apps from which activities should be displayed
79
-	 * @since 11.0.0
80
-	 */
81
-	public function filterTypes(array $types) {
82
-		return array_intersect(['calendar', 'calendar_event'], $types);
83
-	}
76
+    /**
77
+     * @param string[] $types
78
+     * @return string[] An array of allowed apps from which activities should be displayed
79
+     * @since 11.0.0
80
+     */
81
+    public function filterTypes(array $types) {
82
+        return array_intersect(['calendar', 'calendar_event'], $types);
83
+    }
84 84
 
85
-	/**
86
-	 * @return string[] An array of allowed apps from which activities should be displayed
87
-	 * @since 11.0.0
88
-	 */
89
-	public function allowedApps() {
90
-		return [];
91
-	}
85
+    /**
86
+     * @return string[] An array of allowed apps from which activities should be displayed
87
+     * @since 11.0.0
88
+     */
89
+    public function allowedApps() {
90
+        return [];
91
+    }
92 92
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Activity/Filter/Todo.php 1 patch
Indentation   +53 added lines, -53 removed lines patch added patch discarded remove patch
@@ -28,65 +28,65 @@
 block discarded – undo
28 28
 
29 29
 class Todo implements IFilter {
30 30
 
31
-	/** @var IL10N */
32
-	protected $l;
31
+    /** @var IL10N */
32
+    protected $l;
33 33
 
34
-	/** @var IURLGenerator */
35
-	protected $url;
34
+    /** @var IURLGenerator */
35
+    protected $url;
36 36
 
37
-	public function __construct(IL10N $l, IURLGenerator $url) {
38
-		$this->l = $l;
39
-		$this->url = $url;
40
-	}
37
+    public function __construct(IL10N $l, IURLGenerator $url) {
38
+        $this->l = $l;
39
+        $this->url = $url;
40
+    }
41 41
 
42
-	/**
43
-	 * @return string Lowercase a-z and underscore only identifier
44
-	 * @since 11.0.0
45
-	 */
46
-	public function getIdentifier() {
47
-		return 'calendar_todo';
48
-	}
42
+    /**
43
+     * @return string Lowercase a-z and underscore only identifier
44
+     * @since 11.0.0
45
+     */
46
+    public function getIdentifier() {
47
+        return 'calendar_todo';
48
+    }
49 49
 
50
-	/**
51
-	 * @return string A translated string
52
-	 * @since 11.0.0
53
-	 */
54
-	public function getName() {
55
-		return $this->l->t('Todos');
56
-	}
50
+    /**
51
+     * @return string A translated string
52
+     * @since 11.0.0
53
+     */
54
+    public function getName() {
55
+        return $this->l->t('Todos');
56
+    }
57 57
 
58
-	/**
59
-	 * @return int whether the filter should be rather on the top or bottom of
60
-	 * the admin section. The filters are arranged in ascending order of the
61
-	 * priority values. It is required to return a value between 0 and 100.
62
-	 * @since 11.0.0
63
-	 */
64
-	public function getPriority() {
65
-		return 40;
66
-	}
58
+    /**
59
+     * @return int whether the filter should be rather on the top or bottom of
60
+     * the admin section. The filters are arranged in ascending order of the
61
+     * priority values. It is required to return a value between 0 and 100.
62
+     * @since 11.0.0
63
+     */
64
+    public function getPriority() {
65
+        return 40;
66
+    }
67 67
 
68
-	/**
69
-	 * @return string Full URL to an icon, empty string when none is given
70
-	 * @since 11.0.0
71
-	 */
72
-	public function getIcon() {
73
-		return $this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/checkmark.svg'));
74
-	}
68
+    /**
69
+     * @return string Full URL to an icon, empty string when none is given
70
+     * @since 11.0.0
71
+     */
72
+    public function getIcon() {
73
+        return $this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/checkmark.svg'));
74
+    }
75 75
 
76
-	/**
77
-	 * @param string[] $types
78
-	 * @return string[] An array of allowed apps from which activities should be displayed
79
-	 * @since 11.0.0
80
-	 */
81
-	public function filterTypes(array $types) {
82
-		return array_intersect(['calendar_todo'], $types);
83
-	}
76
+    /**
77
+     * @param string[] $types
78
+     * @return string[] An array of allowed apps from which activities should be displayed
79
+     * @since 11.0.0
80
+     */
81
+    public function filterTypes(array $types) {
82
+        return array_intersect(['calendar_todo'], $types);
83
+    }
84 84
 
85
-	/**
86
-	 * @return string[] An array of allowed apps from which activities should be displayed
87
-	 * @since 11.0.0
88
-	 */
89
-	public function allowedApps() {
90
-		return [];
91
-	}
85
+    /**
86
+     * @return string[] An array of allowed apps from which activities should be displayed
87
+     * @since 11.0.0
88
+     */
89
+    public function allowedApps() {
90
+        return [];
91
+    }
92 92
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Activity/Setting/Calendar.php 1 patch
Indentation   +59 added lines, -59 removed lines patch added patch discarded remove patch
@@ -27,72 +27,72 @@
 block discarded – undo
27 27
 
28 28
 class Calendar implements ISetting {
29 29
 
30
-	/** @var IL10N */
31
-	protected $l;
30
+    /** @var IL10N */
31
+    protected $l;
32 32
 
33
-	/**
34
-	 * @param IL10N $l
35
-	 */
36
-	public function __construct(IL10N $l) {
37
-		$this->l = $l;
38
-	}
33
+    /**
34
+     * @param IL10N $l
35
+     */
36
+    public function __construct(IL10N $l) {
37
+        $this->l = $l;
38
+    }
39 39
 
40
-	/**
41
-	 * @return string Lowercase a-z and underscore only identifier
42
-	 * @since 11.0.0
43
-	 */
44
-	public function getIdentifier() {
45
-		return 'calendar';
46
-	}
40
+    /**
41
+     * @return string Lowercase a-z and underscore only identifier
42
+     * @since 11.0.0
43
+     */
44
+    public function getIdentifier() {
45
+        return 'calendar';
46
+    }
47 47
 
48
-	/**
49
-	 * @return string A translated string
50
-	 * @since 11.0.0
51
-	 */
52
-	public function getName() {
53
-		return $this->l->t('A <strong>calendar</strong> was modified');
54
-	}
48
+    /**
49
+     * @return string A translated string
50
+     * @since 11.0.0
51
+     */
52
+    public function getName() {
53
+        return $this->l->t('A <strong>calendar</strong> was modified');
54
+    }
55 55
 
56
-	/**
57
-	 * @return int whether the filter should be rather on the top or bottom of
58
-	 * the admin section. The filters are arranged in ascending order of the
59
-	 * priority values. It is required to return a value between 0 and 100.
60
-	 * @since 11.0.0
61
-	 */
62
-	public function getPriority() {
63
-		return 50;
64
-	}
56
+    /**
57
+     * @return int whether the filter should be rather on the top or bottom of
58
+     * the admin section. The filters are arranged in ascending order of the
59
+     * priority values. It is required to return a value between 0 and 100.
60
+     * @since 11.0.0
61
+     */
62
+    public function getPriority() {
63
+        return 50;
64
+    }
65 65
 
66
-	/**
67
-	 * @return bool True when the option can be changed for the stream
68
-	 * @since 11.0.0
69
-	 */
70
-	public function canChangeStream() {
71
-		return true;
72
-	}
66
+    /**
67
+     * @return bool True when the option can be changed for the stream
68
+     * @since 11.0.0
69
+     */
70
+    public function canChangeStream() {
71
+        return true;
72
+    }
73 73
 
74
-	/**
75
-	 * @return bool True when the option can be changed for the stream
76
-	 * @since 11.0.0
77
-	 */
78
-	public function isDefaultEnabledStream() {
79
-		return true;
80
-	}
74
+    /**
75
+     * @return bool True when the option can be changed for the stream
76
+     * @since 11.0.0
77
+     */
78
+    public function isDefaultEnabledStream() {
79
+        return true;
80
+    }
81 81
 
82
-	/**
83
-	 * @return bool True when the option can be changed for the mail
84
-	 * @since 11.0.0
85
-	 */
86
-	public function canChangeMail() {
87
-		return true;
88
-	}
82
+    /**
83
+     * @return bool True when the option can be changed for the mail
84
+     * @since 11.0.0
85
+     */
86
+    public function canChangeMail() {
87
+        return true;
88
+    }
89 89
 
90
-	/**
91
-	 * @return bool True when the option can be changed for the stream
92
-	 * @since 11.0.0
93
-	 */
94
-	public function isDefaultEnabledMail() {
95
-		return false;
96
-	}
90
+    /**
91
+     * @return bool True when the option can be changed for the stream
92
+     * @since 11.0.0
93
+     */
94
+    public function isDefaultEnabledMail() {
95
+        return false;
96
+    }
97 97
 }
98 98
 
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Activity/Setting/Event.php 1 patch
Indentation   +59 added lines, -59 removed lines patch added patch discarded remove patch
@@ -27,72 +27,72 @@
 block discarded – undo
27 27
 
28 28
 class Event implements ISetting {
29 29
 
30
-	/** @var IL10N */
31
-	protected $l;
30
+    /** @var IL10N */
31
+    protected $l;
32 32
 
33
-	/**
34
-	 * @param IL10N $l
35
-	 */
36
-	public function __construct(IL10N $l) {
37
-		$this->l = $l;
38
-	}
33
+    /**
34
+     * @param IL10N $l
35
+     */
36
+    public function __construct(IL10N $l) {
37
+        $this->l = $l;
38
+    }
39 39
 
40
-	/**
41
-	 * @return string Lowercase a-z and underscore only identifier
42
-	 * @since 11.0.0
43
-	 */
44
-	public function getIdentifier() {
45
-		return 'calendar_event';
46
-	}
40
+    /**
41
+     * @return string Lowercase a-z and underscore only identifier
42
+     * @since 11.0.0
43
+     */
44
+    public function getIdentifier() {
45
+        return 'calendar_event';
46
+    }
47 47
 
48
-	/**
49
-	 * @return string A translated string
50
-	 * @since 11.0.0
51
-	 */
52
-	public function getName() {
53
-		return $this->l->t('A calendar <strong>event</strong> was modified');
54
-	}
48
+    /**
49
+     * @return string A translated string
50
+     * @since 11.0.0
51
+     */
52
+    public function getName() {
53
+        return $this->l->t('A calendar <strong>event</strong> was modified');
54
+    }
55 55
 
56
-	/**
57
-	 * @return int whether the filter should be rather on the top or bottom of
58
-	 * the admin section. The filters are arranged in ascending order of the
59
-	 * priority values. It is required to return a value between 0 and 100.
60
-	 * @since 11.0.0
61
-	 */
62
-	public function getPriority() {
63
-		return 50;
64
-	}
56
+    /**
57
+     * @return int whether the filter should be rather on the top or bottom of
58
+     * the admin section. The filters are arranged in ascending order of the
59
+     * priority values. It is required to return a value between 0 and 100.
60
+     * @since 11.0.0
61
+     */
62
+    public function getPriority() {
63
+        return 50;
64
+    }
65 65
 
66
-	/**
67
-	 * @return bool True when the option can be changed for the stream
68
-	 * @since 11.0.0
69
-	 */
70
-	public function canChangeStream() {
71
-		return true;
72
-	}
66
+    /**
67
+     * @return bool True when the option can be changed for the stream
68
+     * @since 11.0.0
69
+     */
70
+    public function canChangeStream() {
71
+        return true;
72
+    }
73 73
 
74
-	/**
75
-	 * @return bool True when the option can be changed for the stream
76
-	 * @since 11.0.0
77
-	 */
78
-	public function isDefaultEnabledStream() {
79
-		return true;
80
-	}
74
+    /**
75
+     * @return bool True when the option can be changed for the stream
76
+     * @since 11.0.0
77
+     */
78
+    public function isDefaultEnabledStream() {
79
+        return true;
80
+    }
81 81
 
82
-	/**
83
-	 * @return bool True when the option can be changed for the mail
84
-	 * @since 11.0.0
85
-	 */
86
-	public function canChangeMail() {
87
-		return true;
88
-	}
82
+    /**
83
+     * @return bool True when the option can be changed for the mail
84
+     * @since 11.0.0
85
+     */
86
+    public function canChangeMail() {
87
+        return true;
88
+    }
89 89
 
90
-	/**
91
-	 * @return bool True when the option can be changed for the stream
92
-	 * @since 11.0.0
93
-	 */
94
-	public function isDefaultEnabledMail() {
95
-		return false;
96
-	}
90
+    /**
91
+     * @return bool True when the option can be changed for the stream
92
+     * @since 11.0.0
93
+     */
94
+    public function isDefaultEnabledMail() {
95
+        return false;
96
+    }
97 97
 }
98 98
 
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Activity/Setting/Todo.php 1 patch
Indentation   +59 added lines, -59 removed lines patch added patch discarded remove patch
@@ -27,72 +27,72 @@
 block discarded – undo
27 27
 
28 28
 class Todo implements ISetting {
29 29
 
30
-	/** @var IL10N */
31
-	protected $l;
30
+    /** @var IL10N */
31
+    protected $l;
32 32
 
33
-	/**
34
-	 * @param IL10N $l
35
-	 */
36
-	public function __construct(IL10N $l) {
37
-		$this->l = $l;
38
-	}
33
+    /**
34
+     * @param IL10N $l
35
+     */
36
+    public function __construct(IL10N $l) {
37
+        $this->l = $l;
38
+    }
39 39
 
40
-	/**
41
-	 * @return string Lowercase a-z and underscore only identifier
42
-	 * @since 11.0.0
43
-	 */
44
-	public function getIdentifier() {
45
-		return 'calendar_todo';
46
-	}
40
+    /**
41
+     * @return string Lowercase a-z and underscore only identifier
42
+     * @since 11.0.0
43
+     */
44
+    public function getIdentifier() {
45
+        return 'calendar_todo';
46
+    }
47 47
 
48
-	/**
49
-	 * @return string A translated string
50
-	 * @since 11.0.0
51
-	 */
52
-	public function getName() {
53
-		return $this->l->t('A calendar <strong>todo</strong> was modified');
54
-	}
48
+    /**
49
+     * @return string A translated string
50
+     * @since 11.0.0
51
+     */
52
+    public function getName() {
53
+        return $this->l->t('A calendar <strong>todo</strong> was modified');
54
+    }
55 55
 
56
-	/**
57
-	 * @return int whether the filter should be rather on the top or bottom of
58
-	 * the admin section. The filters are arranged in ascending order of the
59
-	 * priority values. It is required to return a value between 0 and 100.
60
-	 * @since 11.0.0
61
-	 */
62
-	public function getPriority() {
63
-		return 50;
64
-	}
56
+    /**
57
+     * @return int whether the filter should be rather on the top or bottom of
58
+     * the admin section. The filters are arranged in ascending order of the
59
+     * priority values. It is required to return a value between 0 and 100.
60
+     * @since 11.0.0
61
+     */
62
+    public function getPriority() {
63
+        return 50;
64
+    }
65 65
 
66
-	/**
67
-	 * @return bool True when the option can be changed for the stream
68
-	 * @since 11.0.0
69
-	 */
70
-	public function canChangeStream() {
71
-		return true;
72
-	}
66
+    /**
67
+     * @return bool True when the option can be changed for the stream
68
+     * @since 11.0.0
69
+     */
70
+    public function canChangeStream() {
71
+        return true;
72
+    }
73 73
 
74
-	/**
75
-	 * @return bool True when the option can be changed for the stream
76
-	 * @since 11.0.0
77
-	 */
78
-	public function isDefaultEnabledStream() {
79
-		return true;
80
-	}
74
+    /**
75
+     * @return bool True when the option can be changed for the stream
76
+     * @since 11.0.0
77
+     */
78
+    public function isDefaultEnabledStream() {
79
+        return true;
80
+    }
81 81
 
82
-	/**
83
-	 * @return bool True when the option can be changed for the mail
84
-	 * @since 11.0.0
85
-	 */
86
-	public function canChangeMail() {
87
-		return true;
88
-	}
82
+    /**
83
+     * @return bool True when the option can be changed for the mail
84
+     * @since 11.0.0
85
+     */
86
+    public function canChangeMail() {
87
+        return true;
88
+    }
89 89
 
90
-	/**
91
-	 * @return bool True when the option can be changed for the stream
92
-	 * @since 11.0.0
93
-	 */
94
-	public function isDefaultEnabledMail() {
95
-		return false;
96
-	}
90
+    /**
91
+     * @return bool True when the option can be changed for the stream
92
+     * @since 11.0.0
93
+     */
94
+    public function isDefaultEnabledMail() {
95
+        return false;
96
+    }
97 97
 }
98 98
 
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/CalDavBackend.php 4 patches
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -808,7 +808,9 @@
 block discarded – undo
808 808
 		$stmt = $query->execute();
809 809
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
810 810
 
811
-		if(!$row) return null;
811
+		if(!$row) {
812
+		    return null;
813
+		}
812 814
 
813 815
 		return [
814 816
 				'id'            => $row['id'],
Please login to merge, or discard this patch.
Doc Comments   +10 added lines, -4 removed lines patch added patch discarded remove patch
@@ -182,7 +182,7 @@  discard block
 block discarded – undo
182 182
 	 *
183 183
 	 * By default this excludes the automatically generated birthday calendar
184 184
 	 *
185
-	 * @param $principalUri
185
+	 * @param string $principalUri
186 186
 	 * @param bool $excludeBirthday
187 187
 	 * @return int
188 188
 	 */
@@ -351,6 +351,9 @@  discard block
 block discarded – undo
351 351
 		return array_values($calendars);
352 352
 	}
353 353
 
354
+	/**
355
+	 * @param string $principalUri
356
+	 */
354 357
 	public function getUsersOwnCalendars($principalUri) {
355 358
 		$principalUri = $this->convertPrincipal($principalUri, true);
356 359
 		$fields = array_values($this->propertyMap);
@@ -946,7 +949,7 @@  discard block
 block discarded – undo
946 949
 	 * calendar-data. If the result of a subsequent GET to this object is not
947 950
 	 * the exact same as this request body, you should omit the ETag.
948 951
 	 *
949
-	 * @param mixed $calendarId
952
+	 * @param integer $calendarId
950 953
 	 * @param string $objectUri
951 954
 	 * @param string $calendarData
952 955
 	 * @return string
@@ -1000,7 +1003,7 @@  discard block
 block discarded – undo
1000 1003
 	 * calendar-data. If the result of a subsequent GET to this object is not
1001 1004
 	 * the exact same as this request body, you should omit the ETag.
1002 1005
 	 *
1003
-	 * @param mixed $calendarId
1006
+	 * @param integer $calendarId
1004 1007
 	 * @param string $objectUri
1005 1008
 	 * @param string $calendarData
1006 1009
 	 * @return string
@@ -1563,7 +1566,7 @@  discard block
 block discarded – undo
1563 1566
 	 * @param string $principalUri
1564 1567
 	 * @param string $uri
1565 1568
 	 * @param array $properties
1566
-	 * @return mixed
1569
+	 * @return integer
1567 1570
 	 */
1568 1571
 	function createSubscription($principalUri, $uri, array $properties) {
1569 1572
 
@@ -2103,6 +2106,9 @@  discard block
 block discarded – undo
2103 2106
 		return (int)$objectIds['id'];
2104 2107
 	}
2105 2108
 
2109
+	/**
2110
+	 * @param boolean $toV2
2111
+	 */
2106 2112
 	private function convertPrincipal($principalUri, $toV2) {
2107 2113
 		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
2108 2114
 			list(, $name) = Uri\split($principalUri);
Please login to merge, or discard this patch.
Spacing   +130 added lines, -130 removed lines patch added patch discarded remove patch
@@ -217,7 +217,7 @@  discard block
 block discarded – undo
217 217
 			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
218 218
 		}
219 219
 
220
-		return (int)$query->execute()->fetchColumn();
220
+		return (int) $query->execute()->fetchColumn();
221 221
 	}
222 222
 
223 223
 	/**
@@ -264,25 +264,25 @@  discard block
 block discarded – undo
264 264
 		$stmt = $query->execute();
265 265
 
266 266
 		$calendars = [];
267
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
267
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
268 268
 
269 269
 			$components = [];
270 270
 			if ($row['components']) {
271
-				$components = explode(',',$row['components']);
271
+				$components = explode(',', $row['components']);
272 272
 			}
273 273
 
274 274
 			$calendar = [
275 275
 				'id' => $row['id'],
276 276
 				'uri' => $row['uri'],
277 277
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
278
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
279
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
280
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
281
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
282
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
278
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
279
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
280
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
281
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
282
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
283 283
 			];
284 284
 
285
-			foreach($this->propertyMap as $xmlName=>$dbName) {
285
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
286 286
 				$calendar[$xmlName] = $row[$dbName];
287 287
 			}
288 288
 
@@ -300,7 +300,7 @@  discard block
 block discarded – undo
300 300
 		$principals = array_map(function($principal) {
301 301
 			return urldecode($principal);
302 302
 		}, $principals);
303
-		$principals[]= $principalUri;
303
+		$principals[] = $principalUri;
304 304
 
305 305
 		$fields = array_values($this->propertyMap);
306 306
 		$fields[] = 'a.id';
@@ -320,8 +320,8 @@  discard block
 block discarded – undo
320 320
 			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
321 321
 			->execute();
322 322
 
323
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
324
-		while($row = $result->fetch()) {
323
+		$readOnlyPropertyName = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only';
324
+		while ($row = $result->fetch()) {
325 325
 			if ($row['principaluri'] === $principalUri) {
326 326
 				continue;
327 327
 			}
@@ -340,25 +340,25 @@  discard block
 block discarded – undo
340 340
 			}
341 341
 
342 342
 			list(, $name) = Uri\split($row['principaluri']);
343
-			$uri = $row['uri'] . '_shared_by_' . $name;
344
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
343
+			$uri = $row['uri'].'_shared_by_'.$name;
344
+			$row['displayname'] = $row['displayname'].' ('.$this->getUserDisplayName($name).')';
345 345
 			$components = [];
346 346
 			if ($row['components']) {
347
-				$components = explode(',',$row['components']);
347
+				$components = explode(',', $row['components']);
348 348
 			}
349 349
 			$calendar = [
350 350
 				'id' => $row['id'],
351 351
 				'uri' => $uri,
352 352
 				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
353
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
354
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
355
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
356
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
357
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
353
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
354
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
355
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
356
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
357
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
358 358
 				$readOnlyPropertyName => $readOnly,
359 359
 			];
360 360
 
361
-			foreach($this->propertyMap as $xmlName=>$dbName) {
361
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
362 362
 				$calendar[$xmlName] = $row[$dbName];
363 363
 			}
364 364
 
@@ -387,21 +387,21 @@  discard block
 block discarded – undo
387 387
 			->orderBy('calendarorder', 'ASC');
388 388
 		$stmt = $query->execute();
389 389
 		$calendars = [];
390
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
390
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
391 391
 			$components = [];
392 392
 			if ($row['components']) {
393
-				$components = explode(',',$row['components']);
393
+				$components = explode(',', $row['components']);
394 394
 			}
395 395
 			$calendar = [
396 396
 				'id' => $row['id'],
397 397
 				'uri' => $row['uri'],
398 398
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
399
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
400
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
401
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
402
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
399
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
400
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
401
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
402
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
403 403
 			];
404
-			foreach($this->propertyMap as $xmlName=>$dbName) {
404
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
405 405
 				$calendar[$xmlName] = $row[$dbName];
406 406
 			}
407 407
 
@@ -452,27 +452,27 @@  discard block
 block discarded – undo
452 452
 			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
453 453
 			->execute();
454 454
 
455
-		while($row = $result->fetch()) {
455
+		while ($row = $result->fetch()) {
456 456
 			list(, $name) = Uri\split($row['principaluri']);
457
-			$row['displayname'] = $row['displayname'] . "($name)";
457
+			$row['displayname'] = $row['displayname']."($name)";
458 458
 			$components = [];
459 459
 			if ($row['components']) {
460
-				$components = explode(',',$row['components']);
460
+				$components = explode(',', $row['components']);
461 461
 			}
462 462
 			$calendar = [
463 463
 				'id' => $row['id'],
464 464
 				'uri' => $row['publicuri'],
465 465
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
466
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
467
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
468
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
469
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
470
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
471
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
472
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
466
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
467
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
468
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
469
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
470
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
471
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
472
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
473 473
 			];
474 474
 
475
-			foreach($this->propertyMap as $xmlName=>$dbName) {
475
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
476 476
 				$calendar[$xmlName] = $row[$dbName];
477 477
 			}
478 478
 
@@ -516,29 +516,29 @@  discard block
 block discarded – undo
516 516
 		$result->closeCursor();
517 517
 
518 518
 		if ($row === false) {
519
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
519
+			throw new NotFound('Node with name \''.$uri.'\' could not be found');
520 520
 		}
521 521
 
522 522
 		list(, $name) = Uri\split($row['principaluri']);
523
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
523
+		$row['displayname'] = $row['displayname'].' '."($name)";
524 524
 		$components = [];
525 525
 		if ($row['components']) {
526
-			$components = explode(',',$row['components']);
526
+			$components = explode(',', $row['components']);
527 527
 		}
528 528
 		$calendar = [
529 529
 			'id' => $row['id'],
530 530
 			'uri' => $row['publicuri'],
531 531
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
532
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
533
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
534
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
535
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
536
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
537
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
538
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
532
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
533
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
534
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
535
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
536
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
537
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
538
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
539 539
 		];
540 540
 
541
-		foreach($this->propertyMap as $xmlName=>$dbName) {
541
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
542 542
 			$calendar[$xmlName] = $row[$dbName];
543 543
 		}
544 544
 
@@ -578,20 +578,20 @@  discard block
 block discarded – undo
578 578
 
579 579
 		$components = [];
580 580
 		if ($row['components']) {
581
-			$components = explode(',',$row['components']);
581
+			$components = explode(',', $row['components']);
582 582
 		}
583 583
 
584 584
 		$calendar = [
585 585
 			'id' => $row['id'],
586 586
 			'uri' => $row['uri'],
587 587
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
588
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
589
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
590
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
591
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
588
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
589
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
590
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
591
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
592 592
 		];
593 593
 
594
-		foreach($this->propertyMap as $xmlName=>$dbName) {
594
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
595 595
 			$calendar[$xmlName] = $row[$dbName];
596 596
 		}
597 597
 
@@ -624,20 +624,20 @@  discard block
 block discarded – undo
624 624
 
625 625
 		$components = [];
626 626
 		if ($row['components']) {
627
-			$components = explode(',',$row['components']);
627
+			$components = explode(',', $row['components']);
628 628
 		}
629 629
 
630 630
 		$calendar = [
631 631
 			'id' => $row['id'],
632 632
 			'uri' => $row['uri'],
633 633
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
634
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
635
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
636
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
637
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
634
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
635
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
636
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
637
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
638 638
 		];
639 639
 
640
-		foreach($this->propertyMap as $xmlName=>$dbName) {
640
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
641 641
 			$calendar[$xmlName] = $row[$dbName];
642 642
 		}
643 643
 
@@ -672,16 +672,16 @@  discard block
 block discarded – undo
672 672
 		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
673 673
 		if (isset($properties[$sccs])) {
674 674
 			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
675
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
675
+				throw new DAV\Exception('The '.$sccs.' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
676 676
 			}
677
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
677
+			$values['components'] = implode(',', $properties[$sccs]->getValue());
678 678
 		}
679
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
679
+		$transp = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
680 680
 		if (isset($properties[$transp])) {
681 681
 			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
682 682
 		}
683 683
 
684
-		foreach($this->propertyMap as $xmlName=>$dbName) {
684
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
685 685
 			if (isset($properties[$xmlName])) {
686 686
 				$values[$dbName] = $properties[$xmlName];
687 687
 			}
@@ -689,7 +689,7 @@  discard block
 block discarded – undo
689 689
 
690 690
 		$query = $this->db->getQueryBuilder();
691 691
 		$query->insert('calendars');
692
-		foreach($values as $column => $value) {
692
+		foreach ($values as $column => $value) {
693 693
 			$query->setValue($column, $query->createNamedParameter($value));
694 694
 		}
695 695
 		$query->execute();
@@ -723,7 +723,7 @@  discard block
 block discarded – undo
723 723
 	 */
724 724
 	function updateCalendar($calendarId, PropPatch $propPatch) {
725 725
 		$supportedProperties = array_keys($this->propertyMap);
726
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
726
+		$supportedProperties[] = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
727 727
 
728 728
 		/**
729 729
 		 * @suppress SqlInjectionChecker
@@ -733,7 +733,7 @@  discard block
 block discarded – undo
733 733
 			foreach ($mutations as $propertyName => $propertyValue) {
734 734
 
735 735
 				switch ($propertyName) {
736
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
736
+					case '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' :
737 737
 						$fieldName = 'transparent';
738 738
 						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
739 739
 						break;
@@ -848,16 +848,16 @@  discard block
 block discarded – undo
848 848
 		$stmt = $query->execute();
849 849
 
850 850
 		$result = [];
851
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
851
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
852 852
 			$result[] = [
853 853
 					'id'           => $row['id'],
854 854
 					'uri'          => $row['uri'],
855 855
 					'lastmodified' => $row['lastmodified'],
856
-					'etag'         => '"' . $row['etag'] . '"',
856
+					'etag'         => '"'.$row['etag'].'"',
857 857
 					'calendarid'   => $row['calendarid'],
858
-					'size'         => (int)$row['size'],
858
+					'size'         => (int) $row['size'],
859 859
 					'component'    => strtolower($row['componenttype']),
860
-					'classification'=> (int)$row['classification']
860
+					'classification'=> (int) $row['classification']
861 861
 			];
862 862
 		}
863 863
 
@@ -890,18 +890,18 @@  discard block
 block discarded – undo
890 890
 		$stmt = $query->execute();
891 891
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
892 892
 
893
-		if(!$row) return null;
893
+		if (!$row) return null;
894 894
 
895 895
 		return [
896 896
 				'id'            => $row['id'],
897 897
 				'uri'           => $row['uri'],
898 898
 				'lastmodified'  => $row['lastmodified'],
899
-				'etag'          => '"' . $row['etag'] . '"',
899
+				'etag'          => '"'.$row['etag'].'"',
900 900
 				'calendarid'    => $row['calendarid'],
901
-				'size'          => (int)$row['size'],
901
+				'size'          => (int) $row['size'],
902 902
 				'calendardata'  => $this->readBlob($row['calendardata']),
903 903
 				'component'     => strtolower($row['componenttype']),
904
-				'classification'=> (int)$row['classification']
904
+				'classification'=> (int) $row['classification']
905 905
 		];
906 906
 	}
907 907
 
@@ -940,12 +940,12 @@  discard block
 block discarded – undo
940 940
 					'id'           => $row['id'],
941 941
 					'uri'          => $row['uri'],
942 942
 					'lastmodified' => $row['lastmodified'],
943
-					'etag'         => '"' . $row['etag'] . '"',
943
+					'etag'         => '"'.$row['etag'].'"',
944 944
 					'calendarid'   => $row['calendarid'],
945
-					'size'         => (int)$row['size'],
945
+					'size'         => (int) $row['size'],
946 946
 					'calendardata' => $this->readBlob($row['calendardata']),
947 947
 					'component'    => strtolower($row['componenttype']),
948
-					'classification' => (int)$row['classification']
948
+					'classification' => (int) $row['classification']
949 949
 				];
950 950
 			}
951 951
 			$result->closeCursor();
@@ -1018,7 +1018,7 @@  discard block
 block discarded – undo
1018 1018
 		));
1019 1019
 		$this->addChange($calendarId, $objectUri, 1);
1020 1020
 
1021
-		return '"' . $extraData['etag'] . '"';
1021
+		return '"'.$extraData['etag'].'"';
1022 1022
 	}
1023 1023
 
1024 1024
 	/**
@@ -1073,7 +1073,7 @@  discard block
 block discarded – undo
1073 1073
 		}
1074 1074
 		$this->addChange($calendarId, $objectUri, 2);
1075 1075
 
1076
-		return '"' . $extraData['etag'] . '"';
1076
+		return '"'.$extraData['etag'].'"';
1077 1077
 	}
1078 1078
 
1079 1079
 	/**
@@ -1226,13 +1226,13 @@  discard block
 block discarded – undo
1226 1226
 		$stmt = $query->execute();
1227 1227
 
1228 1228
 		$result = [];
1229
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1229
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1230 1230
 			if ($requirePostFilter) {
1231 1231
 				// validateFilterForObject will parse the calendar data
1232 1232
 				// catch parsing errors
1233 1233
 				try {
1234 1234
 					$matches = $this->validateFilterForObject($row, $filters);
1235
-				} catch(ParseException $ex) {
1235
+				} catch (ParseException $ex) {
1236 1236
 					$this->logger->logException($ex, [
1237 1237
 						'app' => 'dav',
1238 1238
 						'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri']
@@ -1265,14 +1265,14 @@  discard block
 block discarded – undo
1265 1265
 	 * @param integer|null $offset
1266 1266
 	 * @return array
1267 1267
 	 */
1268
-	public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1268
+	public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) {
1269 1269
 		$calendars = $this->getCalendarsForUser($principalUri);
1270 1270
 		$ownCalendars = [];
1271 1271
 		$sharedCalendars = [];
1272 1272
 
1273 1273
 		$uriMapper = [];
1274 1274
 
1275
-		foreach($calendars as $calendar) {
1275
+		foreach ($calendars as $calendar) {
1276 1276
 			if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1277 1277
 				$ownCalendars[] = $calendar['id'];
1278 1278
 			} else {
@@ -1287,11 +1287,11 @@  discard block
 block discarded – undo
1287 1287
 		$query = $this->db->getQueryBuilder();
1288 1288
 		// Calendar id expressions
1289 1289
 		$calendarExpressions = [];
1290
-		foreach($ownCalendars as $id) {
1290
+		foreach ($ownCalendars as $id) {
1291 1291
 			$calendarExpressions[] = $query->expr()
1292 1292
 				->eq('c.calendarid', $query->createNamedParameter($id));
1293 1293
 		}
1294
-		foreach($sharedCalendars as $id) {
1294
+		foreach ($sharedCalendars as $id) {
1295 1295
 			$calendarExpressions[] = $query->expr()->andX(
1296 1296
 				$query->expr()->eq('c.calendarid',
1297 1297
 					$query->createNamedParameter($id)),
@@ -1308,7 +1308,7 @@  discard block
 block discarded – undo
1308 1308
 
1309 1309
 		// Component expressions
1310 1310
 		$compExpressions = [];
1311
-		foreach($filters['comps'] as $comp) {
1311
+		foreach ($filters['comps'] as $comp) {
1312 1312
 			$compExpressions[] = $query->expr()
1313 1313
 				->eq('c.componenttype', $query->createNamedParameter($comp));
1314 1314
 		}
@@ -1327,13 +1327,13 @@  discard block
 block discarded – undo
1327 1327
 		}
1328 1328
 
1329 1329
 		$propParamExpressions = [];
1330
-		foreach($filters['props'] as $prop) {
1330
+		foreach ($filters['props'] as $prop) {
1331 1331
 			$propParamExpressions[] = $query->expr()->andX(
1332 1332
 				$query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1333 1333
 				$query->expr()->isNull('i.parameter')
1334 1334
 			);
1335 1335
 		}
1336
-		foreach($filters['params'] as $param) {
1336
+		foreach ($filters['params'] as $param) {
1337 1337
 			$propParamExpressions[] = $query->expr()->andX(
1338 1338
 				$query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1339 1339
 				$query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
@@ -1365,8 +1365,8 @@  discard block
 block discarded – undo
1365 1365
 		$stmt = $query->execute();
1366 1366
 
1367 1367
 		$result = [];
1368
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1369
-			$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1368
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1369
+			$path = $uriMapper[$row['calendarid']].'/'.$row['uri'];
1370 1370
 			if (!in_array($path, $result)) {
1371 1371
 				$result[] = $path;
1372 1372
 			}
@@ -1404,7 +1404,7 @@  discard block
 block discarded – undo
1404 1404
 		}
1405 1405
 
1406 1406
 		$or = $innerQuery->expr()->orX();
1407
-		foreach($searchProperties as $searchProperty) {
1407
+		foreach ($searchProperties as $searchProperty) {
1408 1408
 			$or->add($innerQuery->expr()->eq('op.name',
1409 1409
 				$outerQuery->createNamedParameter($searchProperty)));
1410 1410
 		}
@@ -1412,8 +1412,8 @@  discard block
 block discarded – undo
1412 1412
 
1413 1413
 		if ($pattern !== '') {
1414 1414
 			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1415
-				$outerQuery->createNamedParameter('%' .
1416
-					$this->db->escapeLikeParameter($pattern) . '%')));
1415
+				$outerQuery->createNamedParameter('%'.
1416
+					$this->db->escapeLikeParameter($pattern).'%')));
1417 1417
 		}
1418 1418
 
1419 1419
 		$outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
@@ -1433,7 +1433,7 @@  discard block
 block discarded – undo
1433 1433
 
1434 1434
 		if (isset($options['types'])) {
1435 1435
 			$or = $outerQuery->expr()->orX();
1436
-			foreach($options['types'] as $type) {
1436
+			foreach ($options['types'] as $type) {
1437 1437
 				$or->add($outerQuery->expr()->eq('componenttype',
1438 1438
 					$outerQuery->createNamedParameter($type)));
1439 1439
 			}
@@ -1458,7 +1458,7 @@  discard block
 block discarded – undo
1458 1458
 			$comps = $calendarData->getComponents();
1459 1459
 			$objects = [];
1460 1460
 			$timezones = [];
1461
-			foreach($comps as $comp) {
1461
+			foreach ($comps as $comp) {
1462 1462
 				if ($comp instanceof VTimeZone) {
1463 1463
 					$timezones[] = $comp;
1464 1464
 				} else {
@@ -1495,7 +1495,7 @@  discard block
 block discarded – undo
1495 1495
 		});
1496 1496
 		$validationRules = $comp->getValidationRules();
1497 1497
 
1498
-		foreach($subComponents as $subComponent) {
1498
+		foreach ($subComponents as $subComponent) {
1499 1499
 			$name = $subComponent->name;
1500 1500
 			if (!isset($data[$name])) {
1501 1501
 				$data[$name] = [];
@@ -1503,7 +1503,7 @@  discard block
 block discarded – undo
1503 1503
 			$data[$name][] = $this->transformSearchData($subComponent);
1504 1504
 		}
1505 1505
 
1506
-		foreach($properties as $property) {
1506
+		foreach ($properties as $property) {
1507 1507
 			$name = $property->name;
1508 1508
 			if (!isset($validationRules[$name])) {
1509 1509
 				$validationRules[$name] = '*';
@@ -1573,7 +1573,7 @@  discard block
 block discarded – undo
1573 1573
 		$stmt = $query->execute();
1574 1574
 
1575 1575
 		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1576
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1576
+			return $row['calendaruri'].'/'.$row['objecturi'];
1577 1577
 		}
1578 1578
 
1579 1579
 		return null;
@@ -1638,7 +1638,7 @@  discard block
 block discarded – undo
1638 1638
 	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1639 1639
 		// Current synctoken
1640 1640
 		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1641
-		$stmt->execute([ $calendarId ]);
1641
+		$stmt->execute([$calendarId]);
1642 1642
 		$currentToken = $stmt->fetchColumn(0);
1643 1643
 
1644 1644
 		if (is_null($currentToken)) {
@@ -1655,8 +1655,8 @@  discard block
 block discarded – undo
1655 1655
 		if ($syncToken) {
1656 1656
 
1657 1657
 			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1658
-			if ($limit>0) {
1659
-				$query.= " LIMIT " . (int)$limit;
1658
+			if ($limit > 0) {
1659
+				$query .= " LIMIT ".(int) $limit;
1660 1660
 			}
1661 1661
 
1662 1662
 			// Fetching all changes
@@ -1667,15 +1667,15 @@  discard block
 block discarded – undo
1667 1667
 
1668 1668
 			// This loop ensures that any duplicates are overwritten, only the
1669 1669
 			// last change on a node is relevant.
1670
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1670
+			while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1671 1671
 
1672 1672
 				$changes[$row['uri']] = $row['operation'];
1673 1673
 
1674 1674
 			}
1675 1675
 
1676
-			foreach($changes as $uri => $operation) {
1676
+			foreach ($changes as $uri => $operation) {
1677 1677
 
1678
-				switch($operation) {
1678
+				switch ($operation) {
1679 1679
 					case 1 :
1680 1680
 						$result['added'][] = $uri;
1681 1681
 						break;
@@ -1745,10 +1745,10 @@  discard block
 block discarded – undo
1745 1745
 			->from('calendarsubscriptions')
1746 1746
 			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1747 1747
 			->orderBy('calendarorder', 'asc');
1748
-		$stmt =$query->execute();
1748
+		$stmt = $query->execute();
1749 1749
 
1750 1750
 		$subscriptions = [];
1751
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1751
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1752 1752
 
1753 1753
 			$subscription = [
1754 1754
 				'id'           => $row['id'],
@@ -1757,10 +1757,10 @@  discard block
 block discarded – undo
1757 1757
 				'source'       => $row['source'],
1758 1758
 				'lastmodified' => $row['lastmodified'],
1759 1759
 
1760
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1760
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1761 1761
 			];
1762 1762
 
1763
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1763
+			foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1764 1764
 				if (!is_null($row[$dbName])) {
1765 1765
 					$subscription[$xmlName] = $row[$dbName];
1766 1766
 				}
@@ -1799,7 +1799,7 @@  discard block
 block discarded – undo
1799 1799
 
1800 1800
 		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1801 1801
 
1802
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1802
+		foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1803 1803
 			if (array_key_exists($xmlName, $properties)) {
1804 1804
 					$values[$dbName] = $properties[$xmlName];
1805 1805
 					if (in_array($dbName, $propertiesBoolean)) {
@@ -1850,7 +1850,7 @@  discard block
 block discarded – undo
1850 1850
 
1851 1851
 			$newValues = [];
1852 1852
 
1853
-			foreach($mutations as $propertyName=>$propertyValue) {
1853
+			foreach ($mutations as $propertyName=>$propertyValue) {
1854 1854
 				if ($propertyName === '{http://calendarserver.org/ns/}source') {
1855 1855
 					$newValues['source'] = $propertyValue->getHref();
1856 1856
 				} else {
@@ -1862,7 +1862,7 @@  discard block
 block discarded – undo
1862 1862
 			$query = $this->db->getQueryBuilder();
1863 1863
 			$query->update('calendarsubscriptions')
1864 1864
 				->set('lastmodified', $query->createNamedParameter(time()));
1865
-			foreach($newValues as $fieldName=>$value) {
1865
+			foreach ($newValues as $fieldName=>$value) {
1866 1866
 				$query->set($fieldName, $query->createNamedParameter($value));
1867 1867
 			}
1868 1868
 			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
@@ -1912,7 +1912,7 @@  discard block
 block discarded – undo
1912 1912
 
1913 1913
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
1914 1914
 
1915
-		if(!$row) {
1915
+		if (!$row) {
1916 1916
 			return null;
1917 1917
 		}
1918 1918
 
@@ -1920,8 +1920,8 @@  discard block
 block discarded – undo
1920 1920
 				'uri'          => $row['uri'],
1921 1921
 				'calendardata' => $row['calendardata'],
1922 1922
 				'lastmodified' => $row['lastmodified'],
1923
-				'etag'         => '"' . $row['etag'] . '"',
1924
-				'size'         => (int)$row['size'],
1923
+				'etag'         => '"'.$row['etag'].'"',
1924
+				'size'         => (int) $row['size'],
1925 1925
 		];
1926 1926
 	}
1927 1927
 
@@ -1944,13 +1944,13 @@  discard block
 block discarded – undo
1944 1944
 				->execute();
1945 1945
 
1946 1946
 		$result = [];
1947
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1947
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1948 1948
 			$result[] = [
1949 1949
 					'calendardata' => $row['calendardata'],
1950 1950
 					'uri'          => $row['uri'],
1951 1951
 					'lastmodified' => $row['lastmodified'],
1952
-					'etag'         => '"' . $row['etag'] . '"',
1953
-					'size'         => (int)$row['size'],
1952
+					'etag'         => '"'.$row['etag'].'"',
1953
+					'size'         => (int) $row['size'],
1954 1954
 			];
1955 1955
 		}
1956 1956
 
@@ -2042,10 +2042,10 @@  discard block
 block discarded – undo
2042 2042
 		$lastOccurrence = null;
2043 2043
 		$uid = null;
2044 2044
 		$classification = self::CLASSIFICATION_PUBLIC;
2045
-		foreach($vObject->getComponents() as $component) {
2046
-			if ($component->name!=='VTIMEZONE') {
2045
+		foreach ($vObject->getComponents() as $component) {
2046
+			if ($component->name !== 'VTIMEZONE') {
2047 2047
 				$componentType = $component->name;
2048
-				$uid = (string)$component->UID;
2048
+				$uid = (string) $component->UID;
2049 2049
 				break;
2050 2050
 			}
2051 2051
 		}
@@ -2070,13 +2070,13 @@  discard block
 block discarded – undo
2070 2070
 					$lastOccurrence = $firstOccurrence;
2071 2071
 				}
2072 2072
 			} else {
2073
-				$it = new EventIterator($vObject, (string)$component->UID);
2073
+				$it = new EventIterator($vObject, (string) $component->UID);
2074 2074
 				$maxDate = new \DateTime(self::MAX_DATE);
2075 2075
 				if ($it->isInfinite()) {
2076 2076
 					$lastOccurrence = $maxDate->getTimestamp();
2077 2077
 				} else {
2078 2078
 					$end = $it->getDtEnd();
2079
-					while($it->valid() && $end < $maxDate) {
2079
+					while ($it->valid() && $end < $maxDate) {
2080 2080
 						$end = $it->getDtEnd();
2081 2081
 						$it->next();
2082 2082
 
@@ -2295,7 +2295,7 @@  discard block
 block discarded – undo
2295 2295
 			->execute();
2296 2296
 
2297 2297
 		$ids = $result->fetchAll();
2298
-		foreach($ids as $id) {
2298
+		foreach ($ids as $id) {
2299 2299
 			$this->deleteCalendar($id['id']);
2300 2300
 		}
2301 2301
 	}
@@ -2342,10 +2342,10 @@  discard block
 block discarded – undo
2342 2342
 		$result->closeCursor();
2343 2343
 
2344 2344
 		if (!isset($objectIds['id'])) {
2345
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2345
+			throw new \InvalidArgumentException('Calendarobject does not exists: '.$uri);
2346 2346
 		}
2347 2347
 
2348
-		return (int)$objectIds['id'];
2348
+		return (int) $objectIds['id'];
2349 2349
 	}
2350 2350
 
2351 2351
 	private function convertPrincipal($principalUri, $toV2) {
@@ -2360,8 +2360,8 @@  discard block
 block discarded – undo
2360 2360
 	}
2361 2361
 
2362 2362
 	private function addOwnerPrincipal(&$calendarInfo) {
2363
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2364
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2363
+		$ownerPrincipalKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal';
2364
+		$displaynameKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}owner-displayname';
2365 2365
 		if (isset($calendarInfo[$ownerPrincipalKey])) {
2366 2366
 			$uri = $calendarInfo[$ownerPrincipalKey];
2367 2367
 		} else {
Please login to merge, or discard this patch.
Indentation   +2297 added lines, -2297 removed lines patch added patch discarded remove patch
@@ -73,2302 +73,2302 @@
 block discarded – undo
73 73
  */
74 74
 class CalDavBackend extends AbstractBackend implements SyncSupport, SubscriptionSupport, SchedulingSupport {
75 75
 
76
-	const PERSONAL_CALENDAR_URI = 'personal';
77
-	const PERSONAL_CALENDAR_NAME = 'Personal';
78
-
79
-	/**
80
-	 * We need to specify a max date, because we need to stop *somewhere*
81
-	 *
82
-	 * On 32 bit system the maximum for a signed integer is 2147483647, so
83
-	 * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
84
-	 * in 2038-01-19 to avoid problems when the date is converted
85
-	 * to a unix timestamp.
86
-	 */
87
-	const MAX_DATE = '2038-01-01';
88
-
89
-	const ACCESS_PUBLIC = 4;
90
-	const CLASSIFICATION_PUBLIC = 0;
91
-	const CLASSIFICATION_PRIVATE = 1;
92
-	const CLASSIFICATION_CONFIDENTIAL = 2;
93
-
94
-	/**
95
-	 * List of CalDAV properties, and how they map to database field names
96
-	 * Add your own properties by simply adding on to this array.
97
-	 *
98
-	 * Note that only string-based properties are supported here.
99
-	 *
100
-	 * @var array
101
-	 */
102
-	public $propertyMap = [
103
-		'{DAV:}displayname'                          => 'displayname',
104
-		'{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
105
-		'{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
106
-		'{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
107
-		'{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
108
-	];
109
-
110
-	/**
111
-	 * List of subscription properties, and how they map to database field names.
112
-	 *
113
-	 * @var array
114
-	 */
115
-	public $subscriptionPropertyMap = [
116
-		'{DAV:}displayname'                                           => 'displayname',
117
-		'{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
118
-		'{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
119
-		'{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
120
-		'{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
121
-		'{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
122
-		'{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
123
-	];
124
-
125
-	/** @var array properties to index */
126
-	public static $indexProperties = ['CATEGORIES', 'COMMENT', 'DESCRIPTION',
127
-		'LOCATION', 'RESOURCES', 'STATUS', 'SUMMARY', 'ATTENDEE', 'CONTACT',
128
-		'ORGANIZER'];
129
-
130
-	/** @var array parameters to index */
131
-	public static $indexParameters = [
132
-		'ATTENDEE' => ['CN'],
133
-		'ORGANIZER' => ['CN'],
134
-	];
135
-
136
-	/**
137
-	 * @var string[] Map of uid => display name
138
-	 */
139
-	protected $userDisplayNames;
140
-
141
-	/** @var IDBConnection */
142
-	private $db;
143
-
144
-	/** @var Backend */
145
-	private $sharingBackend;
146
-
147
-	/** @var Principal */
148
-	private $principalBackend;
149
-
150
-	/** @var IUserManager */
151
-	private $userManager;
152
-
153
-	/** @var ISecureRandom */
154
-	private $random;
155
-
156
-	/** @var ILogger */
157
-	private $logger;
158
-
159
-	/** @var EventDispatcherInterface */
160
-	private $dispatcher;
161
-
162
-	/** @var bool */
163
-	private $legacyEndpoint;
164
-
165
-	/** @var string */
166
-	private $dbObjectPropertiesTable = 'calendarobjects_props';
167
-
168
-	/**
169
-	 * CalDavBackend constructor.
170
-	 *
171
-	 * @param IDBConnection $db
172
-	 * @param Principal $principalBackend
173
-	 * @param IUserManager $userManager
174
-	 * @param IGroupManager $groupManager
175
-	 * @param ISecureRandom $random
176
-	 * @param ILogger $logger
177
-	 * @param EventDispatcherInterface $dispatcher
178
-	 * @param bool $legacyEndpoint
179
-	 */
180
-	public function __construct(IDBConnection $db,
181
-								Principal $principalBackend,
182
-								IUserManager $userManager,
183
-								IGroupManager $groupManager,
184
-								ISecureRandom $random,
185
-								ILogger $logger,
186
-								EventDispatcherInterface $dispatcher,
187
-								$legacyEndpoint = false) {
188
-		$this->db = $db;
189
-		$this->principalBackend = $principalBackend;
190
-		$this->userManager = $userManager;
191
-		$this->sharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'calendar');
192
-		$this->random = $random;
193
-		$this->logger = $logger;
194
-		$this->dispatcher = $dispatcher;
195
-		$this->legacyEndpoint = $legacyEndpoint;
196
-	}
197
-
198
-	/**
199
-	 * Return the number of calendars for a principal
200
-	 *
201
-	 * By default this excludes the automatically generated birthday calendar
202
-	 *
203
-	 * @param $principalUri
204
-	 * @param bool $excludeBirthday
205
-	 * @return int
206
-	 */
207
-	public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
208
-		$principalUri = $this->convertPrincipal($principalUri, true);
209
-		$query = $this->db->getQueryBuilder();
210
-		$query->select($query->createFunction('COUNT(*)'))
211
-			->from('calendars')
212
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
213
-
214
-		if ($excludeBirthday) {
215
-			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
216
-		}
217
-
218
-		return (int)$query->execute()->fetchColumn();
219
-	}
220
-
221
-	/**
222
-	 * Returns a list of calendars for a principal.
223
-	 *
224
-	 * Every project is an array with the following keys:
225
-	 *  * id, a unique id that will be used by other functions to modify the
226
-	 *    calendar. This can be the same as the uri or a database key.
227
-	 *  * uri, which the basename of the uri with which the calendar is
228
-	 *    accessed.
229
-	 *  * principaluri. The owner of the calendar. Almost always the same as
230
-	 *    principalUri passed to this method.
231
-	 *
232
-	 * Furthermore it can contain webdav properties in clark notation. A very
233
-	 * common one is '{DAV:}displayname'.
234
-	 *
235
-	 * Many clients also require:
236
-	 * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
237
-	 * For this property, you can just return an instance of
238
-	 * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
239
-	 *
240
-	 * If you return {http://sabredav.org/ns}read-only and set the value to 1,
241
-	 * ACL will automatically be put in read-only mode.
242
-	 *
243
-	 * @param string $principalUri
244
-	 * @return array
245
-	 */
246
-	function getCalendarsForUser($principalUri) {
247
-		$principalUriOriginal = $principalUri;
248
-		$principalUri = $this->convertPrincipal($principalUri, true);
249
-		$fields = array_values($this->propertyMap);
250
-		$fields[] = 'id';
251
-		$fields[] = 'uri';
252
-		$fields[] = 'synctoken';
253
-		$fields[] = 'components';
254
-		$fields[] = 'principaluri';
255
-		$fields[] = 'transparent';
256
-
257
-		// Making fields a comma-delimited list
258
-		$query = $this->db->getQueryBuilder();
259
-		$query->select($fields)->from('calendars')
260
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
261
-				->orderBy('calendarorder', 'ASC');
262
-		$stmt = $query->execute();
263
-
264
-		$calendars = [];
265
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
266
-
267
-			$components = [];
268
-			if ($row['components']) {
269
-				$components = explode(',',$row['components']);
270
-			}
271
-
272
-			$calendar = [
273
-				'id' => $row['id'],
274
-				'uri' => $row['uri'],
275
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
276
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
277
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
278
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
279
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
280
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
281
-			];
282
-
283
-			foreach($this->propertyMap as $xmlName=>$dbName) {
284
-				$calendar[$xmlName] = $row[$dbName];
285
-			}
286
-
287
-			$this->addOwnerPrincipal($calendar);
288
-
289
-			if (!isset($calendars[$calendar['id']])) {
290
-				$calendars[$calendar['id']] = $calendar;
291
-			}
292
-		}
293
-
294
-		$stmt->closeCursor();
295
-
296
-		// query for shared calendars
297
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
298
-		$principals = array_map(function($principal) {
299
-			return urldecode($principal);
300
-		}, $principals);
301
-		$principals[]= $principalUri;
302
-
303
-		$fields = array_values($this->propertyMap);
304
-		$fields[] = 'a.id';
305
-		$fields[] = 'a.uri';
306
-		$fields[] = 'a.synctoken';
307
-		$fields[] = 'a.components';
308
-		$fields[] = 'a.principaluri';
309
-		$fields[] = 'a.transparent';
310
-		$fields[] = 's.access';
311
-		$query = $this->db->getQueryBuilder();
312
-		$result = $query->select($fields)
313
-			->from('dav_shares', 's')
314
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
315
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
316
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
317
-			->setParameter('type', 'calendar')
318
-			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
319
-			->execute();
320
-
321
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
322
-		while($row = $result->fetch()) {
323
-			if ($row['principaluri'] === $principalUri) {
324
-				continue;
325
-			}
326
-
327
-			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
328
-			if (isset($calendars[$row['id']])) {
329
-				if ($readOnly) {
330
-					// New share can not have more permissions then the old one.
331
-					continue;
332
-				}
333
-				if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
334
-					$calendars[$row['id']][$readOnlyPropertyName] === 0) {
335
-					// Old share is already read-write, no more permissions can be gained
336
-					continue;
337
-				}
338
-			}
339
-
340
-			list(, $name) = Uri\split($row['principaluri']);
341
-			$uri = $row['uri'] . '_shared_by_' . $name;
342
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
343
-			$components = [];
344
-			if ($row['components']) {
345
-				$components = explode(',',$row['components']);
346
-			}
347
-			$calendar = [
348
-				'id' => $row['id'],
349
-				'uri' => $uri,
350
-				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
351
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
352
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
353
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
354
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
355
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
356
-				$readOnlyPropertyName => $readOnly,
357
-			];
358
-
359
-			foreach($this->propertyMap as $xmlName=>$dbName) {
360
-				$calendar[$xmlName] = $row[$dbName];
361
-			}
362
-
363
-			$this->addOwnerPrincipal($calendar);
364
-
365
-			$calendars[$calendar['id']] = $calendar;
366
-		}
367
-		$result->closeCursor();
368
-
369
-		return array_values($calendars);
370
-	}
371
-
372
-	public function getUsersOwnCalendars($principalUri) {
373
-		$principalUri = $this->convertPrincipal($principalUri, true);
374
-		$fields = array_values($this->propertyMap);
375
-		$fields[] = 'id';
376
-		$fields[] = 'uri';
377
-		$fields[] = 'synctoken';
378
-		$fields[] = 'components';
379
-		$fields[] = 'principaluri';
380
-		$fields[] = 'transparent';
381
-		// Making fields a comma-delimited list
382
-		$query = $this->db->getQueryBuilder();
383
-		$query->select($fields)->from('calendars')
384
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
385
-			->orderBy('calendarorder', 'ASC');
386
-		$stmt = $query->execute();
387
-		$calendars = [];
388
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
389
-			$components = [];
390
-			if ($row['components']) {
391
-				$components = explode(',',$row['components']);
392
-			}
393
-			$calendar = [
394
-				'id' => $row['id'],
395
-				'uri' => $row['uri'],
396
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
397
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
398
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
399
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
400
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
401
-			];
402
-			foreach($this->propertyMap as $xmlName=>$dbName) {
403
-				$calendar[$xmlName] = $row[$dbName];
404
-			}
405
-
406
-			$this->addOwnerPrincipal($calendar);
407
-
408
-			if (!isset($calendars[$calendar['id']])) {
409
-				$calendars[$calendar['id']] = $calendar;
410
-			}
411
-		}
412
-		$stmt->closeCursor();
413
-		return array_values($calendars);
414
-	}
415
-
416
-
417
-	private function getUserDisplayName($uid) {
418
-		if (!isset($this->userDisplayNames[$uid])) {
419
-			$user = $this->userManager->get($uid);
420
-
421
-			if ($user instanceof IUser) {
422
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
423
-			} else {
424
-				$this->userDisplayNames[$uid] = $uid;
425
-			}
426
-		}
427
-
428
-		return $this->userDisplayNames[$uid];
429
-	}
76
+    const PERSONAL_CALENDAR_URI = 'personal';
77
+    const PERSONAL_CALENDAR_NAME = 'Personal';
78
+
79
+    /**
80
+     * We need to specify a max date, because we need to stop *somewhere*
81
+     *
82
+     * On 32 bit system the maximum for a signed integer is 2147483647, so
83
+     * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
84
+     * in 2038-01-19 to avoid problems when the date is converted
85
+     * to a unix timestamp.
86
+     */
87
+    const MAX_DATE = '2038-01-01';
88
+
89
+    const ACCESS_PUBLIC = 4;
90
+    const CLASSIFICATION_PUBLIC = 0;
91
+    const CLASSIFICATION_PRIVATE = 1;
92
+    const CLASSIFICATION_CONFIDENTIAL = 2;
93
+
94
+    /**
95
+     * List of CalDAV properties, and how they map to database field names
96
+     * Add your own properties by simply adding on to this array.
97
+     *
98
+     * Note that only string-based properties are supported here.
99
+     *
100
+     * @var array
101
+     */
102
+    public $propertyMap = [
103
+        '{DAV:}displayname'                          => 'displayname',
104
+        '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
105
+        '{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
106
+        '{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
107
+        '{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
108
+    ];
109
+
110
+    /**
111
+     * List of subscription properties, and how they map to database field names.
112
+     *
113
+     * @var array
114
+     */
115
+    public $subscriptionPropertyMap = [
116
+        '{DAV:}displayname'                                           => 'displayname',
117
+        '{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
118
+        '{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
119
+        '{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
120
+        '{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
121
+        '{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
122
+        '{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
123
+    ];
124
+
125
+    /** @var array properties to index */
126
+    public static $indexProperties = ['CATEGORIES', 'COMMENT', 'DESCRIPTION',
127
+        'LOCATION', 'RESOURCES', 'STATUS', 'SUMMARY', 'ATTENDEE', 'CONTACT',
128
+        'ORGANIZER'];
129
+
130
+    /** @var array parameters to index */
131
+    public static $indexParameters = [
132
+        'ATTENDEE' => ['CN'],
133
+        'ORGANIZER' => ['CN'],
134
+    ];
135
+
136
+    /**
137
+     * @var string[] Map of uid => display name
138
+     */
139
+    protected $userDisplayNames;
140
+
141
+    /** @var IDBConnection */
142
+    private $db;
143
+
144
+    /** @var Backend */
145
+    private $sharingBackend;
146
+
147
+    /** @var Principal */
148
+    private $principalBackend;
149
+
150
+    /** @var IUserManager */
151
+    private $userManager;
152
+
153
+    /** @var ISecureRandom */
154
+    private $random;
155
+
156
+    /** @var ILogger */
157
+    private $logger;
158
+
159
+    /** @var EventDispatcherInterface */
160
+    private $dispatcher;
161
+
162
+    /** @var bool */
163
+    private $legacyEndpoint;
164
+
165
+    /** @var string */
166
+    private $dbObjectPropertiesTable = 'calendarobjects_props';
167
+
168
+    /**
169
+     * CalDavBackend constructor.
170
+     *
171
+     * @param IDBConnection $db
172
+     * @param Principal $principalBackend
173
+     * @param IUserManager $userManager
174
+     * @param IGroupManager $groupManager
175
+     * @param ISecureRandom $random
176
+     * @param ILogger $logger
177
+     * @param EventDispatcherInterface $dispatcher
178
+     * @param bool $legacyEndpoint
179
+     */
180
+    public function __construct(IDBConnection $db,
181
+                                Principal $principalBackend,
182
+                                IUserManager $userManager,
183
+                                IGroupManager $groupManager,
184
+                                ISecureRandom $random,
185
+                                ILogger $logger,
186
+                                EventDispatcherInterface $dispatcher,
187
+                                $legacyEndpoint = false) {
188
+        $this->db = $db;
189
+        $this->principalBackend = $principalBackend;
190
+        $this->userManager = $userManager;
191
+        $this->sharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'calendar');
192
+        $this->random = $random;
193
+        $this->logger = $logger;
194
+        $this->dispatcher = $dispatcher;
195
+        $this->legacyEndpoint = $legacyEndpoint;
196
+    }
197
+
198
+    /**
199
+     * Return the number of calendars for a principal
200
+     *
201
+     * By default this excludes the automatically generated birthday calendar
202
+     *
203
+     * @param $principalUri
204
+     * @param bool $excludeBirthday
205
+     * @return int
206
+     */
207
+    public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
208
+        $principalUri = $this->convertPrincipal($principalUri, true);
209
+        $query = $this->db->getQueryBuilder();
210
+        $query->select($query->createFunction('COUNT(*)'))
211
+            ->from('calendars')
212
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
213
+
214
+        if ($excludeBirthday) {
215
+            $query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
216
+        }
217
+
218
+        return (int)$query->execute()->fetchColumn();
219
+    }
220
+
221
+    /**
222
+     * Returns a list of calendars for a principal.
223
+     *
224
+     * Every project is an array with the following keys:
225
+     *  * id, a unique id that will be used by other functions to modify the
226
+     *    calendar. This can be the same as the uri or a database key.
227
+     *  * uri, which the basename of the uri with which the calendar is
228
+     *    accessed.
229
+     *  * principaluri. The owner of the calendar. Almost always the same as
230
+     *    principalUri passed to this method.
231
+     *
232
+     * Furthermore it can contain webdav properties in clark notation. A very
233
+     * common one is '{DAV:}displayname'.
234
+     *
235
+     * Many clients also require:
236
+     * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
237
+     * For this property, you can just return an instance of
238
+     * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
239
+     *
240
+     * If you return {http://sabredav.org/ns}read-only and set the value to 1,
241
+     * ACL will automatically be put in read-only mode.
242
+     *
243
+     * @param string $principalUri
244
+     * @return array
245
+     */
246
+    function getCalendarsForUser($principalUri) {
247
+        $principalUriOriginal = $principalUri;
248
+        $principalUri = $this->convertPrincipal($principalUri, true);
249
+        $fields = array_values($this->propertyMap);
250
+        $fields[] = 'id';
251
+        $fields[] = 'uri';
252
+        $fields[] = 'synctoken';
253
+        $fields[] = 'components';
254
+        $fields[] = 'principaluri';
255
+        $fields[] = 'transparent';
256
+
257
+        // Making fields a comma-delimited list
258
+        $query = $this->db->getQueryBuilder();
259
+        $query->select($fields)->from('calendars')
260
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
261
+                ->orderBy('calendarorder', 'ASC');
262
+        $stmt = $query->execute();
263
+
264
+        $calendars = [];
265
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
266
+
267
+            $components = [];
268
+            if ($row['components']) {
269
+                $components = explode(',',$row['components']);
270
+            }
271
+
272
+            $calendar = [
273
+                'id' => $row['id'],
274
+                'uri' => $row['uri'],
275
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
276
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
277
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
278
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
279
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
280
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
281
+            ];
282
+
283
+            foreach($this->propertyMap as $xmlName=>$dbName) {
284
+                $calendar[$xmlName] = $row[$dbName];
285
+            }
286
+
287
+            $this->addOwnerPrincipal($calendar);
288
+
289
+            if (!isset($calendars[$calendar['id']])) {
290
+                $calendars[$calendar['id']] = $calendar;
291
+            }
292
+        }
293
+
294
+        $stmt->closeCursor();
295
+
296
+        // query for shared calendars
297
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
298
+        $principals = array_map(function($principal) {
299
+            return urldecode($principal);
300
+        }, $principals);
301
+        $principals[]= $principalUri;
302
+
303
+        $fields = array_values($this->propertyMap);
304
+        $fields[] = 'a.id';
305
+        $fields[] = 'a.uri';
306
+        $fields[] = 'a.synctoken';
307
+        $fields[] = 'a.components';
308
+        $fields[] = 'a.principaluri';
309
+        $fields[] = 'a.transparent';
310
+        $fields[] = 's.access';
311
+        $query = $this->db->getQueryBuilder();
312
+        $result = $query->select($fields)
313
+            ->from('dav_shares', 's')
314
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
315
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
316
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
317
+            ->setParameter('type', 'calendar')
318
+            ->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
319
+            ->execute();
320
+
321
+        $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
322
+        while($row = $result->fetch()) {
323
+            if ($row['principaluri'] === $principalUri) {
324
+                continue;
325
+            }
326
+
327
+            $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
328
+            if (isset($calendars[$row['id']])) {
329
+                if ($readOnly) {
330
+                    // New share can not have more permissions then the old one.
331
+                    continue;
332
+                }
333
+                if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
334
+                    $calendars[$row['id']][$readOnlyPropertyName] === 0) {
335
+                    // Old share is already read-write, no more permissions can be gained
336
+                    continue;
337
+                }
338
+            }
339
+
340
+            list(, $name) = Uri\split($row['principaluri']);
341
+            $uri = $row['uri'] . '_shared_by_' . $name;
342
+            $row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
343
+            $components = [];
344
+            if ($row['components']) {
345
+                $components = explode(',',$row['components']);
346
+            }
347
+            $calendar = [
348
+                'id' => $row['id'],
349
+                'uri' => $uri,
350
+                'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
351
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
352
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
353
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
354
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
355
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
356
+                $readOnlyPropertyName => $readOnly,
357
+            ];
358
+
359
+            foreach($this->propertyMap as $xmlName=>$dbName) {
360
+                $calendar[$xmlName] = $row[$dbName];
361
+            }
362
+
363
+            $this->addOwnerPrincipal($calendar);
364
+
365
+            $calendars[$calendar['id']] = $calendar;
366
+        }
367
+        $result->closeCursor();
368
+
369
+        return array_values($calendars);
370
+    }
371
+
372
+    public function getUsersOwnCalendars($principalUri) {
373
+        $principalUri = $this->convertPrincipal($principalUri, true);
374
+        $fields = array_values($this->propertyMap);
375
+        $fields[] = 'id';
376
+        $fields[] = 'uri';
377
+        $fields[] = 'synctoken';
378
+        $fields[] = 'components';
379
+        $fields[] = 'principaluri';
380
+        $fields[] = 'transparent';
381
+        // Making fields a comma-delimited list
382
+        $query = $this->db->getQueryBuilder();
383
+        $query->select($fields)->from('calendars')
384
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
385
+            ->orderBy('calendarorder', 'ASC');
386
+        $stmt = $query->execute();
387
+        $calendars = [];
388
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
389
+            $components = [];
390
+            if ($row['components']) {
391
+                $components = explode(',',$row['components']);
392
+            }
393
+            $calendar = [
394
+                'id' => $row['id'],
395
+                'uri' => $row['uri'],
396
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
397
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
398
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
399
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
400
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
401
+            ];
402
+            foreach($this->propertyMap as $xmlName=>$dbName) {
403
+                $calendar[$xmlName] = $row[$dbName];
404
+            }
405
+
406
+            $this->addOwnerPrincipal($calendar);
407
+
408
+            if (!isset($calendars[$calendar['id']])) {
409
+                $calendars[$calendar['id']] = $calendar;
410
+            }
411
+        }
412
+        $stmt->closeCursor();
413
+        return array_values($calendars);
414
+    }
415
+
416
+
417
+    private function getUserDisplayName($uid) {
418
+        if (!isset($this->userDisplayNames[$uid])) {
419
+            $user = $this->userManager->get($uid);
420
+
421
+            if ($user instanceof IUser) {
422
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
423
+            } else {
424
+                $this->userDisplayNames[$uid] = $uid;
425
+            }
426
+        }
427
+
428
+        return $this->userDisplayNames[$uid];
429
+    }
430 430
 	
431
-	/**
432
-	 * @return array
433
-	 */
434
-	public function getPublicCalendars() {
435
-		$fields = array_values($this->propertyMap);
436
-		$fields[] = 'a.id';
437
-		$fields[] = 'a.uri';
438
-		$fields[] = 'a.synctoken';
439
-		$fields[] = 'a.components';
440
-		$fields[] = 'a.principaluri';
441
-		$fields[] = 'a.transparent';
442
-		$fields[] = 's.access';
443
-		$fields[] = 's.publicuri';
444
-		$calendars = [];
445
-		$query = $this->db->getQueryBuilder();
446
-		$result = $query->select($fields)
447
-			->from('dav_shares', 's')
448
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
449
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
450
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
451
-			->execute();
452
-
453
-		while($row = $result->fetch()) {
454
-			list(, $name) = Uri\split($row['principaluri']);
455
-			$row['displayname'] = $row['displayname'] . "($name)";
456
-			$components = [];
457
-			if ($row['components']) {
458
-				$components = explode(',',$row['components']);
459
-			}
460
-			$calendar = [
461
-				'id' => $row['id'],
462
-				'uri' => $row['publicuri'],
463
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
464
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
465
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
466
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
467
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
468
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
469
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
470
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
471
-			];
472
-
473
-			foreach($this->propertyMap as $xmlName=>$dbName) {
474
-				$calendar[$xmlName] = $row[$dbName];
475
-			}
476
-
477
-			$this->addOwnerPrincipal($calendar);
478
-
479
-			if (!isset($calendars[$calendar['id']])) {
480
-				$calendars[$calendar['id']] = $calendar;
481
-			}
482
-		}
483
-		$result->closeCursor();
484
-
485
-		return array_values($calendars);
486
-	}
487
-
488
-	/**
489
-	 * @param string $uri
490
-	 * @return array
491
-	 * @throws NotFound
492
-	 */
493
-	public function getPublicCalendar($uri) {
494
-		$fields = array_values($this->propertyMap);
495
-		$fields[] = 'a.id';
496
-		$fields[] = 'a.uri';
497
-		$fields[] = 'a.synctoken';
498
-		$fields[] = 'a.components';
499
-		$fields[] = 'a.principaluri';
500
-		$fields[] = 'a.transparent';
501
-		$fields[] = 's.access';
502
-		$fields[] = 's.publicuri';
503
-		$query = $this->db->getQueryBuilder();
504
-		$result = $query->select($fields)
505
-			->from('dav_shares', 's')
506
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
507
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
508
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
509
-			->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
510
-			->execute();
511
-
512
-		$row = $result->fetch(\PDO::FETCH_ASSOC);
513
-
514
-		$result->closeCursor();
515
-
516
-		if ($row === false) {
517
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
518
-		}
519
-
520
-		list(, $name) = Uri\split($row['principaluri']);
521
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
522
-		$components = [];
523
-		if ($row['components']) {
524
-			$components = explode(',',$row['components']);
525
-		}
526
-		$calendar = [
527
-			'id' => $row['id'],
528
-			'uri' => $row['publicuri'],
529
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
530
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
531
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
532
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
533
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
534
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
535
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
536
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
537
-		];
538
-
539
-		foreach($this->propertyMap as $xmlName=>$dbName) {
540
-			$calendar[$xmlName] = $row[$dbName];
541
-		}
542
-
543
-		$this->addOwnerPrincipal($calendar);
544
-
545
-		return $calendar;
546
-
547
-	}
548
-
549
-	/**
550
-	 * @param string $principal
551
-	 * @param string $uri
552
-	 * @return array|null
553
-	 */
554
-	public function getCalendarByUri($principal, $uri) {
555
-		$fields = array_values($this->propertyMap);
556
-		$fields[] = 'id';
557
-		$fields[] = 'uri';
558
-		$fields[] = 'synctoken';
559
-		$fields[] = 'components';
560
-		$fields[] = 'principaluri';
561
-		$fields[] = 'transparent';
562
-
563
-		// Making fields a comma-delimited list
564
-		$query = $this->db->getQueryBuilder();
565
-		$query->select($fields)->from('calendars')
566
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
567
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
568
-			->setMaxResults(1);
569
-		$stmt = $query->execute();
570
-
571
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
572
-		$stmt->closeCursor();
573
-		if ($row === false) {
574
-			return null;
575
-		}
576
-
577
-		$components = [];
578
-		if ($row['components']) {
579
-			$components = explode(',',$row['components']);
580
-		}
581
-
582
-		$calendar = [
583
-			'id' => $row['id'],
584
-			'uri' => $row['uri'],
585
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
586
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
587
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
588
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
589
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
590
-		];
591
-
592
-		foreach($this->propertyMap as $xmlName=>$dbName) {
593
-			$calendar[$xmlName] = $row[$dbName];
594
-		}
595
-
596
-		$this->addOwnerPrincipal($calendar);
597
-
598
-		return $calendar;
599
-	}
600
-
601
-	public function getCalendarById($calendarId) {
602
-		$fields = array_values($this->propertyMap);
603
-		$fields[] = 'id';
604
-		$fields[] = 'uri';
605
-		$fields[] = 'synctoken';
606
-		$fields[] = 'components';
607
-		$fields[] = 'principaluri';
608
-		$fields[] = 'transparent';
609
-
610
-		// Making fields a comma-delimited list
611
-		$query = $this->db->getQueryBuilder();
612
-		$query->select($fields)->from('calendars')
613
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
614
-			->setMaxResults(1);
615
-		$stmt = $query->execute();
616
-
617
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
618
-		$stmt->closeCursor();
619
-		if ($row === false) {
620
-			return null;
621
-		}
622
-
623
-		$components = [];
624
-		if ($row['components']) {
625
-			$components = explode(',',$row['components']);
626
-		}
627
-
628
-		$calendar = [
629
-			'id' => $row['id'],
630
-			'uri' => $row['uri'],
631
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
632
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
633
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
634
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
635
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
636
-		];
637
-
638
-		foreach($this->propertyMap as $xmlName=>$dbName) {
639
-			$calendar[$xmlName] = $row[$dbName];
640
-		}
641
-
642
-		$this->addOwnerPrincipal($calendar);
643
-
644
-		return $calendar;
645
-	}
646
-
647
-	/**
648
-	 * Creates a new calendar for a principal.
649
-	 *
650
-	 * If the creation was a success, an id must be returned that can be used to reference
651
-	 * this calendar in other methods, such as updateCalendar.
652
-	 *
653
-	 * @param string $principalUri
654
-	 * @param string $calendarUri
655
-	 * @param array $properties
656
-	 * @return int
657
-	 * @suppress SqlInjectionChecker
658
-	 */
659
-	function createCalendar($principalUri, $calendarUri, array $properties) {
660
-		$values = [
661
-			'principaluri' => $this->convertPrincipal($principalUri, true),
662
-			'uri'          => $calendarUri,
663
-			'synctoken'    => 1,
664
-			'transparent'  => 0,
665
-			'components'   => 'VEVENT,VTODO',
666
-			'displayname'  => $calendarUri
667
-		];
668
-
669
-		// Default value
670
-		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
671
-		if (isset($properties[$sccs])) {
672
-			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
673
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
674
-			}
675
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
676
-		}
677
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
678
-		if (isset($properties[$transp])) {
679
-			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
680
-		}
681
-
682
-		foreach($this->propertyMap as $xmlName=>$dbName) {
683
-			if (isset($properties[$xmlName])) {
684
-				$values[$dbName] = $properties[$xmlName];
685
-			}
686
-		}
687
-
688
-		$query = $this->db->getQueryBuilder();
689
-		$query->insert('calendars');
690
-		foreach($values as $column => $value) {
691
-			$query->setValue($column, $query->createNamedParameter($value));
692
-		}
693
-		$query->execute();
694
-		$calendarId = $query->getLastInsertId();
695
-
696
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
697
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
698
-			[
699
-				'calendarId' => $calendarId,
700
-				'calendarData' => $this->getCalendarById($calendarId),
701
-		]));
702
-
703
-		return $calendarId;
704
-	}
705
-
706
-	/**
707
-	 * Updates properties for a calendar.
708
-	 *
709
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
710
-	 * To do the actual updates, you must tell this object which properties
711
-	 * you're going to process with the handle() method.
712
-	 *
713
-	 * Calling the handle method is like telling the PropPatch object "I
714
-	 * promise I can handle updating this property".
715
-	 *
716
-	 * Read the PropPatch documentation for more info and examples.
717
-	 *
718
-	 * @param mixed $calendarId
719
-	 * @param PropPatch $propPatch
720
-	 * @return void
721
-	 */
722
-	function updateCalendar($calendarId, PropPatch $propPatch) {
723
-		$supportedProperties = array_keys($this->propertyMap);
724
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
725
-
726
-		/**
727
-		 * @suppress SqlInjectionChecker
728
-		 */
729
-		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
730
-			$newValues = [];
731
-			foreach ($mutations as $propertyName => $propertyValue) {
732
-
733
-				switch ($propertyName) {
734
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
735
-						$fieldName = 'transparent';
736
-						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
737
-						break;
738
-					default :
739
-						$fieldName = $this->propertyMap[$propertyName];
740
-						$newValues[$fieldName] = $propertyValue;
741
-						break;
742
-				}
743
-
744
-			}
745
-			$query = $this->db->getQueryBuilder();
746
-			$query->update('calendars');
747
-			foreach ($newValues as $fieldName => $value) {
748
-				$query->set($fieldName, $query->createNamedParameter($value));
749
-			}
750
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
751
-			$query->execute();
752
-
753
-			$this->addChange($calendarId, "", 2);
754
-
755
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
756
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
757
-				[
758
-					'calendarId' => $calendarId,
759
-					'calendarData' => $this->getCalendarById($calendarId),
760
-					'shares' => $this->getShares($calendarId),
761
-					'propertyMutations' => $mutations,
762
-			]));
763
-
764
-			return true;
765
-		});
766
-	}
767
-
768
-	/**
769
-	 * Delete a calendar and all it's objects
770
-	 *
771
-	 * @param mixed $calendarId
772
-	 * @return void
773
-	 */
774
-	function deleteCalendar($calendarId) {
775
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
776
-			'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
777
-			[
778
-				'calendarId' => $calendarId,
779
-				'calendarData' => $this->getCalendarById($calendarId),
780
-				'shares' => $this->getShares($calendarId),
781
-		]));
782
-
783
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?');
784
-		$stmt->execute([$calendarId]);
785
-
786
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
787
-		$stmt->execute([$calendarId]);
788
-
789
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ?');
790
-		$stmt->execute([$calendarId]);
791
-
792
-		$this->sharingBackend->deleteAllShares($calendarId);
793
-
794
-		$query = $this->db->getQueryBuilder();
795
-		$query->delete($this->dbObjectPropertiesTable)
796
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
797
-			->execute();
798
-	}
799
-
800
-	/**
801
-	 * Delete all of an user's shares
802
-	 *
803
-	 * @param string $principaluri
804
-	 * @return void
805
-	 */
806
-	function deleteAllSharesByUser($principaluri) {
807
-		$this->sharingBackend->deleteAllSharesByUser($principaluri);
808
-	}
809
-
810
-	/**
811
-	 * Returns all calendar objects within a calendar.
812
-	 *
813
-	 * Every item contains an array with the following keys:
814
-	 *   * calendardata - The iCalendar-compatible calendar data
815
-	 *   * uri - a unique key which will be used to construct the uri. This can
816
-	 *     be any arbitrary string, but making sure it ends with '.ics' is a
817
-	 *     good idea. This is only the basename, or filename, not the full
818
-	 *     path.
819
-	 *   * lastmodified - a timestamp of the last modification time
820
-	 *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
821
-	 *   '"abcdef"')
822
-	 *   * size - The size of the calendar objects, in bytes.
823
-	 *   * component - optional, a string containing the type of object, such
824
-	 *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
825
-	 *     the Content-Type header.
826
-	 *
827
-	 * Note that the etag is optional, but it's highly encouraged to return for
828
-	 * speed reasons.
829
-	 *
830
-	 * The calendardata is also optional. If it's not returned
831
-	 * 'getCalendarObject' will be called later, which *is* expected to return
832
-	 * calendardata.
833
-	 *
834
-	 * If neither etag or size are specified, the calendardata will be
835
-	 * used/fetched to determine these numbers. If both are specified the
836
-	 * amount of times this is needed is reduced by a great degree.
837
-	 *
838
-	 * @param mixed $calendarId
839
-	 * @return array
840
-	 */
841
-	function getCalendarObjects($calendarId) {
842
-		$query = $this->db->getQueryBuilder();
843
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
844
-			->from('calendarobjects')
845
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
846
-		$stmt = $query->execute();
847
-
848
-		$result = [];
849
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
850
-			$result[] = [
851
-					'id'           => $row['id'],
852
-					'uri'          => $row['uri'],
853
-					'lastmodified' => $row['lastmodified'],
854
-					'etag'         => '"' . $row['etag'] . '"',
855
-					'calendarid'   => $row['calendarid'],
856
-					'size'         => (int)$row['size'],
857
-					'component'    => strtolower($row['componenttype']),
858
-					'classification'=> (int)$row['classification']
859
-			];
860
-		}
861
-
862
-		return $result;
863
-	}
864
-
865
-	/**
866
-	 * Returns information from a single calendar object, based on it's object
867
-	 * uri.
868
-	 *
869
-	 * The object uri is only the basename, or filename and not a full path.
870
-	 *
871
-	 * The returned array must have the same keys as getCalendarObjects. The
872
-	 * 'calendardata' object is required here though, while it's not required
873
-	 * for getCalendarObjects.
874
-	 *
875
-	 * This method must return null if the object did not exist.
876
-	 *
877
-	 * @param mixed $calendarId
878
-	 * @param string $objectUri
879
-	 * @return array|null
880
-	 */
881
-	function getCalendarObject($calendarId, $objectUri) {
882
-
883
-		$query = $this->db->getQueryBuilder();
884
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
885
-				->from('calendarobjects')
886
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
887
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)));
888
-		$stmt = $query->execute();
889
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
890
-
891
-		if(!$row) return null;
892
-
893
-		return [
894
-				'id'            => $row['id'],
895
-				'uri'           => $row['uri'],
896
-				'lastmodified'  => $row['lastmodified'],
897
-				'etag'          => '"' . $row['etag'] . '"',
898
-				'calendarid'    => $row['calendarid'],
899
-				'size'          => (int)$row['size'],
900
-				'calendardata'  => $this->readBlob($row['calendardata']),
901
-				'component'     => strtolower($row['componenttype']),
902
-				'classification'=> (int)$row['classification']
903
-		];
904
-	}
905
-
906
-	/**
907
-	 * Returns a list of calendar objects.
908
-	 *
909
-	 * This method should work identical to getCalendarObject, but instead
910
-	 * return all the calendar objects in the list as an array.
911
-	 *
912
-	 * If the backend supports this, it may allow for some speed-ups.
913
-	 *
914
-	 * @param mixed $calendarId
915
-	 * @param string[] $uris
916
-	 * @return array
917
-	 */
918
-	function getMultipleCalendarObjects($calendarId, array $uris) {
919
-		if (empty($uris)) {
920
-			return [];
921
-		}
922
-
923
-		$chunks = array_chunk($uris, 100);
924
-		$objects = [];
925
-
926
-		$query = $this->db->getQueryBuilder();
927
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
928
-			->from('calendarobjects')
929
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
930
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
931
-
932
-		foreach ($chunks as $uris) {
933
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
934
-			$result = $query->execute();
935
-
936
-			while ($row = $result->fetch()) {
937
-				$objects[] = [
938
-					'id'           => $row['id'],
939
-					'uri'          => $row['uri'],
940
-					'lastmodified' => $row['lastmodified'],
941
-					'etag'         => '"' . $row['etag'] . '"',
942
-					'calendarid'   => $row['calendarid'],
943
-					'size'         => (int)$row['size'],
944
-					'calendardata' => $this->readBlob($row['calendardata']),
945
-					'component'    => strtolower($row['componenttype']),
946
-					'classification' => (int)$row['classification']
947
-				];
948
-			}
949
-			$result->closeCursor();
950
-		}
951
-		return $objects;
952
-	}
953
-
954
-	/**
955
-	 * Creates a new calendar object.
956
-	 *
957
-	 * The object uri is only the basename, or filename and not a full path.
958
-	 *
959
-	 * It is possible return an etag from this function, which will be used in
960
-	 * the response to this PUT request. Note that the ETag must be surrounded
961
-	 * by double-quotes.
962
-	 *
963
-	 * However, you should only really return this ETag if you don't mangle the
964
-	 * calendar-data. If the result of a subsequent GET to this object is not
965
-	 * the exact same as this request body, you should omit the ETag.
966
-	 *
967
-	 * @param mixed $calendarId
968
-	 * @param string $objectUri
969
-	 * @param string $calendarData
970
-	 * @return string
971
-	 */
972
-	function createCalendarObject($calendarId, $objectUri, $calendarData) {
973
-		$extraData = $this->getDenormalizedData($calendarData);
974
-
975
-		$q = $this->db->getQueryBuilder();
976
-		$q->select($q->createFunction('COUNT(*)'))
977
-			->from('calendarobjects')
978
-			->where($q->expr()->eq('calendarid', $q->createNamedParameter($calendarId)))
979
-			->andWhere($q->expr()->eq('uid', $q->createNamedParameter($extraData['uid'])));
980
-
981
-		$result = $q->execute();
982
-		$count = (int) $result->fetchColumn();
983
-		$result->closeCursor();
984
-
985
-		if ($count !== 0) {
986
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar object with uid already exists in this calendar collection.');
987
-		}
988
-
989
-		$query = $this->db->getQueryBuilder();
990
-		$query->insert('calendarobjects')
991
-			->values([
992
-				'calendarid' => $query->createNamedParameter($calendarId),
993
-				'uri' => $query->createNamedParameter($objectUri),
994
-				'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
995
-				'lastmodified' => $query->createNamedParameter(time()),
996
-				'etag' => $query->createNamedParameter($extraData['etag']),
997
-				'size' => $query->createNamedParameter($extraData['size']),
998
-				'componenttype' => $query->createNamedParameter($extraData['componentType']),
999
-				'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1000
-				'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1001
-				'classification' => $query->createNamedParameter($extraData['classification']),
1002
-				'uid' => $query->createNamedParameter($extraData['uid']),
1003
-			])
1004
-			->execute();
1005
-
1006
-		$this->updateProperties($calendarId, $objectUri, $calendarData);
1007
-
1008
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
1009
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
1010
-			[
1011
-				'calendarId' => $calendarId,
1012
-				'calendarData' => $this->getCalendarById($calendarId),
1013
-				'shares' => $this->getShares($calendarId),
1014
-				'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1015
-			]
1016
-		));
1017
-		$this->addChange($calendarId, $objectUri, 1);
1018
-
1019
-		return '"' . $extraData['etag'] . '"';
1020
-	}
1021
-
1022
-	/**
1023
-	 * Updates an existing calendarobject, based on it's uri.
1024
-	 *
1025
-	 * The object uri is only the basename, or filename and not a full path.
1026
-	 *
1027
-	 * It is possible return an etag from this function, which will be used in
1028
-	 * the response to this PUT request. Note that the ETag must be surrounded
1029
-	 * by double-quotes.
1030
-	 *
1031
-	 * However, you should only really return this ETag if you don't mangle the
1032
-	 * calendar-data. If the result of a subsequent GET to this object is not
1033
-	 * the exact same as this request body, you should omit the ETag.
1034
-	 *
1035
-	 * @param mixed $calendarId
1036
-	 * @param string $objectUri
1037
-	 * @param string $calendarData
1038
-	 * @return string
1039
-	 */
1040
-	function updateCalendarObject($calendarId, $objectUri, $calendarData) {
1041
-		$extraData = $this->getDenormalizedData($calendarData);
1042
-
1043
-		$query = $this->db->getQueryBuilder();
1044
-		$query->update('calendarobjects')
1045
-				->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1046
-				->set('lastmodified', $query->createNamedParameter(time()))
1047
-				->set('etag', $query->createNamedParameter($extraData['etag']))
1048
-				->set('size', $query->createNamedParameter($extraData['size']))
1049
-				->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1050
-				->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1051
-				->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1052
-				->set('classification', $query->createNamedParameter($extraData['classification']))
1053
-				->set('uid', $query->createNamedParameter($extraData['uid']))
1054
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1055
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1056
-			->execute();
1057
-
1058
-		$this->updateProperties($calendarId, $objectUri, $calendarData);
1059
-
1060
-		$data = $this->getCalendarObject($calendarId, $objectUri);
1061
-		if (is_array($data)) {
1062
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
1063
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
1064
-				[
1065
-					'calendarId' => $calendarId,
1066
-					'calendarData' => $this->getCalendarById($calendarId),
1067
-					'shares' => $this->getShares($calendarId),
1068
-					'objectData' => $data,
1069
-				]
1070
-			));
1071
-		}
1072
-		$this->addChange($calendarId, $objectUri, 2);
1073
-
1074
-		return '"' . $extraData['etag'] . '"';
1075
-	}
1076
-
1077
-	/**
1078
-	 * @param int $calendarObjectId
1079
-	 * @param int $classification
1080
-	 */
1081
-	public function setClassification($calendarObjectId, $classification) {
1082
-		if (!in_array($classification, [
1083
-			self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1084
-		])) {
1085
-			throw new \InvalidArgumentException();
1086
-		}
1087
-		$query = $this->db->getQueryBuilder();
1088
-		$query->update('calendarobjects')
1089
-			->set('classification', $query->createNamedParameter($classification))
1090
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1091
-			->execute();
1092
-	}
1093
-
1094
-	/**
1095
-	 * Deletes an existing calendar object.
1096
-	 *
1097
-	 * The object uri is only the basename, or filename and not a full path.
1098
-	 *
1099
-	 * @param mixed $calendarId
1100
-	 * @param string $objectUri
1101
-	 * @return void
1102
-	 */
1103
-	function deleteCalendarObject($calendarId, $objectUri) {
1104
-		$data = $this->getCalendarObject($calendarId, $objectUri);
1105
-		if (is_array($data)) {
1106
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1107
-				'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1108
-				[
1109
-					'calendarId' => $calendarId,
1110
-					'calendarData' => $this->getCalendarById($calendarId),
1111
-					'shares' => $this->getShares($calendarId),
1112
-					'objectData' => $data,
1113
-				]
1114
-			));
1115
-		}
1116
-
1117
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ?');
1118
-		$stmt->execute([$calendarId, $objectUri]);
1119
-
1120
-		$this->purgeProperties($calendarId, $data['id']);
1121
-
1122
-		$this->addChange($calendarId, $objectUri, 3);
1123
-	}
1124
-
1125
-	/**
1126
-	 * Performs a calendar-query on the contents of this calendar.
1127
-	 *
1128
-	 * The calendar-query is defined in RFC4791 : CalDAV. Using the
1129
-	 * calendar-query it is possible for a client to request a specific set of
1130
-	 * object, based on contents of iCalendar properties, date-ranges and
1131
-	 * iCalendar component types (VTODO, VEVENT).
1132
-	 *
1133
-	 * This method should just return a list of (relative) urls that match this
1134
-	 * query.
1135
-	 *
1136
-	 * The list of filters are specified as an array. The exact array is
1137
-	 * documented by Sabre\CalDAV\CalendarQueryParser.
1138
-	 *
1139
-	 * Note that it is extremely likely that getCalendarObject for every path
1140
-	 * returned from this method will be called almost immediately after. You
1141
-	 * may want to anticipate this to speed up these requests.
1142
-	 *
1143
-	 * This method provides a default implementation, which parses *all* the
1144
-	 * iCalendar objects in the specified calendar.
1145
-	 *
1146
-	 * This default may well be good enough for personal use, and calendars
1147
-	 * that aren't very large. But if you anticipate high usage, big calendars
1148
-	 * or high loads, you are strongly advised to optimize certain paths.
1149
-	 *
1150
-	 * The best way to do so is override this method and to optimize
1151
-	 * specifically for 'common filters'.
1152
-	 *
1153
-	 * Requests that are extremely common are:
1154
-	 *   * requests for just VEVENTS
1155
-	 *   * requests for just VTODO
1156
-	 *   * requests with a time-range-filter on either VEVENT or VTODO.
1157
-	 *
1158
-	 * ..and combinations of these requests. It may not be worth it to try to
1159
-	 * handle every possible situation and just rely on the (relatively
1160
-	 * easy to use) CalendarQueryValidator to handle the rest.
1161
-	 *
1162
-	 * Note that especially time-range-filters may be difficult to parse. A
1163
-	 * time-range filter specified on a VEVENT must for instance also handle
1164
-	 * recurrence rules correctly.
1165
-	 * A good example of how to interprete all these filters can also simply
1166
-	 * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1167
-	 * as possible, so it gives you a good idea on what type of stuff you need
1168
-	 * to think of.
1169
-	 *
1170
-	 * @param mixed $calendarId
1171
-	 * @param array $filters
1172
-	 * @return array
1173
-	 */
1174
-	function calendarQuery($calendarId, array $filters) {
1175
-		$componentType = null;
1176
-		$requirePostFilter = true;
1177
-		$timeRange = null;
1178
-
1179
-		// if no filters were specified, we don't need to filter after a query
1180
-		if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1181
-			$requirePostFilter = false;
1182
-		}
1183
-
1184
-		// Figuring out if there's a component filter
1185
-		if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1186
-			$componentType = $filters['comp-filters'][0]['name'];
1187
-
1188
-			// Checking if we need post-filters
1189
-			if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1190
-				$requirePostFilter = false;
1191
-			}
1192
-			// There was a time-range filter
1193
-			if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1194
-				$timeRange = $filters['comp-filters'][0]['time-range'];
1195
-
1196
-				// If start time OR the end time is not specified, we can do a
1197
-				// 100% accurate mysql query.
1198
-				if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1199
-					$requirePostFilter = false;
1200
-				}
1201
-			}
1202
-
1203
-		}
1204
-		$columns = ['uri'];
1205
-		if ($requirePostFilter) {
1206
-			$columns = ['uri', 'calendardata'];
1207
-		}
1208
-		$query = $this->db->getQueryBuilder();
1209
-		$query->select($columns)
1210
-			->from('calendarobjects')
1211
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
1212
-
1213
-		if ($componentType) {
1214
-			$query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1215
-		}
1216
-
1217
-		if ($timeRange && $timeRange['start']) {
1218
-			$query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1219
-		}
1220
-		if ($timeRange && $timeRange['end']) {
1221
-			$query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1222
-		}
1223
-
1224
-		$stmt = $query->execute();
1225
-
1226
-		$result = [];
1227
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1228
-			if ($requirePostFilter) {
1229
-				// validateFilterForObject will parse the calendar data
1230
-				// catch parsing errors
1231
-				try {
1232
-					$matches = $this->validateFilterForObject($row, $filters);
1233
-				} catch(ParseException $ex) {
1234
-					$this->logger->logException($ex, [
1235
-						'app' => 'dav',
1236
-						'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri']
1237
-					]);
1238
-					continue;
1239
-				} catch (InvalidDataException $ex) {
1240
-					$this->logger->logException($ex, [
1241
-						'app' => 'dav',
1242
-						'message' => 'Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri']
1243
-					]);
1244
-					continue;
1245
-				}
1246
-
1247
-				if (!$matches) {
1248
-					continue;
1249
-				}
1250
-			}
1251
-			$result[] = $row['uri'];
1252
-		}
1253
-
1254
-		return $result;
1255
-	}
1256
-
1257
-	/**
1258
-	 * custom Nextcloud search extension for CalDAV
1259
-	 *
1260
-	 * @param string $principalUri
1261
-	 * @param array $filters
1262
-	 * @param integer|null $limit
1263
-	 * @param integer|null $offset
1264
-	 * @return array
1265
-	 */
1266
-	public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1267
-		$calendars = $this->getCalendarsForUser($principalUri);
1268
-		$ownCalendars = [];
1269
-		$sharedCalendars = [];
1270
-
1271
-		$uriMapper = [];
1272
-
1273
-		foreach($calendars as $calendar) {
1274
-			if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1275
-				$ownCalendars[] = $calendar['id'];
1276
-			} else {
1277
-				$sharedCalendars[] = $calendar['id'];
1278
-			}
1279
-			$uriMapper[$calendar['id']] = $calendar['uri'];
1280
-		}
1281
-		if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1282
-			return [];
1283
-		}
1284
-
1285
-		$query = $this->db->getQueryBuilder();
1286
-		// Calendar id expressions
1287
-		$calendarExpressions = [];
1288
-		foreach($ownCalendars as $id) {
1289
-			$calendarExpressions[] = $query->expr()
1290
-				->eq('c.calendarid', $query->createNamedParameter($id));
1291
-		}
1292
-		foreach($sharedCalendars as $id) {
1293
-			$calendarExpressions[] = $query->expr()->andX(
1294
-				$query->expr()->eq('c.calendarid',
1295
-					$query->createNamedParameter($id)),
1296
-				$query->expr()->eq('c.classification',
1297
-					$query->createNamedParameter(self::CLASSIFICATION_PUBLIC))
1298
-			);
1299
-		}
1300
-
1301
-		if (count($calendarExpressions) === 1) {
1302
-			$calExpr = $calendarExpressions[0];
1303
-		} else {
1304
-			$calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1305
-		}
1306
-
1307
-		// Component expressions
1308
-		$compExpressions = [];
1309
-		foreach($filters['comps'] as $comp) {
1310
-			$compExpressions[] = $query->expr()
1311
-				->eq('c.componenttype', $query->createNamedParameter($comp));
1312
-		}
1313
-
1314
-		if (count($compExpressions) === 1) {
1315
-			$compExpr = $compExpressions[0];
1316
-		} else {
1317
-			$compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1318
-		}
1319
-
1320
-		if (!isset($filters['props'])) {
1321
-			$filters['props'] = [];
1322
-		}
1323
-		if (!isset($filters['params'])) {
1324
-			$filters['params'] = [];
1325
-		}
1326
-
1327
-		$propParamExpressions = [];
1328
-		foreach($filters['props'] as $prop) {
1329
-			$propParamExpressions[] = $query->expr()->andX(
1330
-				$query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1331
-				$query->expr()->isNull('i.parameter')
1332
-			);
1333
-		}
1334
-		foreach($filters['params'] as $param) {
1335
-			$propParamExpressions[] = $query->expr()->andX(
1336
-				$query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1337
-				$query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1338
-			);
1339
-		}
1340
-
1341
-		if (count($propParamExpressions) === 1) {
1342
-			$propParamExpr = $propParamExpressions[0];
1343
-		} else {
1344
-			$propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1345
-		}
1346
-
1347
-		$query->select(['c.calendarid', 'c.uri'])
1348
-			->from($this->dbObjectPropertiesTable, 'i')
1349
-			->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1350
-			->where($calExpr)
1351
-			->andWhere($compExpr)
1352
-			->andWhere($propParamExpr)
1353
-			->andWhere($query->expr()->iLike('i.value',
1354
-				$query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')));
1355
-
1356
-		if ($offset) {
1357
-			$query->setFirstResult($offset);
1358
-		}
1359
-		if ($limit) {
1360
-			$query->setMaxResults($limit);
1361
-		}
1362
-
1363
-		$stmt = $query->execute();
1364
-
1365
-		$result = [];
1366
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1367
-			$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1368
-			if (!in_array($path, $result)) {
1369
-				$result[] = $path;
1370
-			}
1371
-		}
1372
-
1373
-		return $result;
1374
-	}
1375
-
1376
-	/**
1377
-	 * used for Nextcloud's calendar API
1378
-	 *
1379
-	 * @param array $calendarInfo
1380
-	 * @param string $pattern
1381
-	 * @param array $searchProperties
1382
-	 * @param array $options
1383
-	 * @param integer|null $limit
1384
-	 * @param integer|null $offset
1385
-	 *
1386
-	 * @return array
1387
-	 */
1388
-	public function search(array $calendarInfo, $pattern, array $searchProperties,
1389
-						   array $options, $limit, $offset) {
1390
-		$outerQuery = $this->db->getQueryBuilder();
1391
-		$innerQuery = $this->db->getQueryBuilder();
1392
-
1393
-		$innerQuery->selectDistinct('op.objectid')
1394
-			->from($this->dbObjectPropertiesTable, 'op')
1395
-			->andWhere($innerQuery->expr()->eq('op.calendarid',
1396
-				$outerQuery->createNamedParameter($calendarInfo['id'])));
1397
-
1398
-		// only return public items for shared calendars for now
1399
-		if ($calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
1400
-			$innerQuery->andWhere($innerQuery->expr()->eq('c.classification',
1401
-				$outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1402
-		}
1403
-
1404
-		$or = $innerQuery->expr()->orX();
1405
-		foreach($searchProperties as $searchProperty) {
1406
-			$or->add($innerQuery->expr()->eq('op.name',
1407
-				$outerQuery->createNamedParameter($searchProperty)));
1408
-		}
1409
-		$innerQuery->andWhere($or);
1410
-
1411
-		if ($pattern !== '') {
1412
-			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1413
-				$outerQuery->createNamedParameter('%' .
1414
-					$this->db->escapeLikeParameter($pattern) . '%')));
1415
-		}
1416
-
1417
-		$outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1418
-			->from('calendarobjects', 'c');
1419
-
1420
-		if (isset($options['timerange'])) {
1421
-			if (isset($options['timerange']['start'])) {
1422
-				$outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence',
1423
-					$outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp)));
1424
-
1425
-			}
1426
-			if (isset($options['timerange']['end'])) {
1427
-				$outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence',
1428
-					$outerQuery->createNamedParameter($options['timerange']['end']->getTimeStamp)));
1429
-			}
1430
-		}
1431
-
1432
-		if (isset($options['types'])) {
1433
-			$or = $outerQuery->expr()->orX();
1434
-			foreach($options['types'] as $type) {
1435
-				$or->add($outerQuery->expr()->eq('componenttype',
1436
-					$outerQuery->createNamedParameter($type)));
1437
-			}
1438
-			$outerQuery->andWhere($or);
1439
-		}
1440
-
1441
-		$outerQuery->andWhere($outerQuery->expr()->in('c.id',
1442
-			$outerQuery->createFunction($innerQuery->getSQL())));
1443
-
1444
-		if ($offset) {
1445
-			$outerQuery->setFirstResult($offset);
1446
-		}
1447
-		if ($limit) {
1448
-			$outerQuery->setMaxResults($limit);
1449
-		}
1450
-
1451
-		$result = $outerQuery->execute();
1452
-		$calendarObjects = $result->fetchAll();
1453
-
1454
-		return array_map(function($o) {
1455
-			$calendarData = Reader::read($o['calendardata']);
1456
-			$comps = $calendarData->getComponents();
1457
-			$objects = [];
1458
-			$timezones = [];
1459
-			foreach($comps as $comp) {
1460
-				if ($comp instanceof VTimeZone) {
1461
-					$timezones[] = $comp;
1462
-				} else {
1463
-					$objects[] = $comp;
1464
-				}
1465
-			}
1466
-
1467
-			return [
1468
-				'id' => $o['id'],
1469
-				'type' => $o['componenttype'],
1470
-				'uid' => $o['uid'],
1471
-				'uri' => $o['uri'],
1472
-				'objects' => array_map(function($c) {
1473
-					return $this->transformSearchData($c);
1474
-				}, $objects),
1475
-				'timezones' => array_map(function($c) {
1476
-					return $this->transformSearchData($c);
1477
-				}, $timezones),
1478
-			];
1479
-		}, $calendarObjects);
1480
-	}
1481
-
1482
-	/**
1483
-	 * @param Component $comp
1484
-	 * @return array
1485
-	 */
1486
-	private function transformSearchData(Component $comp) {
1487
-		$data = [];
1488
-		/** @var Component[] $subComponents */
1489
-		$subComponents = $comp->getComponents();
1490
-		/** @var Property[] $properties */
1491
-		$properties = array_filter($comp->children(), function($c) {
1492
-			return $c instanceof Property;
1493
-		});
1494
-		$validationRules = $comp->getValidationRules();
1495
-
1496
-		foreach($subComponents as $subComponent) {
1497
-			$name = $subComponent->name;
1498
-			if (!isset($data[$name])) {
1499
-				$data[$name] = [];
1500
-			}
1501
-			$data[$name][] = $this->transformSearchData($subComponent);
1502
-		}
1503
-
1504
-		foreach($properties as $property) {
1505
-			$name = $property->name;
1506
-			if (!isset($validationRules[$name])) {
1507
-				$validationRules[$name] = '*';
1508
-			}
1509
-
1510
-			$rule = $validationRules[$property->name];
1511
-			if ($rule === '+' || $rule === '*') { // multiple
1512
-				if (!isset($data[$name])) {
1513
-					$data[$name] = [];
1514
-				}
1515
-
1516
-				$data[$name][] = $this->transformSearchProperty($property);
1517
-			} else { // once
1518
-				$data[$name] = $this->transformSearchProperty($property);
1519
-			}
1520
-		}
1521
-
1522
-		return $data;
1523
-	}
1524
-
1525
-	/**
1526
-	 * @param Property $prop
1527
-	 * @return array
1528
-	 */
1529
-	private function transformSearchProperty(Property $prop) {
1530
-		// No need to check Date, as it extends DateTime
1531
-		if ($prop instanceof Property\ICalendar\DateTime) {
1532
-			$value = $prop->getDateTime();
1533
-		} else {
1534
-			$value = $prop->getValue();
1535
-		}
1536
-
1537
-		return [
1538
-			$value,
1539
-			$prop->parameters()
1540
-		];
1541
-	}
1542
-
1543
-	/**
1544
-	 * Searches through all of a users calendars and calendar objects to find
1545
-	 * an object with a specific UID.
1546
-	 *
1547
-	 * This method should return the path to this object, relative to the
1548
-	 * calendar home, so this path usually only contains two parts:
1549
-	 *
1550
-	 * calendarpath/objectpath.ics
1551
-	 *
1552
-	 * If the uid is not found, return null.
1553
-	 *
1554
-	 * This method should only consider * objects that the principal owns, so
1555
-	 * any calendars owned by other principals that also appear in this
1556
-	 * collection should be ignored.
1557
-	 *
1558
-	 * @param string $principalUri
1559
-	 * @param string $uid
1560
-	 * @return string|null
1561
-	 */
1562
-	function getCalendarObjectByUID($principalUri, $uid) {
1563
-
1564
-		$query = $this->db->getQueryBuilder();
1565
-		$query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1566
-			->from('calendarobjects', 'co')
1567
-			->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1568
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1569
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1570
-
1571
-		$stmt = $query->execute();
1572
-
1573
-		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1574
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1575
-		}
1576
-
1577
-		return null;
1578
-	}
1579
-
1580
-	/**
1581
-	 * The getChanges method returns all the changes that have happened, since
1582
-	 * the specified syncToken in the specified calendar.
1583
-	 *
1584
-	 * This function should return an array, such as the following:
1585
-	 *
1586
-	 * [
1587
-	 *   'syncToken' => 'The current synctoken',
1588
-	 *   'added'   => [
1589
-	 *      'new.txt',
1590
-	 *   ],
1591
-	 *   'modified'   => [
1592
-	 *      'modified.txt',
1593
-	 *   ],
1594
-	 *   'deleted' => [
1595
-	 *      'foo.php.bak',
1596
-	 *      'old.txt'
1597
-	 *   ]
1598
-	 * );
1599
-	 *
1600
-	 * The returned syncToken property should reflect the *current* syncToken
1601
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1602
-	 * property This is * needed here too, to ensure the operation is atomic.
1603
-	 *
1604
-	 * If the $syncToken argument is specified as null, this is an initial
1605
-	 * sync, and all members should be reported.
1606
-	 *
1607
-	 * The modified property is an array of nodenames that have changed since
1608
-	 * the last token.
1609
-	 *
1610
-	 * The deleted property is an array with nodenames, that have been deleted
1611
-	 * from collection.
1612
-	 *
1613
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
1614
-	 * 1, you only have to report changes that happened only directly in
1615
-	 * immediate descendants. If it's 2, it should also include changes from
1616
-	 * the nodes below the child collections. (grandchildren)
1617
-	 *
1618
-	 * The $limit argument allows a client to specify how many results should
1619
-	 * be returned at most. If the limit is not specified, it should be treated
1620
-	 * as infinite.
1621
-	 *
1622
-	 * If the limit (infinite or not) is higher than you're willing to return,
1623
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1624
-	 *
1625
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
1626
-	 * return null.
1627
-	 *
1628
-	 * The limit is 'suggestive'. You are free to ignore it.
1629
-	 *
1630
-	 * @param string $calendarId
1631
-	 * @param string $syncToken
1632
-	 * @param int $syncLevel
1633
-	 * @param int $limit
1634
-	 * @return array
1635
-	 */
1636
-	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1637
-		// Current synctoken
1638
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1639
-		$stmt->execute([ $calendarId ]);
1640
-		$currentToken = $stmt->fetchColumn(0);
1641
-
1642
-		if (is_null($currentToken)) {
1643
-			return null;
1644
-		}
1645
-
1646
-		$result = [
1647
-			'syncToken' => $currentToken,
1648
-			'added'     => [],
1649
-			'modified'  => [],
1650
-			'deleted'   => [],
1651
-		];
1652
-
1653
-		if ($syncToken) {
1654
-
1655
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1656
-			if ($limit>0) {
1657
-				$query.= " LIMIT " . (int)$limit;
1658
-			}
1659
-
1660
-			// Fetching all changes
1661
-			$stmt = $this->db->prepare($query);
1662
-			$stmt->execute([$syncToken, $currentToken, $calendarId]);
1663
-
1664
-			$changes = [];
1665
-
1666
-			// This loop ensures that any duplicates are overwritten, only the
1667
-			// last change on a node is relevant.
1668
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1669
-
1670
-				$changes[$row['uri']] = $row['operation'];
1671
-
1672
-			}
1673
-
1674
-			foreach($changes as $uri => $operation) {
1675
-
1676
-				switch($operation) {
1677
-					case 1 :
1678
-						$result['added'][] = $uri;
1679
-						break;
1680
-					case 2 :
1681
-						$result['modified'][] = $uri;
1682
-						break;
1683
-					case 3 :
1684
-						$result['deleted'][] = $uri;
1685
-						break;
1686
-				}
1687
-
1688
-			}
1689
-		} else {
1690
-			// No synctoken supplied, this is the initial sync.
1691
-			$query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?";
1692
-			$stmt = $this->db->prepare($query);
1693
-			$stmt->execute([$calendarId]);
1694
-
1695
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1696
-		}
1697
-		return $result;
1698
-
1699
-	}
1700
-
1701
-	/**
1702
-	 * Returns a list of subscriptions for a principal.
1703
-	 *
1704
-	 * Every subscription is an array with the following keys:
1705
-	 *  * id, a unique id that will be used by other functions to modify the
1706
-	 *    subscription. This can be the same as the uri or a database key.
1707
-	 *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1708
-	 *  * principaluri. The owner of the subscription. Almost always the same as
1709
-	 *    principalUri passed to this method.
1710
-	 *
1711
-	 * Furthermore, all the subscription info must be returned too:
1712
-	 *
1713
-	 * 1. {DAV:}displayname
1714
-	 * 2. {http://apple.com/ns/ical/}refreshrate
1715
-	 * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1716
-	 *    should not be stripped).
1717
-	 * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1718
-	 *    should not be stripped).
1719
-	 * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1720
-	 *    attachments should not be stripped).
1721
-	 * 6. {http://calendarserver.org/ns/}source (Must be a
1722
-	 *     Sabre\DAV\Property\Href).
1723
-	 * 7. {http://apple.com/ns/ical/}calendar-color
1724
-	 * 8. {http://apple.com/ns/ical/}calendar-order
1725
-	 * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1726
-	 *    (should just be an instance of
1727
-	 *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1728
-	 *    default components).
1729
-	 *
1730
-	 * @param string $principalUri
1731
-	 * @return array
1732
-	 */
1733
-	function getSubscriptionsForUser($principalUri) {
1734
-		$fields = array_values($this->subscriptionPropertyMap);
1735
-		$fields[] = 'id';
1736
-		$fields[] = 'uri';
1737
-		$fields[] = 'source';
1738
-		$fields[] = 'principaluri';
1739
-		$fields[] = 'lastmodified';
1740
-
1741
-		$query = $this->db->getQueryBuilder();
1742
-		$query->select($fields)
1743
-			->from('calendarsubscriptions')
1744
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1745
-			->orderBy('calendarorder', 'asc');
1746
-		$stmt =$query->execute();
1747
-
1748
-		$subscriptions = [];
1749
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1750
-
1751
-			$subscription = [
1752
-				'id'           => $row['id'],
1753
-				'uri'          => $row['uri'],
1754
-				'principaluri' => $row['principaluri'],
1755
-				'source'       => $row['source'],
1756
-				'lastmodified' => $row['lastmodified'],
1757
-
1758
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1759
-			];
1760
-
1761
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1762
-				if (!is_null($row[$dbName])) {
1763
-					$subscription[$xmlName] = $row[$dbName];
1764
-				}
1765
-			}
1766
-
1767
-			$subscriptions[] = $subscription;
1768
-
1769
-		}
1770
-
1771
-		return $subscriptions;
1772
-	}
1773
-
1774
-	/**
1775
-	 * Creates a new subscription for a principal.
1776
-	 *
1777
-	 * If the creation was a success, an id must be returned that can be used to reference
1778
-	 * this subscription in other methods, such as updateSubscription.
1779
-	 *
1780
-	 * @param string $principalUri
1781
-	 * @param string $uri
1782
-	 * @param array $properties
1783
-	 * @return mixed
1784
-	 */
1785
-	function createSubscription($principalUri, $uri, array $properties) {
1786
-
1787
-		if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1788
-			throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1789
-		}
1790
-
1791
-		$values = [
1792
-			'principaluri' => $principalUri,
1793
-			'uri'          => $uri,
1794
-			'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1795
-			'lastmodified' => time(),
1796
-		];
1797
-
1798
-		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1799
-
1800
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1801
-			if (array_key_exists($xmlName, $properties)) {
1802
-					$values[$dbName] = $properties[$xmlName];
1803
-					if (in_array($dbName, $propertiesBoolean)) {
1804
-						$values[$dbName] = true;
1805
-				}
1806
-			}
1807
-		}
1808
-
1809
-		$valuesToInsert = array();
1810
-
1811
-		$query = $this->db->getQueryBuilder();
1812
-
1813
-		foreach (array_keys($values) as $name) {
1814
-			$valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1815
-		}
1816
-
1817
-		$query->insert('calendarsubscriptions')
1818
-			->values($valuesToInsert)
1819
-			->execute();
1820
-
1821
-		return $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1822
-	}
1823
-
1824
-	/**
1825
-	 * Updates a subscription
1826
-	 *
1827
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1828
-	 * To do the actual updates, you must tell this object which properties
1829
-	 * you're going to process with the handle() method.
1830
-	 *
1831
-	 * Calling the handle method is like telling the PropPatch object "I
1832
-	 * promise I can handle updating this property".
1833
-	 *
1834
-	 * Read the PropPatch documentation for more info and examples.
1835
-	 *
1836
-	 * @param mixed $subscriptionId
1837
-	 * @param PropPatch $propPatch
1838
-	 * @return void
1839
-	 */
1840
-	function updateSubscription($subscriptionId, PropPatch $propPatch) {
1841
-		$supportedProperties = array_keys($this->subscriptionPropertyMap);
1842
-		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
1843
-
1844
-		/**
1845
-		 * @suppress SqlInjectionChecker
1846
-		 */
1847
-		$propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1848
-
1849
-			$newValues = [];
1850
-
1851
-			foreach($mutations as $propertyName=>$propertyValue) {
1852
-				if ($propertyName === '{http://calendarserver.org/ns/}source') {
1853
-					$newValues['source'] = $propertyValue->getHref();
1854
-				} else {
1855
-					$fieldName = $this->subscriptionPropertyMap[$propertyName];
1856
-					$newValues[$fieldName] = $propertyValue;
1857
-				}
1858
-			}
1859
-
1860
-			$query = $this->db->getQueryBuilder();
1861
-			$query->update('calendarsubscriptions')
1862
-				->set('lastmodified', $query->createNamedParameter(time()));
1863
-			foreach($newValues as $fieldName=>$value) {
1864
-				$query->set($fieldName, $query->createNamedParameter($value));
1865
-			}
1866
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1867
-				->execute();
1868
-
1869
-			return true;
1870
-
1871
-		});
1872
-	}
1873
-
1874
-	/**
1875
-	 * Deletes a subscription.
1876
-	 *
1877
-	 * @param mixed $subscriptionId
1878
-	 * @return void
1879
-	 */
1880
-	function deleteSubscription($subscriptionId) {
1881
-		$query = $this->db->getQueryBuilder();
1882
-		$query->delete('calendarsubscriptions')
1883
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1884
-			->execute();
1885
-	}
1886
-
1887
-	/**
1888
-	 * Returns a single scheduling object for the inbox collection.
1889
-	 *
1890
-	 * The returned array should contain the following elements:
1891
-	 *   * uri - A unique basename for the object. This will be used to
1892
-	 *           construct a full uri.
1893
-	 *   * calendardata - The iCalendar object
1894
-	 *   * lastmodified - The last modification date. Can be an int for a unix
1895
-	 *                    timestamp, or a PHP DateTime object.
1896
-	 *   * etag - A unique token that must change if the object changed.
1897
-	 *   * size - The size of the object, in bytes.
1898
-	 *
1899
-	 * @param string $principalUri
1900
-	 * @param string $objectUri
1901
-	 * @return array
1902
-	 */
1903
-	function getSchedulingObject($principalUri, $objectUri) {
1904
-		$query = $this->db->getQueryBuilder();
1905
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1906
-			->from('schedulingobjects')
1907
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1908
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1909
-			->execute();
1910
-
1911
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
1912
-
1913
-		if(!$row) {
1914
-			return null;
1915
-		}
1916
-
1917
-		return [
1918
-				'uri'          => $row['uri'],
1919
-				'calendardata' => $row['calendardata'],
1920
-				'lastmodified' => $row['lastmodified'],
1921
-				'etag'         => '"' . $row['etag'] . '"',
1922
-				'size'         => (int)$row['size'],
1923
-		];
1924
-	}
1925
-
1926
-	/**
1927
-	 * Returns all scheduling objects for the inbox collection.
1928
-	 *
1929
-	 * These objects should be returned as an array. Every item in the array
1930
-	 * should follow the same structure as returned from getSchedulingObject.
1931
-	 *
1932
-	 * The main difference is that 'calendardata' is optional.
1933
-	 *
1934
-	 * @param string $principalUri
1935
-	 * @return array
1936
-	 */
1937
-	function getSchedulingObjects($principalUri) {
1938
-		$query = $this->db->getQueryBuilder();
1939
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1940
-				->from('schedulingobjects')
1941
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1942
-				->execute();
1943
-
1944
-		$result = [];
1945
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1946
-			$result[] = [
1947
-					'calendardata' => $row['calendardata'],
1948
-					'uri'          => $row['uri'],
1949
-					'lastmodified' => $row['lastmodified'],
1950
-					'etag'         => '"' . $row['etag'] . '"',
1951
-					'size'         => (int)$row['size'],
1952
-			];
1953
-		}
1954
-
1955
-		return $result;
1956
-	}
1957
-
1958
-	/**
1959
-	 * Deletes a scheduling object from the inbox collection.
1960
-	 *
1961
-	 * @param string $principalUri
1962
-	 * @param string $objectUri
1963
-	 * @return void
1964
-	 */
1965
-	function deleteSchedulingObject($principalUri, $objectUri) {
1966
-		$query = $this->db->getQueryBuilder();
1967
-		$query->delete('schedulingobjects')
1968
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1969
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1970
-				->execute();
1971
-	}
1972
-
1973
-	/**
1974
-	 * Creates a new scheduling object. This should land in a users' inbox.
1975
-	 *
1976
-	 * @param string $principalUri
1977
-	 * @param string $objectUri
1978
-	 * @param string $objectData
1979
-	 * @return void
1980
-	 */
1981
-	function createSchedulingObject($principalUri, $objectUri, $objectData) {
1982
-		$query = $this->db->getQueryBuilder();
1983
-		$query->insert('schedulingobjects')
1984
-			->values([
1985
-				'principaluri' => $query->createNamedParameter($principalUri),
1986
-				'calendardata' => $query->createNamedParameter($objectData),
1987
-				'uri' => $query->createNamedParameter($objectUri),
1988
-				'lastmodified' => $query->createNamedParameter(time()),
1989
-				'etag' => $query->createNamedParameter(md5($objectData)),
1990
-				'size' => $query->createNamedParameter(strlen($objectData))
1991
-			])
1992
-			->execute();
1993
-	}
1994
-
1995
-	/**
1996
-	 * Adds a change record to the calendarchanges table.
1997
-	 *
1998
-	 * @param mixed $calendarId
1999
-	 * @param string $objectUri
2000
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete.
2001
-	 * @return void
2002
-	 */
2003
-	protected function addChange($calendarId, $objectUri, $operation) {
2004
-
2005
-		$stmt = $this->db->prepare('INSERT INTO `*PREFIX*calendarchanges` (`uri`, `synctoken`, `calendarid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*calendars` WHERE `id` = ?');
2006
-		$stmt->execute([
2007
-			$objectUri,
2008
-			$calendarId,
2009
-			$operation,
2010
-			$calendarId
2011
-		]);
2012
-		$stmt = $this->db->prepare('UPDATE `*PREFIX*calendars` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
2013
-		$stmt->execute([
2014
-			$calendarId
2015
-		]);
2016
-
2017
-	}
2018
-
2019
-	/**
2020
-	 * Parses some information from calendar objects, used for optimized
2021
-	 * calendar-queries.
2022
-	 *
2023
-	 * Returns an array with the following keys:
2024
-	 *   * etag - An md5 checksum of the object without the quotes.
2025
-	 *   * size - Size of the object in bytes
2026
-	 *   * componentType - VEVENT, VTODO or VJOURNAL
2027
-	 *   * firstOccurence
2028
-	 *   * lastOccurence
2029
-	 *   * uid - value of the UID property
2030
-	 *
2031
-	 * @param string $calendarData
2032
-	 * @return array
2033
-	 */
2034
-	public function getDenormalizedData($calendarData) {
2035
-
2036
-		$vObject = Reader::read($calendarData);
2037
-		$componentType = null;
2038
-		$component = null;
2039
-		$firstOccurrence = null;
2040
-		$lastOccurrence = null;
2041
-		$uid = null;
2042
-		$classification = self::CLASSIFICATION_PUBLIC;
2043
-		foreach($vObject->getComponents() as $component) {
2044
-			if ($component->name!=='VTIMEZONE') {
2045
-				$componentType = $component->name;
2046
-				$uid = (string)$component->UID;
2047
-				break;
2048
-			}
2049
-		}
2050
-		if (!$componentType) {
2051
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
2052
-		}
2053
-		if ($componentType === 'VEVENT' && $component->DTSTART) {
2054
-			$firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
2055
-			// Finding the last occurrence is a bit harder
2056
-			if (!isset($component->RRULE)) {
2057
-				if (isset($component->DTEND)) {
2058
-					$lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
2059
-				} elseif (isset($component->DURATION)) {
2060
-					$endDate = clone $component->DTSTART->getDateTime();
2061
-					$endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
2062
-					$lastOccurrence = $endDate->getTimeStamp();
2063
-				} elseif (!$component->DTSTART->hasTime()) {
2064
-					$endDate = clone $component->DTSTART->getDateTime();
2065
-					$endDate->modify('+1 day');
2066
-					$lastOccurrence = $endDate->getTimeStamp();
2067
-				} else {
2068
-					$lastOccurrence = $firstOccurrence;
2069
-				}
2070
-			} else {
2071
-				$it = new EventIterator($vObject, (string)$component->UID);
2072
-				$maxDate = new \DateTime(self::MAX_DATE);
2073
-				if ($it->isInfinite()) {
2074
-					$lastOccurrence = $maxDate->getTimestamp();
2075
-				} else {
2076
-					$end = $it->getDtEnd();
2077
-					while($it->valid() && $end < $maxDate) {
2078
-						$end = $it->getDtEnd();
2079
-						$it->next();
2080
-
2081
-					}
2082
-					$lastOccurrence = $end->getTimestamp();
2083
-				}
2084
-
2085
-			}
2086
-		}
2087
-
2088
-		if ($component->CLASS) {
2089
-			$classification = CalDavBackend::CLASSIFICATION_PRIVATE;
2090
-			switch ($component->CLASS->getValue()) {
2091
-				case 'PUBLIC':
2092
-					$classification = CalDavBackend::CLASSIFICATION_PUBLIC;
2093
-					break;
2094
-				case 'CONFIDENTIAL':
2095
-					$classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
2096
-					break;
2097
-			}
2098
-		}
2099
-		return [
2100
-			'etag' => md5($calendarData),
2101
-			'size' => strlen($calendarData),
2102
-			'componentType' => $componentType,
2103
-			'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
2104
-			'lastOccurence'  => $lastOccurrence,
2105
-			'uid' => $uid,
2106
-			'classification' => $classification
2107
-		];
2108
-
2109
-	}
2110
-
2111
-	private function readBlob($cardData) {
2112
-		if (is_resource($cardData)) {
2113
-			return stream_get_contents($cardData);
2114
-		}
2115
-
2116
-		return $cardData;
2117
-	}
2118
-
2119
-	/**
2120
-	 * @param IShareable $shareable
2121
-	 * @param array $add
2122
-	 * @param array $remove
2123
-	 */
2124
-	public function updateShares($shareable, $add, $remove) {
2125
-		$calendarId = $shareable->getResourceId();
2126
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
2127
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2128
-			[
2129
-				'calendarId' => $calendarId,
2130
-				'calendarData' => $this->getCalendarById($calendarId),
2131
-				'shares' => $this->getShares($calendarId),
2132
-				'add' => $add,
2133
-				'remove' => $remove,
2134
-			]));
2135
-		$this->sharingBackend->updateShares($shareable, $add, $remove);
2136
-	}
2137
-
2138
-	/**
2139
-	 * @param int $resourceId
2140
-	 * @return array
2141
-	 */
2142
-	public function getShares($resourceId) {
2143
-		return $this->sharingBackend->getShares($resourceId);
2144
-	}
2145
-
2146
-	/**
2147
-	 * @param boolean $value
2148
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
2149
-	 * @return string|null
2150
-	 */
2151
-	public function setPublishStatus($value, $calendar) {
2152
-
2153
-		$calendarId = $calendar->getResourceId();
2154
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', new GenericEvent(
2155
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2156
-			[
2157
-				'calendarId' => $calendarId,
2158
-				'calendarData' => $this->getCalendarById($calendarId),
2159
-				'public' => $value,
2160
-			]));
2161
-
2162
-		$query = $this->db->getQueryBuilder();
2163
-		if ($value) {
2164
-			$publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
2165
-			$query->insert('dav_shares')
2166
-				->values([
2167
-					'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
2168
-					'type' => $query->createNamedParameter('calendar'),
2169
-					'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
2170
-					'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
2171
-					'publicuri' => $query->createNamedParameter($publicUri)
2172
-				]);
2173
-			$query->execute();
2174
-			return $publicUri;
2175
-		}
2176
-		$query->delete('dav_shares')
2177
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2178
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
2179
-		$query->execute();
2180
-		return null;
2181
-	}
2182
-
2183
-	/**
2184
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
2185
-	 * @return mixed
2186
-	 */
2187
-	public function getPublishStatus($calendar) {
2188
-		$query = $this->db->getQueryBuilder();
2189
-		$result = $query->select('publicuri')
2190
-			->from('dav_shares')
2191
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2192
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
2193
-			->execute();
2194
-
2195
-		$row = $result->fetch();
2196
-		$result->closeCursor();
2197
-		return $row ? reset($row) : false;
2198
-	}
2199
-
2200
-	/**
2201
-	 * @param int $resourceId
2202
-	 * @param array $acl
2203
-	 * @return array
2204
-	 */
2205
-	public function applyShareAcl($resourceId, $acl) {
2206
-		return $this->sharingBackend->applyShareAcl($resourceId, $acl);
2207
-	}
2208
-
2209
-
2210
-
2211
-	/**
2212
-	 * update properties table
2213
-	 *
2214
-	 * @param int $calendarId
2215
-	 * @param string $objectUri
2216
-	 * @param string $calendarData
2217
-	 */
2218
-	public function updateProperties($calendarId, $objectUri, $calendarData) {
2219
-		$objectId = $this->getCalendarObjectId($calendarId, $objectUri);
2220
-
2221
-		try {
2222
-			$vCalendar = $this->readCalendarData($calendarData);
2223
-		} catch (\Exception $ex) {
2224
-			return;
2225
-		}
2226
-
2227
-		$this->purgeProperties($calendarId, $objectId);
2228
-
2229
-		$query = $this->db->getQueryBuilder();
2230
-		$query->insert($this->dbObjectPropertiesTable)
2231
-			->values(
2232
-				[
2233
-					'calendarid' => $query->createNamedParameter($calendarId),
2234
-					'objectid' => $query->createNamedParameter($objectId),
2235
-					'name' => $query->createParameter('name'),
2236
-					'parameter' => $query->createParameter('parameter'),
2237
-					'value' => $query->createParameter('value'),
2238
-				]
2239
-			);
2240
-
2241
-		$indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
2242
-		foreach ($vCalendar->getComponents() as $component) {
2243
-			if (!in_array($component->name, $indexComponents)) {
2244
-				continue;
2245
-			}
2246
-
2247
-			foreach ($component->children() as $property) {
2248
-				if (in_array($property->name, self::$indexProperties)) {
2249
-					$value = $property->getValue();
2250
-					// is this a shitty db?
2251
-					if (!$this->db->supports4ByteText()) {
2252
-						$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2253
-					}
2254
-					$value = mb_substr($value, 0, 254);
2255
-
2256
-					$query->setParameter('name', $property->name);
2257
-					$query->setParameter('parameter', null);
2258
-					$query->setParameter('value', $value);
2259
-					$query->execute();
2260
-				}
2261
-
2262
-				if (array_key_exists($property->name, self::$indexParameters)) {
2263
-					$parameters = $property->parameters();
2264
-					$indexedParametersForProperty = self::$indexParameters[$property->name];
2265
-
2266
-					foreach ($parameters as $key => $value) {
2267
-						if (in_array($key, $indexedParametersForProperty)) {
2268
-							// is this a shitty db?
2269
-							if ($this->db->supports4ByteText()) {
2270
-								$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2271
-							}
2272
-							$value = mb_substr($value, 0, 254);
2273
-
2274
-							$query->setParameter('name', $property->name);
2275
-							$query->setParameter('parameter', substr($key, 0, 254));
2276
-							$query->setParameter('value', substr($value, 0, 254));
2277
-							$query->execute();
2278
-						}
2279
-					}
2280
-				}
2281
-			}
2282
-		}
2283
-	}
2284
-
2285
-	/**
2286
-	 * deletes all birthday calendars
2287
-	 */
2288
-	public function deleteAllBirthdayCalendars() {
2289
-		$query = $this->db->getQueryBuilder();
2290
-		$result = $query->select(['id'])->from('calendars')
2291
-			->where($query->expr()->eq('uri',
2292
-				$query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
2293
-			->execute();
2294
-
2295
-		$ids = $result->fetchAll();
2296
-		foreach($ids as $id) {
2297
-			$this->deleteCalendar($id['id']);
2298
-		}
2299
-	}
2300
-
2301
-	/**
2302
-	 * read VCalendar data into a VCalendar object
2303
-	 *
2304
-	 * @param string $objectData
2305
-	 * @return VCalendar
2306
-	 */
2307
-	protected function readCalendarData($objectData) {
2308
-		return Reader::read($objectData);
2309
-	}
2310
-
2311
-	/**
2312
-	 * delete all properties from a given calendar object
2313
-	 *
2314
-	 * @param int $calendarId
2315
-	 * @param int $objectId
2316
-	 */
2317
-	protected function purgeProperties($calendarId, $objectId) {
2318
-		$query = $this->db->getQueryBuilder();
2319
-		$query->delete($this->dbObjectPropertiesTable)
2320
-			->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
2321
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2322
-		$query->execute();
2323
-	}
2324
-
2325
-	/**
2326
-	 * get ID from a given calendar object
2327
-	 *
2328
-	 * @param int $calendarId
2329
-	 * @param string $uri
2330
-	 * @return int
2331
-	 */
2332
-	protected function getCalendarObjectId($calendarId, $uri) {
2333
-		$query = $this->db->getQueryBuilder();
2334
-		$query->select('id')->from('calendarobjects')
2335
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2336
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2337
-
2338
-		$result = $query->execute();
2339
-		$objectIds = $result->fetch();
2340
-		$result->closeCursor();
2341
-
2342
-		if (!isset($objectIds['id'])) {
2343
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2344
-		}
2345
-
2346
-		return (int)$objectIds['id'];
2347
-	}
2348
-
2349
-	private function convertPrincipal($principalUri, $toV2) {
2350
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
2351
-			list(, $name) = Uri\split($principalUri);
2352
-			if ($toV2 === true) {
2353
-				return "principals/users/$name";
2354
-			}
2355
-			return "principals/$name";
2356
-		}
2357
-		return $principalUri;
2358
-	}
2359
-
2360
-	private function addOwnerPrincipal(&$calendarInfo) {
2361
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2362
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2363
-		if (isset($calendarInfo[$ownerPrincipalKey])) {
2364
-			$uri = $calendarInfo[$ownerPrincipalKey];
2365
-		} else {
2366
-			$uri = $calendarInfo['principaluri'];
2367
-		}
2368
-
2369
-		$principalInformation = $this->principalBackend->getPrincipalByPath($uri);
2370
-		if (isset($principalInformation['{DAV:}displayname'])) {
2371
-			$calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
2372
-		}
2373
-	}
431
+    /**
432
+     * @return array
433
+     */
434
+    public function getPublicCalendars() {
435
+        $fields = array_values($this->propertyMap);
436
+        $fields[] = 'a.id';
437
+        $fields[] = 'a.uri';
438
+        $fields[] = 'a.synctoken';
439
+        $fields[] = 'a.components';
440
+        $fields[] = 'a.principaluri';
441
+        $fields[] = 'a.transparent';
442
+        $fields[] = 's.access';
443
+        $fields[] = 's.publicuri';
444
+        $calendars = [];
445
+        $query = $this->db->getQueryBuilder();
446
+        $result = $query->select($fields)
447
+            ->from('dav_shares', 's')
448
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
449
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
450
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
451
+            ->execute();
452
+
453
+        while($row = $result->fetch()) {
454
+            list(, $name) = Uri\split($row['principaluri']);
455
+            $row['displayname'] = $row['displayname'] . "($name)";
456
+            $components = [];
457
+            if ($row['components']) {
458
+                $components = explode(',',$row['components']);
459
+            }
460
+            $calendar = [
461
+                'id' => $row['id'],
462
+                'uri' => $row['publicuri'],
463
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
464
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
465
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
466
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
467
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
468
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
469
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
470
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
471
+            ];
472
+
473
+            foreach($this->propertyMap as $xmlName=>$dbName) {
474
+                $calendar[$xmlName] = $row[$dbName];
475
+            }
476
+
477
+            $this->addOwnerPrincipal($calendar);
478
+
479
+            if (!isset($calendars[$calendar['id']])) {
480
+                $calendars[$calendar['id']] = $calendar;
481
+            }
482
+        }
483
+        $result->closeCursor();
484
+
485
+        return array_values($calendars);
486
+    }
487
+
488
+    /**
489
+     * @param string $uri
490
+     * @return array
491
+     * @throws NotFound
492
+     */
493
+    public function getPublicCalendar($uri) {
494
+        $fields = array_values($this->propertyMap);
495
+        $fields[] = 'a.id';
496
+        $fields[] = 'a.uri';
497
+        $fields[] = 'a.synctoken';
498
+        $fields[] = 'a.components';
499
+        $fields[] = 'a.principaluri';
500
+        $fields[] = 'a.transparent';
501
+        $fields[] = 's.access';
502
+        $fields[] = 's.publicuri';
503
+        $query = $this->db->getQueryBuilder();
504
+        $result = $query->select($fields)
505
+            ->from('dav_shares', 's')
506
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
507
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
508
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
509
+            ->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
510
+            ->execute();
511
+
512
+        $row = $result->fetch(\PDO::FETCH_ASSOC);
513
+
514
+        $result->closeCursor();
515
+
516
+        if ($row === false) {
517
+            throw new NotFound('Node with name \'' . $uri . '\' could not be found');
518
+        }
519
+
520
+        list(, $name) = Uri\split($row['principaluri']);
521
+        $row['displayname'] = $row['displayname'] . ' ' . "($name)";
522
+        $components = [];
523
+        if ($row['components']) {
524
+            $components = explode(',',$row['components']);
525
+        }
526
+        $calendar = [
527
+            'id' => $row['id'],
528
+            'uri' => $row['publicuri'],
529
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
530
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
531
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
532
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
533
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
534
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
535
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
536
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
537
+        ];
538
+
539
+        foreach($this->propertyMap as $xmlName=>$dbName) {
540
+            $calendar[$xmlName] = $row[$dbName];
541
+        }
542
+
543
+        $this->addOwnerPrincipal($calendar);
544
+
545
+        return $calendar;
546
+
547
+    }
548
+
549
+    /**
550
+     * @param string $principal
551
+     * @param string $uri
552
+     * @return array|null
553
+     */
554
+    public function getCalendarByUri($principal, $uri) {
555
+        $fields = array_values($this->propertyMap);
556
+        $fields[] = 'id';
557
+        $fields[] = 'uri';
558
+        $fields[] = 'synctoken';
559
+        $fields[] = 'components';
560
+        $fields[] = 'principaluri';
561
+        $fields[] = 'transparent';
562
+
563
+        // Making fields a comma-delimited list
564
+        $query = $this->db->getQueryBuilder();
565
+        $query->select($fields)->from('calendars')
566
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
567
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
568
+            ->setMaxResults(1);
569
+        $stmt = $query->execute();
570
+
571
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
572
+        $stmt->closeCursor();
573
+        if ($row === false) {
574
+            return null;
575
+        }
576
+
577
+        $components = [];
578
+        if ($row['components']) {
579
+            $components = explode(',',$row['components']);
580
+        }
581
+
582
+        $calendar = [
583
+            'id' => $row['id'],
584
+            'uri' => $row['uri'],
585
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
586
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
587
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
588
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
589
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
590
+        ];
591
+
592
+        foreach($this->propertyMap as $xmlName=>$dbName) {
593
+            $calendar[$xmlName] = $row[$dbName];
594
+        }
595
+
596
+        $this->addOwnerPrincipal($calendar);
597
+
598
+        return $calendar;
599
+    }
600
+
601
+    public function getCalendarById($calendarId) {
602
+        $fields = array_values($this->propertyMap);
603
+        $fields[] = 'id';
604
+        $fields[] = 'uri';
605
+        $fields[] = 'synctoken';
606
+        $fields[] = 'components';
607
+        $fields[] = 'principaluri';
608
+        $fields[] = 'transparent';
609
+
610
+        // Making fields a comma-delimited list
611
+        $query = $this->db->getQueryBuilder();
612
+        $query->select($fields)->from('calendars')
613
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
614
+            ->setMaxResults(1);
615
+        $stmt = $query->execute();
616
+
617
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
618
+        $stmt->closeCursor();
619
+        if ($row === false) {
620
+            return null;
621
+        }
622
+
623
+        $components = [];
624
+        if ($row['components']) {
625
+            $components = explode(',',$row['components']);
626
+        }
627
+
628
+        $calendar = [
629
+            'id' => $row['id'],
630
+            'uri' => $row['uri'],
631
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
632
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
633
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
634
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
635
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
636
+        ];
637
+
638
+        foreach($this->propertyMap as $xmlName=>$dbName) {
639
+            $calendar[$xmlName] = $row[$dbName];
640
+        }
641
+
642
+        $this->addOwnerPrincipal($calendar);
643
+
644
+        return $calendar;
645
+    }
646
+
647
+    /**
648
+     * Creates a new calendar for a principal.
649
+     *
650
+     * If the creation was a success, an id must be returned that can be used to reference
651
+     * this calendar in other methods, such as updateCalendar.
652
+     *
653
+     * @param string $principalUri
654
+     * @param string $calendarUri
655
+     * @param array $properties
656
+     * @return int
657
+     * @suppress SqlInjectionChecker
658
+     */
659
+    function createCalendar($principalUri, $calendarUri, array $properties) {
660
+        $values = [
661
+            'principaluri' => $this->convertPrincipal($principalUri, true),
662
+            'uri'          => $calendarUri,
663
+            'synctoken'    => 1,
664
+            'transparent'  => 0,
665
+            'components'   => 'VEVENT,VTODO',
666
+            'displayname'  => $calendarUri
667
+        ];
668
+
669
+        // Default value
670
+        $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
671
+        if (isset($properties[$sccs])) {
672
+            if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
673
+                throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
674
+            }
675
+            $values['components'] = implode(',',$properties[$sccs]->getValue());
676
+        }
677
+        $transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
678
+        if (isset($properties[$transp])) {
679
+            $values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
680
+        }
681
+
682
+        foreach($this->propertyMap as $xmlName=>$dbName) {
683
+            if (isset($properties[$xmlName])) {
684
+                $values[$dbName] = $properties[$xmlName];
685
+            }
686
+        }
687
+
688
+        $query = $this->db->getQueryBuilder();
689
+        $query->insert('calendars');
690
+        foreach($values as $column => $value) {
691
+            $query->setValue($column, $query->createNamedParameter($value));
692
+        }
693
+        $query->execute();
694
+        $calendarId = $query->getLastInsertId();
695
+
696
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
697
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
698
+            [
699
+                'calendarId' => $calendarId,
700
+                'calendarData' => $this->getCalendarById($calendarId),
701
+        ]));
702
+
703
+        return $calendarId;
704
+    }
705
+
706
+    /**
707
+     * Updates properties for a calendar.
708
+     *
709
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
710
+     * To do the actual updates, you must tell this object which properties
711
+     * you're going to process with the handle() method.
712
+     *
713
+     * Calling the handle method is like telling the PropPatch object "I
714
+     * promise I can handle updating this property".
715
+     *
716
+     * Read the PropPatch documentation for more info and examples.
717
+     *
718
+     * @param mixed $calendarId
719
+     * @param PropPatch $propPatch
720
+     * @return void
721
+     */
722
+    function updateCalendar($calendarId, PropPatch $propPatch) {
723
+        $supportedProperties = array_keys($this->propertyMap);
724
+        $supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
725
+
726
+        /**
727
+         * @suppress SqlInjectionChecker
728
+         */
729
+        $propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
730
+            $newValues = [];
731
+            foreach ($mutations as $propertyName => $propertyValue) {
732
+
733
+                switch ($propertyName) {
734
+                    case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
735
+                        $fieldName = 'transparent';
736
+                        $newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
737
+                        break;
738
+                    default :
739
+                        $fieldName = $this->propertyMap[$propertyName];
740
+                        $newValues[$fieldName] = $propertyValue;
741
+                        break;
742
+                }
743
+
744
+            }
745
+            $query = $this->db->getQueryBuilder();
746
+            $query->update('calendars');
747
+            foreach ($newValues as $fieldName => $value) {
748
+                $query->set($fieldName, $query->createNamedParameter($value));
749
+            }
750
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
751
+            $query->execute();
752
+
753
+            $this->addChange($calendarId, "", 2);
754
+
755
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
756
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
757
+                [
758
+                    'calendarId' => $calendarId,
759
+                    'calendarData' => $this->getCalendarById($calendarId),
760
+                    'shares' => $this->getShares($calendarId),
761
+                    'propertyMutations' => $mutations,
762
+            ]));
763
+
764
+            return true;
765
+        });
766
+    }
767
+
768
+    /**
769
+     * Delete a calendar and all it's objects
770
+     *
771
+     * @param mixed $calendarId
772
+     * @return void
773
+     */
774
+    function deleteCalendar($calendarId) {
775
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
776
+            '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
777
+            [
778
+                'calendarId' => $calendarId,
779
+                'calendarData' => $this->getCalendarById($calendarId),
780
+                'shares' => $this->getShares($calendarId),
781
+        ]));
782
+
783
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?');
784
+        $stmt->execute([$calendarId]);
785
+
786
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
787
+        $stmt->execute([$calendarId]);
788
+
789
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ?');
790
+        $stmt->execute([$calendarId]);
791
+
792
+        $this->sharingBackend->deleteAllShares($calendarId);
793
+
794
+        $query = $this->db->getQueryBuilder();
795
+        $query->delete($this->dbObjectPropertiesTable)
796
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
797
+            ->execute();
798
+    }
799
+
800
+    /**
801
+     * Delete all of an user's shares
802
+     *
803
+     * @param string $principaluri
804
+     * @return void
805
+     */
806
+    function deleteAllSharesByUser($principaluri) {
807
+        $this->sharingBackend->deleteAllSharesByUser($principaluri);
808
+    }
809
+
810
+    /**
811
+     * Returns all calendar objects within a calendar.
812
+     *
813
+     * Every item contains an array with the following keys:
814
+     *   * calendardata - The iCalendar-compatible calendar data
815
+     *   * uri - a unique key which will be used to construct the uri. This can
816
+     *     be any arbitrary string, but making sure it ends with '.ics' is a
817
+     *     good idea. This is only the basename, or filename, not the full
818
+     *     path.
819
+     *   * lastmodified - a timestamp of the last modification time
820
+     *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
821
+     *   '"abcdef"')
822
+     *   * size - The size of the calendar objects, in bytes.
823
+     *   * component - optional, a string containing the type of object, such
824
+     *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
825
+     *     the Content-Type header.
826
+     *
827
+     * Note that the etag is optional, but it's highly encouraged to return for
828
+     * speed reasons.
829
+     *
830
+     * The calendardata is also optional. If it's not returned
831
+     * 'getCalendarObject' will be called later, which *is* expected to return
832
+     * calendardata.
833
+     *
834
+     * If neither etag or size are specified, the calendardata will be
835
+     * used/fetched to determine these numbers. If both are specified the
836
+     * amount of times this is needed is reduced by a great degree.
837
+     *
838
+     * @param mixed $calendarId
839
+     * @return array
840
+     */
841
+    function getCalendarObjects($calendarId) {
842
+        $query = $this->db->getQueryBuilder();
843
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
844
+            ->from('calendarobjects')
845
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
846
+        $stmt = $query->execute();
847
+
848
+        $result = [];
849
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
850
+            $result[] = [
851
+                    'id'           => $row['id'],
852
+                    'uri'          => $row['uri'],
853
+                    'lastmodified' => $row['lastmodified'],
854
+                    'etag'         => '"' . $row['etag'] . '"',
855
+                    'calendarid'   => $row['calendarid'],
856
+                    'size'         => (int)$row['size'],
857
+                    'component'    => strtolower($row['componenttype']),
858
+                    'classification'=> (int)$row['classification']
859
+            ];
860
+        }
861
+
862
+        return $result;
863
+    }
864
+
865
+    /**
866
+     * Returns information from a single calendar object, based on it's object
867
+     * uri.
868
+     *
869
+     * The object uri is only the basename, or filename and not a full path.
870
+     *
871
+     * The returned array must have the same keys as getCalendarObjects. The
872
+     * 'calendardata' object is required here though, while it's not required
873
+     * for getCalendarObjects.
874
+     *
875
+     * This method must return null if the object did not exist.
876
+     *
877
+     * @param mixed $calendarId
878
+     * @param string $objectUri
879
+     * @return array|null
880
+     */
881
+    function getCalendarObject($calendarId, $objectUri) {
882
+
883
+        $query = $this->db->getQueryBuilder();
884
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
885
+                ->from('calendarobjects')
886
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
887
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)));
888
+        $stmt = $query->execute();
889
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
890
+
891
+        if(!$row) return null;
892
+
893
+        return [
894
+                'id'            => $row['id'],
895
+                'uri'           => $row['uri'],
896
+                'lastmodified'  => $row['lastmodified'],
897
+                'etag'          => '"' . $row['etag'] . '"',
898
+                'calendarid'    => $row['calendarid'],
899
+                'size'          => (int)$row['size'],
900
+                'calendardata'  => $this->readBlob($row['calendardata']),
901
+                'component'     => strtolower($row['componenttype']),
902
+                'classification'=> (int)$row['classification']
903
+        ];
904
+    }
905
+
906
+    /**
907
+     * Returns a list of calendar objects.
908
+     *
909
+     * This method should work identical to getCalendarObject, but instead
910
+     * return all the calendar objects in the list as an array.
911
+     *
912
+     * If the backend supports this, it may allow for some speed-ups.
913
+     *
914
+     * @param mixed $calendarId
915
+     * @param string[] $uris
916
+     * @return array
917
+     */
918
+    function getMultipleCalendarObjects($calendarId, array $uris) {
919
+        if (empty($uris)) {
920
+            return [];
921
+        }
922
+
923
+        $chunks = array_chunk($uris, 100);
924
+        $objects = [];
925
+
926
+        $query = $this->db->getQueryBuilder();
927
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
928
+            ->from('calendarobjects')
929
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
930
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
931
+
932
+        foreach ($chunks as $uris) {
933
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
934
+            $result = $query->execute();
935
+
936
+            while ($row = $result->fetch()) {
937
+                $objects[] = [
938
+                    'id'           => $row['id'],
939
+                    'uri'          => $row['uri'],
940
+                    'lastmodified' => $row['lastmodified'],
941
+                    'etag'         => '"' . $row['etag'] . '"',
942
+                    'calendarid'   => $row['calendarid'],
943
+                    'size'         => (int)$row['size'],
944
+                    'calendardata' => $this->readBlob($row['calendardata']),
945
+                    'component'    => strtolower($row['componenttype']),
946
+                    'classification' => (int)$row['classification']
947
+                ];
948
+            }
949
+            $result->closeCursor();
950
+        }
951
+        return $objects;
952
+    }
953
+
954
+    /**
955
+     * Creates a new calendar object.
956
+     *
957
+     * The object uri is only the basename, or filename and not a full path.
958
+     *
959
+     * It is possible return an etag from this function, which will be used in
960
+     * the response to this PUT request. Note that the ETag must be surrounded
961
+     * by double-quotes.
962
+     *
963
+     * However, you should only really return this ETag if you don't mangle the
964
+     * calendar-data. If the result of a subsequent GET to this object is not
965
+     * the exact same as this request body, you should omit the ETag.
966
+     *
967
+     * @param mixed $calendarId
968
+     * @param string $objectUri
969
+     * @param string $calendarData
970
+     * @return string
971
+     */
972
+    function createCalendarObject($calendarId, $objectUri, $calendarData) {
973
+        $extraData = $this->getDenormalizedData($calendarData);
974
+
975
+        $q = $this->db->getQueryBuilder();
976
+        $q->select($q->createFunction('COUNT(*)'))
977
+            ->from('calendarobjects')
978
+            ->where($q->expr()->eq('calendarid', $q->createNamedParameter($calendarId)))
979
+            ->andWhere($q->expr()->eq('uid', $q->createNamedParameter($extraData['uid'])));
980
+
981
+        $result = $q->execute();
982
+        $count = (int) $result->fetchColumn();
983
+        $result->closeCursor();
984
+
985
+        if ($count !== 0) {
986
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar object with uid already exists in this calendar collection.');
987
+        }
988
+
989
+        $query = $this->db->getQueryBuilder();
990
+        $query->insert('calendarobjects')
991
+            ->values([
992
+                'calendarid' => $query->createNamedParameter($calendarId),
993
+                'uri' => $query->createNamedParameter($objectUri),
994
+                'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
995
+                'lastmodified' => $query->createNamedParameter(time()),
996
+                'etag' => $query->createNamedParameter($extraData['etag']),
997
+                'size' => $query->createNamedParameter($extraData['size']),
998
+                'componenttype' => $query->createNamedParameter($extraData['componentType']),
999
+                'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1000
+                'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1001
+                'classification' => $query->createNamedParameter($extraData['classification']),
1002
+                'uid' => $query->createNamedParameter($extraData['uid']),
1003
+            ])
1004
+            ->execute();
1005
+
1006
+        $this->updateProperties($calendarId, $objectUri, $calendarData);
1007
+
1008
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
1009
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
1010
+            [
1011
+                'calendarId' => $calendarId,
1012
+                'calendarData' => $this->getCalendarById($calendarId),
1013
+                'shares' => $this->getShares($calendarId),
1014
+                'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1015
+            ]
1016
+        ));
1017
+        $this->addChange($calendarId, $objectUri, 1);
1018
+
1019
+        return '"' . $extraData['etag'] . '"';
1020
+    }
1021
+
1022
+    /**
1023
+     * Updates an existing calendarobject, based on it's uri.
1024
+     *
1025
+     * The object uri is only the basename, or filename and not a full path.
1026
+     *
1027
+     * It is possible return an etag from this function, which will be used in
1028
+     * the response to this PUT request. Note that the ETag must be surrounded
1029
+     * by double-quotes.
1030
+     *
1031
+     * However, you should only really return this ETag if you don't mangle the
1032
+     * calendar-data. If the result of a subsequent GET to this object is not
1033
+     * the exact same as this request body, you should omit the ETag.
1034
+     *
1035
+     * @param mixed $calendarId
1036
+     * @param string $objectUri
1037
+     * @param string $calendarData
1038
+     * @return string
1039
+     */
1040
+    function updateCalendarObject($calendarId, $objectUri, $calendarData) {
1041
+        $extraData = $this->getDenormalizedData($calendarData);
1042
+
1043
+        $query = $this->db->getQueryBuilder();
1044
+        $query->update('calendarobjects')
1045
+                ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1046
+                ->set('lastmodified', $query->createNamedParameter(time()))
1047
+                ->set('etag', $query->createNamedParameter($extraData['etag']))
1048
+                ->set('size', $query->createNamedParameter($extraData['size']))
1049
+                ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1050
+                ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1051
+                ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1052
+                ->set('classification', $query->createNamedParameter($extraData['classification']))
1053
+                ->set('uid', $query->createNamedParameter($extraData['uid']))
1054
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1055
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1056
+            ->execute();
1057
+
1058
+        $this->updateProperties($calendarId, $objectUri, $calendarData);
1059
+
1060
+        $data = $this->getCalendarObject($calendarId, $objectUri);
1061
+        if (is_array($data)) {
1062
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
1063
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
1064
+                [
1065
+                    'calendarId' => $calendarId,
1066
+                    'calendarData' => $this->getCalendarById($calendarId),
1067
+                    'shares' => $this->getShares($calendarId),
1068
+                    'objectData' => $data,
1069
+                ]
1070
+            ));
1071
+        }
1072
+        $this->addChange($calendarId, $objectUri, 2);
1073
+
1074
+        return '"' . $extraData['etag'] . '"';
1075
+    }
1076
+
1077
+    /**
1078
+     * @param int $calendarObjectId
1079
+     * @param int $classification
1080
+     */
1081
+    public function setClassification($calendarObjectId, $classification) {
1082
+        if (!in_array($classification, [
1083
+            self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1084
+        ])) {
1085
+            throw new \InvalidArgumentException();
1086
+        }
1087
+        $query = $this->db->getQueryBuilder();
1088
+        $query->update('calendarobjects')
1089
+            ->set('classification', $query->createNamedParameter($classification))
1090
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1091
+            ->execute();
1092
+    }
1093
+
1094
+    /**
1095
+     * Deletes an existing calendar object.
1096
+     *
1097
+     * The object uri is only the basename, or filename and not a full path.
1098
+     *
1099
+     * @param mixed $calendarId
1100
+     * @param string $objectUri
1101
+     * @return void
1102
+     */
1103
+    function deleteCalendarObject($calendarId, $objectUri) {
1104
+        $data = $this->getCalendarObject($calendarId, $objectUri);
1105
+        if (is_array($data)) {
1106
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1107
+                '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1108
+                [
1109
+                    'calendarId' => $calendarId,
1110
+                    'calendarData' => $this->getCalendarById($calendarId),
1111
+                    'shares' => $this->getShares($calendarId),
1112
+                    'objectData' => $data,
1113
+                ]
1114
+            ));
1115
+        }
1116
+
1117
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ?');
1118
+        $stmt->execute([$calendarId, $objectUri]);
1119
+
1120
+        $this->purgeProperties($calendarId, $data['id']);
1121
+
1122
+        $this->addChange($calendarId, $objectUri, 3);
1123
+    }
1124
+
1125
+    /**
1126
+     * Performs a calendar-query on the contents of this calendar.
1127
+     *
1128
+     * The calendar-query is defined in RFC4791 : CalDAV. Using the
1129
+     * calendar-query it is possible for a client to request a specific set of
1130
+     * object, based on contents of iCalendar properties, date-ranges and
1131
+     * iCalendar component types (VTODO, VEVENT).
1132
+     *
1133
+     * This method should just return a list of (relative) urls that match this
1134
+     * query.
1135
+     *
1136
+     * The list of filters are specified as an array. The exact array is
1137
+     * documented by Sabre\CalDAV\CalendarQueryParser.
1138
+     *
1139
+     * Note that it is extremely likely that getCalendarObject for every path
1140
+     * returned from this method will be called almost immediately after. You
1141
+     * may want to anticipate this to speed up these requests.
1142
+     *
1143
+     * This method provides a default implementation, which parses *all* the
1144
+     * iCalendar objects in the specified calendar.
1145
+     *
1146
+     * This default may well be good enough for personal use, and calendars
1147
+     * that aren't very large. But if you anticipate high usage, big calendars
1148
+     * or high loads, you are strongly advised to optimize certain paths.
1149
+     *
1150
+     * The best way to do so is override this method and to optimize
1151
+     * specifically for 'common filters'.
1152
+     *
1153
+     * Requests that are extremely common are:
1154
+     *   * requests for just VEVENTS
1155
+     *   * requests for just VTODO
1156
+     *   * requests with a time-range-filter on either VEVENT or VTODO.
1157
+     *
1158
+     * ..and combinations of these requests. It may not be worth it to try to
1159
+     * handle every possible situation and just rely on the (relatively
1160
+     * easy to use) CalendarQueryValidator to handle the rest.
1161
+     *
1162
+     * Note that especially time-range-filters may be difficult to parse. A
1163
+     * time-range filter specified on a VEVENT must for instance also handle
1164
+     * recurrence rules correctly.
1165
+     * A good example of how to interprete all these filters can also simply
1166
+     * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1167
+     * as possible, so it gives you a good idea on what type of stuff you need
1168
+     * to think of.
1169
+     *
1170
+     * @param mixed $calendarId
1171
+     * @param array $filters
1172
+     * @return array
1173
+     */
1174
+    function calendarQuery($calendarId, array $filters) {
1175
+        $componentType = null;
1176
+        $requirePostFilter = true;
1177
+        $timeRange = null;
1178
+
1179
+        // if no filters were specified, we don't need to filter after a query
1180
+        if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1181
+            $requirePostFilter = false;
1182
+        }
1183
+
1184
+        // Figuring out if there's a component filter
1185
+        if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1186
+            $componentType = $filters['comp-filters'][0]['name'];
1187
+
1188
+            // Checking if we need post-filters
1189
+            if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1190
+                $requirePostFilter = false;
1191
+            }
1192
+            // There was a time-range filter
1193
+            if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1194
+                $timeRange = $filters['comp-filters'][0]['time-range'];
1195
+
1196
+                // If start time OR the end time is not specified, we can do a
1197
+                // 100% accurate mysql query.
1198
+                if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1199
+                    $requirePostFilter = false;
1200
+                }
1201
+            }
1202
+
1203
+        }
1204
+        $columns = ['uri'];
1205
+        if ($requirePostFilter) {
1206
+            $columns = ['uri', 'calendardata'];
1207
+        }
1208
+        $query = $this->db->getQueryBuilder();
1209
+        $query->select($columns)
1210
+            ->from('calendarobjects')
1211
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
1212
+
1213
+        if ($componentType) {
1214
+            $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1215
+        }
1216
+
1217
+        if ($timeRange && $timeRange['start']) {
1218
+            $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1219
+        }
1220
+        if ($timeRange && $timeRange['end']) {
1221
+            $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1222
+        }
1223
+
1224
+        $stmt = $query->execute();
1225
+
1226
+        $result = [];
1227
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1228
+            if ($requirePostFilter) {
1229
+                // validateFilterForObject will parse the calendar data
1230
+                // catch parsing errors
1231
+                try {
1232
+                    $matches = $this->validateFilterForObject($row, $filters);
1233
+                } catch(ParseException $ex) {
1234
+                    $this->logger->logException($ex, [
1235
+                        'app' => 'dav',
1236
+                        'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri']
1237
+                    ]);
1238
+                    continue;
1239
+                } catch (InvalidDataException $ex) {
1240
+                    $this->logger->logException($ex, [
1241
+                        'app' => 'dav',
1242
+                        'message' => 'Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri']
1243
+                    ]);
1244
+                    continue;
1245
+                }
1246
+
1247
+                if (!$matches) {
1248
+                    continue;
1249
+                }
1250
+            }
1251
+            $result[] = $row['uri'];
1252
+        }
1253
+
1254
+        return $result;
1255
+    }
1256
+
1257
+    /**
1258
+     * custom Nextcloud search extension for CalDAV
1259
+     *
1260
+     * @param string $principalUri
1261
+     * @param array $filters
1262
+     * @param integer|null $limit
1263
+     * @param integer|null $offset
1264
+     * @return array
1265
+     */
1266
+    public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1267
+        $calendars = $this->getCalendarsForUser($principalUri);
1268
+        $ownCalendars = [];
1269
+        $sharedCalendars = [];
1270
+
1271
+        $uriMapper = [];
1272
+
1273
+        foreach($calendars as $calendar) {
1274
+            if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1275
+                $ownCalendars[] = $calendar['id'];
1276
+            } else {
1277
+                $sharedCalendars[] = $calendar['id'];
1278
+            }
1279
+            $uriMapper[$calendar['id']] = $calendar['uri'];
1280
+        }
1281
+        if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1282
+            return [];
1283
+        }
1284
+
1285
+        $query = $this->db->getQueryBuilder();
1286
+        // Calendar id expressions
1287
+        $calendarExpressions = [];
1288
+        foreach($ownCalendars as $id) {
1289
+            $calendarExpressions[] = $query->expr()
1290
+                ->eq('c.calendarid', $query->createNamedParameter($id));
1291
+        }
1292
+        foreach($sharedCalendars as $id) {
1293
+            $calendarExpressions[] = $query->expr()->andX(
1294
+                $query->expr()->eq('c.calendarid',
1295
+                    $query->createNamedParameter($id)),
1296
+                $query->expr()->eq('c.classification',
1297
+                    $query->createNamedParameter(self::CLASSIFICATION_PUBLIC))
1298
+            );
1299
+        }
1300
+
1301
+        if (count($calendarExpressions) === 1) {
1302
+            $calExpr = $calendarExpressions[0];
1303
+        } else {
1304
+            $calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1305
+        }
1306
+
1307
+        // Component expressions
1308
+        $compExpressions = [];
1309
+        foreach($filters['comps'] as $comp) {
1310
+            $compExpressions[] = $query->expr()
1311
+                ->eq('c.componenttype', $query->createNamedParameter($comp));
1312
+        }
1313
+
1314
+        if (count($compExpressions) === 1) {
1315
+            $compExpr = $compExpressions[0];
1316
+        } else {
1317
+            $compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1318
+        }
1319
+
1320
+        if (!isset($filters['props'])) {
1321
+            $filters['props'] = [];
1322
+        }
1323
+        if (!isset($filters['params'])) {
1324
+            $filters['params'] = [];
1325
+        }
1326
+
1327
+        $propParamExpressions = [];
1328
+        foreach($filters['props'] as $prop) {
1329
+            $propParamExpressions[] = $query->expr()->andX(
1330
+                $query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1331
+                $query->expr()->isNull('i.parameter')
1332
+            );
1333
+        }
1334
+        foreach($filters['params'] as $param) {
1335
+            $propParamExpressions[] = $query->expr()->andX(
1336
+                $query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1337
+                $query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1338
+            );
1339
+        }
1340
+
1341
+        if (count($propParamExpressions) === 1) {
1342
+            $propParamExpr = $propParamExpressions[0];
1343
+        } else {
1344
+            $propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1345
+        }
1346
+
1347
+        $query->select(['c.calendarid', 'c.uri'])
1348
+            ->from($this->dbObjectPropertiesTable, 'i')
1349
+            ->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1350
+            ->where($calExpr)
1351
+            ->andWhere($compExpr)
1352
+            ->andWhere($propParamExpr)
1353
+            ->andWhere($query->expr()->iLike('i.value',
1354
+                $query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')));
1355
+
1356
+        if ($offset) {
1357
+            $query->setFirstResult($offset);
1358
+        }
1359
+        if ($limit) {
1360
+            $query->setMaxResults($limit);
1361
+        }
1362
+
1363
+        $stmt = $query->execute();
1364
+
1365
+        $result = [];
1366
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1367
+            $path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1368
+            if (!in_array($path, $result)) {
1369
+                $result[] = $path;
1370
+            }
1371
+        }
1372
+
1373
+        return $result;
1374
+    }
1375
+
1376
+    /**
1377
+     * used for Nextcloud's calendar API
1378
+     *
1379
+     * @param array $calendarInfo
1380
+     * @param string $pattern
1381
+     * @param array $searchProperties
1382
+     * @param array $options
1383
+     * @param integer|null $limit
1384
+     * @param integer|null $offset
1385
+     *
1386
+     * @return array
1387
+     */
1388
+    public function search(array $calendarInfo, $pattern, array $searchProperties,
1389
+                            array $options, $limit, $offset) {
1390
+        $outerQuery = $this->db->getQueryBuilder();
1391
+        $innerQuery = $this->db->getQueryBuilder();
1392
+
1393
+        $innerQuery->selectDistinct('op.objectid')
1394
+            ->from($this->dbObjectPropertiesTable, 'op')
1395
+            ->andWhere($innerQuery->expr()->eq('op.calendarid',
1396
+                $outerQuery->createNamedParameter($calendarInfo['id'])));
1397
+
1398
+        // only return public items for shared calendars for now
1399
+        if ($calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
1400
+            $innerQuery->andWhere($innerQuery->expr()->eq('c.classification',
1401
+                $outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1402
+        }
1403
+
1404
+        $or = $innerQuery->expr()->orX();
1405
+        foreach($searchProperties as $searchProperty) {
1406
+            $or->add($innerQuery->expr()->eq('op.name',
1407
+                $outerQuery->createNamedParameter($searchProperty)));
1408
+        }
1409
+        $innerQuery->andWhere($or);
1410
+
1411
+        if ($pattern !== '') {
1412
+            $innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1413
+                $outerQuery->createNamedParameter('%' .
1414
+                    $this->db->escapeLikeParameter($pattern) . '%')));
1415
+        }
1416
+
1417
+        $outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1418
+            ->from('calendarobjects', 'c');
1419
+
1420
+        if (isset($options['timerange'])) {
1421
+            if (isset($options['timerange']['start'])) {
1422
+                $outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence',
1423
+                    $outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp)));
1424
+
1425
+            }
1426
+            if (isset($options['timerange']['end'])) {
1427
+                $outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence',
1428
+                    $outerQuery->createNamedParameter($options['timerange']['end']->getTimeStamp)));
1429
+            }
1430
+        }
1431
+
1432
+        if (isset($options['types'])) {
1433
+            $or = $outerQuery->expr()->orX();
1434
+            foreach($options['types'] as $type) {
1435
+                $or->add($outerQuery->expr()->eq('componenttype',
1436
+                    $outerQuery->createNamedParameter($type)));
1437
+            }
1438
+            $outerQuery->andWhere($or);
1439
+        }
1440
+
1441
+        $outerQuery->andWhere($outerQuery->expr()->in('c.id',
1442
+            $outerQuery->createFunction($innerQuery->getSQL())));
1443
+
1444
+        if ($offset) {
1445
+            $outerQuery->setFirstResult($offset);
1446
+        }
1447
+        if ($limit) {
1448
+            $outerQuery->setMaxResults($limit);
1449
+        }
1450
+
1451
+        $result = $outerQuery->execute();
1452
+        $calendarObjects = $result->fetchAll();
1453
+
1454
+        return array_map(function($o) {
1455
+            $calendarData = Reader::read($o['calendardata']);
1456
+            $comps = $calendarData->getComponents();
1457
+            $objects = [];
1458
+            $timezones = [];
1459
+            foreach($comps as $comp) {
1460
+                if ($comp instanceof VTimeZone) {
1461
+                    $timezones[] = $comp;
1462
+                } else {
1463
+                    $objects[] = $comp;
1464
+                }
1465
+            }
1466
+
1467
+            return [
1468
+                'id' => $o['id'],
1469
+                'type' => $o['componenttype'],
1470
+                'uid' => $o['uid'],
1471
+                'uri' => $o['uri'],
1472
+                'objects' => array_map(function($c) {
1473
+                    return $this->transformSearchData($c);
1474
+                }, $objects),
1475
+                'timezones' => array_map(function($c) {
1476
+                    return $this->transformSearchData($c);
1477
+                }, $timezones),
1478
+            ];
1479
+        }, $calendarObjects);
1480
+    }
1481
+
1482
+    /**
1483
+     * @param Component $comp
1484
+     * @return array
1485
+     */
1486
+    private function transformSearchData(Component $comp) {
1487
+        $data = [];
1488
+        /** @var Component[] $subComponents */
1489
+        $subComponents = $comp->getComponents();
1490
+        /** @var Property[] $properties */
1491
+        $properties = array_filter($comp->children(), function($c) {
1492
+            return $c instanceof Property;
1493
+        });
1494
+        $validationRules = $comp->getValidationRules();
1495
+
1496
+        foreach($subComponents as $subComponent) {
1497
+            $name = $subComponent->name;
1498
+            if (!isset($data[$name])) {
1499
+                $data[$name] = [];
1500
+            }
1501
+            $data[$name][] = $this->transformSearchData($subComponent);
1502
+        }
1503
+
1504
+        foreach($properties as $property) {
1505
+            $name = $property->name;
1506
+            if (!isset($validationRules[$name])) {
1507
+                $validationRules[$name] = '*';
1508
+            }
1509
+
1510
+            $rule = $validationRules[$property->name];
1511
+            if ($rule === '+' || $rule === '*') { // multiple
1512
+                if (!isset($data[$name])) {
1513
+                    $data[$name] = [];
1514
+                }
1515
+
1516
+                $data[$name][] = $this->transformSearchProperty($property);
1517
+            } else { // once
1518
+                $data[$name] = $this->transformSearchProperty($property);
1519
+            }
1520
+        }
1521
+
1522
+        return $data;
1523
+    }
1524
+
1525
+    /**
1526
+     * @param Property $prop
1527
+     * @return array
1528
+     */
1529
+    private function transformSearchProperty(Property $prop) {
1530
+        // No need to check Date, as it extends DateTime
1531
+        if ($prop instanceof Property\ICalendar\DateTime) {
1532
+            $value = $prop->getDateTime();
1533
+        } else {
1534
+            $value = $prop->getValue();
1535
+        }
1536
+
1537
+        return [
1538
+            $value,
1539
+            $prop->parameters()
1540
+        ];
1541
+    }
1542
+
1543
+    /**
1544
+     * Searches through all of a users calendars and calendar objects to find
1545
+     * an object with a specific UID.
1546
+     *
1547
+     * This method should return the path to this object, relative to the
1548
+     * calendar home, so this path usually only contains two parts:
1549
+     *
1550
+     * calendarpath/objectpath.ics
1551
+     *
1552
+     * If the uid is not found, return null.
1553
+     *
1554
+     * This method should only consider * objects that the principal owns, so
1555
+     * any calendars owned by other principals that also appear in this
1556
+     * collection should be ignored.
1557
+     *
1558
+     * @param string $principalUri
1559
+     * @param string $uid
1560
+     * @return string|null
1561
+     */
1562
+    function getCalendarObjectByUID($principalUri, $uid) {
1563
+
1564
+        $query = $this->db->getQueryBuilder();
1565
+        $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1566
+            ->from('calendarobjects', 'co')
1567
+            ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1568
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1569
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1570
+
1571
+        $stmt = $query->execute();
1572
+
1573
+        if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1574
+            return $row['calendaruri'] . '/' . $row['objecturi'];
1575
+        }
1576
+
1577
+        return null;
1578
+    }
1579
+
1580
+    /**
1581
+     * The getChanges method returns all the changes that have happened, since
1582
+     * the specified syncToken in the specified calendar.
1583
+     *
1584
+     * This function should return an array, such as the following:
1585
+     *
1586
+     * [
1587
+     *   'syncToken' => 'The current synctoken',
1588
+     *   'added'   => [
1589
+     *      'new.txt',
1590
+     *   ],
1591
+     *   'modified'   => [
1592
+     *      'modified.txt',
1593
+     *   ],
1594
+     *   'deleted' => [
1595
+     *      'foo.php.bak',
1596
+     *      'old.txt'
1597
+     *   ]
1598
+     * );
1599
+     *
1600
+     * The returned syncToken property should reflect the *current* syncToken
1601
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1602
+     * property This is * needed here too, to ensure the operation is atomic.
1603
+     *
1604
+     * If the $syncToken argument is specified as null, this is an initial
1605
+     * sync, and all members should be reported.
1606
+     *
1607
+     * The modified property is an array of nodenames that have changed since
1608
+     * the last token.
1609
+     *
1610
+     * The deleted property is an array with nodenames, that have been deleted
1611
+     * from collection.
1612
+     *
1613
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
1614
+     * 1, you only have to report changes that happened only directly in
1615
+     * immediate descendants. If it's 2, it should also include changes from
1616
+     * the nodes below the child collections. (grandchildren)
1617
+     *
1618
+     * The $limit argument allows a client to specify how many results should
1619
+     * be returned at most. If the limit is not specified, it should be treated
1620
+     * as infinite.
1621
+     *
1622
+     * If the limit (infinite or not) is higher than you're willing to return,
1623
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1624
+     *
1625
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
1626
+     * return null.
1627
+     *
1628
+     * The limit is 'suggestive'. You are free to ignore it.
1629
+     *
1630
+     * @param string $calendarId
1631
+     * @param string $syncToken
1632
+     * @param int $syncLevel
1633
+     * @param int $limit
1634
+     * @return array
1635
+     */
1636
+    function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1637
+        // Current synctoken
1638
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1639
+        $stmt->execute([ $calendarId ]);
1640
+        $currentToken = $stmt->fetchColumn(0);
1641
+
1642
+        if (is_null($currentToken)) {
1643
+            return null;
1644
+        }
1645
+
1646
+        $result = [
1647
+            'syncToken' => $currentToken,
1648
+            'added'     => [],
1649
+            'modified'  => [],
1650
+            'deleted'   => [],
1651
+        ];
1652
+
1653
+        if ($syncToken) {
1654
+
1655
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1656
+            if ($limit>0) {
1657
+                $query.= " LIMIT " . (int)$limit;
1658
+            }
1659
+
1660
+            // Fetching all changes
1661
+            $stmt = $this->db->prepare($query);
1662
+            $stmt->execute([$syncToken, $currentToken, $calendarId]);
1663
+
1664
+            $changes = [];
1665
+
1666
+            // This loop ensures that any duplicates are overwritten, only the
1667
+            // last change on a node is relevant.
1668
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1669
+
1670
+                $changes[$row['uri']] = $row['operation'];
1671
+
1672
+            }
1673
+
1674
+            foreach($changes as $uri => $operation) {
1675
+
1676
+                switch($operation) {
1677
+                    case 1 :
1678
+                        $result['added'][] = $uri;
1679
+                        break;
1680
+                    case 2 :
1681
+                        $result['modified'][] = $uri;
1682
+                        break;
1683
+                    case 3 :
1684
+                        $result['deleted'][] = $uri;
1685
+                        break;
1686
+                }
1687
+
1688
+            }
1689
+        } else {
1690
+            // No synctoken supplied, this is the initial sync.
1691
+            $query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?";
1692
+            $stmt = $this->db->prepare($query);
1693
+            $stmt->execute([$calendarId]);
1694
+
1695
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1696
+        }
1697
+        return $result;
1698
+
1699
+    }
1700
+
1701
+    /**
1702
+     * Returns a list of subscriptions for a principal.
1703
+     *
1704
+     * Every subscription is an array with the following keys:
1705
+     *  * id, a unique id that will be used by other functions to modify the
1706
+     *    subscription. This can be the same as the uri or a database key.
1707
+     *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1708
+     *  * principaluri. The owner of the subscription. Almost always the same as
1709
+     *    principalUri passed to this method.
1710
+     *
1711
+     * Furthermore, all the subscription info must be returned too:
1712
+     *
1713
+     * 1. {DAV:}displayname
1714
+     * 2. {http://apple.com/ns/ical/}refreshrate
1715
+     * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1716
+     *    should not be stripped).
1717
+     * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1718
+     *    should not be stripped).
1719
+     * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1720
+     *    attachments should not be stripped).
1721
+     * 6. {http://calendarserver.org/ns/}source (Must be a
1722
+     *     Sabre\DAV\Property\Href).
1723
+     * 7. {http://apple.com/ns/ical/}calendar-color
1724
+     * 8. {http://apple.com/ns/ical/}calendar-order
1725
+     * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1726
+     *    (should just be an instance of
1727
+     *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1728
+     *    default components).
1729
+     *
1730
+     * @param string $principalUri
1731
+     * @return array
1732
+     */
1733
+    function getSubscriptionsForUser($principalUri) {
1734
+        $fields = array_values($this->subscriptionPropertyMap);
1735
+        $fields[] = 'id';
1736
+        $fields[] = 'uri';
1737
+        $fields[] = 'source';
1738
+        $fields[] = 'principaluri';
1739
+        $fields[] = 'lastmodified';
1740
+
1741
+        $query = $this->db->getQueryBuilder();
1742
+        $query->select($fields)
1743
+            ->from('calendarsubscriptions')
1744
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1745
+            ->orderBy('calendarorder', 'asc');
1746
+        $stmt =$query->execute();
1747
+
1748
+        $subscriptions = [];
1749
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1750
+
1751
+            $subscription = [
1752
+                'id'           => $row['id'],
1753
+                'uri'          => $row['uri'],
1754
+                'principaluri' => $row['principaluri'],
1755
+                'source'       => $row['source'],
1756
+                'lastmodified' => $row['lastmodified'],
1757
+
1758
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1759
+            ];
1760
+
1761
+            foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1762
+                if (!is_null($row[$dbName])) {
1763
+                    $subscription[$xmlName] = $row[$dbName];
1764
+                }
1765
+            }
1766
+
1767
+            $subscriptions[] = $subscription;
1768
+
1769
+        }
1770
+
1771
+        return $subscriptions;
1772
+    }
1773
+
1774
+    /**
1775
+     * Creates a new subscription for a principal.
1776
+     *
1777
+     * If the creation was a success, an id must be returned that can be used to reference
1778
+     * this subscription in other methods, such as updateSubscription.
1779
+     *
1780
+     * @param string $principalUri
1781
+     * @param string $uri
1782
+     * @param array $properties
1783
+     * @return mixed
1784
+     */
1785
+    function createSubscription($principalUri, $uri, array $properties) {
1786
+
1787
+        if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1788
+            throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1789
+        }
1790
+
1791
+        $values = [
1792
+            'principaluri' => $principalUri,
1793
+            'uri'          => $uri,
1794
+            'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1795
+            'lastmodified' => time(),
1796
+        ];
1797
+
1798
+        $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1799
+
1800
+        foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1801
+            if (array_key_exists($xmlName, $properties)) {
1802
+                    $values[$dbName] = $properties[$xmlName];
1803
+                    if (in_array($dbName, $propertiesBoolean)) {
1804
+                        $values[$dbName] = true;
1805
+                }
1806
+            }
1807
+        }
1808
+
1809
+        $valuesToInsert = array();
1810
+
1811
+        $query = $this->db->getQueryBuilder();
1812
+
1813
+        foreach (array_keys($values) as $name) {
1814
+            $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1815
+        }
1816
+
1817
+        $query->insert('calendarsubscriptions')
1818
+            ->values($valuesToInsert)
1819
+            ->execute();
1820
+
1821
+        return $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1822
+    }
1823
+
1824
+    /**
1825
+     * Updates a subscription
1826
+     *
1827
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1828
+     * To do the actual updates, you must tell this object which properties
1829
+     * you're going to process with the handle() method.
1830
+     *
1831
+     * Calling the handle method is like telling the PropPatch object "I
1832
+     * promise I can handle updating this property".
1833
+     *
1834
+     * Read the PropPatch documentation for more info and examples.
1835
+     *
1836
+     * @param mixed $subscriptionId
1837
+     * @param PropPatch $propPatch
1838
+     * @return void
1839
+     */
1840
+    function updateSubscription($subscriptionId, PropPatch $propPatch) {
1841
+        $supportedProperties = array_keys($this->subscriptionPropertyMap);
1842
+        $supportedProperties[] = '{http://calendarserver.org/ns/}source';
1843
+
1844
+        /**
1845
+         * @suppress SqlInjectionChecker
1846
+         */
1847
+        $propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1848
+
1849
+            $newValues = [];
1850
+
1851
+            foreach($mutations as $propertyName=>$propertyValue) {
1852
+                if ($propertyName === '{http://calendarserver.org/ns/}source') {
1853
+                    $newValues['source'] = $propertyValue->getHref();
1854
+                } else {
1855
+                    $fieldName = $this->subscriptionPropertyMap[$propertyName];
1856
+                    $newValues[$fieldName] = $propertyValue;
1857
+                }
1858
+            }
1859
+
1860
+            $query = $this->db->getQueryBuilder();
1861
+            $query->update('calendarsubscriptions')
1862
+                ->set('lastmodified', $query->createNamedParameter(time()));
1863
+            foreach($newValues as $fieldName=>$value) {
1864
+                $query->set($fieldName, $query->createNamedParameter($value));
1865
+            }
1866
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1867
+                ->execute();
1868
+
1869
+            return true;
1870
+
1871
+        });
1872
+    }
1873
+
1874
+    /**
1875
+     * Deletes a subscription.
1876
+     *
1877
+     * @param mixed $subscriptionId
1878
+     * @return void
1879
+     */
1880
+    function deleteSubscription($subscriptionId) {
1881
+        $query = $this->db->getQueryBuilder();
1882
+        $query->delete('calendarsubscriptions')
1883
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1884
+            ->execute();
1885
+    }
1886
+
1887
+    /**
1888
+     * Returns a single scheduling object for the inbox collection.
1889
+     *
1890
+     * The returned array should contain the following elements:
1891
+     *   * uri - A unique basename for the object. This will be used to
1892
+     *           construct a full uri.
1893
+     *   * calendardata - The iCalendar object
1894
+     *   * lastmodified - The last modification date. Can be an int for a unix
1895
+     *                    timestamp, or a PHP DateTime object.
1896
+     *   * etag - A unique token that must change if the object changed.
1897
+     *   * size - The size of the object, in bytes.
1898
+     *
1899
+     * @param string $principalUri
1900
+     * @param string $objectUri
1901
+     * @return array
1902
+     */
1903
+    function getSchedulingObject($principalUri, $objectUri) {
1904
+        $query = $this->db->getQueryBuilder();
1905
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1906
+            ->from('schedulingobjects')
1907
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1908
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1909
+            ->execute();
1910
+
1911
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
1912
+
1913
+        if(!$row) {
1914
+            return null;
1915
+        }
1916
+
1917
+        return [
1918
+                'uri'          => $row['uri'],
1919
+                'calendardata' => $row['calendardata'],
1920
+                'lastmodified' => $row['lastmodified'],
1921
+                'etag'         => '"' . $row['etag'] . '"',
1922
+                'size'         => (int)$row['size'],
1923
+        ];
1924
+    }
1925
+
1926
+    /**
1927
+     * Returns all scheduling objects for the inbox collection.
1928
+     *
1929
+     * These objects should be returned as an array. Every item in the array
1930
+     * should follow the same structure as returned from getSchedulingObject.
1931
+     *
1932
+     * The main difference is that 'calendardata' is optional.
1933
+     *
1934
+     * @param string $principalUri
1935
+     * @return array
1936
+     */
1937
+    function getSchedulingObjects($principalUri) {
1938
+        $query = $this->db->getQueryBuilder();
1939
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1940
+                ->from('schedulingobjects')
1941
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1942
+                ->execute();
1943
+
1944
+        $result = [];
1945
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1946
+            $result[] = [
1947
+                    'calendardata' => $row['calendardata'],
1948
+                    'uri'          => $row['uri'],
1949
+                    'lastmodified' => $row['lastmodified'],
1950
+                    'etag'         => '"' . $row['etag'] . '"',
1951
+                    'size'         => (int)$row['size'],
1952
+            ];
1953
+        }
1954
+
1955
+        return $result;
1956
+    }
1957
+
1958
+    /**
1959
+     * Deletes a scheduling object from the inbox collection.
1960
+     *
1961
+     * @param string $principalUri
1962
+     * @param string $objectUri
1963
+     * @return void
1964
+     */
1965
+    function deleteSchedulingObject($principalUri, $objectUri) {
1966
+        $query = $this->db->getQueryBuilder();
1967
+        $query->delete('schedulingobjects')
1968
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1969
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1970
+                ->execute();
1971
+    }
1972
+
1973
+    /**
1974
+     * Creates a new scheduling object. This should land in a users' inbox.
1975
+     *
1976
+     * @param string $principalUri
1977
+     * @param string $objectUri
1978
+     * @param string $objectData
1979
+     * @return void
1980
+     */
1981
+    function createSchedulingObject($principalUri, $objectUri, $objectData) {
1982
+        $query = $this->db->getQueryBuilder();
1983
+        $query->insert('schedulingobjects')
1984
+            ->values([
1985
+                'principaluri' => $query->createNamedParameter($principalUri),
1986
+                'calendardata' => $query->createNamedParameter($objectData),
1987
+                'uri' => $query->createNamedParameter($objectUri),
1988
+                'lastmodified' => $query->createNamedParameter(time()),
1989
+                'etag' => $query->createNamedParameter(md5($objectData)),
1990
+                'size' => $query->createNamedParameter(strlen($objectData))
1991
+            ])
1992
+            ->execute();
1993
+    }
1994
+
1995
+    /**
1996
+     * Adds a change record to the calendarchanges table.
1997
+     *
1998
+     * @param mixed $calendarId
1999
+     * @param string $objectUri
2000
+     * @param int $operation 1 = add, 2 = modify, 3 = delete.
2001
+     * @return void
2002
+     */
2003
+    protected function addChange($calendarId, $objectUri, $operation) {
2004
+
2005
+        $stmt = $this->db->prepare('INSERT INTO `*PREFIX*calendarchanges` (`uri`, `synctoken`, `calendarid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*calendars` WHERE `id` = ?');
2006
+        $stmt->execute([
2007
+            $objectUri,
2008
+            $calendarId,
2009
+            $operation,
2010
+            $calendarId
2011
+        ]);
2012
+        $stmt = $this->db->prepare('UPDATE `*PREFIX*calendars` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
2013
+        $stmt->execute([
2014
+            $calendarId
2015
+        ]);
2016
+
2017
+    }
2018
+
2019
+    /**
2020
+     * Parses some information from calendar objects, used for optimized
2021
+     * calendar-queries.
2022
+     *
2023
+     * Returns an array with the following keys:
2024
+     *   * etag - An md5 checksum of the object without the quotes.
2025
+     *   * size - Size of the object in bytes
2026
+     *   * componentType - VEVENT, VTODO or VJOURNAL
2027
+     *   * firstOccurence
2028
+     *   * lastOccurence
2029
+     *   * uid - value of the UID property
2030
+     *
2031
+     * @param string $calendarData
2032
+     * @return array
2033
+     */
2034
+    public function getDenormalizedData($calendarData) {
2035
+
2036
+        $vObject = Reader::read($calendarData);
2037
+        $componentType = null;
2038
+        $component = null;
2039
+        $firstOccurrence = null;
2040
+        $lastOccurrence = null;
2041
+        $uid = null;
2042
+        $classification = self::CLASSIFICATION_PUBLIC;
2043
+        foreach($vObject->getComponents() as $component) {
2044
+            if ($component->name!=='VTIMEZONE') {
2045
+                $componentType = $component->name;
2046
+                $uid = (string)$component->UID;
2047
+                break;
2048
+            }
2049
+        }
2050
+        if (!$componentType) {
2051
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
2052
+        }
2053
+        if ($componentType === 'VEVENT' && $component->DTSTART) {
2054
+            $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
2055
+            // Finding the last occurrence is a bit harder
2056
+            if (!isset($component->RRULE)) {
2057
+                if (isset($component->DTEND)) {
2058
+                    $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
2059
+                } elseif (isset($component->DURATION)) {
2060
+                    $endDate = clone $component->DTSTART->getDateTime();
2061
+                    $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
2062
+                    $lastOccurrence = $endDate->getTimeStamp();
2063
+                } elseif (!$component->DTSTART->hasTime()) {
2064
+                    $endDate = clone $component->DTSTART->getDateTime();
2065
+                    $endDate->modify('+1 day');
2066
+                    $lastOccurrence = $endDate->getTimeStamp();
2067
+                } else {
2068
+                    $lastOccurrence = $firstOccurrence;
2069
+                }
2070
+            } else {
2071
+                $it = new EventIterator($vObject, (string)$component->UID);
2072
+                $maxDate = new \DateTime(self::MAX_DATE);
2073
+                if ($it->isInfinite()) {
2074
+                    $lastOccurrence = $maxDate->getTimestamp();
2075
+                } else {
2076
+                    $end = $it->getDtEnd();
2077
+                    while($it->valid() && $end < $maxDate) {
2078
+                        $end = $it->getDtEnd();
2079
+                        $it->next();
2080
+
2081
+                    }
2082
+                    $lastOccurrence = $end->getTimestamp();
2083
+                }
2084
+
2085
+            }
2086
+        }
2087
+
2088
+        if ($component->CLASS) {
2089
+            $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
2090
+            switch ($component->CLASS->getValue()) {
2091
+                case 'PUBLIC':
2092
+                    $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
2093
+                    break;
2094
+                case 'CONFIDENTIAL':
2095
+                    $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
2096
+                    break;
2097
+            }
2098
+        }
2099
+        return [
2100
+            'etag' => md5($calendarData),
2101
+            'size' => strlen($calendarData),
2102
+            'componentType' => $componentType,
2103
+            'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
2104
+            'lastOccurence'  => $lastOccurrence,
2105
+            'uid' => $uid,
2106
+            'classification' => $classification
2107
+        ];
2108
+
2109
+    }
2110
+
2111
+    private function readBlob($cardData) {
2112
+        if (is_resource($cardData)) {
2113
+            return stream_get_contents($cardData);
2114
+        }
2115
+
2116
+        return $cardData;
2117
+    }
2118
+
2119
+    /**
2120
+     * @param IShareable $shareable
2121
+     * @param array $add
2122
+     * @param array $remove
2123
+     */
2124
+    public function updateShares($shareable, $add, $remove) {
2125
+        $calendarId = $shareable->getResourceId();
2126
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
2127
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2128
+            [
2129
+                'calendarId' => $calendarId,
2130
+                'calendarData' => $this->getCalendarById($calendarId),
2131
+                'shares' => $this->getShares($calendarId),
2132
+                'add' => $add,
2133
+                'remove' => $remove,
2134
+            ]));
2135
+        $this->sharingBackend->updateShares($shareable, $add, $remove);
2136
+    }
2137
+
2138
+    /**
2139
+     * @param int $resourceId
2140
+     * @return array
2141
+     */
2142
+    public function getShares($resourceId) {
2143
+        return $this->sharingBackend->getShares($resourceId);
2144
+    }
2145
+
2146
+    /**
2147
+     * @param boolean $value
2148
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
2149
+     * @return string|null
2150
+     */
2151
+    public function setPublishStatus($value, $calendar) {
2152
+
2153
+        $calendarId = $calendar->getResourceId();
2154
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', new GenericEvent(
2155
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2156
+            [
2157
+                'calendarId' => $calendarId,
2158
+                'calendarData' => $this->getCalendarById($calendarId),
2159
+                'public' => $value,
2160
+            ]));
2161
+
2162
+        $query = $this->db->getQueryBuilder();
2163
+        if ($value) {
2164
+            $publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
2165
+            $query->insert('dav_shares')
2166
+                ->values([
2167
+                    'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
2168
+                    'type' => $query->createNamedParameter('calendar'),
2169
+                    'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
2170
+                    'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
2171
+                    'publicuri' => $query->createNamedParameter($publicUri)
2172
+                ]);
2173
+            $query->execute();
2174
+            return $publicUri;
2175
+        }
2176
+        $query->delete('dav_shares')
2177
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2178
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
2179
+        $query->execute();
2180
+        return null;
2181
+    }
2182
+
2183
+    /**
2184
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
2185
+     * @return mixed
2186
+     */
2187
+    public function getPublishStatus($calendar) {
2188
+        $query = $this->db->getQueryBuilder();
2189
+        $result = $query->select('publicuri')
2190
+            ->from('dav_shares')
2191
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2192
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
2193
+            ->execute();
2194
+
2195
+        $row = $result->fetch();
2196
+        $result->closeCursor();
2197
+        return $row ? reset($row) : false;
2198
+    }
2199
+
2200
+    /**
2201
+     * @param int $resourceId
2202
+     * @param array $acl
2203
+     * @return array
2204
+     */
2205
+    public function applyShareAcl($resourceId, $acl) {
2206
+        return $this->sharingBackend->applyShareAcl($resourceId, $acl);
2207
+    }
2208
+
2209
+
2210
+
2211
+    /**
2212
+     * update properties table
2213
+     *
2214
+     * @param int $calendarId
2215
+     * @param string $objectUri
2216
+     * @param string $calendarData
2217
+     */
2218
+    public function updateProperties($calendarId, $objectUri, $calendarData) {
2219
+        $objectId = $this->getCalendarObjectId($calendarId, $objectUri);
2220
+
2221
+        try {
2222
+            $vCalendar = $this->readCalendarData($calendarData);
2223
+        } catch (\Exception $ex) {
2224
+            return;
2225
+        }
2226
+
2227
+        $this->purgeProperties($calendarId, $objectId);
2228
+
2229
+        $query = $this->db->getQueryBuilder();
2230
+        $query->insert($this->dbObjectPropertiesTable)
2231
+            ->values(
2232
+                [
2233
+                    'calendarid' => $query->createNamedParameter($calendarId),
2234
+                    'objectid' => $query->createNamedParameter($objectId),
2235
+                    'name' => $query->createParameter('name'),
2236
+                    'parameter' => $query->createParameter('parameter'),
2237
+                    'value' => $query->createParameter('value'),
2238
+                ]
2239
+            );
2240
+
2241
+        $indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
2242
+        foreach ($vCalendar->getComponents() as $component) {
2243
+            if (!in_array($component->name, $indexComponents)) {
2244
+                continue;
2245
+            }
2246
+
2247
+            foreach ($component->children() as $property) {
2248
+                if (in_array($property->name, self::$indexProperties)) {
2249
+                    $value = $property->getValue();
2250
+                    // is this a shitty db?
2251
+                    if (!$this->db->supports4ByteText()) {
2252
+                        $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2253
+                    }
2254
+                    $value = mb_substr($value, 0, 254);
2255
+
2256
+                    $query->setParameter('name', $property->name);
2257
+                    $query->setParameter('parameter', null);
2258
+                    $query->setParameter('value', $value);
2259
+                    $query->execute();
2260
+                }
2261
+
2262
+                if (array_key_exists($property->name, self::$indexParameters)) {
2263
+                    $parameters = $property->parameters();
2264
+                    $indexedParametersForProperty = self::$indexParameters[$property->name];
2265
+
2266
+                    foreach ($parameters as $key => $value) {
2267
+                        if (in_array($key, $indexedParametersForProperty)) {
2268
+                            // is this a shitty db?
2269
+                            if ($this->db->supports4ByteText()) {
2270
+                                $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2271
+                            }
2272
+                            $value = mb_substr($value, 0, 254);
2273
+
2274
+                            $query->setParameter('name', $property->name);
2275
+                            $query->setParameter('parameter', substr($key, 0, 254));
2276
+                            $query->setParameter('value', substr($value, 0, 254));
2277
+                            $query->execute();
2278
+                        }
2279
+                    }
2280
+                }
2281
+            }
2282
+        }
2283
+    }
2284
+
2285
+    /**
2286
+     * deletes all birthday calendars
2287
+     */
2288
+    public function deleteAllBirthdayCalendars() {
2289
+        $query = $this->db->getQueryBuilder();
2290
+        $result = $query->select(['id'])->from('calendars')
2291
+            ->where($query->expr()->eq('uri',
2292
+                $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
2293
+            ->execute();
2294
+
2295
+        $ids = $result->fetchAll();
2296
+        foreach($ids as $id) {
2297
+            $this->deleteCalendar($id['id']);
2298
+        }
2299
+    }
2300
+
2301
+    /**
2302
+     * read VCalendar data into a VCalendar object
2303
+     *
2304
+     * @param string $objectData
2305
+     * @return VCalendar
2306
+     */
2307
+    protected function readCalendarData($objectData) {
2308
+        return Reader::read($objectData);
2309
+    }
2310
+
2311
+    /**
2312
+     * delete all properties from a given calendar object
2313
+     *
2314
+     * @param int $calendarId
2315
+     * @param int $objectId
2316
+     */
2317
+    protected function purgeProperties($calendarId, $objectId) {
2318
+        $query = $this->db->getQueryBuilder();
2319
+        $query->delete($this->dbObjectPropertiesTable)
2320
+            ->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
2321
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2322
+        $query->execute();
2323
+    }
2324
+
2325
+    /**
2326
+     * get ID from a given calendar object
2327
+     *
2328
+     * @param int $calendarId
2329
+     * @param string $uri
2330
+     * @return int
2331
+     */
2332
+    protected function getCalendarObjectId($calendarId, $uri) {
2333
+        $query = $this->db->getQueryBuilder();
2334
+        $query->select('id')->from('calendarobjects')
2335
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2336
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2337
+
2338
+        $result = $query->execute();
2339
+        $objectIds = $result->fetch();
2340
+        $result->closeCursor();
2341
+
2342
+        if (!isset($objectIds['id'])) {
2343
+            throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2344
+        }
2345
+
2346
+        return (int)$objectIds['id'];
2347
+    }
2348
+
2349
+    private function convertPrincipal($principalUri, $toV2) {
2350
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
2351
+            list(, $name) = Uri\split($principalUri);
2352
+            if ($toV2 === true) {
2353
+                return "principals/users/$name";
2354
+            }
2355
+            return "principals/$name";
2356
+        }
2357
+        return $principalUri;
2358
+    }
2359
+
2360
+    private function addOwnerPrincipal(&$calendarInfo) {
2361
+        $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2362
+        $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2363
+        if (isset($calendarInfo[$ownerPrincipalKey])) {
2364
+            $uri = $calendarInfo[$ownerPrincipalKey];
2365
+        } else {
2366
+            $uri = $calendarInfo['principaluri'];
2367
+        }
2368
+
2369
+        $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
2370
+        if (isset($principalInformation['{DAV:}displayname'])) {
2371
+            $calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
2372
+        }
2373
+    }
2374 2374
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Schedule/Plugin.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -70,7 +70,7 @@  discard block
 block discarded – undo
70 70
 	 */
71 71
 	function propFindDefaultCalendarUrl(PropFind $propFind, INode $node) {
72 72
 		if ($node instanceof IPrincipal) {
73
-			$propFind->handle('{' . self::NS_CALDAV . '}schedule-default-calendar-URL', function() use ($node) {
73
+			$propFind->handle('{'.self::NS_CALDAV.'}schedule-default-calendar-URL', function() use ($node) {
74 74
 				/** @var \OCA\DAV\CalDAV\Plugin $caldavPlugin */
75 75
 				$caldavPlugin = $this->server->getPlugin('caldav');
76 76
 				$principalUrl = $node->getPrincipalUrl();
@@ -89,7 +89,7 @@  discard block
 block discarded – undo
89 89
 					]);
90 90
 				}
91 91
 
92
-				$result = $this->server->getPropertiesForPath($calendarHomePath . '/' . CalDavBackend::PERSONAL_CALENDAR_URI, [], 1);
92
+				$result = $this->server->getPropertiesForPath($calendarHomePath.'/'.CalDavBackend::PERSONAL_CALENDAR_URI, [], 1);
93 93
 				if (empty($result)) {
94 94
 					return null;
95 95
 				}
Please login to merge, or discard this patch.
Indentation   +127 added lines, -127 removed lines patch added patch discarded remove patch
@@ -38,131 +38,131 @@
 block discarded – undo
38 38
 
39 39
 class Plugin extends \Sabre\CalDAV\Schedule\Plugin {
40 40
 
41
-	/**
42
-	 * Initializes the plugin
43
-	 *
44
-	 * @param Server $server
45
-	 * @return void
46
-	 */
47
-	function initialize(Server $server) {
48
-		parent::initialize($server);
49
-		$server->on('propFind', [$this, 'propFindDefaultCalendarUrl'], 90);
50
-	}
51
-
52
-	/**
53
-	 * Returns a list of addresses that are associated with a principal.
54
-	 *
55
-	 * @param string $principal
56
-	 * @return array
57
-	 */
58
-	protected function getAddressesForPrincipal($principal) {
59
-		$result = parent::getAddressesForPrincipal($principal);
60
-
61
-		if ($result === null) {
62
-			$result = [];
63
-		}
64
-
65
-		return $result;
66
-	}
67
-
68
-	/**
69
-	 * Always use the personal calendar as target for scheduled events
70
-	 *
71
-	 * @param PropFind $propFind
72
-	 * @param INode $node
73
-	 * @return void
74
-	 */
75
-	function propFindDefaultCalendarUrl(PropFind $propFind, INode $node) {
76
-		if ($node instanceof IPrincipal) {
77
-			$propFind->handle('{' . self::NS_CALDAV . '}schedule-default-calendar-URL', function() use ($node) {
78
-				/** @var \OCA\DAV\CalDAV\Plugin $caldavPlugin */
79
-				$caldavPlugin = $this->server->getPlugin('caldav');
80
-				$principalUrl = $node->getPrincipalUrl();
81
-
82
-				$calendarHomePath = $caldavPlugin->getCalendarHomeForPrincipal($principalUrl);
83
-
84
-				if (!$calendarHomePath) {
85
-					return null;
86
-				}
87
-
88
-				/** @var CalendarHome $calendarHome */
89
-				$calendarHome = $this->server->tree->getNodeForPath($calendarHomePath);
90
-				if (!$calendarHome->childExists(CalDavBackend::PERSONAL_CALENDAR_URI)) {
91
-					$calendarHome->getCalDAVBackend()->createCalendar($principalUrl, CalDavBackend::PERSONAL_CALENDAR_URI, [
92
-						'{DAV:}displayname' => CalDavBackend::PERSONAL_CALENDAR_NAME,
93
-					]);
94
-				}
95
-
96
-				$result = $this->server->getPropertiesForPath($calendarHomePath . '/' . CalDavBackend::PERSONAL_CALENDAR_URI, [], 1);
97
-				if (empty($result)) {
98
-					return null;
99
-				}
100
-
101
-				return new LocalHref($result[0]['href']);
102
-			});
103
-		}
104
-	}
105
-
106
-	/**
107
-	 * This method is triggered whenever there was a calendar object gets
108
-	 * created or updated.
109
-	 *
110
-	 * Basically just a copy of parent::calendarObjectChange, with the change
111
-	 * from:
112
-	 * $addresses = $this->getAddressesForPrincipal($calendarNode->getOwner());
113
-	 * to:
114
-	 * $addresses = $this->getAddressesForPrincipal($calendarNode->getPrincipalURI());
115
-	 *
116
-	 * @param RequestInterface $request HTTP request
117
-	 * @param ResponseInterface $response HTTP Response
118
-	 * @param VCalendar $vCal Parsed iCalendar object
119
-	 * @param mixed $calendarPath Path to calendar collection
120
-	 * @param mixed $modified The iCalendar object has been touched.
121
-	 * @param mixed $isNew Whether this was a new item or we're updating one
122
-	 * @return void
123
-	 */
124
-	function calendarObjectChange(RequestInterface $request, ResponseInterface $response, VCalendar $vCal, $calendarPath, &$modified, $isNew) {
125
-
126
-		if (!$this->scheduleReply($this->server->httpRequest)) {
127
-			return;
128
-		}
129
-
130
-		$calendarNode = $this->server->tree->getNodeForPath($calendarPath);
131
-
132
-		$addresses = $this->getAddressesForPrincipal(
133
-			$calendarNode->getPrincipalURI()
134
-		);
135
-
136
-		if (!$isNew) {
137
-			$node = $this->server->tree->getNodeForPath($request->getPath());
138
-			$oldObj = Reader::read($node->get());
139
-		} else {
140
-			$oldObj = null;
141
-		}
142
-
143
-		$this->processICalendarChange($oldObj, $vCal, $addresses, [], $modified);
144
-
145
-		if ($oldObj) {
146
-			// Destroy circular references so PHP will GC the object.
147
-			$oldObj->destroy();
148
-		}
149
-
150
-	}
151
-
152
-	/**
153
-	 * This method checks the 'Schedule-Reply' header
154
-	 * and returns false if it's 'F', otherwise true.
155
-	 *
156
-	 * Copied from Sabre/DAV's Schedule plugin, because it's
157
-	 * private for whatever reason
158
-	 *
159
-	 * @param RequestInterface $request
160
-	 * @return bool
161
-	 */
162
-	private function scheduleReply(RequestInterface $request) {
163
-
164
-		$scheduleReply = $request->getHeader('Schedule-Reply');
165
-		return $scheduleReply !== 'F';
166
-
167
-	}
41
+    /**
42
+     * Initializes the plugin
43
+     *
44
+     * @param Server $server
45
+     * @return void
46
+     */
47
+    function initialize(Server $server) {
48
+        parent::initialize($server);
49
+        $server->on('propFind', [$this, 'propFindDefaultCalendarUrl'], 90);
50
+    }
51
+
52
+    /**
53
+     * Returns a list of addresses that are associated with a principal.
54
+     *
55
+     * @param string $principal
56
+     * @return array
57
+     */
58
+    protected function getAddressesForPrincipal($principal) {
59
+        $result = parent::getAddressesForPrincipal($principal);
60
+
61
+        if ($result === null) {
62
+            $result = [];
63
+        }
64
+
65
+        return $result;
66
+    }
67
+
68
+    /**
69
+     * Always use the personal calendar as target for scheduled events
70
+     *
71
+     * @param PropFind $propFind
72
+     * @param INode $node
73
+     * @return void
74
+     */
75
+    function propFindDefaultCalendarUrl(PropFind $propFind, INode $node) {
76
+        if ($node instanceof IPrincipal) {
77
+            $propFind->handle('{' . self::NS_CALDAV . '}schedule-default-calendar-URL', function() use ($node) {
78
+                /** @var \OCA\DAV\CalDAV\Plugin $caldavPlugin */
79
+                $caldavPlugin = $this->server->getPlugin('caldav');
80
+                $principalUrl = $node->getPrincipalUrl();
81
+
82
+                $calendarHomePath = $caldavPlugin->getCalendarHomeForPrincipal($principalUrl);
83
+
84
+                if (!$calendarHomePath) {
85
+                    return null;
86
+                }
87
+
88
+                /** @var CalendarHome $calendarHome */
89
+                $calendarHome = $this->server->tree->getNodeForPath($calendarHomePath);
90
+                if (!$calendarHome->childExists(CalDavBackend::PERSONAL_CALENDAR_URI)) {
91
+                    $calendarHome->getCalDAVBackend()->createCalendar($principalUrl, CalDavBackend::PERSONAL_CALENDAR_URI, [
92
+                        '{DAV:}displayname' => CalDavBackend::PERSONAL_CALENDAR_NAME,
93
+                    ]);
94
+                }
95
+
96
+                $result = $this->server->getPropertiesForPath($calendarHomePath . '/' . CalDavBackend::PERSONAL_CALENDAR_URI, [], 1);
97
+                if (empty($result)) {
98
+                    return null;
99
+                }
100
+
101
+                return new LocalHref($result[0]['href']);
102
+            });
103
+        }
104
+    }
105
+
106
+    /**
107
+     * This method is triggered whenever there was a calendar object gets
108
+     * created or updated.
109
+     *
110
+     * Basically just a copy of parent::calendarObjectChange, with the change
111
+     * from:
112
+     * $addresses = $this->getAddressesForPrincipal($calendarNode->getOwner());
113
+     * to:
114
+     * $addresses = $this->getAddressesForPrincipal($calendarNode->getPrincipalURI());
115
+     *
116
+     * @param RequestInterface $request HTTP request
117
+     * @param ResponseInterface $response HTTP Response
118
+     * @param VCalendar $vCal Parsed iCalendar object
119
+     * @param mixed $calendarPath Path to calendar collection
120
+     * @param mixed $modified The iCalendar object has been touched.
121
+     * @param mixed $isNew Whether this was a new item or we're updating one
122
+     * @return void
123
+     */
124
+    function calendarObjectChange(RequestInterface $request, ResponseInterface $response, VCalendar $vCal, $calendarPath, &$modified, $isNew) {
125
+
126
+        if (!$this->scheduleReply($this->server->httpRequest)) {
127
+            return;
128
+        }
129
+
130
+        $calendarNode = $this->server->tree->getNodeForPath($calendarPath);
131
+
132
+        $addresses = $this->getAddressesForPrincipal(
133
+            $calendarNode->getPrincipalURI()
134
+        );
135
+
136
+        if (!$isNew) {
137
+            $node = $this->server->tree->getNodeForPath($request->getPath());
138
+            $oldObj = Reader::read($node->get());
139
+        } else {
140
+            $oldObj = null;
141
+        }
142
+
143
+        $this->processICalendarChange($oldObj, $vCal, $addresses, [], $modified);
144
+
145
+        if ($oldObj) {
146
+            // Destroy circular references so PHP will GC the object.
147
+            $oldObj->destroy();
148
+        }
149
+
150
+    }
151
+
152
+    /**
153
+     * This method checks the 'Schedule-Reply' header
154
+     * and returns false if it's 'F', otherwise true.
155
+     *
156
+     * Copied from Sabre/DAV's Schedule plugin, because it's
157
+     * private for whatever reason
158
+     *
159
+     * @param RequestInterface $request
160
+     * @return bool
161
+     */
162
+    private function scheduleReply(RequestInterface $request) {
163
+
164
+        $scheduleReply = $request->getHeader('Schedule-Reply');
165
+        return $scheduleReply !== 'F';
166
+
167
+    }
168 168
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Publishing/Xml/Publisher.php 1 patch
Indentation   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -26,58 +26,58 @@
 block discarded – undo
26 26
 
27 27
 class Publisher implements XmlSerializable {
28 28
 
29
-	/**
30
-	 * @var string $publishUrl
31
-	 */
32
-	protected $publishUrl;
29
+    /**
30
+     * @var string $publishUrl
31
+     */
32
+    protected $publishUrl;
33 33
 
34
-	/**
35
-	 * @var boolean $isPublished
36
-	 */
37
-	protected $isPublished;
34
+    /**
35
+     * @var boolean $isPublished
36
+     */
37
+    protected $isPublished;
38 38
 
39
-	/**
40
-	 * @param string $publishUrl
41
-	 * @param boolean $isPublished
42
-	 */
43
-	function __construct($publishUrl, $isPublished) {
44
-		$this->publishUrl = $publishUrl;
45
-		$this->isPublished = $isPublished;
46
-	}
39
+    /**
40
+     * @param string $publishUrl
41
+     * @param boolean $isPublished
42
+     */
43
+    function __construct($publishUrl, $isPublished) {
44
+        $this->publishUrl = $publishUrl;
45
+        $this->isPublished = $isPublished;
46
+    }
47 47
 
48
-	/**
49
-	 * @return string
50
-	 */
51
-	function getValue() {
52
-		return $this->publishUrl;
53
-	}
48
+    /**
49
+     * @return string
50
+     */
51
+    function getValue() {
52
+        return $this->publishUrl;
53
+    }
54 54
 
55
-	/**
56
-	 * The xmlSerialize metod is called during xml writing.
57
-	 *
58
-	 * Use the $writer argument to write its own xml serialization.
59
-	 *
60
-	 * An important note: do _not_ create a parent element. Any element
61
-	 * implementing XmlSerializble should only ever write what's considered
62
-	 * its 'inner xml'.
63
-	 *
64
-	 * The parent of the current element is responsible for writing a
65
-	 * containing element.
66
-	 *
67
-	 * This allows serializers to be re-used for different element names.
68
-	 *
69
-	 * If you are opening new elements, you must also close them again.
70
-	 *
71
-	 * @param Writer $writer
72
-	 * @return void
73
-	 */
74
-	function xmlSerialize(Writer $writer) {
75
-		if (!$this->isPublished) {
76
-			// for pre-publish-url
77
-			$writer->write($this->publishUrl);
78
-		} else {
79
-			// for publish-url
80
-			$writer->writeElement('{DAV:}href', $this->publishUrl);
81
-		}
82
-	}
55
+    /**
56
+     * The xmlSerialize metod is called during xml writing.
57
+     *
58
+     * Use the $writer argument to write its own xml serialization.
59
+     *
60
+     * An important note: do _not_ create a parent element. Any element
61
+     * implementing XmlSerializble should only ever write what's considered
62
+     * its 'inner xml'.
63
+     *
64
+     * The parent of the current element is responsible for writing a
65
+     * containing element.
66
+     *
67
+     * This allows serializers to be re-used for different element names.
68
+     *
69
+     * If you are opening new elements, you must also close them again.
70
+     *
71
+     * @param Writer $writer
72
+     * @return void
73
+     */
74
+    function xmlSerialize(Writer $writer) {
75
+        if (!$this->isPublished) {
76
+            // for pre-publish-url
77
+            $writer->write($this->publishUrl);
78
+        } else {
79
+            // for publish-url
80
+            $writer->writeElement('{DAV:}href', $this->publishUrl);
81
+        }
82
+    }
83 83
 }
Please login to merge, or discard this patch.