Completed
Pull Request — master (#3590)
by Individual IT
11:38
created
lib/private/legacy/template/functions.php 3 patches
Doc Comments   +2 added lines, -1 removed lines patch added patch discarded remove patch
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
  * make preview_icon available as a simple function
184 184
  * Returns the path to the preview of the image.
185 185
  * @param string $path path of file
186
- * @return link to the preview
186
+ * @return string to the preview
187 187
  */
188 188
 function preview_icon( $path ) {
189 189
 	return \OC::$server->getURLGenerator()->linkToRoute('core.Preview.getPreview', ['x' => 32, 'y' => 32, 'file' => $path]);
@@ -191,6 +191,7 @@  discard block
 block discarded – undo
191 191
 
192 192
 /**
193 193
  * @param string $path
194
+ * @param string $token
194 195
  */
195 196
 function publicPreview_icon ( $path, $token ) {
196 197
 	return \OC::$server->getURLGenerator()->linkToRoute('files_sharing.PublicPreview.getPreview', ['x' => 32, 'y' => 32, 'file' => $path, 't' => $token]);
Please login to merge, or discard this patch.
Indentation   +81 added lines, -81 removed lines patch added patch discarded remove patch
@@ -34,7 +34,7 @@  discard block
 block discarded – undo
34 34
  * @param string $string the string which will be escaped and printed
35 35
  */
36 36
 function p($string) {
37
-	print(\OCP\Util::sanitizeHTML($string));
37
+    print(\OCP\Util::sanitizeHTML($string));
38 38
 }
39 39
 
40 40
 /**
@@ -43,7 +43,7 @@  discard block
 block discarded – undo
43 43
  * @param string|array $string the string which will be printed as it is
44 44
  */
45 45
 function print_unescaped($string) {
46
-	print($string);
46
+    print($string);
47 47
 }
48 48
 
49 49
 /**
@@ -53,13 +53,13 @@  discard block
 block discarded – undo
53 53
  * if an array is given it will add all scripts
54 54
  */
55 55
 function script($app, $file = null) {
56
-	if(is_array($file)) {
57
-		foreach($file as $f) {
58
-			OC_Util::addScript($app, $f);
59
-		}
60
-	} else {
61
-		OC_Util::addScript($app, $file);
62
-	}
56
+    if(is_array($file)) {
57
+        foreach($file as $f) {
58
+            OC_Util::addScript($app, $f);
59
+        }
60
+    } else {
61
+        OC_Util::addScript($app, $file);
62
+    }
63 63
 }
64 64
 
65 65
 /**
@@ -69,13 +69,13 @@  discard block
 block discarded – undo
69 69
  * if an array is given it will add all scripts
70 70
  */
71 71
 function vendor_script($app, $file = null) {
72
-	if(is_array($file)) {
73
-		foreach($file as $f) {
74
-			OC_Util::addVendorScript($app, $f);
75
-		}
76
-	} else {
77
-		OC_Util::addVendorScript($app, $file);
78
-	}
72
+    if(is_array($file)) {
73
+        foreach($file as $f) {
74
+            OC_Util::addVendorScript($app, $f);
75
+        }
76
+    } else {
77
+        OC_Util::addVendorScript($app, $file);
78
+    }
79 79
 }
80 80
 
81 81
 /**
@@ -85,13 +85,13 @@  discard block
 block discarded – undo
85 85
  * if an array is given it will add all styles
86 86
  */
87 87
 function style($app, $file = null) {
88
-	if(is_array($file)) {
89
-		foreach($file as $f) {
90
-			OC_Util::addStyle($app, $f);
91
-		}
92
-	} else {
93
-		OC_Util::addStyle($app, $file);
94
-	}
88
+    if(is_array($file)) {
89
+        foreach($file as $f) {
90
+            OC_Util::addStyle($app, $f);
91
+        }
92
+    } else {
93
+        OC_Util::addStyle($app, $file);
94
+    }
95 95
 }
96 96
 
97 97
 /**
@@ -101,13 +101,13 @@  discard block
 block discarded – undo
101 101
  * if an array is given it will add all styles
102 102
  */
103 103
 function vendor_style($app, $file = null) {
104
-	if(is_array($file)) {
105
-		foreach($file as $f) {
106
-			OC_Util::addVendorStyle($app, $f);
107
-		}
108
-	} else {
109
-		OC_Util::addVendorStyle($app, $file);
110
-	}
104
+    if(is_array($file)) {
105
+        foreach($file as $f) {
106
+            OC_Util::addVendorStyle($app, $f);
107
+        }
108
+    } else {
109
+        OC_Util::addVendorStyle($app, $file);
110
+    }
111 111
 }
112 112
 
113 113
 /**
@@ -116,7 +116,7 @@  discard block
 block discarded – undo
116 116
  * if an array is given it will add all styles
117 117
  */
118 118
 function translation($app) {
119
-	OC_Util::addTranslations($app);
119
+    OC_Util::addTranslations($app);
120 120
 }
121 121
 
122 122
 /**
@@ -126,15 +126,15 @@  discard block
 block discarded – undo
126 126
  * if an array is given it will add all components
127 127
  */
128 128
 function component($app, $file) {
129
-	if(is_array($file)) {
130
-		foreach($file as $f) {
131
-			$url = link_to($app, 'component/' . $f . '.html');
132
-			OC_Util::addHeader('link', array('rel' => 'import', 'href' => $url));
133
-		}
134
-	} else {
135
-		$url = link_to($app, 'component/' . $file . '.html');
136
-		OC_Util::addHeader('link', array('rel' => 'import', 'href' => $url));
137
-	}
129
+    if(is_array($file)) {
130
+        foreach($file as $f) {
131
+            $url = link_to($app, 'component/' . $f . '.html');
132
+            OC_Util::addHeader('link', array('rel' => 'import', 'href' => $url));
133
+        }
134
+    } else {
135
+        $url = link_to($app, 'component/' . $file . '.html');
136
+        OC_Util::addHeader('link', array('rel' => 'import', 'href' => $url));
137
+    }
138 138
 }
139 139
 
140 140
 /**
@@ -147,7 +147,7 @@  discard block
 block discarded – undo
147 147
  * For further information have a look at \OCP\IURLGenerator::linkTo
148 148
  */
149 149
 function link_to( $app, $file, $args = array() ) {
150
-	return \OC::$server->getURLGenerator()->linkTo($app, $file, $args);
150
+    return \OC::$server->getURLGenerator()->linkTo($app, $file, $args);
151 151
 }
152 152
 
153 153
 /**
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
  * @return string url to the online documentation
156 156
  */
157 157
 function link_to_docs($key) {
158
-	return \OC::$server->getURLGenerator()->linkToDocs($key);
158
+    return \OC::$server->getURLGenerator()->linkToDocs($key);
159 159
 }
160 160
 
161 161
 /**
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
  * For further information have a look at \OCP\IURLGenerator::imagePath
168 168
  */
169 169
 function image_path( $app, $image ) {
170
-	return \OC::$server->getURLGenerator()->imagePath( $app, $image );
170
+    return \OC::$server->getURLGenerator()->imagePath( $app, $image );
171 171
 }
172 172
 
173 173
 /**
@@ -176,7 +176,7 @@  discard block
 block discarded – undo
176 176
  * @return string link to the image
177 177
  */
178 178
 function mimetype_icon( $mimetype ) {
179
-	return \OC::$server->getMimeTypeDetector()->mimeTypeIcon( $mimetype );
179
+    return \OC::$server->getMimeTypeDetector()->mimeTypeIcon( $mimetype );
180 180
 }
181 181
 
182 182
 /**
@@ -186,14 +186,14 @@  discard block
 block discarded – undo
186 186
  * @return link to the preview
187 187
  */
188 188
 function preview_icon( $path ) {
189
-	return \OC::$server->getURLGenerator()->linkToRoute('core.Preview.getPreview', ['x' => 32, 'y' => 32, 'file' => $path]);
189
+    return \OC::$server->getURLGenerator()->linkToRoute('core.Preview.getPreview', ['x' => 32, 'y' => 32, 'file' => $path]);
190 190
 }
191 191
 
192 192
 /**
193 193
  * @param string $path
194 194
  */
195 195
 function publicPreview_icon ( $path, $token ) {
196
-	return \OC::$server->getURLGenerator()->linkToRoute('files_sharing.PublicPreview.getPreview', ['x' => 32, 'y' => 32, 'file' => $path, 't' => $token]);
196
+    return \OC::$server->getURLGenerator()->linkToRoute('files_sharing.PublicPreview.getPreview', ['x' => 32, 'y' => 32, 'file' => $path, 't' => $token]);
197 197
 }
198 198
 
199 199
 /**
@@ -204,7 +204,7 @@  discard block
 block discarded – undo
204 204
  * For further information have a look at OC_Helper::humanFileSize
205 205
  */
206 206
 function human_file_size( $bytes ) {
207
-	return OC_Helper::humanFileSize( $bytes );
207
+    return OC_Helper::humanFileSize( $bytes );
208 208
 }
209 209
 
210 210
 /**
@@ -213,9 +213,9 @@  discard block
 block discarded – undo
213 213
  * @return $timestamp without time value
214 214
  */
215 215
 function strip_time($timestamp){
216
-	$date = new \DateTime("@{$timestamp}");
217
-	$date->setTime(0, 0, 0);
218
-	return intval($date->format('U'));
216
+    $date = new \DateTime("@{$timestamp}");
217
+    $date->setTime(0, 0, 0);
218
+    return intval($date->format('U'));
219 219
 }
220 220
 
221 221
 /**
@@ -227,39 +227,39 @@  discard block
 block discarded – undo
227 227
  * @return string timestamp
228 228
  */
229 229
 function relative_modified_date($timestamp, $fromTime = null, $dateOnly = false) {
230
-	/** @var \OC\DateTimeFormatter $formatter */
231
-	$formatter = \OC::$server->query('DateTimeFormatter');
230
+    /** @var \OC\DateTimeFormatter $formatter */
231
+    $formatter = \OC::$server->query('DateTimeFormatter');
232 232
 
233
-	if ($dateOnly){
234
-		return $formatter->formatDateSpan($timestamp, $fromTime);
235
-	}
236
-	return $formatter->formatTimeSpan($timestamp, $fromTime);
233
+    if ($dateOnly){
234
+        return $formatter->formatDateSpan($timestamp, $fromTime);
235
+    }
236
+    return $formatter->formatTimeSpan($timestamp, $fromTime);
237 237
 }
238 238
 
239 239
 function html_select_options($options, $selected, $params=array()) {
240
-	if (!is_array($selected)) {
241
-		$selected=array($selected);
242
-	}
243
-	if (isset($params['combine']) && $params['combine']) {
244
-		$options = array_combine($options, $options);
245
-	}
246
-	$value_name = $label_name = false;
247
-	if (isset($params['value'])) {
248
-		$value_name = $params['value'];
249
-	}
250
-	if (isset($params['label'])) {
251
-		$label_name = $params['label'];
252
-	}
253
-	$html = '';
254
-	foreach($options as $value => $label) {
255
-		if ($value_name && is_array($label)) {
256
-			$value = $label[$value_name];
257
-		}
258
-		if ($label_name && is_array($label)) {
259
-			$label = $label[$label_name];
260
-		}
261
-		$select = in_array($value, $selected) ? ' selected="selected"' : '';
262
-		$html .= '<option value="' . \OCP\Util::sanitizeHTML($value) . '"' . $select . '>' . \OCP\Util::sanitizeHTML($label) . '</option>'."\n";
263
-	}
264
-	return $html;
240
+    if (!is_array($selected)) {
241
+        $selected=array($selected);
242
+    }
243
+    if (isset($params['combine']) && $params['combine']) {
244
+        $options = array_combine($options, $options);
245
+    }
246
+    $value_name = $label_name = false;
247
+    if (isset($params['value'])) {
248
+        $value_name = $params['value'];
249
+    }
250
+    if (isset($params['label'])) {
251
+        $label_name = $params['label'];
252
+    }
253
+    $html = '';
254
+    foreach($options as $value => $label) {
255
+        if ($value_name && is_array($label)) {
256
+            $value = $label[$value_name];
257
+        }
258
+        if ($label_name && is_array($label)) {
259
+            $label = $label[$label_name];
260
+        }
261
+        $select = in_array($value, $selected) ? ' selected="selected"' : '';
262
+        $html .= '<option value="' . \OCP\Util::sanitizeHTML($value) . '"' . $select . '>' . \OCP\Util::sanitizeHTML($label) . '</option>'."\n";
263
+    }
264
+    return $html;
265 265
 }
Please login to merge, or discard this patch.
Spacing   +27 added lines, -27 removed lines patch added patch discarded remove patch
@@ -53,8 +53,8 @@  discard block
 block discarded – undo
53 53
  * if an array is given it will add all scripts
54 54
  */
55 55
 function script($app, $file = null) {
56
-	if(is_array($file)) {
57
-		foreach($file as $f) {
56
+	if (is_array($file)) {
57
+		foreach ($file as $f) {
58 58
 			OC_Util::addScript($app, $f);
59 59
 		}
60 60
 	} else {
@@ -69,8 +69,8 @@  discard block
 block discarded – undo
69 69
  * if an array is given it will add all scripts
70 70
  */
71 71
 function vendor_script($app, $file = null) {
72
-	if(is_array($file)) {
73
-		foreach($file as $f) {
72
+	if (is_array($file)) {
73
+		foreach ($file as $f) {
74 74
 			OC_Util::addVendorScript($app, $f);
75 75
 		}
76 76
 	} else {
@@ -85,8 +85,8 @@  discard block
 block discarded – undo
85 85
  * if an array is given it will add all styles
86 86
  */
87 87
 function style($app, $file = null) {
88
-	if(is_array($file)) {
89
-		foreach($file as $f) {
88
+	if (is_array($file)) {
89
+		foreach ($file as $f) {
90 90
 			OC_Util::addStyle($app, $f);
91 91
 		}
92 92
 	} else {
@@ -101,8 +101,8 @@  discard block
 block discarded – undo
101 101
  * if an array is given it will add all styles
102 102
  */
103 103
 function vendor_style($app, $file = null) {
104
-	if(is_array($file)) {
105
-		foreach($file as $f) {
104
+	if (is_array($file)) {
105
+		foreach ($file as $f) {
106 106
 			OC_Util::addVendorStyle($app, $f);
107 107
 		}
108 108
 	} else {
@@ -126,13 +126,13 @@  discard block
 block discarded – undo
126 126
  * if an array is given it will add all components
127 127
  */
128 128
 function component($app, $file) {
129
-	if(is_array($file)) {
130
-		foreach($file as $f) {
131
-			$url = link_to($app, 'component/' . $f . '.html');
129
+	if (is_array($file)) {
130
+		foreach ($file as $f) {
131
+			$url = link_to($app, 'component/'.$f.'.html');
132 132
 			OC_Util::addHeader('link', array('rel' => 'import', 'href' => $url));
133 133
 		}
134 134
 	} else {
135
-		$url = link_to($app, 'component/' . $file . '.html');
135
+		$url = link_to($app, 'component/'.$file.'.html');
136 136
 		OC_Util::addHeader('link', array('rel' => 'import', 'href' => $url));
137 137
 	}
138 138
 }
@@ -146,7 +146,7 @@  discard block
 block discarded – undo
146 146
  *
147 147
  * For further information have a look at \OCP\IURLGenerator::linkTo
148 148
  */
149
-function link_to( $app, $file, $args = array() ) {
149
+function link_to($app, $file, $args = array()) {
150 150
 	return \OC::$server->getURLGenerator()->linkTo($app, $file, $args);
151 151
 }
152 152
 
@@ -166,8 +166,8 @@  discard block
 block discarded – undo
166 166
  *
167 167
  * For further information have a look at \OCP\IURLGenerator::imagePath
168 168
  */
169
-function image_path( $app, $image ) {
170
-	return \OC::$server->getURLGenerator()->imagePath( $app, $image );
169
+function image_path($app, $image) {
170
+	return \OC::$server->getURLGenerator()->imagePath($app, $image);
171 171
 }
172 172
 
173 173
 /**
@@ -175,8 +175,8 @@  discard block
 block discarded – undo
175 175
  * @param string $mimetype mimetype
176 176
  * @return string link to the image
177 177
  */
178
-function mimetype_icon( $mimetype ) {
179
-	return \OC::$server->getMimeTypeDetector()->mimeTypeIcon( $mimetype );
178
+function mimetype_icon($mimetype) {
179
+	return \OC::$server->getMimeTypeDetector()->mimeTypeIcon($mimetype);
180 180
 }
181 181
 
182 182
 /**
@@ -185,14 +185,14 @@  discard block
 block discarded – undo
185 185
  * @param string $path path of file
186 186
  * @return link to the preview
187 187
  */
188
-function preview_icon( $path ) {
188
+function preview_icon($path) {
189 189
 	return \OC::$server->getURLGenerator()->linkToRoute('core.Preview.getPreview', ['x' => 32, 'y' => 32, 'file' => $path]);
190 190
 }
191 191
 
192 192
 /**
193 193
  * @param string $path
194 194
  */
195
-function publicPreview_icon ( $path, $token ) {
195
+function publicPreview_icon($path, $token) {
196 196
 	return \OC::$server->getURLGenerator()->linkToRoute('files_sharing.PublicPreview.getPreview', ['x' => 32, 'y' => 32, 'file' => $path, 't' => $token]);
197 197
 }
198 198
 
@@ -203,8 +203,8 @@  discard block
 block discarded – undo
203 203
  *
204 204
  * For further information have a look at OC_Helper::humanFileSize
205 205
  */
206
-function human_file_size( $bytes ) {
207
-	return OC_Helper::humanFileSize( $bytes );
206
+function human_file_size($bytes) {
207
+	return OC_Helper::humanFileSize($bytes);
208 208
 }
209 209
 
210 210
 /**
@@ -212,7 +212,7 @@  discard block
 block discarded – undo
212 212
  * @param int $timestamp UNIX timestamp to strip
213 213
  * @return $timestamp without time value
214 214
  */
215
-function strip_time($timestamp){
215
+function strip_time($timestamp) {
216 216
 	$date = new \DateTime("@{$timestamp}");
217 217
 	$date->setTime(0, 0, 0);
218 218
 	return intval($date->format('U'));
@@ -230,15 +230,15 @@  discard block
 block discarded – undo
230 230
 	/** @var \OC\DateTimeFormatter $formatter */
231 231
 	$formatter = \OC::$server->query('DateTimeFormatter');
232 232
 
233
-	if ($dateOnly){
233
+	if ($dateOnly) {
234 234
 		return $formatter->formatDateSpan($timestamp, $fromTime);
235 235
 	}
236 236
 	return $formatter->formatTimeSpan($timestamp, $fromTime);
237 237
 }
238 238
 
239
-function html_select_options($options, $selected, $params=array()) {
239
+function html_select_options($options, $selected, $params = array()) {
240 240
 	if (!is_array($selected)) {
241
-		$selected=array($selected);
241
+		$selected = array($selected);
242 242
 	}
243 243
 	if (isset($params['combine']) && $params['combine']) {
244 244
 		$options = array_combine($options, $options);
@@ -251,7 +251,7 @@  discard block
 block discarded – undo
251 251
 		$label_name = $params['label'];
252 252
 	}
253 253
 	$html = '';
254
-	foreach($options as $value => $label) {
254
+	foreach ($options as $value => $label) {
255 255
 		if ($value_name && is_array($label)) {
256 256
 			$value = $label[$value_name];
257 257
 		}
@@ -259,7 +259,7 @@  discard block
 block discarded – undo
259 259
 			$label = $label[$label_name];
260 260
 		}
261 261
 		$select = in_array($value, $selected) ? ' selected="selected"' : '';
262
-		$html .= '<option value="' . \OCP\Util::sanitizeHTML($value) . '"' . $select . '>' . \OCP\Util::sanitizeHTML($label) . '</option>'."\n";
262
+		$html .= '<option value="'.\OCP\Util::sanitizeHTML($value).'"'.$select.'>'.\OCP\Util::sanitizeHTML($label).'</option>'."\n";
263 263
 	}
264 264
 	return $html;
265 265
 }
Please login to merge, or discard this patch.
lib/private/Memcache/APCu.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -65,7 +65,7 @@
 block discarded – undo
65 65
 	 * Set a value in the cache if it's not already stored
66 66
 	 *
67 67
 	 * @param string $key
68
-	 * @param mixed $value
68
+	 * @param integer $value
69 69
 	 * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
70 70
 	 * @return bool
71 71
 	 */
Please login to merge, or discard this patch.
Indentation   +125 added lines, -125 removed lines patch added patch discarded remove patch
@@ -30,140 +30,140 @@
 block discarded – undo
30 30
 use OCP\IMemcache;
31 31
 
32 32
 class APCu extends Cache implements IMemcache {
33
-	use CASTrait {
34
-		cas as casEmulated;
35
-	}
33
+    use CASTrait {
34
+        cas as casEmulated;
35
+    }
36 36
 
37
-	use CADTrait;
37
+    use CADTrait;
38 38
 
39
-	public function get($key) {
40
-		$result = apcu_fetch($this->getPrefix() . $key, $success);
41
-		if (!$success) {
42
-			return null;
43
-		}
44
-		return $result;
45
-	}
39
+    public function get($key) {
40
+        $result = apcu_fetch($this->getPrefix() . $key, $success);
41
+        if (!$success) {
42
+            return null;
43
+        }
44
+        return $result;
45
+    }
46 46
 
47
-	public function set($key, $value, $ttl = 0) {
48
-		return apcu_store($this->getPrefix() . $key, $value, $ttl);
49
-	}
47
+    public function set($key, $value, $ttl = 0) {
48
+        return apcu_store($this->getPrefix() . $key, $value, $ttl);
49
+    }
50 50
 
51
-	public function hasKey($key) {
52
-		return apcu_exists($this->getPrefix() . $key);
53
-	}
51
+    public function hasKey($key) {
52
+        return apcu_exists($this->getPrefix() . $key);
53
+    }
54 54
 
55
-	public function remove($key) {
56
-		return apcu_delete($this->getPrefix() . $key);
57
-	}
55
+    public function remove($key) {
56
+        return apcu_delete($this->getPrefix() . $key);
57
+    }
58 58
 
59
-	public function clear($prefix = '') {
60
-		$ns = $this->getPrefix() . $prefix;
61
-		$ns = preg_quote($ns, '/');
62
-		if(class_exists('\APCIterator')) {
63
-			$iter = new \APCIterator('user', '/^' . $ns . '/', APC_ITER_KEY);
64
-		} else {
65
-			$iter = new \APCUIterator('/^' . $ns . '/', APC_ITER_KEY);
66
-		}
67
-		return apcu_delete($iter);
68
-	}
59
+    public function clear($prefix = '') {
60
+        $ns = $this->getPrefix() . $prefix;
61
+        $ns = preg_quote($ns, '/');
62
+        if(class_exists('\APCIterator')) {
63
+            $iter = new \APCIterator('user', '/^' . $ns . '/', APC_ITER_KEY);
64
+        } else {
65
+            $iter = new \APCUIterator('/^' . $ns . '/', APC_ITER_KEY);
66
+        }
67
+        return apcu_delete($iter);
68
+    }
69 69
 
70
-	/**
71
-	 * Set a value in the cache if it's not already stored
72
-	 *
73
-	 * @param string $key
74
-	 * @param mixed $value
75
-	 * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
76
-	 * @return bool
77
-	 */
78
-	public function add($key, $value, $ttl = 0) {
79
-		return apcu_add($this->getPrefix() . $key, $value, $ttl);
80
-	}
70
+    /**
71
+     * Set a value in the cache if it's not already stored
72
+     *
73
+     * @param string $key
74
+     * @param mixed $value
75
+     * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
76
+     * @return bool
77
+     */
78
+    public function add($key, $value, $ttl = 0) {
79
+        return apcu_add($this->getPrefix() . $key, $value, $ttl);
80
+    }
81 81
 
82
-	/**
83
-	 * Increase a stored number
84
-	 *
85
-	 * @param string $key
86
-	 * @param int $step
87
-	 * @return int | bool
88
-	 */
89
-	public function inc($key, $step = 1) {
90
-		$this->add($key, 0);
91
-		/**
92
-		 * TODO - hack around a PHP 7 specific issue in APCu
93
-		 *
94
-		 * on PHP 7 the apcu_inc method on a non-existing object will increment
95
-		 * "0" and result in "1" as value - therefore we check for existence
96
-		 * first
97
-		 *
98
-		 * on PHP 5.6 this is not the case
99
-		 *
100
-		 * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
101
-		 * for details
102
-		 */
103
-		return apcu_exists($this->getPrefix() . $key)
104
-			? apcu_inc($this->getPrefix() . $key, $step)
105
-			: false;
106
-	}
82
+    /**
83
+     * Increase a stored number
84
+     *
85
+     * @param string $key
86
+     * @param int $step
87
+     * @return int | bool
88
+     */
89
+    public function inc($key, $step = 1) {
90
+        $this->add($key, 0);
91
+        /**
92
+         * TODO - hack around a PHP 7 specific issue in APCu
93
+         *
94
+         * on PHP 7 the apcu_inc method on a non-existing object will increment
95
+         * "0" and result in "1" as value - therefore we check for existence
96
+         * first
97
+         *
98
+         * on PHP 5.6 this is not the case
99
+         *
100
+         * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
101
+         * for details
102
+         */
103
+        return apcu_exists($this->getPrefix() . $key)
104
+            ? apcu_inc($this->getPrefix() . $key, $step)
105
+            : false;
106
+    }
107 107
 
108
-	/**
109
-	 * Decrease a stored number
110
-	 *
111
-	 * @param string $key
112
-	 * @param int $step
113
-	 * @return int | bool
114
-	 */
115
-	public function dec($key, $step = 1) {
116
-		/**
117
-		 * TODO - hack around a PHP 7 specific issue in APCu
118
-		 *
119
-		 * on PHP 7 the apcu_dec method on a non-existing object will decrement
120
-		 * "0" and result in "-1" as value - therefore we check for existence
121
-		 * first
122
-		 *
123
-		 * on PHP 5.6 this is not the case
124
-		 *
125
-		 * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
126
-		 * for details
127
-		 */
128
-		return apcu_exists($this->getPrefix() . $key)
129
-			? apcu_dec($this->getPrefix() . $key, $step)
130
-			: false;
131
-	}
108
+    /**
109
+     * Decrease a stored number
110
+     *
111
+     * @param string $key
112
+     * @param int $step
113
+     * @return int | bool
114
+     */
115
+    public function dec($key, $step = 1) {
116
+        /**
117
+         * TODO - hack around a PHP 7 specific issue in APCu
118
+         *
119
+         * on PHP 7 the apcu_dec method on a non-existing object will decrement
120
+         * "0" and result in "-1" as value - therefore we check for existence
121
+         * first
122
+         *
123
+         * on PHP 5.6 this is not the case
124
+         *
125
+         * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
126
+         * for details
127
+         */
128
+        return apcu_exists($this->getPrefix() . $key)
129
+            ? apcu_dec($this->getPrefix() . $key, $step)
130
+            : false;
131
+    }
132 132
 
133
-	/**
134
-	 * Compare and set
135
-	 *
136
-	 * @param string $key
137
-	 * @param mixed $old
138
-	 * @param mixed $new
139
-	 * @return bool
140
-	 */
141
-	public function cas($key, $old, $new) {
142
-		// apc only does cas for ints
143
-		if (is_int($old) and is_int($new)) {
144
-			return apcu_cas($this->getPrefix() . $key, $old, $new);
145
-		} else {
146
-			return $this->casEmulated($key, $old, $new);
147
-		}
148
-	}
133
+    /**
134
+     * Compare and set
135
+     *
136
+     * @param string $key
137
+     * @param mixed $old
138
+     * @param mixed $new
139
+     * @return bool
140
+     */
141
+    public function cas($key, $old, $new) {
142
+        // apc only does cas for ints
143
+        if (is_int($old) and is_int($new)) {
144
+            return apcu_cas($this->getPrefix() . $key, $old, $new);
145
+        } else {
146
+            return $this->casEmulated($key, $old, $new);
147
+        }
148
+    }
149 149
 
150
-	/**
151
-	 * @return bool
152
-	 */
153
-	static public function isAvailable() {
154
-		if (!extension_loaded('apcu')) {
155
-			return false;
156
-		} elseif (!\OC::$server->getIniWrapper()->getBool('apc.enabled')) {
157
-			return false;
158
-		} elseif (!\OC::$server->getIniWrapper()->getBool('apc.enable_cli') && \OC::$CLI) {
159
-			return false;
160
-		} elseif (
161
-				version_compare(phpversion('apc'), '4.0.6') === -1 &&
162
-				version_compare(phpversion('apcu'), '5.1.0') === -1
163
-		) {
164
-			return false;
165
-		} else {
166
-			return true;
167
-		}
168
-	}
150
+    /**
151
+     * @return bool
152
+     */
153
+    static public function isAvailable() {
154
+        if (!extension_loaded('apcu')) {
155
+            return false;
156
+        } elseif (!\OC::$server->getIniWrapper()->getBool('apc.enabled')) {
157
+            return false;
158
+        } elseif (!\OC::$server->getIniWrapper()->getBool('apc.enable_cli') && \OC::$CLI) {
159
+            return false;
160
+        } elseif (
161
+                version_compare(phpversion('apc'), '4.0.6') === -1 &&
162
+                version_compare(phpversion('apcu'), '5.1.0') === -1
163
+        ) {
164
+            return false;
165
+        } else {
166
+            return true;
167
+        }
168
+    }
169 169
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -37,7 +37,7 @@  discard block
 block discarded – undo
37 37
 	use CADTrait;
38 38
 
39 39
 	public function get($key) {
40
-		$result = apcu_fetch($this->getPrefix() . $key, $success);
40
+		$result = apcu_fetch($this->getPrefix().$key, $success);
41 41
 		if (!$success) {
42 42
 			return null;
43 43
 		}
@@ -45,24 +45,24 @@  discard block
 block discarded – undo
45 45
 	}
46 46
 
47 47
 	public function set($key, $value, $ttl = 0) {
48
-		return apcu_store($this->getPrefix() . $key, $value, $ttl);
48
+		return apcu_store($this->getPrefix().$key, $value, $ttl);
49 49
 	}
50 50
 
51 51
 	public function hasKey($key) {
52
-		return apcu_exists($this->getPrefix() . $key);
52
+		return apcu_exists($this->getPrefix().$key);
53 53
 	}
54 54
 
55 55
 	public function remove($key) {
56
-		return apcu_delete($this->getPrefix() . $key);
56
+		return apcu_delete($this->getPrefix().$key);
57 57
 	}
58 58
 
59 59
 	public function clear($prefix = '') {
60
-		$ns = $this->getPrefix() . $prefix;
60
+		$ns = $this->getPrefix().$prefix;
61 61
 		$ns = preg_quote($ns, '/');
62
-		if(class_exists('\APCIterator')) {
63
-			$iter = new \APCIterator('user', '/^' . $ns . '/', APC_ITER_KEY);
62
+		if (class_exists('\APCIterator')) {
63
+			$iter = new \APCIterator('user', '/^'.$ns.'/', APC_ITER_KEY);
64 64
 		} else {
65
-			$iter = new \APCUIterator('/^' . $ns . '/', APC_ITER_KEY);
65
+			$iter = new \APCUIterator('/^'.$ns.'/', APC_ITER_KEY);
66 66
 		}
67 67
 		return apcu_delete($iter);
68 68
 	}
@@ -76,7 +76,7 @@  discard block
 block discarded – undo
76 76
 	 * @return bool
77 77
 	 */
78 78
 	public function add($key, $value, $ttl = 0) {
79
-		return apcu_add($this->getPrefix() . $key, $value, $ttl);
79
+		return apcu_add($this->getPrefix().$key, $value, $ttl);
80 80
 	}
81 81
 
82 82
 	/**
@@ -100,8 +100,8 @@  discard block
 block discarded – undo
100 100
 		 * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
101 101
 		 * for details
102 102
 		 */
103
-		return apcu_exists($this->getPrefix() . $key)
104
-			? apcu_inc($this->getPrefix() . $key, $step)
103
+		return apcu_exists($this->getPrefix().$key)
104
+			? apcu_inc($this->getPrefix().$key, $step)
105 105
 			: false;
106 106
 	}
107 107
 
@@ -125,8 +125,8 @@  discard block
 block discarded – undo
125 125
 		 * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
126 126
 		 * for details
127 127
 		 */
128
-		return apcu_exists($this->getPrefix() . $key)
129
-			? apcu_dec($this->getPrefix() . $key, $step)
128
+		return apcu_exists($this->getPrefix().$key)
129
+			? apcu_dec($this->getPrefix().$key, $step)
130 130
 			: false;
131 131
 	}
132 132
 
@@ -141,7 +141,7 @@  discard block
 block discarded – undo
141 141
 	public function cas($key, $old, $new) {
142 142
 		// apc only does cas for ints
143 143
 		if (is_int($old) and is_int($new)) {
144
-			return apcu_cas($this->getPrefix() . $key, $old, $new);
144
+			return apcu_cas($this->getPrefix().$key, $old, $new);
145 145
 		} else {
146 146
 			return $this->casEmulated($key, $old, $new);
147 147
 		}
Please login to merge, or discard this patch.
lib/private/Memcache/ArrayCache.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -65,7 +65,7 @@
 block discarded – undo
65 65
 	 * Set a value in the cache if it's not already stored
66 66
 	 *
67 67
 	 * @param string $key
68
-	 * @param mixed $value
68
+	 * @param integer $value
69 69
 	 * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
70 70
 	 * @return bool
71 71
 	 */
Please login to merge, or discard this patch.
Indentation   +117 added lines, -117 removed lines patch added patch discarded remove patch
@@ -27,133 +27,133 @@
 block discarded – undo
27 27
 use OCP\IMemcache;
28 28
 
29 29
 class ArrayCache extends Cache implements IMemcache {
30
-	/** @var array Array with the cached data */
31
-	protected $cachedData = array();
30
+    /** @var array Array with the cached data */
31
+    protected $cachedData = array();
32 32
 
33
-	use CADTrait;
33
+    use CADTrait;
34 34
 
35
-	/**
36
-	 * {@inheritDoc}
37
-	 */
38
-	public function get($key) {
39
-		if ($this->hasKey($key)) {
40
-			return $this->cachedData[$key];
41
-		}
42
-		return null;
43
-	}
35
+    /**
36
+     * {@inheritDoc}
37
+     */
38
+    public function get($key) {
39
+        if ($this->hasKey($key)) {
40
+            return $this->cachedData[$key];
41
+        }
42
+        return null;
43
+    }
44 44
 
45
-	/**
46
-	 * {@inheritDoc}
47
-	 */
48
-	public function set($key, $value, $ttl = 0) {
49
-		$this->cachedData[$key] = $value;
50
-		return true;
51
-	}
45
+    /**
46
+     * {@inheritDoc}
47
+     */
48
+    public function set($key, $value, $ttl = 0) {
49
+        $this->cachedData[$key] = $value;
50
+        return true;
51
+    }
52 52
 
53
-	/**
54
-	 * {@inheritDoc}
55
-	 */
56
-	public function hasKey($key) {
57
-		return isset($this->cachedData[$key]);
58
-	}
53
+    /**
54
+     * {@inheritDoc}
55
+     */
56
+    public function hasKey($key) {
57
+        return isset($this->cachedData[$key]);
58
+    }
59 59
 
60
-	/**
61
-	 * {@inheritDoc}
62
-	 */
63
-	public function remove($key) {
64
-		unset($this->cachedData[$key]);
65
-		return true;
66
-	}
60
+    /**
61
+     * {@inheritDoc}
62
+     */
63
+    public function remove($key) {
64
+        unset($this->cachedData[$key]);
65
+        return true;
66
+    }
67 67
 
68
-	/**
69
-	 * {@inheritDoc}
70
-	 */
71
-	public function clear($prefix = '') {
72
-		if ($prefix === '') {
73
-			$this->cachedData = [];
74
-			return true;
75
-		}
68
+    /**
69
+     * {@inheritDoc}
70
+     */
71
+    public function clear($prefix = '') {
72
+        if ($prefix === '') {
73
+            $this->cachedData = [];
74
+            return true;
75
+        }
76 76
 
77
-		foreach ($this->cachedData as $key => $value) {
78
-			if (strpos($key, $prefix) === 0) {
79
-				$this->remove($key);
80
-			}
81
-		}
82
-		return true;
83
-	}
77
+        foreach ($this->cachedData as $key => $value) {
78
+            if (strpos($key, $prefix) === 0) {
79
+                $this->remove($key);
80
+            }
81
+        }
82
+        return true;
83
+    }
84 84
 
85
-	/**
86
-	 * Set a value in the cache if it's not already stored
87
-	 *
88
-	 * @param string $key
89
-	 * @param mixed $value
90
-	 * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
91
-	 * @return bool
92
-	 */
93
-	public function add($key, $value, $ttl = 0) {
94
-		// since this cache is not shared race conditions aren't an issue
95
-		if ($this->hasKey($key)) {
96
-			return false;
97
-		} else {
98
-			return $this->set($key, $value, $ttl);
99
-		}
100
-	}
85
+    /**
86
+     * Set a value in the cache if it's not already stored
87
+     *
88
+     * @param string $key
89
+     * @param mixed $value
90
+     * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
91
+     * @return bool
92
+     */
93
+    public function add($key, $value, $ttl = 0) {
94
+        // since this cache is not shared race conditions aren't an issue
95
+        if ($this->hasKey($key)) {
96
+            return false;
97
+        } else {
98
+            return $this->set($key, $value, $ttl);
99
+        }
100
+    }
101 101
 
102
-	/**
103
-	 * Increase a stored number
104
-	 *
105
-	 * @param string $key
106
-	 * @param int $step
107
-	 * @return int | bool
108
-	 */
109
-	public function inc($key, $step = 1) {
110
-		$oldValue = $this->get($key);
111
-		if (is_int($oldValue)) {
112
-			$this->set($key, $oldValue + $step);
113
-			return $oldValue + $step;
114
-		} else {
115
-			$success = $this->add($key, $step);
116
-			return ($success) ? $step : false;
117
-		}
118
-	}
102
+    /**
103
+     * Increase a stored number
104
+     *
105
+     * @param string $key
106
+     * @param int $step
107
+     * @return int | bool
108
+     */
109
+    public function inc($key, $step = 1) {
110
+        $oldValue = $this->get($key);
111
+        if (is_int($oldValue)) {
112
+            $this->set($key, $oldValue + $step);
113
+            return $oldValue + $step;
114
+        } else {
115
+            $success = $this->add($key, $step);
116
+            return ($success) ? $step : false;
117
+        }
118
+    }
119 119
 
120
-	/**
121
-	 * Decrease a stored number
122
-	 *
123
-	 * @param string $key
124
-	 * @param int $step
125
-	 * @return int | bool
126
-	 */
127
-	public function dec($key, $step = 1) {
128
-		$oldValue = $this->get($key);
129
-		if (is_int($oldValue)) {
130
-			$this->set($key, $oldValue - $step);
131
-			return $oldValue - $step;
132
-		} else {
133
-			return false;
134
-		}
135
-	}
120
+    /**
121
+     * Decrease a stored number
122
+     *
123
+     * @param string $key
124
+     * @param int $step
125
+     * @return int | bool
126
+     */
127
+    public function dec($key, $step = 1) {
128
+        $oldValue = $this->get($key);
129
+        if (is_int($oldValue)) {
130
+            $this->set($key, $oldValue - $step);
131
+            return $oldValue - $step;
132
+        } else {
133
+            return false;
134
+        }
135
+    }
136 136
 
137
-	/**
138
-	 * Compare and set
139
-	 *
140
-	 * @param string $key
141
-	 * @param mixed $old
142
-	 * @param mixed $new
143
-	 * @return bool
144
-	 */
145
-	public function cas($key, $old, $new) {
146
-		if ($this->get($key) === $old) {
147
-			return $this->set($key, $new);
148
-		} else {
149
-			return false;
150
-		}
151
-	}
137
+    /**
138
+     * Compare and set
139
+     *
140
+     * @param string $key
141
+     * @param mixed $old
142
+     * @param mixed $new
143
+     * @return bool
144
+     */
145
+    public function cas($key, $old, $new) {
146
+        if ($this->get($key) === $old) {
147
+            return $this->set($key, $new);
148
+        } else {
149
+            return false;
150
+        }
151
+    }
152 152
 
153
-	/**
154
-	 * {@inheritDoc}
155
-	 */
156
-	static public function isAvailable() {
157
-		return true;
158
-	}
153
+    /**
154
+     * {@inheritDoc}
155
+     */
156
+    static public function isAvailable() {
157
+        return true;
158
+    }
159 159
 }
Please login to merge, or discard this patch.
lib/private/User/Session.php 3 patches
Doc Comments   +4 added lines, -1 removed lines patch added patch discarded remove patch
@@ -311,7 +311,7 @@  discard block
 block discarded – undo
311 311
 	 * @param OC\Security\Bruteforce\Throttler $throttler
312 312
 	 * @throws LoginException
313 313
 	 * @throws PasswordLoginForbiddenException
314
-	 * @return boolean
314
+	 * @return boolean|null
315 315
 	 */
316 316
 	public function logClientIn($user,
317 317
 								$password,
@@ -361,6 +361,9 @@  discard block
 block discarded – undo
361 361
 		return $this->config->getSystemValue('token_auth_enforced', false);
362 362
 	}
363 363
 
364
+	/**
365
+	 * @param string $username
366
+	 */
364 367
 	protected function isTwoFactorEnforced($username) {
365 368
 		Util::emitHook(
366 369
 			'\OCA\Files_Sharing\API\Server2Server',
Please login to merge, or discard this patch.
Indentation   +782 added lines, -782 removed lines patch added patch discarded remove patch
@@ -75,788 +75,788 @@
 block discarded – undo
75 75
  */
76 76
 class Session implements IUserSession, Emitter {
77 77
 
78
-	/** @var IUserManager $manager */
79
-	private $manager;
80
-
81
-	/** @var ISession $session */
82
-	private $session;
83
-
84
-	/** @var ITimeFactory */
85
-	private $timeFacory;
86
-
87
-	/** @var IProvider */
88
-	private $tokenProvider;
89
-
90
-	/** @var IConfig */
91
-	private $config;
92
-
93
-	/** @var User $activeUser */
94
-	protected $activeUser;
95
-
96
-	/** @var ISecureRandom */
97
-	private $random;
98
-
99
-	/**
100
-	 * @param IUserManager $manager
101
-	 * @param ISession $session
102
-	 * @param ITimeFactory $timeFacory
103
-	 * @param IProvider $tokenProvider
104
-	 * @param IConfig $config
105
-	 * @param ISecureRandom $random
106
-	 */
107
-	public function __construct(IUserManager $manager,
108
-								ISession $session,
109
-								ITimeFactory $timeFacory,
110
-								$tokenProvider,
111
-								IConfig $config,
112
-								ISecureRandom $random) {
113
-		$this->manager = $manager;
114
-		$this->session = $session;
115
-		$this->timeFacory = $timeFacory;
116
-		$this->tokenProvider = $tokenProvider;
117
-		$this->config = $config;
118
-		$this->random = $random;
119
-	}
120
-
121
-	/**
122
-	 * @param IProvider $provider
123
-	 */
124
-	public function setTokenProvider(IProvider $provider) {
125
-		$this->tokenProvider = $provider;
126
-	}
127
-
128
-	/**
129
-	 * @param string $scope
130
-	 * @param string $method
131
-	 * @param callable $callback
132
-	 */
133
-	public function listen($scope, $method, callable $callback) {
134
-		$this->manager->listen($scope, $method, $callback);
135
-	}
136
-
137
-	/**
138
-	 * @param string $scope optional
139
-	 * @param string $method optional
140
-	 * @param callable $callback optional
141
-	 */
142
-	public function removeListener($scope = null, $method = null, callable $callback = null) {
143
-		$this->manager->removeListener($scope, $method, $callback);
144
-	}
145
-
146
-	/**
147
-	 * get the manager object
148
-	 *
149
-	 * @return Manager
150
-	 */
151
-	public function getManager() {
152
-		return $this->manager;
153
-	}
154
-
155
-	/**
156
-	 * get the session object
157
-	 *
158
-	 * @return ISession
159
-	 */
160
-	public function getSession() {
161
-		return $this->session;
162
-	}
163
-
164
-	/**
165
-	 * set the session object
166
-	 *
167
-	 * @param ISession $session
168
-	 */
169
-	public function setSession(ISession $session) {
170
-		if ($this->session instanceof ISession) {
171
-			$this->session->close();
172
-		}
173
-		$this->session = $session;
174
-		$this->activeUser = null;
175
-	}
176
-
177
-	/**
178
-	 * set the currently active user
179
-	 *
180
-	 * @param IUser|null $user
181
-	 */
182
-	public function setUser($user) {
183
-		if (is_null($user)) {
184
-			$this->session->remove('user_id');
185
-		} else {
186
-			$this->session->set('user_id', $user->getUID());
187
-		}
188
-		$this->activeUser = $user;
189
-	}
190
-
191
-	/**
192
-	 * get the current active user
193
-	 *
194
-	 * @return IUser|null Current user, otherwise null
195
-	 */
196
-	public function getUser() {
197
-		// FIXME: This is a quick'n dirty work-around for the incognito mode as
198
-		// described at https://github.com/owncloud/core/pull/12912#issuecomment-67391155
199
-		if (OC_User::isIncognitoMode()) {
200
-			return null;
201
-		}
202
-		if (is_null($this->activeUser)) {
203
-			$uid = $this->session->get('user_id');
204
-			if (is_null($uid)) {
205
-				return null;
206
-			}
207
-			$this->activeUser = $this->manager->get($uid);
208
-			if (is_null($this->activeUser)) {
209
-				return null;
210
-			}
211
-			$this->validateSession();
212
-		}
213
-		return $this->activeUser;
214
-	}
215
-
216
-	/**
217
-	 * Validate whether the current session is valid
218
-	 *
219
-	 * - For token-authenticated clients, the token validity is checked
220
-	 * - For browsers, the session token validity is checked
221
-	 */
222
-	protected function validateSession() {
223
-		$token = null;
224
-		$appPassword = $this->session->get('app_password');
225
-
226
-		if (is_null($appPassword)) {
227
-			try {
228
-				$token = $this->session->getId();
229
-			} catch (SessionNotAvailableException $ex) {
230
-				return;
231
-			}
232
-		} else {
233
-			$token = $appPassword;
234
-		}
235
-
236
-		if (!$this->validateToken($token)) {
237
-			// Session was invalidated
238
-			$this->logout();
239
-		}
240
-	}
241
-
242
-	/**
243
-	 * Checks whether the user is logged in
244
-	 *
245
-	 * @return bool if logged in
246
-	 */
247
-	public function isLoggedIn() {
248
-		$user = $this->getUser();
249
-		if (is_null($user)) {
250
-			return false;
251
-		}
252
-
253
-		return $user->isEnabled();
254
-	}
255
-
256
-	/**
257
-	 * set the login name
258
-	 *
259
-	 * @param string|null $loginName for the logged in user
260
-	 */
261
-	public function setLoginName($loginName) {
262
-		if (is_null($loginName)) {
263
-			$this->session->remove('loginname');
264
-		} else {
265
-			$this->session->set('loginname', $loginName);
266
-		}
267
-	}
268
-
269
-	/**
270
-	 * get the login name of the current user
271
-	 *
272
-	 * @return string
273
-	 */
274
-	public function getLoginName() {
275
-		if ($this->activeUser) {
276
-			return $this->session->get('loginname');
277
-		} else {
278
-			$uid = $this->session->get('user_id');
279
-			if ($uid) {
280
-				$this->activeUser = $this->manager->get($uid);
281
-				return $this->session->get('loginname');
282
-			} else {
283
-				return null;
284
-			}
285
-		}
286
-	}
287
-
288
-	/**
289
-	 * set the token id
290
-	 *
291
-	 * @param int|null $token that was used to log in
292
-	 */
293
-	protected function setToken($token) {
294
-		if ($token === null) {
295
-			$this->session->remove('token-id');
296
-		} else {
297
-			$this->session->set('token-id', $token);
298
-		}
299
-	}
300
-
301
-	/**
302
-	 * try to log in with the provided credentials
303
-	 *
304
-	 * @param string $uid
305
-	 * @param string $password
306
-	 * @return boolean|null
307
-	 * @throws LoginException
308
-	 */
309
-	public function login($uid, $password) {
310
-		$this->session->regenerateId();
311
-		if ($this->validateToken($password, $uid)) {
312
-			return $this->loginWithToken($password);
313
-		}
314
-		return $this->loginWithPassword($uid, $password);
315
-	}
316
-
317
-	/**
318
-	 * Tries to log in a client
319
-	 *
320
-	 * Checks token auth enforced
321
-	 * Checks 2FA enabled
322
-	 *
323
-	 * @param string $user
324
-	 * @param string $password
325
-	 * @param IRequest $request
326
-	 * @param OC\Security\Bruteforce\Throttler $throttler
327
-	 * @throws LoginException
328
-	 * @throws PasswordLoginForbiddenException
329
-	 * @return boolean
330
-	 */
331
-	public function logClientIn($user,
332
-								$password,
333
-								IRequest $request,
334
-								OC\Security\Bruteforce\Throttler $throttler) {
335
-		$currentDelay = $throttler->sleepDelay($request->getRemoteAddress(), 'login');
336
-
337
-		if ($this->manager instanceof PublicEmitter) {
338
-			$this->manager->emit('\OC\User', 'preLogin', array($user, $password));
339
-		}
340
-
341
-		$isTokenPassword = $this->isTokenPassword($password);
342
-		if (!$isTokenPassword && $this->isTokenAuthEnforced()) {
343
-			throw new PasswordLoginForbiddenException();
344
-		}
345
-		if (!$isTokenPassword && $this->isTwoFactorEnforced($user)) {
346
-			throw new PasswordLoginForbiddenException();
347
-		}
348
-		if (!$this->login($user, $password) ) {
349
-			$users = $this->manager->getByEmail($user);
350
-			if (count($users) === 1) {
351
-				return $this->login($users[0]->getUID(), $password);
352
-			}
353
-
354
-			$throttler->registerAttempt('login', $request->getRemoteAddress(), ['uid' => $user]);
355
-			if($currentDelay === 0) {
356
-				$throttler->sleepDelay($request->getRemoteAddress(), 'login');
357
-			}
358
-			return false;
359
-		}
360
-
361
-		if ($isTokenPassword) {
362
-			$this->session->set('app_password', $password);
363
-		} else if($this->supportsCookies($request)) {
364
-			// Password login, but cookies supported -> create (browser) session token
365
-			$this->createSessionToken($request, $this->getUser()->getUID(), $user, $password);
366
-		}
367
-
368
-		return true;
369
-	}
370
-
371
-	protected function supportsCookies(IRequest $request) {
372
-		if (!is_null($request->getCookie('cookie_test'))) {
373
-			return true;
374
-		}
375
-		setcookie('cookie_test', 'test', $this->timeFacory->getTime() + 3600);
376
-		return false;
377
-	}
378
-
379
-	private function isTokenAuthEnforced() {
380
-		return $this->config->getSystemValue('token_auth_enforced', false);
381
-	}
382
-
383
-	protected function isTwoFactorEnforced($username) {
384
-		Util::emitHook(
385
-			'\OCA\Files_Sharing\API\Server2Server',
386
-			'preLoginNameUsedAsUserName',
387
-			array('uid' => &$username)
388
-		);
389
-		$user = $this->manager->get($username);
390
-		if (is_null($user)) {
391
-			$users = $this->manager->getByEmail($username);
392
-			if (empty($users)) {
393
-				return false;
394
-			}
395
-			if (count($users) !== 1) {
396
-				return true;
397
-			}
398
-			$user = $users[0];
399
-		}
400
-		// DI not possible due to cyclic dependencies :'-/
401
-		return OC::$server->getTwoFactorAuthManager()->isTwoFactorAuthenticated($user);
402
-	}
403
-
404
-	/**
405
-	 * Check if the given 'password' is actually a device token
406
-	 *
407
-	 * @param string $password
408
-	 * @return boolean
409
-	 */
410
-	public function isTokenPassword($password) {
411
-		try {
412
-			$this->tokenProvider->getToken($password);
413
-			return true;
414
-		} catch (InvalidTokenException $ex) {
415
-			return false;
416
-		}
417
-	}
418
-
419
-	protected function prepareUserLogin($firstTimeLogin) {
420
-		// TODO: mock/inject/use non-static
421
-		// Refresh the token
422
-		\OC::$server->getCsrfTokenManager()->refreshToken();
423
-		//we need to pass the user name, which may differ from login name
424
-		$user = $this->getUser()->getUID();
425
-		OC_Util::setupFS($user);
426
-
427
-		if ($firstTimeLogin) {
428
-			// TODO: lock necessary?
429
-			//trigger creation of user home and /files folder
430
-			$userFolder = \OC::$server->getUserFolder($user);
431
-
432
-			// copy skeleton
433
-			\OC_Util::copySkeleton($user, $userFolder);
434
-
435
-			// trigger any other initialization
436
-			\OC::$server->getEventDispatcher()->dispatch(IUser::class . '::firstLogin', new GenericEvent($this->getUser()));
437
-		}
438
-	}
439
-
440
-	/**
441
-	 * Tries to login the user with HTTP Basic Authentication
442
-	 *
443
-	 * @todo do not allow basic auth if the user is 2FA enforced
444
-	 * @param IRequest $request
445
-	 * @param OC\Security\Bruteforce\Throttler $throttler
446
-	 * @return boolean if the login was successful
447
-	 */
448
-	public function tryBasicAuthLogin(IRequest $request,
449
-									  OC\Security\Bruteforce\Throttler $throttler) {
450
-		if (!empty($request->server['PHP_AUTH_USER']) && !empty($request->server['PHP_AUTH_PW'])) {
451
-			try {
452
-				if ($this->logClientIn($request->server['PHP_AUTH_USER'], $request->server['PHP_AUTH_PW'], $request, $throttler)) {
453
-					/**
454
-					 * Add DAV authenticated. This should in an ideal world not be
455
-					 * necessary but the iOS App reads cookies from anywhere instead
456
-					 * only the DAV endpoint.
457
-					 * This makes sure that the cookies will be valid for the whole scope
458
-					 * @see https://github.com/owncloud/core/issues/22893
459
-					 */
460
-					$this->session->set(
461
-						Auth::DAV_AUTHENTICATED, $this->getUser()->getUID()
462
-					);
463
-
464
-					// Set the last-password-confirm session to make the sudo mode work
465
-					 $this->session->set('last-password-confirm', $this->timeFacory->getTime());
466
-
467
-					return true;
468
-				}
469
-			} catch (PasswordLoginForbiddenException $ex) {
470
-				// Nothing to do
471
-			}
472
-		}
473
-		return false;
474
-	}
475
-
476
-	/**
477
-	 * Log an user in via login name and password
478
-	 *
479
-	 * @param string $uid
480
-	 * @param string $password
481
-	 * @return boolean
482
-	 * @throws LoginException if an app canceld the login process or the user is not enabled
483
-	 */
484
-	private function loginWithPassword($uid, $password) {
485
-		$user = $this->manager->checkPassword($uid, $password);
486
-		if ($user === false) {
487
-			// Password check failed
488
-			return false;
489
-		}
490
-
491
-		if ($user->isEnabled()) {
492
-			$this->setUser($user);
493
-			$this->setLoginName($uid);
494
-			$this->setToken(null);
495
-			$firstTimeLogin = $user->updateLastLoginTimestamp();
496
-			$this->manager->emit('\OC\User', 'postLogin', [$user, $password]);
497
-			if ($this->isLoggedIn()) {
498
-				$this->prepareUserLogin($firstTimeLogin);
499
-				return true;
500
-			} else {
501
-				// injecting l10n does not work - there is a circular dependency between session and \OCP\L10N\IFactory
502
-				$message = \OC::$server->getL10N('lib')->t('Login canceled by app');
503
-				throw new LoginException($message);
504
-			}
505
-		} else {
506
-			// injecting l10n does not work - there is a circular dependency between session and \OCP\L10N\IFactory
507
-			$message = \OC::$server->getL10N('lib')->t('User disabled');
508
-			throw new LoginException($message);
509
-		}
510
-	}
511
-
512
-	/**
513
-	 * Log an user in with a given token (id)
514
-	 *
515
-	 * @param string $token
516
-	 * @return boolean
517
-	 * @throws LoginException if an app canceled the login process or the user is not enabled
518
-	 */
519
-	private function loginWithToken($token) {
520
-		try {
521
-			$dbToken = $this->tokenProvider->getToken($token);
522
-		} catch (InvalidTokenException $ex) {
523
-			return false;
524
-		}
525
-		$uid = $dbToken->getUID();
526
-
527
-		// When logging in with token, the password must be decrypted first before passing to login hook
528
-		$password = '';
529
-		try {
530
-			$password = $this->tokenProvider->getPassword($dbToken, $token);
531
-		} catch (PasswordlessTokenException $ex) {
532
-			// Ignore and use empty string instead
533
-		}
534
-
535
-		$user = $this->manager->get($uid);
536
-		if (is_null($user)) {
537
-			// user does not exist
538
-			return false;
539
-		}
540
-		if (!$user->isEnabled()) {
541
-			// disabled users can not log in
542
-			// injecting l10n does not work - there is a circular dependency between session and \OCP\L10N\IFactory
543
-			$message = \OC::$server->getL10N('lib')->t('User disabled');
544
-			throw new LoginException($message);
545
-		}
546
-
547
-		//login
548
-		$this->setUser($user);
549
-		$this->setLoginName($dbToken->getLoginName());
550
-		$this->setToken($dbToken->getId());
551
-		\OC::$server->getLockdownManager()->setToken($dbToken);
552
-		$this->manager->emit('\OC\User', 'postLogin', array($user, $password));
553
-
554
-		if ($this->isLoggedIn()) {
555
-			$this->prepareUserLogin(false); // token login cant be the first
556
-		} else {
557
-			// injecting l10n does not work - there is a circular dependency between session and \OCP\L10N\IFactory
558
-			$message = \OC::$server->getL10N('lib')->t('Login canceled by app');
559
-			throw new LoginException($message);
560
-		}
561
-
562
-		return true;
563
-	}
564
-
565
-	/**
566
-	 * Create a new session token for the given user credentials
567
-	 *
568
-	 * @param IRequest $request
569
-	 * @param string $uid user UID
570
-	 * @param string $loginName login name
571
-	 * @param string $password
572
-	 * @param int $remember
573
-	 * @return boolean
574
-	 */
575
-	public function createSessionToken(IRequest $request, $uid, $loginName, $password = null, $remember = IToken::DO_NOT_REMEMBER) {
576
-		if (is_null($this->manager->get($uid))) {
577
-			// User does not exist
578
-			return false;
579
-		}
580
-		$name = isset($request->server['HTTP_USER_AGENT']) ? $request->server['HTTP_USER_AGENT'] : 'unknown browser';
581
-		try {
582
-			$sessionId = $this->session->getId();
583
-			$pwd = $this->getPassword($password);
584
-			$this->tokenProvider->generateToken($sessionId, $uid, $loginName, $pwd, $name, IToken::TEMPORARY_TOKEN, $remember);
585
-			return true;
586
-		} catch (SessionNotAvailableException $ex) {
587
-			// This can happen with OCC, where a memory session is used
588
-			// if a memory session is used, we shouldn't create a session token anyway
589
-			return false;
590
-		}
591
-	}
592
-
593
-	/**
594
-	 * Checks if the given password is a token.
595
-	 * If yes, the password is extracted from the token.
596
-	 * If no, the same password is returned.
597
-	 *
598
-	 * @param string $password either the login password or a device token
599
-	 * @return string|null the password or null if none was set in the token
600
-	 */
601
-	private function getPassword($password) {
602
-		if (is_null($password)) {
603
-			// This is surely no token ;-)
604
-			return null;
605
-		}
606
-		try {
607
-			$token = $this->tokenProvider->getToken($password);
608
-			try {
609
-				return $this->tokenProvider->getPassword($token, $password);
610
-			} catch (PasswordlessTokenException $ex) {
611
-				return null;
612
-			}
613
-		} catch (InvalidTokenException $ex) {
614
-			return $password;
615
-		}
616
-	}
617
-
618
-	/**
619
-	 * @param IToken $dbToken
620
-	 * @param string $token
621
-	 * @return boolean
622
-	 */
623
-	private function checkTokenCredentials(IToken $dbToken, $token) {
624
-		// Check whether login credentials are still valid and the user was not disabled
625
-		// This check is performed each 5 minutes
626
-		$lastCheck = $dbToken->getLastCheck() ? : 0;
627
-		$now = $this->timeFacory->getTime();
628
-		if ($lastCheck > ($now - 60 * 5)) {
629
-			// Checked performed recently, nothing to do now
630
-			return true;
631
-		}
632
-
633
-		try {
634
-			$pwd = $this->tokenProvider->getPassword($dbToken, $token);
635
-		} catch (InvalidTokenException $ex) {
636
-			// An invalid token password was used -> log user out
637
-			return false;
638
-		} catch (PasswordlessTokenException $ex) {
639
-			// Token has no password
640
-
641
-			if (!is_null($this->activeUser) && !$this->activeUser->isEnabled()) {
642
-				$this->tokenProvider->invalidateToken($token);
643
-				return false;
644
-			}
645
-
646
-			$dbToken->setLastCheck($now);
647
-			return true;
648
-		}
649
-
650
-		if ($this->manager->checkPassword($dbToken->getLoginName(), $pwd) === false
651
-			|| (!is_null($this->activeUser) && !$this->activeUser->isEnabled())) {
652
-			$this->tokenProvider->invalidateToken($token);
653
-			// Password has changed or user was disabled -> log user out
654
-			return false;
655
-		}
656
-		$dbToken->setLastCheck($now);
657
-		return true;
658
-	}
659
-
660
-	/**
661
-	 * Check if the given token exists and performs password/user-enabled checks
662
-	 *
663
-	 * Invalidates the token if checks fail
664
-	 *
665
-	 * @param string $token
666
-	 * @param string $user login name
667
-	 * @return boolean
668
-	 */
669
-	private function validateToken($token, $user = null) {
670
-		try {
671
-			$dbToken = $this->tokenProvider->getToken($token);
672
-		} catch (InvalidTokenException $ex) {
673
-			return false;
674
-		}
675
-
676
-		// Check if login names match
677
-		if (!is_null($user) && $dbToken->getLoginName() !== $user) {
678
-			// TODO: this makes it imposssible to use different login names on browser and client
679
-			// e.g. login by e-mail '[email protected]' on browser for generating the token will not
680
-			//      allow to use the client token with the login name 'user'.
681
-			return false;
682
-		}
683
-
684
-		if (!$this->checkTokenCredentials($dbToken, $token)) {
685
-			return false;
686
-		}
687
-
688
-		$this->tokenProvider->updateTokenActivity($dbToken);
689
-
690
-		return true;
691
-	}
692
-
693
-	/**
694
-	 * Tries to login the user with auth token header
695
-	 *
696
-	 * @param IRequest $request
697
-	 * @todo check remember me cookie
698
-	 * @return boolean
699
-	 */
700
-	public function tryTokenLogin(IRequest $request) {
701
-		$authHeader = $request->getHeader('Authorization');
702
-		if (strpos($authHeader, 'token ') === false) {
703
-			// No auth header, let's try session id
704
-			try {
705
-				$token = $this->session->getId();
706
-			} catch (SessionNotAvailableException $ex) {
707
-				return false;
708
-			}
709
-		} else {
710
-			$token = substr($authHeader, 6);
711
-		}
712
-
713
-		if (!$this->loginWithToken($token)) {
714
-			return false;
715
-		}
716
-		if(!$this->validateToken($token)) {
717
-			return false;
718
-		}
719
-		return true;
720
-	}
721
-
722
-	/**
723
-	 * perform login using the magic cookie (remember login)
724
-	 *
725
-	 * @param string $uid the username
726
-	 * @param string $currentToken
727
-	 * @param string $oldSessionId
728
-	 * @return bool
729
-	 */
730
-	public function loginWithCookie($uid, $currentToken, $oldSessionId) {
731
-		$this->session->regenerateId();
732
-		$this->manager->emit('\OC\User', 'preRememberedLogin', array($uid));
733
-		$user = $this->manager->get($uid);
734
-		if (is_null($user)) {
735
-			// user does not exist
736
-			return false;
737
-		}
738
-
739
-		// get stored tokens
740
-		$tokens = $this->config->getUserKeys($uid, 'login_token');
741
-		// test cookies token against stored tokens
742
-		if (!in_array($currentToken, $tokens, true)) {
743
-			return false;
744
-		}
745
-		// replace successfully used token with a new one
746
-		$this->config->deleteUserValue($uid, 'login_token', $currentToken);
747
-		$newToken = $this->random->generate(32);
748
-		$this->config->setUserValue($uid, 'login_token', $newToken, $this->timeFacory->getTime());
749
-
750
-		try {
751
-			$sessionId = $this->session->getId();
752
-			$this->tokenProvider->renewSessionToken($oldSessionId, $sessionId);
753
-		} catch (SessionNotAvailableException $ex) {
754
-			return false;
755
-		} catch (InvalidTokenException $ex) {
756
-			\OC::$server->getLogger()->warning('Renewing session token failed', ['app' => 'core']);
757
-			return false;
758
-		}
759
-
760
-		$this->setMagicInCookie($user->getUID(), $newToken);
761
-		$token = $this->tokenProvider->getToken($sessionId);
762
-
763
-		//login
764
-		$this->setUser($user);
765
-		$this->setLoginName($token->getLoginName());
766
-		$this->setToken($token->getId());
767
-		$user->updateLastLoginTimestamp();
768
-		$this->manager->emit('\OC\User', 'postRememberedLogin', [$user]);
769
-		return true;
770
-	}
771
-
772
-	/**
773
-	 * @param IUser $user
774
-	 */
775
-	public function createRememberMeToken(IUser $user) {
776
-		$token = $this->random->generate(32);
777
-		$this->config->setUserValue($user->getUID(), 'login_token', $token, $this->timeFacory->getTime());
778
-		$this->setMagicInCookie($user->getUID(), $token);
779
-	}
780
-
781
-	/**
782
-	 * logout the user from the session
783
-	 */
784
-	public function logout() {
785
-		$this->manager->emit('\OC\User', 'logout');
786
-		$user = $this->getUser();
787
-		if (!is_null($user)) {
788
-			try {
789
-				$this->tokenProvider->invalidateToken($this->session->getId());
790
-			} catch (SessionNotAvailableException $ex) {
791
-
792
-			}
793
-		}
794
-		$this->setUser(null);
795
-		$this->setLoginName(null);
796
-		$this->setToken(null);
797
-		$this->unsetMagicInCookie();
798
-		$this->session->clear();
799
-	}
800
-
801
-	/**
802
-	 * Set cookie value to use in next page load
803
-	 *
804
-	 * @param string $username username to be set
805
-	 * @param string $token
806
-	 */
807
-	public function setMagicInCookie($username, $token) {
808
-		$secureCookie = OC::$server->getRequest()->getServerProtocol() === 'https';
809
-		$webRoot = \OC::$WEBROOT;
810
-		if ($webRoot === '') {
811
-			$webRoot = '/';
812
-		}
813
-
814
-		$expires = $this->timeFacory->getTime() + $this->config->getSystemValue('remember_login_cookie_lifetime', 60 * 60 * 24 * 15);
815
-		setcookie('nc_username', $username, $expires, $webRoot, '', $secureCookie, true);
816
-		setcookie('nc_token', $token, $expires, $webRoot, '', $secureCookie, true);
817
-		try {
818
-			setcookie('nc_session_id', $this->session->getId(), $expires, $webRoot, '', $secureCookie, true);
819
-		} catch (SessionNotAvailableException $ex) {
820
-			// ignore
821
-		}
822
-	}
823
-
824
-	/**
825
-	 * Remove cookie for "remember username"
826
-	 */
827
-	public function unsetMagicInCookie() {
828
-		//TODO: DI for cookies and IRequest
829
-		$secureCookie = OC::$server->getRequest()->getServerProtocol() === 'https';
830
-
831
-		unset($_COOKIE['nc_username']); //TODO: DI
832
-		unset($_COOKIE['nc_token']);
833
-		unset($_COOKIE['nc_session_id']);
834
-		setcookie('nc_username', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
835
-		setcookie('nc_token', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
836
-		setcookie('nc_session_id', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
837
-		// old cookies might be stored under /webroot/ instead of /webroot
838
-		// and Firefox doesn't like it!
839
-		setcookie('nc_username', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
840
-		setcookie('nc_token', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
841
-		setcookie('nc_session_id', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
842
-	}
843
-
844
-	/**
845
-	 * Update password of the browser session token if there is one
846
-	 *
847
-	 * @param string $password
848
-	 */
849
-	public function updateSessionTokenPassword($password) {
850
-		try {
851
-			$sessionId = $this->session->getId();
852
-			$token = $this->tokenProvider->getToken($sessionId);
853
-			$this->tokenProvider->setPassword($token, $sessionId, $password);
854
-		} catch (SessionNotAvailableException $ex) {
855
-			// Nothing to do
856
-		} catch (InvalidTokenException $ex) {
857
-			// Nothing to do
858
-		}
859
-	}
78
+    /** @var IUserManager $manager */
79
+    private $manager;
80
+
81
+    /** @var ISession $session */
82
+    private $session;
83
+
84
+    /** @var ITimeFactory */
85
+    private $timeFacory;
86
+
87
+    /** @var IProvider */
88
+    private $tokenProvider;
89
+
90
+    /** @var IConfig */
91
+    private $config;
92
+
93
+    /** @var User $activeUser */
94
+    protected $activeUser;
95
+
96
+    /** @var ISecureRandom */
97
+    private $random;
98
+
99
+    /**
100
+     * @param IUserManager $manager
101
+     * @param ISession $session
102
+     * @param ITimeFactory $timeFacory
103
+     * @param IProvider $tokenProvider
104
+     * @param IConfig $config
105
+     * @param ISecureRandom $random
106
+     */
107
+    public function __construct(IUserManager $manager,
108
+                                ISession $session,
109
+                                ITimeFactory $timeFacory,
110
+                                $tokenProvider,
111
+                                IConfig $config,
112
+                                ISecureRandom $random) {
113
+        $this->manager = $manager;
114
+        $this->session = $session;
115
+        $this->timeFacory = $timeFacory;
116
+        $this->tokenProvider = $tokenProvider;
117
+        $this->config = $config;
118
+        $this->random = $random;
119
+    }
120
+
121
+    /**
122
+     * @param IProvider $provider
123
+     */
124
+    public function setTokenProvider(IProvider $provider) {
125
+        $this->tokenProvider = $provider;
126
+    }
127
+
128
+    /**
129
+     * @param string $scope
130
+     * @param string $method
131
+     * @param callable $callback
132
+     */
133
+    public function listen($scope, $method, callable $callback) {
134
+        $this->manager->listen($scope, $method, $callback);
135
+    }
136
+
137
+    /**
138
+     * @param string $scope optional
139
+     * @param string $method optional
140
+     * @param callable $callback optional
141
+     */
142
+    public function removeListener($scope = null, $method = null, callable $callback = null) {
143
+        $this->manager->removeListener($scope, $method, $callback);
144
+    }
145
+
146
+    /**
147
+     * get the manager object
148
+     *
149
+     * @return Manager
150
+     */
151
+    public function getManager() {
152
+        return $this->manager;
153
+    }
154
+
155
+    /**
156
+     * get the session object
157
+     *
158
+     * @return ISession
159
+     */
160
+    public function getSession() {
161
+        return $this->session;
162
+    }
163
+
164
+    /**
165
+     * set the session object
166
+     *
167
+     * @param ISession $session
168
+     */
169
+    public function setSession(ISession $session) {
170
+        if ($this->session instanceof ISession) {
171
+            $this->session->close();
172
+        }
173
+        $this->session = $session;
174
+        $this->activeUser = null;
175
+    }
176
+
177
+    /**
178
+     * set the currently active user
179
+     *
180
+     * @param IUser|null $user
181
+     */
182
+    public function setUser($user) {
183
+        if (is_null($user)) {
184
+            $this->session->remove('user_id');
185
+        } else {
186
+            $this->session->set('user_id', $user->getUID());
187
+        }
188
+        $this->activeUser = $user;
189
+    }
190
+
191
+    /**
192
+     * get the current active user
193
+     *
194
+     * @return IUser|null Current user, otherwise null
195
+     */
196
+    public function getUser() {
197
+        // FIXME: This is a quick'n dirty work-around for the incognito mode as
198
+        // described at https://github.com/owncloud/core/pull/12912#issuecomment-67391155
199
+        if (OC_User::isIncognitoMode()) {
200
+            return null;
201
+        }
202
+        if (is_null($this->activeUser)) {
203
+            $uid = $this->session->get('user_id');
204
+            if (is_null($uid)) {
205
+                return null;
206
+            }
207
+            $this->activeUser = $this->manager->get($uid);
208
+            if (is_null($this->activeUser)) {
209
+                return null;
210
+            }
211
+            $this->validateSession();
212
+        }
213
+        return $this->activeUser;
214
+    }
215
+
216
+    /**
217
+     * Validate whether the current session is valid
218
+     *
219
+     * - For token-authenticated clients, the token validity is checked
220
+     * - For browsers, the session token validity is checked
221
+     */
222
+    protected function validateSession() {
223
+        $token = null;
224
+        $appPassword = $this->session->get('app_password');
225
+
226
+        if (is_null($appPassword)) {
227
+            try {
228
+                $token = $this->session->getId();
229
+            } catch (SessionNotAvailableException $ex) {
230
+                return;
231
+            }
232
+        } else {
233
+            $token = $appPassword;
234
+        }
235
+
236
+        if (!$this->validateToken($token)) {
237
+            // Session was invalidated
238
+            $this->logout();
239
+        }
240
+    }
241
+
242
+    /**
243
+     * Checks whether the user is logged in
244
+     *
245
+     * @return bool if logged in
246
+     */
247
+    public function isLoggedIn() {
248
+        $user = $this->getUser();
249
+        if (is_null($user)) {
250
+            return false;
251
+        }
252
+
253
+        return $user->isEnabled();
254
+    }
255
+
256
+    /**
257
+     * set the login name
258
+     *
259
+     * @param string|null $loginName for the logged in user
260
+     */
261
+    public function setLoginName($loginName) {
262
+        if (is_null($loginName)) {
263
+            $this->session->remove('loginname');
264
+        } else {
265
+            $this->session->set('loginname', $loginName);
266
+        }
267
+    }
268
+
269
+    /**
270
+     * get the login name of the current user
271
+     *
272
+     * @return string
273
+     */
274
+    public function getLoginName() {
275
+        if ($this->activeUser) {
276
+            return $this->session->get('loginname');
277
+        } else {
278
+            $uid = $this->session->get('user_id');
279
+            if ($uid) {
280
+                $this->activeUser = $this->manager->get($uid);
281
+                return $this->session->get('loginname');
282
+            } else {
283
+                return null;
284
+            }
285
+        }
286
+    }
287
+
288
+    /**
289
+     * set the token id
290
+     *
291
+     * @param int|null $token that was used to log in
292
+     */
293
+    protected function setToken($token) {
294
+        if ($token === null) {
295
+            $this->session->remove('token-id');
296
+        } else {
297
+            $this->session->set('token-id', $token);
298
+        }
299
+    }
300
+
301
+    /**
302
+     * try to log in with the provided credentials
303
+     *
304
+     * @param string $uid
305
+     * @param string $password
306
+     * @return boolean|null
307
+     * @throws LoginException
308
+     */
309
+    public function login($uid, $password) {
310
+        $this->session->regenerateId();
311
+        if ($this->validateToken($password, $uid)) {
312
+            return $this->loginWithToken($password);
313
+        }
314
+        return $this->loginWithPassword($uid, $password);
315
+    }
316
+
317
+    /**
318
+     * Tries to log in a client
319
+     *
320
+     * Checks token auth enforced
321
+     * Checks 2FA enabled
322
+     *
323
+     * @param string $user
324
+     * @param string $password
325
+     * @param IRequest $request
326
+     * @param OC\Security\Bruteforce\Throttler $throttler
327
+     * @throws LoginException
328
+     * @throws PasswordLoginForbiddenException
329
+     * @return boolean
330
+     */
331
+    public function logClientIn($user,
332
+                                $password,
333
+                                IRequest $request,
334
+                                OC\Security\Bruteforce\Throttler $throttler) {
335
+        $currentDelay = $throttler->sleepDelay($request->getRemoteAddress(), 'login');
336
+
337
+        if ($this->manager instanceof PublicEmitter) {
338
+            $this->manager->emit('\OC\User', 'preLogin', array($user, $password));
339
+        }
340
+
341
+        $isTokenPassword = $this->isTokenPassword($password);
342
+        if (!$isTokenPassword && $this->isTokenAuthEnforced()) {
343
+            throw new PasswordLoginForbiddenException();
344
+        }
345
+        if (!$isTokenPassword && $this->isTwoFactorEnforced($user)) {
346
+            throw new PasswordLoginForbiddenException();
347
+        }
348
+        if (!$this->login($user, $password) ) {
349
+            $users = $this->manager->getByEmail($user);
350
+            if (count($users) === 1) {
351
+                return $this->login($users[0]->getUID(), $password);
352
+            }
353
+
354
+            $throttler->registerAttempt('login', $request->getRemoteAddress(), ['uid' => $user]);
355
+            if($currentDelay === 0) {
356
+                $throttler->sleepDelay($request->getRemoteAddress(), 'login');
357
+            }
358
+            return false;
359
+        }
360
+
361
+        if ($isTokenPassword) {
362
+            $this->session->set('app_password', $password);
363
+        } else if($this->supportsCookies($request)) {
364
+            // Password login, but cookies supported -> create (browser) session token
365
+            $this->createSessionToken($request, $this->getUser()->getUID(), $user, $password);
366
+        }
367
+
368
+        return true;
369
+    }
370
+
371
+    protected function supportsCookies(IRequest $request) {
372
+        if (!is_null($request->getCookie('cookie_test'))) {
373
+            return true;
374
+        }
375
+        setcookie('cookie_test', 'test', $this->timeFacory->getTime() + 3600);
376
+        return false;
377
+    }
378
+
379
+    private function isTokenAuthEnforced() {
380
+        return $this->config->getSystemValue('token_auth_enforced', false);
381
+    }
382
+
383
+    protected function isTwoFactorEnforced($username) {
384
+        Util::emitHook(
385
+            '\OCA\Files_Sharing\API\Server2Server',
386
+            'preLoginNameUsedAsUserName',
387
+            array('uid' => &$username)
388
+        );
389
+        $user = $this->manager->get($username);
390
+        if (is_null($user)) {
391
+            $users = $this->manager->getByEmail($username);
392
+            if (empty($users)) {
393
+                return false;
394
+            }
395
+            if (count($users) !== 1) {
396
+                return true;
397
+            }
398
+            $user = $users[0];
399
+        }
400
+        // DI not possible due to cyclic dependencies :'-/
401
+        return OC::$server->getTwoFactorAuthManager()->isTwoFactorAuthenticated($user);
402
+    }
403
+
404
+    /**
405
+     * Check if the given 'password' is actually a device token
406
+     *
407
+     * @param string $password
408
+     * @return boolean
409
+     */
410
+    public function isTokenPassword($password) {
411
+        try {
412
+            $this->tokenProvider->getToken($password);
413
+            return true;
414
+        } catch (InvalidTokenException $ex) {
415
+            return false;
416
+        }
417
+    }
418
+
419
+    protected function prepareUserLogin($firstTimeLogin) {
420
+        // TODO: mock/inject/use non-static
421
+        // Refresh the token
422
+        \OC::$server->getCsrfTokenManager()->refreshToken();
423
+        //we need to pass the user name, which may differ from login name
424
+        $user = $this->getUser()->getUID();
425
+        OC_Util::setupFS($user);
426
+
427
+        if ($firstTimeLogin) {
428
+            // TODO: lock necessary?
429
+            //trigger creation of user home and /files folder
430
+            $userFolder = \OC::$server->getUserFolder($user);
431
+
432
+            // copy skeleton
433
+            \OC_Util::copySkeleton($user, $userFolder);
434
+
435
+            // trigger any other initialization
436
+            \OC::$server->getEventDispatcher()->dispatch(IUser::class . '::firstLogin', new GenericEvent($this->getUser()));
437
+        }
438
+    }
439
+
440
+    /**
441
+     * Tries to login the user with HTTP Basic Authentication
442
+     *
443
+     * @todo do not allow basic auth if the user is 2FA enforced
444
+     * @param IRequest $request
445
+     * @param OC\Security\Bruteforce\Throttler $throttler
446
+     * @return boolean if the login was successful
447
+     */
448
+    public function tryBasicAuthLogin(IRequest $request,
449
+                                        OC\Security\Bruteforce\Throttler $throttler) {
450
+        if (!empty($request->server['PHP_AUTH_USER']) && !empty($request->server['PHP_AUTH_PW'])) {
451
+            try {
452
+                if ($this->logClientIn($request->server['PHP_AUTH_USER'], $request->server['PHP_AUTH_PW'], $request, $throttler)) {
453
+                    /**
454
+                     * Add DAV authenticated. This should in an ideal world not be
455
+                     * necessary but the iOS App reads cookies from anywhere instead
456
+                     * only the DAV endpoint.
457
+                     * This makes sure that the cookies will be valid for the whole scope
458
+                     * @see https://github.com/owncloud/core/issues/22893
459
+                     */
460
+                    $this->session->set(
461
+                        Auth::DAV_AUTHENTICATED, $this->getUser()->getUID()
462
+                    );
463
+
464
+                    // Set the last-password-confirm session to make the sudo mode work
465
+                        $this->session->set('last-password-confirm', $this->timeFacory->getTime());
466
+
467
+                    return true;
468
+                }
469
+            } catch (PasswordLoginForbiddenException $ex) {
470
+                // Nothing to do
471
+            }
472
+        }
473
+        return false;
474
+    }
475
+
476
+    /**
477
+     * Log an user in via login name and password
478
+     *
479
+     * @param string $uid
480
+     * @param string $password
481
+     * @return boolean
482
+     * @throws LoginException if an app canceld the login process or the user is not enabled
483
+     */
484
+    private function loginWithPassword($uid, $password) {
485
+        $user = $this->manager->checkPassword($uid, $password);
486
+        if ($user === false) {
487
+            // Password check failed
488
+            return false;
489
+        }
490
+
491
+        if ($user->isEnabled()) {
492
+            $this->setUser($user);
493
+            $this->setLoginName($uid);
494
+            $this->setToken(null);
495
+            $firstTimeLogin = $user->updateLastLoginTimestamp();
496
+            $this->manager->emit('\OC\User', 'postLogin', [$user, $password]);
497
+            if ($this->isLoggedIn()) {
498
+                $this->prepareUserLogin($firstTimeLogin);
499
+                return true;
500
+            } else {
501
+                // injecting l10n does not work - there is a circular dependency between session and \OCP\L10N\IFactory
502
+                $message = \OC::$server->getL10N('lib')->t('Login canceled by app');
503
+                throw new LoginException($message);
504
+            }
505
+        } else {
506
+            // injecting l10n does not work - there is a circular dependency between session and \OCP\L10N\IFactory
507
+            $message = \OC::$server->getL10N('lib')->t('User disabled');
508
+            throw new LoginException($message);
509
+        }
510
+    }
511
+
512
+    /**
513
+     * Log an user in with a given token (id)
514
+     *
515
+     * @param string $token
516
+     * @return boolean
517
+     * @throws LoginException if an app canceled the login process or the user is not enabled
518
+     */
519
+    private function loginWithToken($token) {
520
+        try {
521
+            $dbToken = $this->tokenProvider->getToken($token);
522
+        } catch (InvalidTokenException $ex) {
523
+            return false;
524
+        }
525
+        $uid = $dbToken->getUID();
526
+
527
+        // When logging in with token, the password must be decrypted first before passing to login hook
528
+        $password = '';
529
+        try {
530
+            $password = $this->tokenProvider->getPassword($dbToken, $token);
531
+        } catch (PasswordlessTokenException $ex) {
532
+            // Ignore and use empty string instead
533
+        }
534
+
535
+        $user = $this->manager->get($uid);
536
+        if (is_null($user)) {
537
+            // user does not exist
538
+            return false;
539
+        }
540
+        if (!$user->isEnabled()) {
541
+            // disabled users can not log in
542
+            // injecting l10n does not work - there is a circular dependency between session and \OCP\L10N\IFactory
543
+            $message = \OC::$server->getL10N('lib')->t('User disabled');
544
+            throw new LoginException($message);
545
+        }
546
+
547
+        //login
548
+        $this->setUser($user);
549
+        $this->setLoginName($dbToken->getLoginName());
550
+        $this->setToken($dbToken->getId());
551
+        \OC::$server->getLockdownManager()->setToken($dbToken);
552
+        $this->manager->emit('\OC\User', 'postLogin', array($user, $password));
553
+
554
+        if ($this->isLoggedIn()) {
555
+            $this->prepareUserLogin(false); // token login cant be the first
556
+        } else {
557
+            // injecting l10n does not work - there is a circular dependency between session and \OCP\L10N\IFactory
558
+            $message = \OC::$server->getL10N('lib')->t('Login canceled by app');
559
+            throw new LoginException($message);
560
+        }
561
+
562
+        return true;
563
+    }
564
+
565
+    /**
566
+     * Create a new session token for the given user credentials
567
+     *
568
+     * @param IRequest $request
569
+     * @param string $uid user UID
570
+     * @param string $loginName login name
571
+     * @param string $password
572
+     * @param int $remember
573
+     * @return boolean
574
+     */
575
+    public function createSessionToken(IRequest $request, $uid, $loginName, $password = null, $remember = IToken::DO_NOT_REMEMBER) {
576
+        if (is_null($this->manager->get($uid))) {
577
+            // User does not exist
578
+            return false;
579
+        }
580
+        $name = isset($request->server['HTTP_USER_AGENT']) ? $request->server['HTTP_USER_AGENT'] : 'unknown browser';
581
+        try {
582
+            $sessionId = $this->session->getId();
583
+            $pwd = $this->getPassword($password);
584
+            $this->tokenProvider->generateToken($sessionId, $uid, $loginName, $pwd, $name, IToken::TEMPORARY_TOKEN, $remember);
585
+            return true;
586
+        } catch (SessionNotAvailableException $ex) {
587
+            // This can happen with OCC, where a memory session is used
588
+            // if a memory session is used, we shouldn't create a session token anyway
589
+            return false;
590
+        }
591
+    }
592
+
593
+    /**
594
+     * Checks if the given password is a token.
595
+     * If yes, the password is extracted from the token.
596
+     * If no, the same password is returned.
597
+     *
598
+     * @param string $password either the login password or a device token
599
+     * @return string|null the password or null if none was set in the token
600
+     */
601
+    private function getPassword($password) {
602
+        if (is_null($password)) {
603
+            // This is surely no token ;-)
604
+            return null;
605
+        }
606
+        try {
607
+            $token = $this->tokenProvider->getToken($password);
608
+            try {
609
+                return $this->tokenProvider->getPassword($token, $password);
610
+            } catch (PasswordlessTokenException $ex) {
611
+                return null;
612
+            }
613
+        } catch (InvalidTokenException $ex) {
614
+            return $password;
615
+        }
616
+    }
617
+
618
+    /**
619
+     * @param IToken $dbToken
620
+     * @param string $token
621
+     * @return boolean
622
+     */
623
+    private function checkTokenCredentials(IToken $dbToken, $token) {
624
+        // Check whether login credentials are still valid and the user was not disabled
625
+        // This check is performed each 5 minutes
626
+        $lastCheck = $dbToken->getLastCheck() ? : 0;
627
+        $now = $this->timeFacory->getTime();
628
+        if ($lastCheck > ($now - 60 * 5)) {
629
+            // Checked performed recently, nothing to do now
630
+            return true;
631
+        }
632
+
633
+        try {
634
+            $pwd = $this->tokenProvider->getPassword($dbToken, $token);
635
+        } catch (InvalidTokenException $ex) {
636
+            // An invalid token password was used -> log user out
637
+            return false;
638
+        } catch (PasswordlessTokenException $ex) {
639
+            // Token has no password
640
+
641
+            if (!is_null($this->activeUser) && !$this->activeUser->isEnabled()) {
642
+                $this->tokenProvider->invalidateToken($token);
643
+                return false;
644
+            }
645
+
646
+            $dbToken->setLastCheck($now);
647
+            return true;
648
+        }
649
+
650
+        if ($this->manager->checkPassword($dbToken->getLoginName(), $pwd) === false
651
+            || (!is_null($this->activeUser) && !$this->activeUser->isEnabled())) {
652
+            $this->tokenProvider->invalidateToken($token);
653
+            // Password has changed or user was disabled -> log user out
654
+            return false;
655
+        }
656
+        $dbToken->setLastCheck($now);
657
+        return true;
658
+    }
659
+
660
+    /**
661
+     * Check if the given token exists and performs password/user-enabled checks
662
+     *
663
+     * Invalidates the token if checks fail
664
+     *
665
+     * @param string $token
666
+     * @param string $user login name
667
+     * @return boolean
668
+     */
669
+    private function validateToken($token, $user = null) {
670
+        try {
671
+            $dbToken = $this->tokenProvider->getToken($token);
672
+        } catch (InvalidTokenException $ex) {
673
+            return false;
674
+        }
675
+
676
+        // Check if login names match
677
+        if (!is_null($user) && $dbToken->getLoginName() !== $user) {
678
+            // TODO: this makes it imposssible to use different login names on browser and client
679
+            // e.g. login by e-mail '[email protected]' on browser for generating the token will not
680
+            //      allow to use the client token with the login name 'user'.
681
+            return false;
682
+        }
683
+
684
+        if (!$this->checkTokenCredentials($dbToken, $token)) {
685
+            return false;
686
+        }
687
+
688
+        $this->tokenProvider->updateTokenActivity($dbToken);
689
+
690
+        return true;
691
+    }
692
+
693
+    /**
694
+     * Tries to login the user with auth token header
695
+     *
696
+     * @param IRequest $request
697
+     * @todo check remember me cookie
698
+     * @return boolean
699
+     */
700
+    public function tryTokenLogin(IRequest $request) {
701
+        $authHeader = $request->getHeader('Authorization');
702
+        if (strpos($authHeader, 'token ') === false) {
703
+            // No auth header, let's try session id
704
+            try {
705
+                $token = $this->session->getId();
706
+            } catch (SessionNotAvailableException $ex) {
707
+                return false;
708
+            }
709
+        } else {
710
+            $token = substr($authHeader, 6);
711
+        }
712
+
713
+        if (!$this->loginWithToken($token)) {
714
+            return false;
715
+        }
716
+        if(!$this->validateToken($token)) {
717
+            return false;
718
+        }
719
+        return true;
720
+    }
721
+
722
+    /**
723
+     * perform login using the magic cookie (remember login)
724
+     *
725
+     * @param string $uid the username
726
+     * @param string $currentToken
727
+     * @param string $oldSessionId
728
+     * @return bool
729
+     */
730
+    public function loginWithCookie($uid, $currentToken, $oldSessionId) {
731
+        $this->session->regenerateId();
732
+        $this->manager->emit('\OC\User', 'preRememberedLogin', array($uid));
733
+        $user = $this->manager->get($uid);
734
+        if (is_null($user)) {
735
+            // user does not exist
736
+            return false;
737
+        }
738
+
739
+        // get stored tokens
740
+        $tokens = $this->config->getUserKeys($uid, 'login_token');
741
+        // test cookies token against stored tokens
742
+        if (!in_array($currentToken, $tokens, true)) {
743
+            return false;
744
+        }
745
+        // replace successfully used token with a new one
746
+        $this->config->deleteUserValue($uid, 'login_token', $currentToken);
747
+        $newToken = $this->random->generate(32);
748
+        $this->config->setUserValue($uid, 'login_token', $newToken, $this->timeFacory->getTime());
749
+
750
+        try {
751
+            $sessionId = $this->session->getId();
752
+            $this->tokenProvider->renewSessionToken($oldSessionId, $sessionId);
753
+        } catch (SessionNotAvailableException $ex) {
754
+            return false;
755
+        } catch (InvalidTokenException $ex) {
756
+            \OC::$server->getLogger()->warning('Renewing session token failed', ['app' => 'core']);
757
+            return false;
758
+        }
759
+
760
+        $this->setMagicInCookie($user->getUID(), $newToken);
761
+        $token = $this->tokenProvider->getToken($sessionId);
762
+
763
+        //login
764
+        $this->setUser($user);
765
+        $this->setLoginName($token->getLoginName());
766
+        $this->setToken($token->getId());
767
+        $user->updateLastLoginTimestamp();
768
+        $this->manager->emit('\OC\User', 'postRememberedLogin', [$user]);
769
+        return true;
770
+    }
771
+
772
+    /**
773
+     * @param IUser $user
774
+     */
775
+    public function createRememberMeToken(IUser $user) {
776
+        $token = $this->random->generate(32);
777
+        $this->config->setUserValue($user->getUID(), 'login_token', $token, $this->timeFacory->getTime());
778
+        $this->setMagicInCookie($user->getUID(), $token);
779
+    }
780
+
781
+    /**
782
+     * logout the user from the session
783
+     */
784
+    public function logout() {
785
+        $this->manager->emit('\OC\User', 'logout');
786
+        $user = $this->getUser();
787
+        if (!is_null($user)) {
788
+            try {
789
+                $this->tokenProvider->invalidateToken($this->session->getId());
790
+            } catch (SessionNotAvailableException $ex) {
791
+
792
+            }
793
+        }
794
+        $this->setUser(null);
795
+        $this->setLoginName(null);
796
+        $this->setToken(null);
797
+        $this->unsetMagicInCookie();
798
+        $this->session->clear();
799
+    }
800
+
801
+    /**
802
+     * Set cookie value to use in next page load
803
+     *
804
+     * @param string $username username to be set
805
+     * @param string $token
806
+     */
807
+    public function setMagicInCookie($username, $token) {
808
+        $secureCookie = OC::$server->getRequest()->getServerProtocol() === 'https';
809
+        $webRoot = \OC::$WEBROOT;
810
+        if ($webRoot === '') {
811
+            $webRoot = '/';
812
+        }
813
+
814
+        $expires = $this->timeFacory->getTime() + $this->config->getSystemValue('remember_login_cookie_lifetime', 60 * 60 * 24 * 15);
815
+        setcookie('nc_username', $username, $expires, $webRoot, '', $secureCookie, true);
816
+        setcookie('nc_token', $token, $expires, $webRoot, '', $secureCookie, true);
817
+        try {
818
+            setcookie('nc_session_id', $this->session->getId(), $expires, $webRoot, '', $secureCookie, true);
819
+        } catch (SessionNotAvailableException $ex) {
820
+            // ignore
821
+        }
822
+    }
823
+
824
+    /**
825
+     * Remove cookie for "remember username"
826
+     */
827
+    public function unsetMagicInCookie() {
828
+        //TODO: DI for cookies and IRequest
829
+        $secureCookie = OC::$server->getRequest()->getServerProtocol() === 'https';
830
+
831
+        unset($_COOKIE['nc_username']); //TODO: DI
832
+        unset($_COOKIE['nc_token']);
833
+        unset($_COOKIE['nc_session_id']);
834
+        setcookie('nc_username', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
835
+        setcookie('nc_token', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
836
+        setcookie('nc_session_id', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
837
+        // old cookies might be stored under /webroot/ instead of /webroot
838
+        // and Firefox doesn't like it!
839
+        setcookie('nc_username', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
840
+        setcookie('nc_token', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
841
+        setcookie('nc_session_id', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
842
+    }
843
+
844
+    /**
845
+     * Update password of the browser session token if there is one
846
+     *
847
+     * @param string $password
848
+     */
849
+    public function updateSessionTokenPassword($password) {
850
+        try {
851
+            $sessionId = $this->session->getId();
852
+            $token = $this->tokenProvider->getToken($sessionId);
853
+            $this->tokenProvider->setPassword($token, $sessionId, $password);
854
+        } catch (SessionNotAvailableException $ex) {
855
+            // Nothing to do
856
+        } catch (InvalidTokenException $ex) {
857
+            // Nothing to do
858
+        }
859
+    }
860 860
 
861 861
 
862 862
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -345,14 +345,14 @@  discard block
 block discarded – undo
345 345
 		if (!$isTokenPassword && $this->isTwoFactorEnforced($user)) {
346 346
 			throw new PasswordLoginForbiddenException();
347 347
 		}
348
-		if (!$this->login($user, $password) ) {
348
+		if (!$this->login($user, $password)) {
349 349
 			$users = $this->manager->getByEmail($user);
350 350
 			if (count($users) === 1) {
351 351
 				return $this->login($users[0]->getUID(), $password);
352 352
 			}
353 353
 
354 354
 			$throttler->registerAttempt('login', $request->getRemoteAddress(), ['uid' => $user]);
355
-			if($currentDelay === 0) {
355
+			if ($currentDelay === 0) {
356 356
 				$throttler->sleepDelay($request->getRemoteAddress(), 'login');
357 357
 			}
358 358
 			return false;
@@ -360,7 +360,7 @@  discard block
 block discarded – undo
360 360
 
361 361
 		if ($isTokenPassword) {
362 362
 			$this->session->set('app_password', $password);
363
-		} else if($this->supportsCookies($request)) {
363
+		} else if ($this->supportsCookies($request)) {
364 364
 			// Password login, but cookies supported -> create (browser) session token
365 365
 			$this->createSessionToken($request, $this->getUser()->getUID(), $user, $password);
366 366
 		}
@@ -433,7 +433,7 @@  discard block
 block discarded – undo
433 433
 			\OC_Util::copySkeleton($user, $userFolder);
434 434
 
435 435
 			// trigger any other initialization
436
-			\OC::$server->getEventDispatcher()->dispatch(IUser::class . '::firstLogin', new GenericEvent($this->getUser()));
436
+			\OC::$server->getEventDispatcher()->dispatch(IUser::class.'::firstLogin', new GenericEvent($this->getUser()));
437 437
 		}
438 438
 	}
439 439
 
@@ -623,7 +623,7 @@  discard block
 block discarded – undo
623 623
 	private function checkTokenCredentials(IToken $dbToken, $token) {
624 624
 		// Check whether login credentials are still valid and the user was not disabled
625 625
 		// This check is performed each 5 minutes
626
-		$lastCheck = $dbToken->getLastCheck() ? : 0;
626
+		$lastCheck = $dbToken->getLastCheck() ?: 0;
627 627
 		$now = $this->timeFacory->getTime();
628 628
 		if ($lastCheck > ($now - 60 * 5)) {
629 629
 			// Checked performed recently, nothing to do now
@@ -713,7 +713,7 @@  discard block
 block discarded – undo
713 713
 		if (!$this->loginWithToken($token)) {
714 714
 			return false;
715 715
 		}
716
-		if(!$this->validateToken($token)) {
716
+		if (!$this->validateToken($token)) {
717 717
 			return false;
718 718
 		}
719 719
 		return true;
@@ -836,9 +836,9 @@  discard block
 block discarded – undo
836 836
 		setcookie('nc_session_id', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT, '', $secureCookie, true);
837 837
 		// old cookies might be stored under /webroot/ instead of /webroot
838 838
 		// and Firefox doesn't like it!
839
-		setcookie('nc_username', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
840
-		setcookie('nc_token', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
841
-		setcookie('nc_session_id', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
839
+		setcookie('nc_username', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT.'/', '', $secureCookie, true);
840
+		setcookie('nc_token', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT.'/', '', $secureCookie, true);
841
+		setcookie('nc_session_id', '', $this->timeFacory->getTime() - 3600, OC::$WEBROOT.'/', '', $secureCookie, true);
842 842
 	}
843 843
 
844 844
 	/**
Please login to merge, or discard this patch.
lib/public/AppFramework/Http/StreamResponse.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -37,7 +37,7 @@
 block discarded – undo
37 37
 	private $filePath;
38 38
 
39 39
 	/**
40
-	 * @param string|resource $filePath the path to the file or a file handle which should be streamed
40
+	 * @param string $filePath the path to the file or a file handle which should be streamed
41 41
 	 * @since 8.1.0
42 42
 	 */
43 43
 	public function __construct ($filePath) {
Please login to merge, or discard this patch.
Indentation   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -33,33 +33,33 @@
 block discarded – undo
33 33
  * @since 8.1.0
34 34
  */
35 35
 class StreamResponse extends Response implements ICallbackResponse {
36
-	/** @var string */
37
-	private $filePath;
36
+    /** @var string */
37
+    private $filePath;
38 38
 
39
-	/**
40
-	 * @param string|resource $filePath the path to the file or a file handle which should be streamed
41
-	 * @since 8.1.0
42
-	 */
43
-	public function __construct ($filePath) {
44
-		$this->filePath = $filePath;
45
-	}
39
+    /**
40
+     * @param string|resource $filePath the path to the file or a file handle which should be streamed
41
+     * @since 8.1.0
42
+     */
43
+    public function __construct ($filePath) {
44
+        $this->filePath = $filePath;
45
+    }
46 46
 
47 47
 
48
-	/**
49
-	 * Streams the file using readfile
50
-	 *
51
-	 * @param IOutput $output a small wrapper that handles output
52
-	 * @since 8.1.0
53
-	 */
54
-	public function callback (IOutput $output) {
55
-		// handle caching
56
-		if ($output->getHttpResponseCode() !== Http::STATUS_NOT_MODIFIED) {
57
-			if (!(is_resource($this->filePath) || file_exists($this->filePath))) {
58
-				$output->setHttpResponseCode(Http::STATUS_NOT_FOUND);
59
-			} elseif ($output->setReadfile($this->filePath) === false) {
60
-				$output->setHttpResponseCode(Http::STATUS_BAD_REQUEST);
61
-			}
62
-		}
63
-	}
48
+    /**
49
+     * Streams the file using readfile
50
+     *
51
+     * @param IOutput $output a small wrapper that handles output
52
+     * @since 8.1.0
53
+     */
54
+    public function callback (IOutput $output) {
55
+        // handle caching
56
+        if ($output->getHttpResponseCode() !== Http::STATUS_NOT_MODIFIED) {
57
+            if (!(is_resource($this->filePath) || file_exists($this->filePath))) {
58
+                $output->setHttpResponseCode(Http::STATUS_NOT_FOUND);
59
+            } elseif ($output->setReadfile($this->filePath) === false) {
60
+                $output->setHttpResponseCode(Http::STATUS_BAD_REQUEST);
61
+            }
62
+        }
63
+    }
64 64
 
65 65
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -40,7 +40,7 @@  discard block
 block discarded – undo
40 40
 	 * @param string|resource $filePath the path to the file or a file handle which should be streamed
41 41
 	 * @since 8.1.0
42 42
 	 */
43
-	public function __construct ($filePath) {
43
+	public function __construct($filePath) {
44 44
 		$this->filePath = $filePath;
45 45
 	}
46 46
 
@@ -51,7 +51,7 @@  discard block
 block discarded – undo
51 51
 	 * @param IOutput $output a small wrapper that handles output
52 52
 	 * @since 8.1.0
53 53
 	 */
54
-	public function callback (IOutput $output) {
54
+	public function callback(IOutput $output) {
55 55
 		// handle caching
56 56
 		if ($output->getHttpResponseCode() !== Http::STATUS_NOT_MODIFIED) {
57 57
 			if (!(is_resource($this->filePath) || file_exists($this->filePath))) {
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/DavAclPlugin.php 4 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -47,6 +47,9 @@
 block discarded – undo
47 47
 		$this->allowUnauthenticatedAccess = false;
48 48
 	}
49 49
 
50
+	/**
51
+	 * @param string $privileges
52
+	 */
50 53
 	function checkPrivileges($uri, $privileges, $recursion = self::R_PARENT, $throwExceptions = true) {
51 54
 		$access = parent::checkPrivileges($uri, $privileges, $recursion, false);
52 55
 		if($access === false && $throwExceptions) {
Please login to merge, or discard this patch.
Unused Use Statements   -3 removed lines patch added patch discarded remove patch
@@ -25,14 +25,11 @@
 block discarded – undo
25 25
 
26 26
 use Sabre\CalDAV\Principal\User;
27 27
 use Sabre\DAV\Exception\NotFound;
28
-use Sabre\DAV\IFile;
29 28
 use Sabre\DAV\INode;
30 29
 use \Sabre\DAV\PropFind;
31 30
 use \Sabre\DAV\PropPatch;
32
-use Sabre\DAVACL\Exception\NeedPrivileges;
33 31
 use \Sabre\HTTP\RequestInterface;
34 32
 use \Sabre\HTTP\ResponseInterface;
35
-use Sabre\HTTP\URLUtil;
36 33
 
37 34
 /**
38 35
  * Class DavAclPlugin is a wrapper around \Sabre\DAVACL\Plugin that returns 404
Please login to merge, or discard this patch.
Indentation   +41 added lines, -41 removed lines patch added patch discarded remove patch
@@ -43,50 +43,50 @@
 block discarded – undo
43 43
  * @package OCA\DAV\Connector\Sabre
44 44
  */
45 45
 class DavAclPlugin extends \Sabre\DAVACL\Plugin {
46
-	public function __construct() {
47
-		$this->hideNodesFromListings = true;
48
-		$this->allowUnauthenticatedAccess = false;
49
-	}
46
+    public function __construct() {
47
+        $this->hideNodesFromListings = true;
48
+        $this->allowUnauthenticatedAccess = false;
49
+    }
50 50
 
51
-	function checkPrivileges($uri, $privileges, $recursion = self::R_PARENT, $throwExceptions = true) {
52
-		$access = parent::checkPrivileges($uri, $privileges, $recursion, false);
53
-		if($access === false && $throwExceptions) {
54
-			/** @var INode $node */
55
-			$node = $this->server->tree->getNodeForPath($uri);
51
+    function checkPrivileges($uri, $privileges, $recursion = self::R_PARENT, $throwExceptions = true) {
52
+        $access = parent::checkPrivileges($uri, $privileges, $recursion, false);
53
+        if($access === false && $throwExceptions) {
54
+            /** @var INode $node */
55
+            $node = $this->server->tree->getNodeForPath($uri);
56 56
 
57
-			switch(get_class($node)) {
58
-				case 'OCA\DAV\CardDAV\AddressBook':
59
-					$type = 'Addressbook';
60
-					break;
61
-				default:
62
-					$type = 'Node';
63
-					break;
64
-			}
65
-			throw new NotFound(
66
-				sprintf(
67
-					"%s with name '%s' could not be found",
68
-					$type,
69
-					$node->getName()
70
-				)
71
-			);
72
-		}
57
+            switch(get_class($node)) {
58
+                case 'OCA\DAV\CardDAV\AddressBook':
59
+                    $type = 'Addressbook';
60
+                    break;
61
+                default:
62
+                    $type = 'Node';
63
+                    break;
64
+            }
65
+            throw new NotFound(
66
+                sprintf(
67
+                    "%s with name '%s' could not be found",
68
+                    $type,
69
+                    $node->getName()
70
+                )
71
+            );
72
+        }
73 73
 
74
-		return $access;
75
-	}
74
+        return $access;
75
+    }
76 76
 
77
-	public function propFind(PropFind $propFind, INode $node) {
78
-		// If the node is neither readable nor writable then fail unless its of
79
-		// the standard user-principal
80
-		if(!($node instanceof User)) {
81
-			$path = $propFind->getPath();
82
-			$readPermissions = $this->checkPrivileges($path, '{DAV:}read', self::R_PARENT, false);
83
-			$writePermissions = $this->checkPrivileges($path, '{DAV:}write', self::R_PARENT, false);
84
-			if ($readPermissions === false && $writePermissions === false) {
85
-				$this->checkPrivileges($path, '{DAV:}read', self::R_PARENT, true);
86
-				$this->checkPrivileges($path, '{DAV:}write', self::R_PARENT, true);
87
-			}
88
-		}
77
+    public function propFind(PropFind $propFind, INode $node) {
78
+        // If the node is neither readable nor writable then fail unless its of
79
+        // the standard user-principal
80
+        if(!($node instanceof User)) {
81
+            $path = $propFind->getPath();
82
+            $readPermissions = $this->checkPrivileges($path, '{DAV:}read', self::R_PARENT, false);
83
+            $writePermissions = $this->checkPrivileges($path, '{DAV:}write', self::R_PARENT, false);
84
+            if ($readPermissions === false && $writePermissions === false) {
85
+                $this->checkPrivileges($path, '{DAV:}read', self::R_PARENT, true);
86
+                $this->checkPrivileges($path, '{DAV:}write', self::R_PARENT, true);
87
+            }
88
+        }
89 89
 
90
-		return parent::propFind($propFind, $node);
91
-	}
90
+        return parent::propFind($propFind, $node);
91
+    }
92 92
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -50,11 +50,11 @@  discard block
 block discarded – undo
50 50
 
51 51
 	function checkPrivileges($uri, $privileges, $recursion = self::R_PARENT, $throwExceptions = true) {
52 52
 		$access = parent::checkPrivileges($uri, $privileges, $recursion, false);
53
-		if($access === false && $throwExceptions) {
53
+		if ($access === false && $throwExceptions) {
54 54
 			/** @var INode $node */
55 55
 			$node = $this->server->tree->getNodeForPath($uri);
56 56
 
57
-			switch(get_class($node)) {
57
+			switch (get_class($node)) {
58 58
 				case 'OCA\DAV\CardDAV\AddressBook':
59 59
 					$type = 'Addressbook';
60 60
 					break;
@@ -77,7 +77,7 @@  discard block
 block discarded – undo
77 77
 	public function propFind(PropFind $propFind, INode $node) {
78 78
 		// If the node is neither readable nor writable then fail unless its of
79 79
 		// the standard user-principal
80
-		if(!($node instanceof User)) {
80
+		if (!($node instanceof User)) {
81 81
 			$path = $propFind->getPath();
82 82
 			$readPermissions = $this->checkPrivileges($path, '{DAV:}read', self::R_PARENT, false);
83 83
 			$writePermissions = $this->checkPrivileges($path, '{DAV:}write', self::R_PARENT, false);
Please login to merge, or discard this patch.
lib/private/Files/Storage/Storage.php 2 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -100,6 +100,7 @@  discard block
 block discarded – undo
100 100
 	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
101 101
 	 * @param \OCP\Lock\ILockingProvider $provider
102 102
 	 * @throws \OCP\Lock\LockedException
103
+	 * @return void
103 104
 	 */
104 105
 	public function acquireLock($path, $type, ILockingProvider $provider);
105 106
 
@@ -108,6 +109,7 @@  discard block
 block discarded – undo
108 109
 	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
109 110
 	 * @param \OCP\Lock\ILockingProvider $provider
110 111
 	 * @throws \OCP\Lock\LockedException
112
+	 * @return void
111 113
 	 */
112 114
 	public function releaseLock($path, $type, ILockingProvider $provider);
113 115
 
@@ -116,6 +118,7 @@  discard block
 block discarded – undo
116 118
 	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
117 119
 	 * @param \OCP\Lock\ILockingProvider $provider
118 120
 	 * @throws \OCP\Lock\LockedException
121
+	 * @return void
119 122
 	 */
120 123
 	public function changeLock($path, $type, ILockingProvider $provider);
121 124
 }
Please login to merge, or discard this patch.
Indentation   +75 added lines, -75 removed lines patch added patch discarded remove patch
@@ -32,90 +32,90 @@
 block discarded – undo
32 32
  */
33 33
 interface Storage extends \OCP\Files\Storage {
34 34
 
35
-	/**
36
-	 * get a cache instance for the storage
37
-	 *
38
-	 * @param string $path
39
-	 * @param \OC\Files\Storage\Storage (optional) the storage to pass to the cache
40
-	 * @return \OC\Files\Cache\Cache
41
-	 */
42
-	public function getCache($path = '', $storage = null);
35
+    /**
36
+     * get a cache instance for the storage
37
+     *
38
+     * @param string $path
39
+     * @param \OC\Files\Storage\Storage (optional) the storage to pass to the cache
40
+     * @return \OC\Files\Cache\Cache
41
+     */
42
+    public function getCache($path = '', $storage = null);
43 43
 
44
-	/**
45
-	 * get a scanner instance for the storage
46
-	 *
47
-	 * @param string $path
48
-	 * @param \OC\Files\Storage\Storage (optional) the storage to pass to the scanner
49
-	 * @return \OC\Files\Cache\Scanner
50
-	 */
51
-	public function getScanner($path = '', $storage = null);
44
+    /**
45
+     * get a scanner instance for the storage
46
+     *
47
+     * @param string $path
48
+     * @param \OC\Files\Storage\Storage (optional) the storage to pass to the scanner
49
+     * @return \OC\Files\Cache\Scanner
50
+     */
51
+    public function getScanner($path = '', $storage = null);
52 52
 
53 53
 
54
-	/**
55
-	 * get the user id of the owner of a file or folder
56
-	 *
57
-	 * @param string $path
58
-	 * @return string
59
-	 */
60
-	public function getOwner($path);
54
+    /**
55
+     * get the user id of the owner of a file or folder
56
+     *
57
+     * @param string $path
58
+     * @return string
59
+     */
60
+    public function getOwner($path);
61 61
 
62
-	/**
63
-	 * get a watcher instance for the cache
64
-	 *
65
-	 * @param string $path
66
-	 * @param \OC\Files\Storage\Storage (optional) the storage to pass to the watcher
67
-	 * @return \OC\Files\Cache\Watcher
68
-	 */
69
-	public function getWatcher($path = '', $storage = null);
62
+    /**
63
+     * get a watcher instance for the cache
64
+     *
65
+     * @param string $path
66
+     * @param \OC\Files\Storage\Storage (optional) the storage to pass to the watcher
67
+     * @return \OC\Files\Cache\Watcher
68
+     */
69
+    public function getWatcher($path = '', $storage = null);
70 70
 
71
-	/**
72
-	 * get a propagator instance for the cache
73
-	 *
74
-	 * @param \OC\Files\Storage\Storage (optional) the storage to pass to the watcher
75
-	 * @return \OC\Files\Cache\Propagator
76
-	 */
77
-	public function getPropagator($storage = null);
71
+    /**
72
+     * get a propagator instance for the cache
73
+     *
74
+     * @param \OC\Files\Storage\Storage (optional) the storage to pass to the watcher
75
+     * @return \OC\Files\Cache\Propagator
76
+     */
77
+    public function getPropagator($storage = null);
78 78
 
79
-	/**
80
-	 * get a updater instance for the cache
81
-	 *
82
-	 * @param \OC\Files\Storage\Storage (optional) the storage to pass to the watcher
83
-	 * @return \OC\Files\Cache\Updater
84
-	 */
85
-	public function getUpdater($storage = null);
79
+    /**
80
+     * get a updater instance for the cache
81
+     *
82
+     * @param \OC\Files\Storage\Storage (optional) the storage to pass to the watcher
83
+     * @return \OC\Files\Cache\Updater
84
+     */
85
+    public function getUpdater($storage = null);
86 86
 
87
-	/**
88
-	 * @return \OC\Files\Cache\Storage
89
-	 */
90
-	public function getStorageCache();
87
+    /**
88
+     * @return \OC\Files\Cache\Storage
89
+     */
90
+    public function getStorageCache();
91 91
 
92
-	/**
93
-	 * @param string $path
94
-	 * @return array
95
-	 */
96
-	public function getMetaData($path);
92
+    /**
93
+     * @param string $path
94
+     * @return array
95
+     */
96
+    public function getMetaData($path);
97 97
 
98
-	/**
99
-	 * @param string $path The path of the file to acquire the lock for
100
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
101
-	 * @param \OCP\Lock\ILockingProvider $provider
102
-	 * @throws \OCP\Lock\LockedException
103
-	 */
104
-	public function acquireLock($path, $type, ILockingProvider $provider);
98
+    /**
99
+     * @param string $path The path of the file to acquire the lock for
100
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
101
+     * @param \OCP\Lock\ILockingProvider $provider
102
+     * @throws \OCP\Lock\LockedException
103
+     */
104
+    public function acquireLock($path, $type, ILockingProvider $provider);
105 105
 
106
-	/**
107
-	 * @param string $path The path of the file to release the lock for
108
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
109
-	 * @param \OCP\Lock\ILockingProvider $provider
110
-	 * @throws \OCP\Lock\LockedException
111
-	 */
112
-	public function releaseLock($path, $type, ILockingProvider $provider);
106
+    /**
107
+     * @param string $path The path of the file to release the lock for
108
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
109
+     * @param \OCP\Lock\ILockingProvider $provider
110
+     * @throws \OCP\Lock\LockedException
111
+     */
112
+    public function releaseLock($path, $type, ILockingProvider $provider);
113 113
 
114
-	/**
115
-	 * @param string $path The path of the file to change the lock for
116
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
117
-	 * @param \OCP\Lock\ILockingProvider $provider
118
-	 * @throws \OCP\Lock\LockedException
119
-	 */
120
-	public function changeLock($path, $type, ILockingProvider $provider);
114
+    /**
115
+     * @param string $path The path of the file to change the lock for
116
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
117
+     * @param \OCP\Lock\ILockingProvider $provider
118
+     * @throws \OCP\Lock\LockedException
119
+     */
120
+    public function changeLock($path, $type, ILockingProvider $provider);
121 121
 }
Please login to merge, or discard this patch.
lib/private/AppFramework/DependencyInjection/DIContainer.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -46,7 +46,6 @@
 block discarded – undo
46 46
 use OC\AppFramework\Utility\TimeFactory;
47 47
 use OC\Core\Middleware\TwoFactorMiddleware;
48 48
 use OC\RichObjectStrings\Validator;
49
-use OC\Security\Bruteforce\Throttler;
50 49
 use OCP\AppFramework\IApi;
51 50
 use OCP\AppFramework\IAppContainer;
52 51
 use OCP\Federation\ICloudIdManager;
Please login to merge, or discard this patch.
Indentation   +483 added lines, -483 removed lines patch added patch discarded remove patch
@@ -56,510 +56,510 @@
 block discarded – undo
56 56
 
57 57
 class DIContainer extends SimpleContainer implements IAppContainer {
58 58
 
59
-	/**
60
-	 * @var array
61
-	 */
62
-	private $middleWares = array();
63
-
64
-	/**
65
-	 * Put your class dependencies in here
66
-	 * @param string $appName the name of the app
67
-	 */
68
-	public function __construct($appName, $urlParams = array()){
69
-		parent::__construct();
70
-		$this['AppName'] = $appName;
71
-		$this['urlParams'] = $urlParams;
72
-
73
-		/** @var \OC\ServerContainer $server */
74
-		$server = $this->getServer();
75
-		$server->registerAppContainer($appName, $this);
76
-
77
-		// aliases
78
-		$this->registerAlias('appName', 'AppName');
79
-		$this->registerAlias('webRoot', 'WebRoot');
80
-		$this->registerAlias('userId', 'UserId');
81
-
82
-		/**
83
-		 * Core services
84
-		 */
85
-		$this->registerService('OCP\\IAppConfig', function($c) {
86
-			return $this->getServer()->getAppConfig();
87
-		});
88
-
89
-		$this->registerService('OCP\\App\\IAppManager', function($c) {
90
-			return $this->getServer()->getAppManager();
91
-		});
92
-
93
-		$this->registerService('OCP\\AppFramework\\Http\\IOutput', function($c){
94
-			return new Output($this->getServer()->getWebRoot());
95
-		});
96
-
97
-		$this->registerService(\OCP\Authentication\LoginCredentials\IStore::class, function() {
98
-			return $this->getServer()->query(\OCP\Authentication\LoginCredentials\IStore::class);
99
-		});
100
-
101
-		$this->registerService('OCP\\IAvatarManager', function($c) {
102
-			return $this->getServer()->getAvatarManager();
103
-		});
104
-
105
-		$this->registerService('OCP\\Activity\\IManager', function($c) {
106
-			return $this->getServer()->getActivityManager();
107
-		});
108
-		$this->registerService(\OCP\Activity\IEventMerger::class, function($c) {
109
-			return $this->getServer()->query(\OCP\Activity\IEventMerger::class);
110
-		});
111
-
112
-		$this->registerService('OCP\\ICache', function($c) {
113
-			return $this->getServer()->getCache();
114
-		});
115
-
116
-		$this->registerService('OCP\\ICacheFactory', function($c) {
117
-			return $this->getServer()->getMemCacheFactory();
118
-		});
119
-
120
-		$this->registerService('OC\\CapabilitiesManager', function($c) {
121
-			return $this->getServer()->getCapabilitiesManager();
122
-		});
123
-
124
-		$this->registerService('OCP\Comments\ICommentsManager', function($c) {
125
-			return $this->getServer()->getCommentsManager();
126
-		});
127
-
128
-		$this->registerService('OCP\\IConfig', function($c) {
129
-			return $this->getServer()->getConfig();
130
-		});
131
-
132
-		$this->registerService('OCP\\Contacts\\IManager', function($c) {
133
-			return $this->getServer()->getContactsManager();
134
-		});
135
-
136
-		$this->registerService('OCP\\IDateTimeZone', function($c) {
137
-			return $this->getServer()->getDateTimeZone();
138
-		});
139
-
140
-		$this->registerService('OCP\\IDateTimeFormatter', function($c) {
141
-			return $this->getServer()->getDateTimeFormatter();
142
-		});
143
-
144
-		$this->registerService('OCP\\IDBConnection', function($c) {
145
-			return $this->getServer()->getDatabaseConnection();
146
-		});
147
-
148
-		$this->registerService('OCP\\Diagnostics\\IEventLogger', function($c) {
149
-			return $this->getServer()->getEventLogger();
150
-		});
151
-
152
-		$this->registerService('OCP\\Diagnostics\\IQueryLogger', function($c) {
153
-			return $this->getServer()->getQueryLogger();
154
-		});
155
-
156
-		$this->registerService(ICloudIdManager::class, function($c) {
157
-			return $this->getServer()->getCloudIdManager();
158
-		});
159
-
160
-		$this->registerService('OCP\\Files\\IMimeTypeDetector', function($c) {
161
-			return $this->getServer()->getMimeTypeDetector();
162
-		});
163
-
164
-		$this->registerService('OCP\\Files\\Config\\IMountProviderCollection', function($c) {
165
-			return $this->getServer()->getMountProviderCollection();
166
-		});
167
-
168
-		$this->registerService('OCP\\Files\\Config\\IUserMountCache', function($c) {
169
-			return $this->getServer()->getUserMountCache();
170
-		});
59
+    /**
60
+     * @var array
61
+     */
62
+    private $middleWares = array();
63
+
64
+    /**
65
+     * Put your class dependencies in here
66
+     * @param string $appName the name of the app
67
+     */
68
+    public function __construct($appName, $urlParams = array()){
69
+        parent::__construct();
70
+        $this['AppName'] = $appName;
71
+        $this['urlParams'] = $urlParams;
72
+
73
+        /** @var \OC\ServerContainer $server */
74
+        $server = $this->getServer();
75
+        $server->registerAppContainer($appName, $this);
76
+
77
+        // aliases
78
+        $this->registerAlias('appName', 'AppName');
79
+        $this->registerAlias('webRoot', 'WebRoot');
80
+        $this->registerAlias('userId', 'UserId');
81
+
82
+        /**
83
+         * Core services
84
+         */
85
+        $this->registerService('OCP\\IAppConfig', function($c) {
86
+            return $this->getServer()->getAppConfig();
87
+        });
88
+
89
+        $this->registerService('OCP\\App\\IAppManager', function($c) {
90
+            return $this->getServer()->getAppManager();
91
+        });
92
+
93
+        $this->registerService('OCP\\AppFramework\\Http\\IOutput', function($c){
94
+            return new Output($this->getServer()->getWebRoot());
95
+        });
96
+
97
+        $this->registerService(\OCP\Authentication\LoginCredentials\IStore::class, function() {
98
+            return $this->getServer()->query(\OCP\Authentication\LoginCredentials\IStore::class);
99
+        });
100
+
101
+        $this->registerService('OCP\\IAvatarManager', function($c) {
102
+            return $this->getServer()->getAvatarManager();
103
+        });
104
+
105
+        $this->registerService('OCP\\Activity\\IManager', function($c) {
106
+            return $this->getServer()->getActivityManager();
107
+        });
108
+        $this->registerService(\OCP\Activity\IEventMerger::class, function($c) {
109
+            return $this->getServer()->query(\OCP\Activity\IEventMerger::class);
110
+        });
111
+
112
+        $this->registerService('OCP\\ICache', function($c) {
113
+            return $this->getServer()->getCache();
114
+        });
115
+
116
+        $this->registerService('OCP\\ICacheFactory', function($c) {
117
+            return $this->getServer()->getMemCacheFactory();
118
+        });
119
+
120
+        $this->registerService('OC\\CapabilitiesManager', function($c) {
121
+            return $this->getServer()->getCapabilitiesManager();
122
+        });
123
+
124
+        $this->registerService('OCP\Comments\ICommentsManager', function($c) {
125
+            return $this->getServer()->getCommentsManager();
126
+        });
127
+
128
+        $this->registerService('OCP\\IConfig', function($c) {
129
+            return $this->getServer()->getConfig();
130
+        });
131
+
132
+        $this->registerService('OCP\\Contacts\\IManager', function($c) {
133
+            return $this->getServer()->getContactsManager();
134
+        });
135
+
136
+        $this->registerService('OCP\\IDateTimeZone', function($c) {
137
+            return $this->getServer()->getDateTimeZone();
138
+        });
139
+
140
+        $this->registerService('OCP\\IDateTimeFormatter', function($c) {
141
+            return $this->getServer()->getDateTimeFormatter();
142
+        });
143
+
144
+        $this->registerService('OCP\\IDBConnection', function($c) {
145
+            return $this->getServer()->getDatabaseConnection();
146
+        });
147
+
148
+        $this->registerService('OCP\\Diagnostics\\IEventLogger', function($c) {
149
+            return $this->getServer()->getEventLogger();
150
+        });
151
+
152
+        $this->registerService('OCP\\Diagnostics\\IQueryLogger', function($c) {
153
+            return $this->getServer()->getQueryLogger();
154
+        });
155
+
156
+        $this->registerService(ICloudIdManager::class, function($c) {
157
+            return $this->getServer()->getCloudIdManager();
158
+        });
159
+
160
+        $this->registerService('OCP\\Files\\IMimeTypeDetector', function($c) {
161
+            return $this->getServer()->getMimeTypeDetector();
162
+        });
163
+
164
+        $this->registerService('OCP\\Files\\Config\\IMountProviderCollection', function($c) {
165
+            return $this->getServer()->getMountProviderCollection();
166
+        });
167
+
168
+        $this->registerService('OCP\\Files\\Config\\IUserMountCache', function($c) {
169
+            return $this->getServer()->getUserMountCache();
170
+        });
171 171
 
172
-		$this->registerService('OCP\\Files\\IRootFolder', function($c) {
173
-			return $this->getServer()->getRootFolder();
174
-		});
172
+        $this->registerService('OCP\\Files\\IRootFolder', function($c) {
173
+            return $this->getServer()->getRootFolder();
174
+        });
175 175
 
176
-		$this->registerService('OCP\\Files\\Folder', function() {
177
-			return $this->getServer()->getUserFolder();
178
-		});
176
+        $this->registerService('OCP\\Files\\Folder', function() {
177
+            return $this->getServer()->getUserFolder();
178
+        });
179 179
 
180
-		$this->registerService('OCP\\Http\\Client\\IClientService', function($c) {
181
-			return $this->getServer()->getHTTPClientService();
182
-		});
180
+        $this->registerService('OCP\\Http\\Client\\IClientService', function($c) {
181
+            return $this->getServer()->getHTTPClientService();
182
+        });
183 183
 
184
-		$this->registerService(IAppData::class, function (SimpleContainer $c) {
185
-			return $this->getServer()->getAppDataDir($c->query('AppName'));
186
-		});
184
+        $this->registerService(IAppData::class, function (SimpleContainer $c) {
185
+            return $this->getServer()->getAppDataDir($c->query('AppName'));
186
+        });
187 187
 
188
-		$this->registerService('OCP\\IGroupManager', function($c) {
189
-			return $this->getServer()->getGroupManager();
190
-		});
188
+        $this->registerService('OCP\\IGroupManager', function($c) {
189
+            return $this->getServer()->getGroupManager();
190
+        });
191 191
 
192
-		$this->registerService('OCP\\Http\\Client\\IClientService', function() {
193
-			return $this->getServer()->getHTTPClientService();
194
-		});
192
+        $this->registerService('OCP\\Http\\Client\\IClientService', function() {
193
+            return $this->getServer()->getHTTPClientService();
194
+        });
195 195
 
196
-		$this->registerService('OCP\\IL10N', function($c) {
197
-			return $this->getServer()->getL10N($c->query('AppName'));
198
-		});
196
+        $this->registerService('OCP\\IL10N', function($c) {
197
+            return $this->getServer()->getL10N($c->query('AppName'));
198
+        });
199 199
 
200
-		$this->registerService('OCP\\L10N\\IFactory', function($c) {
201
-			return $this->getServer()->getL10NFactory();
202
-		});
200
+        $this->registerService('OCP\\L10N\\IFactory', function($c) {
201
+            return $this->getServer()->getL10NFactory();
202
+        });
203 203
 
204
-		$this->registerService('OCP\\ILogger', function($c) {
205
-			return $this->getServer()->getLogger();
206
-		});
204
+        $this->registerService('OCP\\ILogger', function($c) {
205
+            return $this->getServer()->getLogger();
206
+        });
207 207
 
208
-		$this->registerService('OCP\\BackgroundJob\\IJobList', function($c) {
209
-			return $this->getServer()->getJobList();
210
-		});
208
+        $this->registerService('OCP\\BackgroundJob\\IJobList', function($c) {
209
+            return $this->getServer()->getJobList();
210
+        });
211 211
 
212
-		$this->registerAlias('OCP\\AppFramework\\Utility\\IControllerMethodReflector', 'OC\AppFramework\Utility\ControllerMethodReflector');
213
-		$this->registerAlias('ControllerMethodReflector', 'OCP\\AppFramework\\Utility\\IControllerMethodReflector');
212
+        $this->registerAlias('OCP\\AppFramework\\Utility\\IControllerMethodReflector', 'OC\AppFramework\Utility\ControllerMethodReflector');
213
+        $this->registerAlias('ControllerMethodReflector', 'OCP\\AppFramework\\Utility\\IControllerMethodReflector');
214 214
 
215
-		$this->registerService('OCP\\Files\\IMimeTypeDetector', function($c) {
216
-			return $this->getServer()->getMimeTypeDetector();
217
-		});
215
+        $this->registerService('OCP\\Files\\IMimeTypeDetector', function($c) {
216
+            return $this->getServer()->getMimeTypeDetector();
217
+        });
218 218
 
219
-		$this->registerService('OCP\\Mail\\IMailer', function() {
220
-			return $this->getServer()->getMailer();
221
-		});
219
+        $this->registerService('OCP\\Mail\\IMailer', function() {
220
+            return $this->getServer()->getMailer();
221
+        });
222 222
 
223
-		$this->registerService('OCP\\INavigationManager', function($c) {
224
-			return $this->getServer()->getNavigationManager();
225
-		});
223
+        $this->registerService('OCP\\INavigationManager', function($c) {
224
+            return $this->getServer()->getNavigationManager();
225
+        });
226 226
 
227
-		$this->registerService('OCP\\Notification\IManager', function($c) {
228
-			return $this->getServer()->getNotificationManager();
229
-		});
227
+        $this->registerService('OCP\\Notification\IManager', function($c) {
228
+            return $this->getServer()->getNotificationManager();
229
+        });
230 230
 
231
-		$this->registerService('OCP\\IPreview', function($c) {
232
-			return $this->getServer()->getPreviewManager();
233
-		});
231
+        $this->registerService('OCP\\IPreview', function($c) {
232
+            return $this->getServer()->getPreviewManager();
233
+        });
234 234
 
235
-		$this->registerService('OCP\\IRequest', function () {
236
-			return $this->getServer()->getRequest();
237
-		});
238
-		$this->registerAlias('Request', 'OCP\\IRequest');
235
+        $this->registerService('OCP\\IRequest', function () {
236
+            return $this->getServer()->getRequest();
237
+        });
238
+        $this->registerAlias('Request', 'OCP\\IRequest');
239 239
 
240
-		$this->registerService('OCP\\ITagManager', function($c) {
241
-			return $this->getServer()->getTagManager();
242
-		});
240
+        $this->registerService('OCP\\ITagManager', function($c) {
241
+            return $this->getServer()->getTagManager();
242
+        });
243 243
 
244
-		$this->registerService('OCP\\ITempManager', function($c) {
245
-			return $this->getServer()->getTempManager();
246
-		});
244
+        $this->registerService('OCP\\ITempManager', function($c) {
245
+            return $this->getServer()->getTempManager();
246
+        });
247 247
 
248
-		$this->registerAlias('OCP\\AppFramework\\Utility\\ITimeFactory', 'OC\AppFramework\Utility\TimeFactory');
249
-		$this->registerAlias('TimeFactory', 'OCP\\AppFramework\\Utility\\ITimeFactory');
248
+        $this->registerAlias('OCP\\AppFramework\\Utility\\ITimeFactory', 'OC\AppFramework\Utility\TimeFactory');
249
+        $this->registerAlias('TimeFactory', 'OCP\\AppFramework\\Utility\\ITimeFactory');
250 250
 
251 251
 
252
-		$this->registerService('OCP\\Route\\IRouter', function($c) {
253
-			return $this->getServer()->getRouter();
254
-		});
255
-
256
-		$this->registerService('OCP\\ISearch', function($c) {
257
-			return $this->getServer()->getSearch();
258
-		});
252
+        $this->registerService('OCP\\Route\\IRouter', function($c) {
253
+            return $this->getServer()->getRouter();
254
+        });
255
+
256
+        $this->registerService('OCP\\ISearch', function($c) {
257
+            return $this->getServer()->getSearch();
258
+        });
259 259
 
260
-		$this->registerService('OCP\\ISearch', function($c) {
261
-			return $this->getServer()->getSearch();
262
-		});
263
-
264
-		$this->registerService('OCP\\Security\\ICrypto', function($c) {
265
-			return $this->getServer()->getCrypto();
266
-		});
267
-
268
-		$this->registerService('OCP\\Security\\IHasher', function($c) {
269
-			return $this->getServer()->getHasher();
270
-		});
271
-
272
-		$this->registerService('OCP\\Security\\ICredentialsManager', function($c) {
273
-			return $this->getServer()->getCredentialsManager();
274
-		});
275
-
276
-		$this->registerService('OCP\\Security\\ISecureRandom', function($c) {
277
-			return $this->getServer()->getSecureRandom();
278
-		});
279
-
280
-		$this->registerService('OCP\\Share\\IManager', function($c) {
281
-			return $this->getServer()->getShareManager();
282
-		});
283
-
284
-		$this->registerService('OCP\\SystemTag\\ISystemTagManager', function() {
285
-			return $this->getServer()->getSystemTagManager();
286
-		});
287
-
288
-		$this->registerService('OCP\\SystemTag\\ISystemTagObjectMapper', function() {
289
-			return $this->getServer()->getSystemTagObjectMapper();
290
-		});
291
-
292
-		$this->registerService('OCP\\IURLGenerator', function($c) {
293
-			return $this->getServer()->getURLGenerator();
294
-		});
295
-
296
-		$this->registerService('OCP\\IUserManager', function($c) {
297
-			return $this->getServer()->getUserManager();
298
-		});
299
-
300
-		$this->registerService('OCP\\IUserSession', function($c) {
301
-			return $this->getServer()->getUserSession();
302
-		});
303
-		$this->registerAlias(\OC\User\Session::class, \OCP\IUserSession::class);
304
-
305
-		$this->registerService('OCP\\ISession', function($c) {
306
-			return $this->getServer()->getSession();
307
-		});
308
-
309
-		$this->registerService('OCP\\Security\\IContentSecurityPolicyManager', function($c) {
310
-			return $this->getServer()->getContentSecurityPolicyManager();
311
-		});
312
-
313
-		$this->registerService('ServerContainer', function ($c) {
314
-			return $this->getServer();
315
-		});
316
-		$this->registerAlias('OCP\\IServerContainer', 'ServerContainer');
317
-
318
-		$this->registerService('Symfony\Component\EventDispatcher\EventDispatcherInterface', function ($c) {
319
-			return $this->getServer()->getEventDispatcher();
320
-		});
321
-
322
-		$this->registerService('OCP\WorkflowEngine\IManager', function ($c) {
323
-			return $c->query('OCA\WorkflowEngine\Manager');
324
-		});
325
-
326
-		$this->registerService('OCP\\AppFramework\\IAppContainer', function ($c) {
327
-			return $c;
328
-		});
329
-		$this->registerService(IMountManager::class, function () {
330
-			return $this->getServer()->getMountManager();
331
-		});
332
-
333
-		// commonly used attributes
334
-		$this->registerService('UserId', function ($c) {
335
-			return $c->query('OCP\\IUserSession')->getSession()->get('user_id');
336
-		});
337
-
338
-		$this->registerService('WebRoot', function ($c) {
339
-			return $c->query('ServerContainer')->getWebRoot();
340
-		});
341
-
342
-		$this->registerService('OCP\Encryption\IManager', function ($c) {
343
-			return $this->getServer()->getEncryptionManager();
344
-		});
345
-
346
-		$this->registerService(IValidator::class, function($c) {
347
-			return $c->query(Validator::class);
348
-		});
349
-
350
-		$this->registerService(\OC\Security\IdentityProof\Manager::class, function ($c) {
351
-			return new \OC\Security\IdentityProof\Manager(
352
-				$this->getServer()->getAppDataDir('identityproof'),
353
-				$this->getServer()->getCrypto()
354
-			);
355
-		});
356
-
357
-
358
-		/**
359
-		 * App Framework APIs
360
-		 */
361
-		$this->registerService('API', function($c){
362
-			$c->query('OCP\\ILogger')->debug(
363
-				'Accessing the API class is deprecated! Use the appropriate ' .
364
-				'services instead!'
365
-			);
366
-			return new API($c['AppName']);
367
-		});
368
-
369
-		$this->registerService('Protocol', function($c){
370
-			/** @var \OC\Server $server */
371
-			$server = $c->query('ServerContainer');
372
-			$protocol = $server->getRequest()->getHttpProtocol();
373
-			return new Http($_SERVER, $protocol);
374
-		});
375
-
376
-		$this->registerService('Dispatcher', function($c) {
377
-			return new Dispatcher(
378
-				$c['Protocol'],
379
-				$c['MiddlewareDispatcher'],
380
-				$c['ControllerMethodReflector'],
381
-				$c['Request']
382
-			);
383
-		});
384
-
385
-		/**
386
-		 * App Framework default arguments
387
-		 */
388
-		$this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
389
-		$this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
390
-		$this->registerParameter('corsMaxAge', 1728000);
391
-
392
-		/**
393
-		 * Middleware
394
-		 */
395
-		$app = $this;
396
-		$this->registerService('SecurityMiddleware', function($c) use ($app){
397
-			/** @var \OC\Server $server */
398
-			$server = $app->getServer();
399
-
400
-			return new SecurityMiddleware(
401
-				$c['Request'],
402
-				$c['ControllerMethodReflector'],
403
-				$server->getNavigationManager(),
404
-				$server->getURLGenerator(),
405
-				$server->getLogger(),
406
-				$server->getSession(),
407
-				$c['AppName'],
408
-				$app->isLoggedIn(),
409
-				$app->isAdminUser(),
410
-				$server->getContentSecurityPolicyManager(),
411
-				$server->getCsrfTokenManager(),
412
-				$server->getContentSecurityPolicyNonceManager(),
413
-				$server->getBruteForceThrottler()
414
-			);
415
-
416
-		});
417
-
418
-		$this->registerService('CORSMiddleware', function($c) {
419
-			return new CORSMiddleware(
420
-				$c['Request'],
421
-				$c['ControllerMethodReflector'],
422
-				$c['OCP\IUserSession'],
423
-				$c->getServer()->getBruteForceThrottler()
424
-			);
425
-		});
426
-
427
-		$this->registerService('SessionMiddleware', function($c) use ($app) {
428
-			return new SessionMiddleware(
429
-				$c['Request'],
430
-				$c['ControllerMethodReflector'],
431
-				$app->getServer()->getSession()
432
-			);
433
-		});
434
-
435
-		$this->registerService('TwoFactorMiddleware', function (SimpleContainer $c) use ($app) {
436
-			$twoFactorManager = $c->getServer()->getTwoFactorAuthManager();
437
-			$userSession = $app->getServer()->getUserSession();
438
-			$session = $app->getServer()->getSession();
439
-			$urlGenerator = $app->getServer()->getURLGenerator();
440
-			$reflector = $c['ControllerMethodReflector'];
441
-			$request = $app->getServer()->getRequest();
442
-			return new TwoFactorMiddleware($twoFactorManager, $userSession, $session, $urlGenerator, $reflector, $request);
443
-		});
444
-
445
-		$this->registerService('OCSMiddleware', function (SimpleContainer $c) {
446
-			return new OCSMiddleware(
447
-				$c['Request']
448
-			);
449
-		});
450
-
451
-		$middleWares = &$this->middleWares;
452
-		$this->registerService('MiddlewareDispatcher', function($c) use (&$middleWares) {
453
-			$dispatcher = new MiddlewareDispatcher();
454
-			$dispatcher->registerMiddleware($c['CORSMiddleware']);
455
-			$dispatcher->registerMiddleware($c['OCSMiddleware']);
456
-			$dispatcher->registerMiddleware($c['SecurityMiddleware']);
457
-			$dispatcher->registerMiddleWare($c['TwoFactorMiddleware']);
458
-
459
-			foreach($middleWares as $middleWare) {
460
-				$dispatcher->registerMiddleware($c[$middleWare]);
461
-			}
462
-
463
-			$dispatcher->registerMiddleware($c['SessionMiddleware']);
464
-			return $dispatcher;
465
-		});
466
-
467
-	}
468
-
469
-
470
-	/**
471
-	 * @deprecated implements only deprecated methods
472
-	 * @return IApi
473
-	 */
474
-	function getCoreApi()
475
-	{
476
-		return $this->query('API');
477
-	}
478
-
479
-	/**
480
-	 * @return \OCP\IServerContainer
481
-	 */
482
-	function getServer()
483
-	{
484
-		return OC::$server;
485
-	}
486
-
487
-	/**
488
-	 * @param string $middleWare
489
-	 * @return boolean|null
490
-	 */
491
-	function registerMiddleWare($middleWare) {
492
-		array_push($this->middleWares, $middleWare);
493
-	}
494
-
495
-	/**
496
-	 * used to return the appname of the set application
497
-	 * @return string the name of your application
498
-	 */
499
-	function getAppName() {
500
-		return $this->query('AppName');
501
-	}
502
-
503
-	/**
504
-	 * @deprecated use IUserSession->isLoggedIn()
505
-	 * @return boolean
506
-	 */
507
-	function isLoggedIn() {
508
-		return \OC_User::isLoggedIn();
509
-	}
510
-
511
-	/**
512
-	 * @deprecated use IGroupManager->isAdmin($userId)
513
-	 * @return boolean
514
-	 */
515
-	function isAdminUser() {
516
-		$uid = $this->getUserId();
517
-		return \OC_User::isAdminUser($uid);
518
-	}
519
-
520
-	private function getUserId() {
521
-		return $this->getServer()->getSession()->get('user_id');
522
-	}
523
-
524
-	/**
525
-	 * @deprecated use the ILogger instead
526
-	 * @param string $message
527
-	 * @param string $level
528
-	 * @return mixed
529
-	 */
530
-	function log($message, $level) {
531
-		switch($level){
532
-			case 'debug':
533
-				$level = \OCP\Util::DEBUG;
534
-				break;
535
-			case 'info':
536
-				$level = \OCP\Util::INFO;
537
-				break;
538
-			case 'warn':
539
-				$level = \OCP\Util::WARN;
540
-				break;
541
-			case 'fatal':
542
-				$level = \OCP\Util::FATAL;
543
-				break;
544
-			default:
545
-				$level = \OCP\Util::ERROR;
546
-				break;
547
-		}
548
-		\OCP\Util::writeLog($this->getAppName(), $message, $level);
549
-	}
550
-
551
-	/**
552
-	 * Register a capability
553
-	 *
554
-	 * @param string $serviceName e.g. 'OCA\Files\Capabilities'
555
-	 */
556
-	public function registerCapability($serviceName) {
557
-		$this->query('OC\CapabilitiesManager')->registerCapability(function() use ($serviceName) {
558
-			return $this->query($serviceName);
559
-		});
560
-	}
561
-
562
-	public function query($name) {
563
-		return parent::query($name);
564
-	}
260
+        $this->registerService('OCP\\ISearch', function($c) {
261
+            return $this->getServer()->getSearch();
262
+        });
263
+
264
+        $this->registerService('OCP\\Security\\ICrypto', function($c) {
265
+            return $this->getServer()->getCrypto();
266
+        });
267
+
268
+        $this->registerService('OCP\\Security\\IHasher', function($c) {
269
+            return $this->getServer()->getHasher();
270
+        });
271
+
272
+        $this->registerService('OCP\\Security\\ICredentialsManager', function($c) {
273
+            return $this->getServer()->getCredentialsManager();
274
+        });
275
+
276
+        $this->registerService('OCP\\Security\\ISecureRandom', function($c) {
277
+            return $this->getServer()->getSecureRandom();
278
+        });
279
+
280
+        $this->registerService('OCP\\Share\\IManager', function($c) {
281
+            return $this->getServer()->getShareManager();
282
+        });
283
+
284
+        $this->registerService('OCP\\SystemTag\\ISystemTagManager', function() {
285
+            return $this->getServer()->getSystemTagManager();
286
+        });
287
+
288
+        $this->registerService('OCP\\SystemTag\\ISystemTagObjectMapper', function() {
289
+            return $this->getServer()->getSystemTagObjectMapper();
290
+        });
291
+
292
+        $this->registerService('OCP\\IURLGenerator', function($c) {
293
+            return $this->getServer()->getURLGenerator();
294
+        });
295
+
296
+        $this->registerService('OCP\\IUserManager', function($c) {
297
+            return $this->getServer()->getUserManager();
298
+        });
299
+
300
+        $this->registerService('OCP\\IUserSession', function($c) {
301
+            return $this->getServer()->getUserSession();
302
+        });
303
+        $this->registerAlias(\OC\User\Session::class, \OCP\IUserSession::class);
304
+
305
+        $this->registerService('OCP\\ISession', function($c) {
306
+            return $this->getServer()->getSession();
307
+        });
308
+
309
+        $this->registerService('OCP\\Security\\IContentSecurityPolicyManager', function($c) {
310
+            return $this->getServer()->getContentSecurityPolicyManager();
311
+        });
312
+
313
+        $this->registerService('ServerContainer', function ($c) {
314
+            return $this->getServer();
315
+        });
316
+        $this->registerAlias('OCP\\IServerContainer', 'ServerContainer');
317
+
318
+        $this->registerService('Symfony\Component\EventDispatcher\EventDispatcherInterface', function ($c) {
319
+            return $this->getServer()->getEventDispatcher();
320
+        });
321
+
322
+        $this->registerService('OCP\WorkflowEngine\IManager', function ($c) {
323
+            return $c->query('OCA\WorkflowEngine\Manager');
324
+        });
325
+
326
+        $this->registerService('OCP\\AppFramework\\IAppContainer', function ($c) {
327
+            return $c;
328
+        });
329
+        $this->registerService(IMountManager::class, function () {
330
+            return $this->getServer()->getMountManager();
331
+        });
332
+
333
+        // commonly used attributes
334
+        $this->registerService('UserId', function ($c) {
335
+            return $c->query('OCP\\IUserSession')->getSession()->get('user_id');
336
+        });
337
+
338
+        $this->registerService('WebRoot', function ($c) {
339
+            return $c->query('ServerContainer')->getWebRoot();
340
+        });
341
+
342
+        $this->registerService('OCP\Encryption\IManager', function ($c) {
343
+            return $this->getServer()->getEncryptionManager();
344
+        });
345
+
346
+        $this->registerService(IValidator::class, function($c) {
347
+            return $c->query(Validator::class);
348
+        });
349
+
350
+        $this->registerService(\OC\Security\IdentityProof\Manager::class, function ($c) {
351
+            return new \OC\Security\IdentityProof\Manager(
352
+                $this->getServer()->getAppDataDir('identityproof'),
353
+                $this->getServer()->getCrypto()
354
+            );
355
+        });
356
+
357
+
358
+        /**
359
+         * App Framework APIs
360
+         */
361
+        $this->registerService('API', function($c){
362
+            $c->query('OCP\\ILogger')->debug(
363
+                'Accessing the API class is deprecated! Use the appropriate ' .
364
+                'services instead!'
365
+            );
366
+            return new API($c['AppName']);
367
+        });
368
+
369
+        $this->registerService('Protocol', function($c){
370
+            /** @var \OC\Server $server */
371
+            $server = $c->query('ServerContainer');
372
+            $protocol = $server->getRequest()->getHttpProtocol();
373
+            return new Http($_SERVER, $protocol);
374
+        });
375
+
376
+        $this->registerService('Dispatcher', function($c) {
377
+            return new Dispatcher(
378
+                $c['Protocol'],
379
+                $c['MiddlewareDispatcher'],
380
+                $c['ControllerMethodReflector'],
381
+                $c['Request']
382
+            );
383
+        });
384
+
385
+        /**
386
+         * App Framework default arguments
387
+         */
388
+        $this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
389
+        $this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
390
+        $this->registerParameter('corsMaxAge', 1728000);
391
+
392
+        /**
393
+         * Middleware
394
+         */
395
+        $app = $this;
396
+        $this->registerService('SecurityMiddleware', function($c) use ($app){
397
+            /** @var \OC\Server $server */
398
+            $server = $app->getServer();
399
+
400
+            return new SecurityMiddleware(
401
+                $c['Request'],
402
+                $c['ControllerMethodReflector'],
403
+                $server->getNavigationManager(),
404
+                $server->getURLGenerator(),
405
+                $server->getLogger(),
406
+                $server->getSession(),
407
+                $c['AppName'],
408
+                $app->isLoggedIn(),
409
+                $app->isAdminUser(),
410
+                $server->getContentSecurityPolicyManager(),
411
+                $server->getCsrfTokenManager(),
412
+                $server->getContentSecurityPolicyNonceManager(),
413
+                $server->getBruteForceThrottler()
414
+            );
415
+
416
+        });
417
+
418
+        $this->registerService('CORSMiddleware', function($c) {
419
+            return new CORSMiddleware(
420
+                $c['Request'],
421
+                $c['ControllerMethodReflector'],
422
+                $c['OCP\IUserSession'],
423
+                $c->getServer()->getBruteForceThrottler()
424
+            );
425
+        });
426
+
427
+        $this->registerService('SessionMiddleware', function($c) use ($app) {
428
+            return new SessionMiddleware(
429
+                $c['Request'],
430
+                $c['ControllerMethodReflector'],
431
+                $app->getServer()->getSession()
432
+            );
433
+        });
434
+
435
+        $this->registerService('TwoFactorMiddleware', function (SimpleContainer $c) use ($app) {
436
+            $twoFactorManager = $c->getServer()->getTwoFactorAuthManager();
437
+            $userSession = $app->getServer()->getUserSession();
438
+            $session = $app->getServer()->getSession();
439
+            $urlGenerator = $app->getServer()->getURLGenerator();
440
+            $reflector = $c['ControllerMethodReflector'];
441
+            $request = $app->getServer()->getRequest();
442
+            return new TwoFactorMiddleware($twoFactorManager, $userSession, $session, $urlGenerator, $reflector, $request);
443
+        });
444
+
445
+        $this->registerService('OCSMiddleware', function (SimpleContainer $c) {
446
+            return new OCSMiddleware(
447
+                $c['Request']
448
+            );
449
+        });
450
+
451
+        $middleWares = &$this->middleWares;
452
+        $this->registerService('MiddlewareDispatcher', function($c) use (&$middleWares) {
453
+            $dispatcher = new MiddlewareDispatcher();
454
+            $dispatcher->registerMiddleware($c['CORSMiddleware']);
455
+            $dispatcher->registerMiddleware($c['OCSMiddleware']);
456
+            $dispatcher->registerMiddleware($c['SecurityMiddleware']);
457
+            $dispatcher->registerMiddleWare($c['TwoFactorMiddleware']);
458
+
459
+            foreach($middleWares as $middleWare) {
460
+                $dispatcher->registerMiddleware($c[$middleWare]);
461
+            }
462
+
463
+            $dispatcher->registerMiddleware($c['SessionMiddleware']);
464
+            return $dispatcher;
465
+        });
466
+
467
+    }
468
+
469
+
470
+    /**
471
+     * @deprecated implements only deprecated methods
472
+     * @return IApi
473
+     */
474
+    function getCoreApi()
475
+    {
476
+        return $this->query('API');
477
+    }
478
+
479
+    /**
480
+     * @return \OCP\IServerContainer
481
+     */
482
+    function getServer()
483
+    {
484
+        return OC::$server;
485
+    }
486
+
487
+    /**
488
+     * @param string $middleWare
489
+     * @return boolean|null
490
+     */
491
+    function registerMiddleWare($middleWare) {
492
+        array_push($this->middleWares, $middleWare);
493
+    }
494
+
495
+    /**
496
+     * used to return the appname of the set application
497
+     * @return string the name of your application
498
+     */
499
+    function getAppName() {
500
+        return $this->query('AppName');
501
+    }
502
+
503
+    /**
504
+     * @deprecated use IUserSession->isLoggedIn()
505
+     * @return boolean
506
+     */
507
+    function isLoggedIn() {
508
+        return \OC_User::isLoggedIn();
509
+    }
510
+
511
+    /**
512
+     * @deprecated use IGroupManager->isAdmin($userId)
513
+     * @return boolean
514
+     */
515
+    function isAdminUser() {
516
+        $uid = $this->getUserId();
517
+        return \OC_User::isAdminUser($uid);
518
+    }
519
+
520
+    private function getUserId() {
521
+        return $this->getServer()->getSession()->get('user_id');
522
+    }
523
+
524
+    /**
525
+     * @deprecated use the ILogger instead
526
+     * @param string $message
527
+     * @param string $level
528
+     * @return mixed
529
+     */
530
+    function log($message, $level) {
531
+        switch($level){
532
+            case 'debug':
533
+                $level = \OCP\Util::DEBUG;
534
+                break;
535
+            case 'info':
536
+                $level = \OCP\Util::INFO;
537
+                break;
538
+            case 'warn':
539
+                $level = \OCP\Util::WARN;
540
+                break;
541
+            case 'fatal':
542
+                $level = \OCP\Util::FATAL;
543
+                break;
544
+            default:
545
+                $level = \OCP\Util::ERROR;
546
+                break;
547
+        }
548
+        \OCP\Util::writeLog($this->getAppName(), $message, $level);
549
+    }
550
+
551
+    /**
552
+     * Register a capability
553
+     *
554
+     * @param string $serviceName e.g. 'OCA\Files\Capabilities'
555
+     */
556
+    public function registerCapability($serviceName) {
557
+        $this->query('OC\CapabilitiesManager')->registerCapability(function() use ($serviceName) {
558
+            return $this->query($serviceName);
559
+        });
560
+    }
561
+
562
+    public function query($name) {
563
+        return parent::query($name);
564
+    }
565 565
 }
Please login to merge, or discard this patch.
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -65,7 +65,7 @@  discard block
 block discarded – undo
65 65
 	 * Put your class dependencies in here
66 66
 	 * @param string $appName the name of the app
67 67
 	 */
68
-	public function __construct($appName, $urlParams = array()){
68
+	public function __construct($appName, $urlParams = array()) {
69 69
 		parent::__construct();
70 70
 		$this['AppName'] = $appName;
71 71
 		$this['urlParams'] = $urlParams;
@@ -90,7 +90,7 @@  discard block
 block discarded – undo
90 90
 			return $this->getServer()->getAppManager();
91 91
 		});
92 92
 
93
-		$this->registerService('OCP\\AppFramework\\Http\\IOutput', function($c){
93
+		$this->registerService('OCP\\AppFramework\\Http\\IOutput', function($c) {
94 94
 			return new Output($this->getServer()->getWebRoot());
95 95
 		});
96 96
 
@@ -181,7 +181,7 @@  discard block
 block discarded – undo
181 181
 			return $this->getServer()->getHTTPClientService();
182 182
 		});
183 183
 
184
-		$this->registerService(IAppData::class, function (SimpleContainer $c) {
184
+		$this->registerService(IAppData::class, function(SimpleContainer $c) {
185 185
 			return $this->getServer()->getAppDataDir($c->query('AppName'));
186 186
 		});
187 187
 
@@ -232,7 +232,7 @@  discard block
 block discarded – undo
232 232
 			return $this->getServer()->getPreviewManager();
233 233
 		});
234 234
 
235
-		$this->registerService('OCP\\IRequest', function () {
235
+		$this->registerService('OCP\\IRequest', function() {
236 236
 			return $this->getServer()->getRequest();
237 237
 		});
238 238
 		$this->registerAlias('Request', 'OCP\\IRequest');
@@ -310,36 +310,36 @@  discard block
 block discarded – undo
310 310
 			return $this->getServer()->getContentSecurityPolicyManager();
311 311
 		});
312 312
 
313
-		$this->registerService('ServerContainer', function ($c) {
313
+		$this->registerService('ServerContainer', function($c) {
314 314
 			return $this->getServer();
315 315
 		});
316 316
 		$this->registerAlias('OCP\\IServerContainer', 'ServerContainer');
317 317
 
318
-		$this->registerService('Symfony\Component\EventDispatcher\EventDispatcherInterface', function ($c) {
318
+		$this->registerService('Symfony\Component\EventDispatcher\EventDispatcherInterface', function($c) {
319 319
 			return $this->getServer()->getEventDispatcher();
320 320
 		});
321 321
 
322
-		$this->registerService('OCP\WorkflowEngine\IManager', function ($c) {
322
+		$this->registerService('OCP\WorkflowEngine\IManager', function($c) {
323 323
 			return $c->query('OCA\WorkflowEngine\Manager');
324 324
 		});
325 325
 
326
-		$this->registerService('OCP\\AppFramework\\IAppContainer', function ($c) {
326
+		$this->registerService('OCP\\AppFramework\\IAppContainer', function($c) {
327 327
 			return $c;
328 328
 		});
329
-		$this->registerService(IMountManager::class, function () {
329
+		$this->registerService(IMountManager::class, function() {
330 330
 			return $this->getServer()->getMountManager();
331 331
 		});
332 332
 
333 333
 		// commonly used attributes
334
-		$this->registerService('UserId', function ($c) {
334
+		$this->registerService('UserId', function($c) {
335 335
 			return $c->query('OCP\\IUserSession')->getSession()->get('user_id');
336 336
 		});
337 337
 
338
-		$this->registerService('WebRoot', function ($c) {
338
+		$this->registerService('WebRoot', function($c) {
339 339
 			return $c->query('ServerContainer')->getWebRoot();
340 340
 		});
341 341
 
342
-		$this->registerService('OCP\Encryption\IManager', function ($c) {
342
+		$this->registerService('OCP\Encryption\IManager', function($c) {
343 343
 			return $this->getServer()->getEncryptionManager();
344 344
 		});
345 345
 
@@ -347,7 +347,7 @@  discard block
 block discarded – undo
347 347
 			return $c->query(Validator::class);
348 348
 		});
349 349
 
350
-		$this->registerService(\OC\Security\IdentityProof\Manager::class, function ($c) {
350
+		$this->registerService(\OC\Security\IdentityProof\Manager::class, function($c) {
351 351
 			return new \OC\Security\IdentityProof\Manager(
352 352
 				$this->getServer()->getAppDataDir('identityproof'),
353 353
 				$this->getServer()->getCrypto()
@@ -358,15 +358,15 @@  discard block
 block discarded – undo
358 358
 		/**
359 359
 		 * App Framework APIs
360 360
 		 */
361
-		$this->registerService('API', function($c){
361
+		$this->registerService('API', function($c) {
362 362
 			$c->query('OCP\\ILogger')->debug(
363
-				'Accessing the API class is deprecated! Use the appropriate ' .
363
+				'Accessing the API class is deprecated! Use the appropriate '.
364 364
 				'services instead!'
365 365
 			);
366 366
 			return new API($c['AppName']);
367 367
 		});
368 368
 
369
-		$this->registerService('Protocol', function($c){
369
+		$this->registerService('Protocol', function($c) {
370 370
 			/** @var \OC\Server $server */
371 371
 			$server = $c->query('ServerContainer');
372 372
 			$protocol = $server->getRequest()->getHttpProtocol();
@@ -432,7 +432,7 @@  discard block
 block discarded – undo
432 432
 			);
433 433
 		});
434 434
 
435
-		$this->registerService('TwoFactorMiddleware', function (SimpleContainer $c) use ($app) {
435
+		$this->registerService('TwoFactorMiddleware', function(SimpleContainer $c) use ($app) {
436 436
 			$twoFactorManager = $c->getServer()->getTwoFactorAuthManager();
437 437
 			$userSession = $app->getServer()->getUserSession();
438 438
 			$session = $app->getServer()->getSession();
@@ -442,7 +442,7 @@  discard block
 block discarded – undo
442 442
 			return new TwoFactorMiddleware($twoFactorManager, $userSession, $session, $urlGenerator, $reflector, $request);
443 443
 		});
444 444
 
445
-		$this->registerService('OCSMiddleware', function (SimpleContainer $c) {
445
+		$this->registerService('OCSMiddleware', function(SimpleContainer $c) {
446 446
 			return new OCSMiddleware(
447 447
 				$c['Request']
448 448
 			);
@@ -456,7 +456,7 @@  discard block
 block discarded – undo
456 456
 			$dispatcher->registerMiddleware($c['SecurityMiddleware']);
457 457
 			$dispatcher->registerMiddleWare($c['TwoFactorMiddleware']);
458 458
 
459
-			foreach($middleWares as $middleWare) {
459
+			foreach ($middleWares as $middleWare) {
460 460
 				$dispatcher->registerMiddleware($c[$middleWare]);
461 461
 			}
462 462
 
@@ -528,7 +528,7 @@  discard block
 block discarded – undo
528 528
 	 * @return mixed
529 529
 	 */
530 530
 	function log($message, $level) {
531
-		switch($level){
531
+		switch ($level) {
532 532
 			case 'debug':
533 533
 				$level = \OCP\Util::DEBUG;
534 534
 				break;
Please login to merge, or discard this patch.
apps/dav/lib/CardDAV/CardDavBackend.php 4 patches
Doc Comments   +11 added lines, -3 removed lines patch added patch discarded remove patch
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 	/**
105 105
 	 * Return the number of address books for a principal
106 106
 	 *
107
-	 * @param $principalUri
107
+	 * @param string $principalUri
108 108
 	 * @return int
109 109
 	 */
110 110
 	public function getAddressBooksForUserCount($principalUri) {
@@ -195,6 +195,9 @@  discard block
 block discarded – undo
195 195
 		return array_values($addressBooks);
196 196
 	}
197 197
 
198
+	/**
199
+	 * @param string $principalUri
200
+	 */
198 201
 	public function getUsersOwnAddressBooks($principalUri) {
199 202
 		$principalUriOriginal = $principalUri;
200 203
 		$principalUri = $this->convertPrincipal($principalUri, true);
@@ -264,7 +267,8 @@  discard block
 block discarded – undo
264 267
 	}
265 268
 
266 269
 	/**
267
-	 * @param $addressBookUri
270
+	 * @param string $addressBookUri
271
+	 * @param string $principal
268 272
 	 * @return array|null
269 273
 	 */
270 274
 	public function getAddressBooksByUri($principal, $addressBookUri) {
@@ -953,6 +957,7 @@  discard block
 block discarded – undo
953 957
 	 *   * readOnly - boolean
954 958
 	 *   * summary - Optional, a description for the share
955 959
 	 *
960
+	 * @param integer $addressBookId
956 961
 	 * @return array
957 962
 	 */
958 963
 	public function getShares($addressBookId) {
@@ -1052,7 +1057,7 @@  discard block
 block discarded – undo
1052 1057
 
1053 1058
 	/**
1054 1059
 	 * For shared address books the sharee is set in the ACL of the address book
1055
-	 * @param $addressBookId
1060
+	 * @param integer $addressBookId
1056 1061
 	 * @param $acl
1057 1062
 	 * @return array
1058 1063
 	 */
@@ -1060,6 +1065,9 @@  discard block
 block discarded – undo
1060 1065
 		return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
1061 1066
 	}
1062 1067
 
1068
+	/**
1069
+	 * @param boolean $toV2
1070
+	 */
1063 1071
 	private function convertPrincipal($principalUri, $toV2) {
1064 1072
 		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1065 1073
 			list(, $name) = URLUtil::splitPath($principalUri);
Please login to merge, or discard this patch.
Indentation   +1022 added lines, -1022 removed lines patch added patch discarded remove patch
@@ -48,1026 +48,1026 @@
 block discarded – undo
48 48
 
49 49
 class CardDavBackend implements BackendInterface, SyncSupport {
50 50
 
51
-	const PERSONAL_ADDRESSBOOK_URI = 'contacts';
52
-	const PERSONAL_ADDRESSBOOK_NAME = 'Contacts';
53
-
54
-	/** @var Principal */
55
-	private $principalBackend;
56
-
57
-	/** @var string */
58
-	private $dbCardsTable = 'cards';
59
-
60
-	/** @var string */
61
-	private $dbCardsPropertiesTable = 'cards_properties';
62
-
63
-	/** @var IDBConnection */
64
-	private $db;
65
-
66
-	/** @var Backend */
67
-	private $sharingBackend;
68
-
69
-	/** @var array properties to index */
70
-	public static $indexProperties = array(
71
-			'BDAY', 'UID', 'N', 'FN', 'TITLE', 'ROLE', 'NOTE', 'NICKNAME',
72
-			'ORG', 'CATEGORIES', 'EMAIL', 'TEL', 'IMPP', 'ADR', 'URL', 'GEO', 'CLOUD');
73
-
74
-	/**
75
-	 * @var string[] Map of uid => display name
76
-	 */
77
-	protected $userDisplayNames;
78
-
79
-	/** @var IUserManager */
80
-	private $userManager;
81
-
82
-	/** @var EventDispatcherInterface */
83
-	private $dispatcher;
84
-
85
-	/**
86
-	 * CardDavBackend constructor.
87
-	 *
88
-	 * @param IDBConnection $db
89
-	 * @param Principal $principalBackend
90
-	 * @param IUserManager $userManager
91
-	 * @param EventDispatcherInterface $dispatcher
92
-	 */
93
-	public function __construct(IDBConnection $db,
94
-								Principal $principalBackend,
95
-								IUserManager $userManager,
96
-								EventDispatcherInterface $dispatcher = null) {
97
-		$this->db = $db;
98
-		$this->principalBackend = $principalBackend;
99
-		$this->userManager = $userManager;
100
-		$this->dispatcher = $dispatcher;
101
-		$this->sharingBackend = new Backend($this->db, $principalBackend, 'addressbook');
102
-	}
103
-
104
-	/**
105
-	 * Return the number of address books for a principal
106
-	 *
107
-	 * @param $principalUri
108
-	 * @return int
109
-	 */
110
-	public function getAddressBooksForUserCount($principalUri) {
111
-		$principalUri = $this->convertPrincipal($principalUri, true);
112
-		$query = $this->db->getQueryBuilder();
113
-		$query->select($query->createFunction('COUNT(*)'))
114
-			->from('addressbooks')
115
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
116
-
117
-		return (int)$query->execute()->fetchColumn();
118
-	}
119
-
120
-	/**
121
-	 * Returns the list of address books for a specific user.
122
-	 *
123
-	 * Every addressbook should have the following properties:
124
-	 *   id - an arbitrary unique id
125
-	 *   uri - the 'basename' part of the url
126
-	 *   principaluri - Same as the passed parameter
127
-	 *
128
-	 * Any additional clark-notation property may be passed besides this. Some
129
-	 * common ones are :
130
-	 *   {DAV:}displayname
131
-	 *   {urn:ietf:params:xml:ns:carddav}addressbook-description
132
-	 *   {http://calendarserver.org/ns/}getctag
133
-	 *
134
-	 * @param string $principalUri
135
-	 * @return array
136
-	 */
137
-	function getAddressBooksForUser($principalUri) {
138
-		$principalUriOriginal = $principalUri;
139
-		$principalUri = $this->convertPrincipal($principalUri, true);
140
-		$query = $this->db->getQueryBuilder();
141
-		$query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
142
-			->from('addressbooks')
143
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
144
-
145
-		$addressBooks = [];
146
-
147
-		$result = $query->execute();
148
-		while($row = $result->fetch()) {
149
-			$addressBooks[$row['id']] = [
150
-				'id'  => $row['id'],
151
-				'uri' => $row['uri'],
152
-				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
153
-				'{DAV:}displayname' => $row['displayname'],
154
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
155
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
156
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
157
-			];
158
-		}
159
-		$result->closeCursor();
160
-
161
-		// query for shared calendars
162
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
163
-		$principals[]= $principalUri;
164
-
165
-		$query = $this->db->getQueryBuilder();
166
-		$result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
167
-			->from('dav_shares', 's')
168
-			->join('s', 'addressbooks', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
169
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
170
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
171
-			->setParameter('type', 'addressbook')
172
-			->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
173
-			->execute();
174
-
175
-		while($row = $result->fetch()) {
176
-			list(, $name) = URLUtil::splitPath($row['principaluri']);
177
-			$uri = $row['uri'] . '_shared_by_' . $name;
178
-			$displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
179
-			if (!isset($addressBooks[$row['id']])) {
180
-				$addressBooks[$row['id']] = [
181
-					'id'  => $row['id'],
182
-					'uri' => $uri,
183
-					'principaluri' => $principalUri,
184
-					'{DAV:}displayname' => $displayName,
185
-					'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
186
-					'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
187
-					'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
188
-					'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
189
-					'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
190
-				];
191
-			}
192
-		}
193
-		$result->closeCursor();
194
-
195
-		return array_values($addressBooks);
196
-	}
197
-
198
-	public function getUsersOwnAddressBooks($principalUri) {
199
-		$principalUriOriginal = $principalUri;
200
-		$principalUri = $this->convertPrincipal($principalUri, true);
201
-		$query = $this->db->getQueryBuilder();
202
-		$query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
203
-			  ->from('addressbooks')
204
-			  ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
205
-
206
-		$addressBooks = [];
207
-
208
-		$result = $query->execute();
209
-		while($row = $result->fetch()) {
210
-			$addressBooks[$row['id']] = [
211
-				'id'  => $row['id'],
212
-				'uri' => $row['uri'],
213
-				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
214
-				'{DAV:}displayname' => $row['displayname'],
215
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
216
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
217
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
218
-			];
219
-		}
220
-		$result->closeCursor();
221
-
222
-		return array_values($addressBooks);
223
-	}
224
-
225
-	private function getUserDisplayName($uid) {
226
-		if (!isset($this->userDisplayNames[$uid])) {
227
-			$user = $this->userManager->get($uid);
228
-
229
-			if ($user instanceof IUser) {
230
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
231
-			} else {
232
-				$this->userDisplayNames[$uid] = $uid;
233
-			}
234
-		}
235
-
236
-		return $this->userDisplayNames[$uid];
237
-	}
238
-
239
-	/**
240
-	 * @param int $addressBookId
241
-	 */
242
-	public function getAddressBookById($addressBookId) {
243
-		$query = $this->db->getQueryBuilder();
244
-		$result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
245
-			->from('addressbooks')
246
-			->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
247
-			->execute();
248
-
249
-		$row = $result->fetch();
250
-		$result->closeCursor();
251
-		if ($row === false) {
252
-			return null;
253
-		}
254
-
255
-		return [
256
-			'id'  => $row['id'],
257
-			'uri' => $row['uri'],
258
-			'principaluri' => $row['principaluri'],
259
-			'{DAV:}displayname' => $row['displayname'],
260
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
261
-			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
262
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
263
-		];
264
-	}
265
-
266
-	/**
267
-	 * @param $addressBookUri
268
-	 * @return array|null
269
-	 */
270
-	public function getAddressBooksByUri($principal, $addressBookUri) {
271
-		$query = $this->db->getQueryBuilder();
272
-		$result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
273
-			->from('addressbooks')
274
-			->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
275
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
276
-			->setMaxResults(1)
277
-			->execute();
278
-
279
-		$row = $result->fetch();
280
-		$result->closeCursor();
281
-		if ($row === false) {
282
-			return null;
283
-		}
284
-
285
-		return [
286
-				'id'  => $row['id'],
287
-				'uri' => $row['uri'],
288
-				'principaluri' => $row['principaluri'],
289
-				'{DAV:}displayname' => $row['displayname'],
290
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
291
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
292
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
293
-			];
294
-	}
295
-
296
-	/**
297
-	 * Updates properties for an address book.
298
-	 *
299
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
300
-	 * To do the actual updates, you must tell this object which properties
301
-	 * you're going to process with the handle() method.
302
-	 *
303
-	 * Calling the handle method is like telling the PropPatch object "I
304
-	 * promise I can handle updating this property".
305
-	 *
306
-	 * Read the PropPatch documentation for more info and examples.
307
-	 *
308
-	 * @param string $addressBookId
309
-	 * @param \Sabre\DAV\PropPatch $propPatch
310
-	 * @return void
311
-	 */
312
-	function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
313
-		$supportedProperties = [
314
-			'{DAV:}displayname',
315
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description',
316
-		];
317
-
318
-		$propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
319
-
320
-			$updates = [];
321
-			foreach($mutations as $property=>$newValue) {
322
-
323
-				switch($property) {
324
-					case '{DAV:}displayname' :
325
-						$updates['displayname'] = $newValue;
326
-						break;
327
-					case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
328
-						$updates['description'] = $newValue;
329
-						break;
330
-				}
331
-			}
332
-			$query = $this->db->getQueryBuilder();
333
-			$query->update('addressbooks');
334
-
335
-			foreach($updates as $key=>$value) {
336
-				$query->set($key, $query->createNamedParameter($value));
337
-			}
338
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
339
-			->execute();
340
-
341
-			$this->addChange($addressBookId, "", 2);
342
-
343
-			return true;
344
-
345
-		});
346
-	}
347
-
348
-	/**
349
-	 * Creates a new address book
350
-	 *
351
-	 * @param string $principalUri
352
-	 * @param string $url Just the 'basename' of the url.
353
-	 * @param array $properties
354
-	 * @return int
355
-	 * @throws BadRequest
356
-	 */
357
-	function createAddressBook($principalUri, $url, array $properties) {
358
-		$values = [
359
-			'displayname' => null,
360
-			'description' => null,
361
-			'principaluri' => $principalUri,
362
-			'uri' => $url,
363
-			'synctoken' => 1
364
-		];
365
-
366
-		foreach($properties as $property=>$newValue) {
367
-
368
-			switch($property) {
369
-				case '{DAV:}displayname' :
370
-					$values['displayname'] = $newValue;
371
-					break;
372
-				case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
373
-					$values['description'] = $newValue;
374
-					break;
375
-				default :
376
-					throw new BadRequest('Unknown property: ' . $property);
377
-			}
378
-
379
-		}
380
-
381
-		// Fallback to make sure the displayname is set. Some clients may refuse
382
-		// to work with addressbooks not having a displayname.
383
-		if(is_null($values['displayname'])) {
384
-			$values['displayname'] = $url;
385
-		}
386
-
387
-		$query = $this->db->getQueryBuilder();
388
-		$query->insert('addressbooks')
389
-			->values([
390
-				'uri' => $query->createParameter('uri'),
391
-				'displayname' => $query->createParameter('displayname'),
392
-				'description' => $query->createParameter('description'),
393
-				'principaluri' => $query->createParameter('principaluri'),
394
-				'synctoken' => $query->createParameter('synctoken'),
395
-			])
396
-			->setParameters($values)
397
-			->execute();
398
-
399
-		return $query->getLastInsertId();
400
-	}
401
-
402
-	/**
403
-	 * Deletes an entire addressbook and all its contents
404
-	 *
405
-	 * @param mixed $addressBookId
406
-	 * @return void
407
-	 */
408
-	function deleteAddressBook($addressBookId) {
409
-		$query = $this->db->getQueryBuilder();
410
-		$query->delete('cards')
411
-			->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
412
-			->setParameter('addressbookid', $addressBookId)
413
-			->execute();
414
-
415
-		$query->delete('addressbookchanges')
416
-			->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
417
-			->setParameter('addressbookid', $addressBookId)
418
-			->execute();
419
-
420
-		$query->delete('addressbooks')
421
-			->where($query->expr()->eq('id', $query->createParameter('id')))
422
-			->setParameter('id', $addressBookId)
423
-			->execute();
424
-
425
-		$this->sharingBackend->deleteAllShares($addressBookId);
426
-
427
-		$query->delete($this->dbCardsPropertiesTable)
428
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
429
-			->execute();
430
-
431
-	}
432
-
433
-	/**
434
-	 * Returns all cards for a specific addressbook id.
435
-	 *
436
-	 * This method should return the following properties for each card:
437
-	 *   * carddata - raw vcard data
438
-	 *   * uri - Some unique url
439
-	 *   * lastmodified - A unix timestamp
440
-	 *
441
-	 * It's recommended to also return the following properties:
442
-	 *   * etag - A unique etag. This must change every time the card changes.
443
-	 *   * size - The size of the card in bytes.
444
-	 *
445
-	 * If these last two properties are provided, less time will be spent
446
-	 * calculating them. If they are specified, you can also ommit carddata.
447
-	 * This may speed up certain requests, especially with large cards.
448
-	 *
449
-	 * @param mixed $addressBookId
450
-	 * @return array
451
-	 */
452
-	function getCards($addressBookId) {
453
-		$query = $this->db->getQueryBuilder();
454
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
455
-			->from('cards')
456
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
457
-
458
-		$cards = [];
459
-
460
-		$result = $query->execute();
461
-		while($row = $result->fetch()) {
462
-			$row['etag'] = '"' . $row['etag'] . '"';
463
-			$row['carddata'] = $this->readBlob($row['carddata']);
464
-			$cards[] = $row;
465
-		}
466
-		$result->closeCursor();
467
-
468
-		return $cards;
469
-	}
470
-
471
-	/**
472
-	 * Returns a specific card.
473
-	 *
474
-	 * The same set of properties must be returned as with getCards. The only
475
-	 * exception is that 'carddata' is absolutely required.
476
-	 *
477
-	 * If the card does not exist, you must return false.
478
-	 *
479
-	 * @param mixed $addressBookId
480
-	 * @param string $cardUri
481
-	 * @return array
482
-	 */
483
-	function getCard($addressBookId, $cardUri) {
484
-		$query = $this->db->getQueryBuilder();
485
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
486
-			->from('cards')
487
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
488
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
489
-			->setMaxResults(1);
490
-
491
-		$result = $query->execute();
492
-		$row = $result->fetch();
493
-		if (!$row) {
494
-			return false;
495
-		}
496
-		$row['etag'] = '"' . $row['etag'] . '"';
497
-		$row['carddata'] = $this->readBlob($row['carddata']);
498
-
499
-		return $row;
500
-	}
501
-
502
-	/**
503
-	 * Returns a list of cards.
504
-	 *
505
-	 * This method should work identical to getCard, but instead return all the
506
-	 * cards in the list as an array.
507
-	 *
508
-	 * If the backend supports this, it may allow for some speed-ups.
509
-	 *
510
-	 * @param mixed $addressBookId
511
-	 * @param string[] $uris
512
-	 * @return array
513
-	 */
514
-	function getMultipleCards($addressBookId, array $uris) {
515
-		if (empty($uris)) {
516
-			return [];
517
-		}
518
-
519
-		$chunks = array_chunk($uris, 100);
520
-		$cards = [];
521
-
522
-		$query = $this->db->getQueryBuilder();
523
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
524
-			->from('cards')
525
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
526
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
527
-
528
-		foreach ($chunks as $uris) {
529
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
530
-			$result = $query->execute();
531
-
532
-			while ($row = $result->fetch()) {
533
-				$row['etag'] = '"' . $row['etag'] . '"';
534
-				$row['carddata'] = $this->readBlob($row['carddata']);
535
-				$cards[] = $row;
536
-			}
537
-			$result->closeCursor();
538
-		}
539
-		return $cards;
540
-	}
541
-
542
-	/**
543
-	 * Creates a new card.
544
-	 *
545
-	 * The addressbook id will be passed as the first argument. This is the
546
-	 * same id as it is returned from the getAddressBooksForUser method.
547
-	 *
548
-	 * The cardUri is a base uri, and doesn't include the full path. The
549
-	 * cardData argument is the vcard body, and is passed as a string.
550
-	 *
551
-	 * It is possible to return an ETag from this method. This ETag is for the
552
-	 * newly created resource, and must be enclosed with double quotes (that
553
-	 * is, the string itself must contain the double quotes).
554
-	 *
555
-	 * You should only return the ETag if you store the carddata as-is. If a
556
-	 * subsequent GET request on the same card does not have the same body,
557
-	 * byte-by-byte and you did return an ETag here, clients tend to get
558
-	 * confused.
559
-	 *
560
-	 * If you don't return an ETag, you can just return null.
561
-	 *
562
-	 * @param mixed $addressBookId
563
-	 * @param string $cardUri
564
-	 * @param string $cardData
565
-	 * @return string
566
-	 */
567
-	function createCard($addressBookId, $cardUri, $cardData) {
568
-		$etag = md5($cardData);
569
-
570
-		$query = $this->db->getQueryBuilder();
571
-		$query->insert('cards')
572
-			->values([
573
-				'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
574
-				'uri' => $query->createNamedParameter($cardUri),
575
-				'lastmodified' => $query->createNamedParameter(time()),
576
-				'addressbookid' => $query->createNamedParameter($addressBookId),
577
-				'size' => $query->createNamedParameter(strlen($cardData)),
578
-				'etag' => $query->createNamedParameter($etag),
579
-			])
580
-			->execute();
581
-
582
-		$this->addChange($addressBookId, $cardUri, 1);
583
-		$this->updateProperties($addressBookId, $cardUri, $cardData);
584
-
585
-		if (!is_null($this->dispatcher)) {
586
-			$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard',
587
-				new GenericEvent(null, [
588
-					'addressBookId' => $addressBookId,
589
-					'cardUri' => $cardUri,
590
-					'cardData' => $cardData]));
591
-		}
592
-
593
-		return '"' . $etag . '"';
594
-	}
595
-
596
-	/**
597
-	 * Updates a card.
598
-	 *
599
-	 * The addressbook id will be passed as the first argument. This is the
600
-	 * same id as it is returned from the getAddressBooksForUser method.
601
-	 *
602
-	 * The cardUri is a base uri, and doesn't include the full path. The
603
-	 * cardData argument is the vcard body, and is passed as a string.
604
-	 *
605
-	 * It is possible to return an ETag from this method. This ETag should
606
-	 * match that of the updated resource, and must be enclosed with double
607
-	 * quotes (that is: the string itself must contain the actual quotes).
608
-	 *
609
-	 * You should only return the ETag if you store the carddata as-is. If a
610
-	 * subsequent GET request on the same card does not have the same body,
611
-	 * byte-by-byte and you did return an ETag here, clients tend to get
612
-	 * confused.
613
-	 *
614
-	 * If you don't return an ETag, you can just return null.
615
-	 *
616
-	 * @param mixed $addressBookId
617
-	 * @param string $cardUri
618
-	 * @param string $cardData
619
-	 * @return string
620
-	 */
621
-	function updateCard($addressBookId, $cardUri, $cardData) {
622
-
623
-		$etag = md5($cardData);
624
-		$query = $this->db->getQueryBuilder();
625
-		$query->update('cards')
626
-			->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
627
-			->set('lastmodified', $query->createNamedParameter(time()))
628
-			->set('size', $query->createNamedParameter(strlen($cardData)))
629
-			->set('etag', $query->createNamedParameter($etag))
630
-			->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
631
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
632
-			->execute();
633
-
634
-		$this->addChange($addressBookId, $cardUri, 2);
635
-		$this->updateProperties($addressBookId, $cardUri, $cardData);
636
-
637
-		if (!is_null($this->dispatcher)) {
638
-			$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard',
639
-				new GenericEvent(null, [
640
-					'addressBookId' => $addressBookId,
641
-					'cardUri' => $cardUri,
642
-					'cardData' => $cardData]));
643
-		}
644
-
645
-		return '"' . $etag . '"';
646
-	}
647
-
648
-	/**
649
-	 * Deletes a card
650
-	 *
651
-	 * @param mixed $addressBookId
652
-	 * @param string $cardUri
653
-	 * @return bool
654
-	 */
655
-	function deleteCard($addressBookId, $cardUri) {
656
-		try {
657
-			$cardId = $this->getCardId($addressBookId, $cardUri);
658
-		} catch (\InvalidArgumentException $e) {
659
-			$cardId = null;
660
-		}
661
-		$query = $this->db->getQueryBuilder();
662
-		$ret = $query->delete('cards')
663
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
664
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
665
-			->execute();
666
-
667
-		$this->addChange($addressBookId, $cardUri, 3);
668
-
669
-		if (!is_null($this->dispatcher)) {
670
-			$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard',
671
-				new GenericEvent(null, [
672
-					'addressBookId' => $addressBookId,
673
-					'cardUri' => $cardUri]));
674
-		}
675
-
676
-		if ($ret === 1) {
677
-			if ($cardId !== null) {
678
-				$this->purgeProperties($addressBookId, $cardId);
679
-			}
680
-			return true;
681
-		}
682
-
683
-		return false;
684
-	}
685
-
686
-	/**
687
-	 * The getChanges method returns all the changes that have happened, since
688
-	 * the specified syncToken in the specified address book.
689
-	 *
690
-	 * This function should return an array, such as the following:
691
-	 *
692
-	 * [
693
-	 *   'syncToken' => 'The current synctoken',
694
-	 *   'added'   => [
695
-	 *      'new.txt',
696
-	 *   ],
697
-	 *   'modified'   => [
698
-	 *      'modified.txt',
699
-	 *   ],
700
-	 *   'deleted' => [
701
-	 *      'foo.php.bak',
702
-	 *      'old.txt'
703
-	 *   ]
704
-	 * ];
705
-	 *
706
-	 * The returned syncToken property should reflect the *current* syncToken
707
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
708
-	 * property. This is needed here too, to ensure the operation is atomic.
709
-	 *
710
-	 * If the $syncToken argument is specified as null, this is an initial
711
-	 * sync, and all members should be reported.
712
-	 *
713
-	 * The modified property is an array of nodenames that have changed since
714
-	 * the last token.
715
-	 *
716
-	 * The deleted property is an array with nodenames, that have been deleted
717
-	 * from collection.
718
-	 *
719
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
720
-	 * 1, you only have to report changes that happened only directly in
721
-	 * immediate descendants. If it's 2, it should also include changes from
722
-	 * the nodes below the child collections. (grandchildren)
723
-	 *
724
-	 * The $limit argument allows a client to specify how many results should
725
-	 * be returned at most. If the limit is not specified, it should be treated
726
-	 * as infinite.
727
-	 *
728
-	 * If the limit (infinite or not) is higher than you're willing to return,
729
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
730
-	 *
731
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
732
-	 * return null.
733
-	 *
734
-	 * The limit is 'suggestive'. You are free to ignore it.
735
-	 *
736
-	 * @param string $addressBookId
737
-	 * @param string $syncToken
738
-	 * @param int $syncLevel
739
-	 * @param int $limit
740
-	 * @return array
741
-	 */
742
-	function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
743
-		// Current synctoken
744
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
745
-		$stmt->execute([ $addressBookId ]);
746
-		$currentToken = $stmt->fetchColumn(0);
747
-
748
-		if (is_null($currentToken)) return null;
749
-
750
-		$result = [
751
-			'syncToken' => $currentToken,
752
-			'added'     => [],
753
-			'modified'  => [],
754
-			'deleted'   => [],
755
-		];
756
-
757
-		if ($syncToken) {
758
-
759
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
760
-			if ($limit>0) {
761
-				$query .= " `LIMIT` " . (int)$limit;
762
-			}
763
-
764
-			// Fetching all changes
765
-			$stmt = $this->db->prepare($query);
766
-			$stmt->execute([$syncToken, $currentToken, $addressBookId]);
767
-
768
-			$changes = [];
769
-
770
-			// This loop ensures that any duplicates are overwritten, only the
771
-			// last change on a node is relevant.
772
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
773
-
774
-				$changes[$row['uri']] = $row['operation'];
775
-
776
-			}
777
-
778
-			foreach($changes as $uri => $operation) {
779
-
780
-				switch($operation) {
781
-					case 1:
782
-						$result['added'][] = $uri;
783
-						break;
784
-					case 2:
785
-						$result['modified'][] = $uri;
786
-						break;
787
-					case 3:
788
-						$result['deleted'][] = $uri;
789
-						break;
790
-				}
791
-
792
-			}
793
-		} else {
794
-			// No synctoken supplied, this is the initial sync.
795
-			$query = "SELECT `uri` FROM `*PREFIX*cards` WHERE `addressbookid` = ?";
796
-			$stmt = $this->db->prepare($query);
797
-			$stmt->execute([$addressBookId]);
798
-
799
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
800
-		}
801
-		return $result;
802
-	}
803
-
804
-	/**
805
-	 * Adds a change record to the addressbookchanges table.
806
-	 *
807
-	 * @param mixed $addressBookId
808
-	 * @param string $objectUri
809
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete
810
-	 * @return void
811
-	 */
812
-	protected function addChange($addressBookId, $objectUri, $operation) {
813
-		$sql = 'INSERT INTO `*PREFIX*addressbookchanges`(`uri`, `synctoken`, `addressbookid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*addressbooks` WHERE `id` = ?';
814
-		$stmt = $this->db->prepare($sql);
815
-		$stmt->execute([
816
-			$objectUri,
817
-			$addressBookId,
818
-			$operation,
819
-			$addressBookId
820
-		]);
821
-		$stmt = $this->db->prepare('UPDATE `*PREFIX*addressbooks` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
822
-		$stmt->execute([
823
-			$addressBookId
824
-		]);
825
-	}
826
-
827
-	private function readBlob($cardData) {
828
-		if (is_resource($cardData)) {
829
-			return stream_get_contents($cardData);
830
-		}
831
-
832
-		return $cardData;
833
-	}
834
-
835
-	/**
836
-	 * @param IShareable $shareable
837
-	 * @param string[] $add
838
-	 * @param string[] $remove
839
-	 */
840
-	public function updateShares(IShareable $shareable, $add, $remove) {
841
-		$this->sharingBackend->updateShares($shareable, $add, $remove);
842
-	}
843
-
844
-	/**
845
-	 * search contact
846
-	 *
847
-	 * @param int $addressBookId
848
-	 * @param string $pattern which should match within the $searchProperties
849
-	 * @param array $searchProperties defines the properties within the query pattern should match
850
-	 * @return array an array of contacts which are arrays of key-value-pairs
851
-	 */
852
-	public function search($addressBookId, $pattern, $searchProperties) {
853
-		$query = $this->db->getQueryBuilder();
854
-		$query2 = $this->db->getQueryBuilder();
855
-		$query2->selectDistinct('cp.cardid')->from($this->dbCardsPropertiesTable, 'cp');
856
-		foreach ($searchProperties as $property) {
857
-			$query2->orWhere(
858
-				$query2->expr()->andX(
859
-					$query2->expr()->eq('cp.name', $query->createNamedParameter($property)),
860
-					$query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%'))
861
-				)
862
-			);
863
-		}
864
-		$query2->andWhere($query2->expr()->eq('cp.addressbookid', $query->createNamedParameter($addressBookId)));
865
-
866
-		$query->select('c.carddata', 'c.uri')->from($this->dbCardsTable, 'c')
867
-			->where($query->expr()->in('c.id', $query->createFunction($query2->getSQL())));
868
-
869
-		$result = $query->execute();
870
-		$cards = $result->fetchAll();
871
-
872
-		$result->closeCursor();
873
-
874
-		return array_map(function($array) {
875
-			$array['carddata'] = $this->readBlob($array['carddata']);
876
-			return $array;
877
-		}, $cards);
878
-	}
879
-
880
-	/**
881
-	 * @param int $bookId
882
-	 * @param string $name
883
-	 * @return array
884
-	 */
885
-	public function collectCardProperties($bookId, $name) {
886
-		$query = $this->db->getQueryBuilder();
887
-		$result = $query->selectDistinct('value')
888
-			->from($this->dbCardsPropertiesTable)
889
-			->where($query->expr()->eq('name', $query->createNamedParameter($name)))
890
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
891
-			->execute();
892
-
893
-		$all = $result->fetchAll(PDO::FETCH_COLUMN);
894
-		$result->closeCursor();
895
-
896
-		return $all;
897
-	}
898
-
899
-	/**
900
-	 * get URI from a given contact
901
-	 *
902
-	 * @param int $id
903
-	 * @return string
904
-	 */
905
-	public function getCardUri($id) {
906
-		$query = $this->db->getQueryBuilder();
907
-		$query->select('uri')->from($this->dbCardsTable)
908
-				->where($query->expr()->eq('id', $query->createParameter('id')))
909
-				->setParameter('id', $id);
910
-
911
-		$result = $query->execute();
912
-		$uri = $result->fetch();
913
-		$result->closeCursor();
914
-
915
-		if (!isset($uri['uri'])) {
916
-			throw new \InvalidArgumentException('Card does not exists: ' . $id);
917
-		}
918
-
919
-		return $uri['uri'];
920
-	}
921
-
922
-	/**
923
-	 * return contact with the given URI
924
-	 *
925
-	 * @param int $addressBookId
926
-	 * @param string $uri
927
-	 * @returns array
928
-	 */
929
-	public function getContact($addressBookId, $uri) {
930
-		$result = [];
931
-		$query = $this->db->getQueryBuilder();
932
-		$query->select('*')->from($this->dbCardsTable)
933
-				->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
934
-				->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
935
-		$queryResult = $query->execute();
936
-		$contact = $queryResult->fetch();
937
-		$queryResult->closeCursor();
938
-
939
-		if (is_array($contact)) {
940
-			$result = $contact;
941
-		}
942
-
943
-		return $result;
944
-	}
945
-
946
-	/**
947
-	 * Returns the list of people whom this address book is shared with.
948
-	 *
949
-	 * Every element in this array should have the following properties:
950
-	 *   * href - Often a mailto: address
951
-	 *   * commonName - Optional, for example a first + last name
952
-	 *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
953
-	 *   * readOnly - boolean
954
-	 *   * summary - Optional, a description for the share
955
-	 *
956
-	 * @return array
957
-	 */
958
-	public function getShares($addressBookId) {
959
-		return $this->sharingBackend->getShares($addressBookId);
960
-	}
961
-
962
-	/**
963
-	 * update properties table
964
-	 *
965
-	 * @param int $addressBookId
966
-	 * @param string $cardUri
967
-	 * @param string $vCardSerialized
968
-	 */
969
-	protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
970
-		$cardId = $this->getCardId($addressBookId, $cardUri);
971
-		$vCard = $this->readCard($vCardSerialized);
972
-
973
-		$this->purgeProperties($addressBookId, $cardId);
974
-
975
-		$query = $this->db->getQueryBuilder();
976
-		$query->insert($this->dbCardsPropertiesTable)
977
-			->values(
978
-				[
979
-					'addressbookid' => $query->createNamedParameter($addressBookId),
980
-					'cardid' => $query->createNamedParameter($cardId),
981
-					'name' => $query->createParameter('name'),
982
-					'value' => $query->createParameter('value'),
983
-					'preferred' => $query->createParameter('preferred')
984
-				]
985
-			);
986
-
987
-		foreach ($vCard->children() as $property) {
988
-			if(!in_array($property->name, self::$indexProperties)) {
989
-				continue;
990
-			}
991
-			$preferred = 0;
992
-			foreach($property->parameters as $parameter) {
993
-				if ($parameter->name == 'TYPE' && strtoupper($parameter->getValue()) == 'PREF') {
994
-					$preferred = 1;
995
-					break;
996
-				}
997
-			}
998
-			$query->setParameter('name', $property->name);
999
-			$query->setParameter('value', substr($property->getValue(), 0, 254));
1000
-			$query->setParameter('preferred', $preferred);
1001
-			$query->execute();
1002
-		}
1003
-	}
1004
-
1005
-	/**
1006
-	 * read vCard data into a vCard object
1007
-	 *
1008
-	 * @param string $cardData
1009
-	 * @return VCard
1010
-	 */
1011
-	protected function readCard($cardData) {
1012
-		return  Reader::read($cardData);
1013
-	}
1014
-
1015
-	/**
1016
-	 * delete all properties from a given card
1017
-	 *
1018
-	 * @param int $addressBookId
1019
-	 * @param int $cardId
1020
-	 */
1021
-	protected function purgeProperties($addressBookId, $cardId) {
1022
-		$query = $this->db->getQueryBuilder();
1023
-		$query->delete($this->dbCardsPropertiesTable)
1024
-			->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
1025
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1026
-		$query->execute();
1027
-	}
1028
-
1029
-	/**
1030
-	 * get ID from a given contact
1031
-	 *
1032
-	 * @param int $addressBookId
1033
-	 * @param string $uri
1034
-	 * @return int
1035
-	 */
1036
-	protected function getCardId($addressBookId, $uri) {
1037
-		$query = $this->db->getQueryBuilder();
1038
-		$query->select('id')->from($this->dbCardsTable)
1039
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1040
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1041
-
1042
-		$result = $query->execute();
1043
-		$cardIds = $result->fetch();
1044
-		$result->closeCursor();
1045
-
1046
-		if (!isset($cardIds['id'])) {
1047
-			throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1048
-		}
1049
-
1050
-		return (int)$cardIds['id'];
1051
-	}
1052
-
1053
-	/**
1054
-	 * For shared address books the sharee is set in the ACL of the address book
1055
-	 * @param $addressBookId
1056
-	 * @param $acl
1057
-	 * @return array
1058
-	 */
1059
-	public function applyShareAcl($addressBookId, $acl) {
1060
-		return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
1061
-	}
1062
-
1063
-	private function convertPrincipal($principalUri, $toV2) {
1064
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1065
-			list(, $name) = URLUtil::splitPath($principalUri);
1066
-			if ($toV2 === true) {
1067
-				return "principals/users/$name";
1068
-			}
1069
-			return "principals/$name";
1070
-		}
1071
-		return $principalUri;
1072
-	}
51
+    const PERSONAL_ADDRESSBOOK_URI = 'contacts';
52
+    const PERSONAL_ADDRESSBOOK_NAME = 'Contacts';
53
+
54
+    /** @var Principal */
55
+    private $principalBackend;
56
+
57
+    /** @var string */
58
+    private $dbCardsTable = 'cards';
59
+
60
+    /** @var string */
61
+    private $dbCardsPropertiesTable = 'cards_properties';
62
+
63
+    /** @var IDBConnection */
64
+    private $db;
65
+
66
+    /** @var Backend */
67
+    private $sharingBackend;
68
+
69
+    /** @var array properties to index */
70
+    public static $indexProperties = array(
71
+            'BDAY', 'UID', 'N', 'FN', 'TITLE', 'ROLE', 'NOTE', 'NICKNAME',
72
+            'ORG', 'CATEGORIES', 'EMAIL', 'TEL', 'IMPP', 'ADR', 'URL', 'GEO', 'CLOUD');
73
+
74
+    /**
75
+     * @var string[] Map of uid => display name
76
+     */
77
+    protected $userDisplayNames;
78
+
79
+    /** @var IUserManager */
80
+    private $userManager;
81
+
82
+    /** @var EventDispatcherInterface */
83
+    private $dispatcher;
84
+
85
+    /**
86
+     * CardDavBackend constructor.
87
+     *
88
+     * @param IDBConnection $db
89
+     * @param Principal $principalBackend
90
+     * @param IUserManager $userManager
91
+     * @param EventDispatcherInterface $dispatcher
92
+     */
93
+    public function __construct(IDBConnection $db,
94
+                                Principal $principalBackend,
95
+                                IUserManager $userManager,
96
+                                EventDispatcherInterface $dispatcher = null) {
97
+        $this->db = $db;
98
+        $this->principalBackend = $principalBackend;
99
+        $this->userManager = $userManager;
100
+        $this->dispatcher = $dispatcher;
101
+        $this->sharingBackend = new Backend($this->db, $principalBackend, 'addressbook');
102
+    }
103
+
104
+    /**
105
+     * Return the number of address books for a principal
106
+     *
107
+     * @param $principalUri
108
+     * @return int
109
+     */
110
+    public function getAddressBooksForUserCount($principalUri) {
111
+        $principalUri = $this->convertPrincipal($principalUri, true);
112
+        $query = $this->db->getQueryBuilder();
113
+        $query->select($query->createFunction('COUNT(*)'))
114
+            ->from('addressbooks')
115
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
116
+
117
+        return (int)$query->execute()->fetchColumn();
118
+    }
119
+
120
+    /**
121
+     * Returns the list of address books for a specific user.
122
+     *
123
+     * Every addressbook should have the following properties:
124
+     *   id - an arbitrary unique id
125
+     *   uri - the 'basename' part of the url
126
+     *   principaluri - Same as the passed parameter
127
+     *
128
+     * Any additional clark-notation property may be passed besides this. Some
129
+     * common ones are :
130
+     *   {DAV:}displayname
131
+     *   {urn:ietf:params:xml:ns:carddav}addressbook-description
132
+     *   {http://calendarserver.org/ns/}getctag
133
+     *
134
+     * @param string $principalUri
135
+     * @return array
136
+     */
137
+    function getAddressBooksForUser($principalUri) {
138
+        $principalUriOriginal = $principalUri;
139
+        $principalUri = $this->convertPrincipal($principalUri, true);
140
+        $query = $this->db->getQueryBuilder();
141
+        $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
142
+            ->from('addressbooks')
143
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
144
+
145
+        $addressBooks = [];
146
+
147
+        $result = $query->execute();
148
+        while($row = $result->fetch()) {
149
+            $addressBooks[$row['id']] = [
150
+                'id'  => $row['id'],
151
+                'uri' => $row['uri'],
152
+                'principaluri' => $this->convertPrincipal($row['principaluri'], false),
153
+                '{DAV:}displayname' => $row['displayname'],
154
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
155
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
156
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
157
+            ];
158
+        }
159
+        $result->closeCursor();
160
+
161
+        // query for shared calendars
162
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
163
+        $principals[]= $principalUri;
164
+
165
+        $query = $this->db->getQueryBuilder();
166
+        $result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
167
+            ->from('dav_shares', 's')
168
+            ->join('s', 'addressbooks', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
169
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
170
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
171
+            ->setParameter('type', 'addressbook')
172
+            ->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
173
+            ->execute();
174
+
175
+        while($row = $result->fetch()) {
176
+            list(, $name) = URLUtil::splitPath($row['principaluri']);
177
+            $uri = $row['uri'] . '_shared_by_' . $name;
178
+            $displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
179
+            if (!isset($addressBooks[$row['id']])) {
180
+                $addressBooks[$row['id']] = [
181
+                    'id'  => $row['id'],
182
+                    'uri' => $uri,
183
+                    'principaluri' => $principalUri,
184
+                    '{DAV:}displayname' => $displayName,
185
+                    '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
186
+                    '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
187
+                    '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
188
+                    '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
189
+                    '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
190
+                ];
191
+            }
192
+        }
193
+        $result->closeCursor();
194
+
195
+        return array_values($addressBooks);
196
+    }
197
+
198
+    public function getUsersOwnAddressBooks($principalUri) {
199
+        $principalUriOriginal = $principalUri;
200
+        $principalUri = $this->convertPrincipal($principalUri, true);
201
+        $query = $this->db->getQueryBuilder();
202
+        $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
203
+                ->from('addressbooks')
204
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
205
+
206
+        $addressBooks = [];
207
+
208
+        $result = $query->execute();
209
+        while($row = $result->fetch()) {
210
+            $addressBooks[$row['id']] = [
211
+                'id'  => $row['id'],
212
+                'uri' => $row['uri'],
213
+                'principaluri' => $this->convertPrincipal($row['principaluri'], false),
214
+                '{DAV:}displayname' => $row['displayname'],
215
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
216
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
217
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
218
+            ];
219
+        }
220
+        $result->closeCursor();
221
+
222
+        return array_values($addressBooks);
223
+    }
224
+
225
+    private function getUserDisplayName($uid) {
226
+        if (!isset($this->userDisplayNames[$uid])) {
227
+            $user = $this->userManager->get($uid);
228
+
229
+            if ($user instanceof IUser) {
230
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
231
+            } else {
232
+                $this->userDisplayNames[$uid] = $uid;
233
+            }
234
+        }
235
+
236
+        return $this->userDisplayNames[$uid];
237
+    }
238
+
239
+    /**
240
+     * @param int $addressBookId
241
+     */
242
+    public function getAddressBookById($addressBookId) {
243
+        $query = $this->db->getQueryBuilder();
244
+        $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
245
+            ->from('addressbooks')
246
+            ->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
247
+            ->execute();
248
+
249
+        $row = $result->fetch();
250
+        $result->closeCursor();
251
+        if ($row === false) {
252
+            return null;
253
+        }
254
+
255
+        return [
256
+            'id'  => $row['id'],
257
+            'uri' => $row['uri'],
258
+            'principaluri' => $row['principaluri'],
259
+            '{DAV:}displayname' => $row['displayname'],
260
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
261
+            '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
262
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
263
+        ];
264
+    }
265
+
266
+    /**
267
+     * @param $addressBookUri
268
+     * @return array|null
269
+     */
270
+    public function getAddressBooksByUri($principal, $addressBookUri) {
271
+        $query = $this->db->getQueryBuilder();
272
+        $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
273
+            ->from('addressbooks')
274
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
275
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
276
+            ->setMaxResults(1)
277
+            ->execute();
278
+
279
+        $row = $result->fetch();
280
+        $result->closeCursor();
281
+        if ($row === false) {
282
+            return null;
283
+        }
284
+
285
+        return [
286
+                'id'  => $row['id'],
287
+                'uri' => $row['uri'],
288
+                'principaluri' => $row['principaluri'],
289
+                '{DAV:}displayname' => $row['displayname'],
290
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
291
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
292
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
293
+            ];
294
+    }
295
+
296
+    /**
297
+     * Updates properties for an address book.
298
+     *
299
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
300
+     * To do the actual updates, you must tell this object which properties
301
+     * you're going to process with the handle() method.
302
+     *
303
+     * Calling the handle method is like telling the PropPatch object "I
304
+     * promise I can handle updating this property".
305
+     *
306
+     * Read the PropPatch documentation for more info and examples.
307
+     *
308
+     * @param string $addressBookId
309
+     * @param \Sabre\DAV\PropPatch $propPatch
310
+     * @return void
311
+     */
312
+    function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
313
+        $supportedProperties = [
314
+            '{DAV:}displayname',
315
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description',
316
+        ];
317
+
318
+        $propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
319
+
320
+            $updates = [];
321
+            foreach($mutations as $property=>$newValue) {
322
+
323
+                switch($property) {
324
+                    case '{DAV:}displayname' :
325
+                        $updates['displayname'] = $newValue;
326
+                        break;
327
+                    case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
328
+                        $updates['description'] = $newValue;
329
+                        break;
330
+                }
331
+            }
332
+            $query = $this->db->getQueryBuilder();
333
+            $query->update('addressbooks');
334
+
335
+            foreach($updates as $key=>$value) {
336
+                $query->set($key, $query->createNamedParameter($value));
337
+            }
338
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
339
+            ->execute();
340
+
341
+            $this->addChange($addressBookId, "", 2);
342
+
343
+            return true;
344
+
345
+        });
346
+    }
347
+
348
+    /**
349
+     * Creates a new address book
350
+     *
351
+     * @param string $principalUri
352
+     * @param string $url Just the 'basename' of the url.
353
+     * @param array $properties
354
+     * @return int
355
+     * @throws BadRequest
356
+     */
357
+    function createAddressBook($principalUri, $url, array $properties) {
358
+        $values = [
359
+            'displayname' => null,
360
+            'description' => null,
361
+            'principaluri' => $principalUri,
362
+            'uri' => $url,
363
+            'synctoken' => 1
364
+        ];
365
+
366
+        foreach($properties as $property=>$newValue) {
367
+
368
+            switch($property) {
369
+                case '{DAV:}displayname' :
370
+                    $values['displayname'] = $newValue;
371
+                    break;
372
+                case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
373
+                    $values['description'] = $newValue;
374
+                    break;
375
+                default :
376
+                    throw new BadRequest('Unknown property: ' . $property);
377
+            }
378
+
379
+        }
380
+
381
+        // Fallback to make sure the displayname is set. Some clients may refuse
382
+        // to work with addressbooks not having a displayname.
383
+        if(is_null($values['displayname'])) {
384
+            $values['displayname'] = $url;
385
+        }
386
+
387
+        $query = $this->db->getQueryBuilder();
388
+        $query->insert('addressbooks')
389
+            ->values([
390
+                'uri' => $query->createParameter('uri'),
391
+                'displayname' => $query->createParameter('displayname'),
392
+                'description' => $query->createParameter('description'),
393
+                'principaluri' => $query->createParameter('principaluri'),
394
+                'synctoken' => $query->createParameter('synctoken'),
395
+            ])
396
+            ->setParameters($values)
397
+            ->execute();
398
+
399
+        return $query->getLastInsertId();
400
+    }
401
+
402
+    /**
403
+     * Deletes an entire addressbook and all its contents
404
+     *
405
+     * @param mixed $addressBookId
406
+     * @return void
407
+     */
408
+    function deleteAddressBook($addressBookId) {
409
+        $query = $this->db->getQueryBuilder();
410
+        $query->delete('cards')
411
+            ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
412
+            ->setParameter('addressbookid', $addressBookId)
413
+            ->execute();
414
+
415
+        $query->delete('addressbookchanges')
416
+            ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
417
+            ->setParameter('addressbookid', $addressBookId)
418
+            ->execute();
419
+
420
+        $query->delete('addressbooks')
421
+            ->where($query->expr()->eq('id', $query->createParameter('id')))
422
+            ->setParameter('id', $addressBookId)
423
+            ->execute();
424
+
425
+        $this->sharingBackend->deleteAllShares($addressBookId);
426
+
427
+        $query->delete($this->dbCardsPropertiesTable)
428
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
429
+            ->execute();
430
+
431
+    }
432
+
433
+    /**
434
+     * Returns all cards for a specific addressbook id.
435
+     *
436
+     * This method should return the following properties for each card:
437
+     *   * carddata - raw vcard data
438
+     *   * uri - Some unique url
439
+     *   * lastmodified - A unix timestamp
440
+     *
441
+     * It's recommended to also return the following properties:
442
+     *   * etag - A unique etag. This must change every time the card changes.
443
+     *   * size - The size of the card in bytes.
444
+     *
445
+     * If these last two properties are provided, less time will be spent
446
+     * calculating them. If they are specified, you can also ommit carddata.
447
+     * This may speed up certain requests, especially with large cards.
448
+     *
449
+     * @param mixed $addressBookId
450
+     * @return array
451
+     */
452
+    function getCards($addressBookId) {
453
+        $query = $this->db->getQueryBuilder();
454
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
455
+            ->from('cards')
456
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
457
+
458
+        $cards = [];
459
+
460
+        $result = $query->execute();
461
+        while($row = $result->fetch()) {
462
+            $row['etag'] = '"' . $row['etag'] . '"';
463
+            $row['carddata'] = $this->readBlob($row['carddata']);
464
+            $cards[] = $row;
465
+        }
466
+        $result->closeCursor();
467
+
468
+        return $cards;
469
+    }
470
+
471
+    /**
472
+     * Returns a specific card.
473
+     *
474
+     * The same set of properties must be returned as with getCards. The only
475
+     * exception is that 'carddata' is absolutely required.
476
+     *
477
+     * If the card does not exist, you must return false.
478
+     *
479
+     * @param mixed $addressBookId
480
+     * @param string $cardUri
481
+     * @return array
482
+     */
483
+    function getCard($addressBookId, $cardUri) {
484
+        $query = $this->db->getQueryBuilder();
485
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
486
+            ->from('cards')
487
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
488
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
489
+            ->setMaxResults(1);
490
+
491
+        $result = $query->execute();
492
+        $row = $result->fetch();
493
+        if (!$row) {
494
+            return false;
495
+        }
496
+        $row['etag'] = '"' . $row['etag'] . '"';
497
+        $row['carddata'] = $this->readBlob($row['carddata']);
498
+
499
+        return $row;
500
+    }
501
+
502
+    /**
503
+     * Returns a list of cards.
504
+     *
505
+     * This method should work identical to getCard, but instead return all the
506
+     * cards in the list as an array.
507
+     *
508
+     * If the backend supports this, it may allow for some speed-ups.
509
+     *
510
+     * @param mixed $addressBookId
511
+     * @param string[] $uris
512
+     * @return array
513
+     */
514
+    function getMultipleCards($addressBookId, array $uris) {
515
+        if (empty($uris)) {
516
+            return [];
517
+        }
518
+
519
+        $chunks = array_chunk($uris, 100);
520
+        $cards = [];
521
+
522
+        $query = $this->db->getQueryBuilder();
523
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
524
+            ->from('cards')
525
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
526
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
527
+
528
+        foreach ($chunks as $uris) {
529
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
530
+            $result = $query->execute();
531
+
532
+            while ($row = $result->fetch()) {
533
+                $row['etag'] = '"' . $row['etag'] . '"';
534
+                $row['carddata'] = $this->readBlob($row['carddata']);
535
+                $cards[] = $row;
536
+            }
537
+            $result->closeCursor();
538
+        }
539
+        return $cards;
540
+    }
541
+
542
+    /**
543
+     * Creates a new card.
544
+     *
545
+     * The addressbook id will be passed as the first argument. This is the
546
+     * same id as it is returned from the getAddressBooksForUser method.
547
+     *
548
+     * The cardUri is a base uri, and doesn't include the full path. The
549
+     * cardData argument is the vcard body, and is passed as a string.
550
+     *
551
+     * It is possible to return an ETag from this method. This ETag is for the
552
+     * newly created resource, and must be enclosed with double quotes (that
553
+     * is, the string itself must contain the double quotes).
554
+     *
555
+     * You should only return the ETag if you store the carddata as-is. If a
556
+     * subsequent GET request on the same card does not have the same body,
557
+     * byte-by-byte and you did return an ETag here, clients tend to get
558
+     * confused.
559
+     *
560
+     * If you don't return an ETag, you can just return null.
561
+     *
562
+     * @param mixed $addressBookId
563
+     * @param string $cardUri
564
+     * @param string $cardData
565
+     * @return string
566
+     */
567
+    function createCard($addressBookId, $cardUri, $cardData) {
568
+        $etag = md5($cardData);
569
+
570
+        $query = $this->db->getQueryBuilder();
571
+        $query->insert('cards')
572
+            ->values([
573
+                'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
574
+                'uri' => $query->createNamedParameter($cardUri),
575
+                'lastmodified' => $query->createNamedParameter(time()),
576
+                'addressbookid' => $query->createNamedParameter($addressBookId),
577
+                'size' => $query->createNamedParameter(strlen($cardData)),
578
+                'etag' => $query->createNamedParameter($etag),
579
+            ])
580
+            ->execute();
581
+
582
+        $this->addChange($addressBookId, $cardUri, 1);
583
+        $this->updateProperties($addressBookId, $cardUri, $cardData);
584
+
585
+        if (!is_null($this->dispatcher)) {
586
+            $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard',
587
+                new GenericEvent(null, [
588
+                    'addressBookId' => $addressBookId,
589
+                    'cardUri' => $cardUri,
590
+                    'cardData' => $cardData]));
591
+        }
592
+
593
+        return '"' . $etag . '"';
594
+    }
595
+
596
+    /**
597
+     * Updates a card.
598
+     *
599
+     * The addressbook id will be passed as the first argument. This is the
600
+     * same id as it is returned from the getAddressBooksForUser method.
601
+     *
602
+     * The cardUri is a base uri, and doesn't include the full path. The
603
+     * cardData argument is the vcard body, and is passed as a string.
604
+     *
605
+     * It is possible to return an ETag from this method. This ETag should
606
+     * match that of the updated resource, and must be enclosed with double
607
+     * quotes (that is: the string itself must contain the actual quotes).
608
+     *
609
+     * You should only return the ETag if you store the carddata as-is. If a
610
+     * subsequent GET request on the same card does not have the same body,
611
+     * byte-by-byte and you did return an ETag here, clients tend to get
612
+     * confused.
613
+     *
614
+     * If you don't return an ETag, you can just return null.
615
+     *
616
+     * @param mixed $addressBookId
617
+     * @param string $cardUri
618
+     * @param string $cardData
619
+     * @return string
620
+     */
621
+    function updateCard($addressBookId, $cardUri, $cardData) {
622
+
623
+        $etag = md5($cardData);
624
+        $query = $this->db->getQueryBuilder();
625
+        $query->update('cards')
626
+            ->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
627
+            ->set('lastmodified', $query->createNamedParameter(time()))
628
+            ->set('size', $query->createNamedParameter(strlen($cardData)))
629
+            ->set('etag', $query->createNamedParameter($etag))
630
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
631
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
632
+            ->execute();
633
+
634
+        $this->addChange($addressBookId, $cardUri, 2);
635
+        $this->updateProperties($addressBookId, $cardUri, $cardData);
636
+
637
+        if (!is_null($this->dispatcher)) {
638
+            $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard',
639
+                new GenericEvent(null, [
640
+                    'addressBookId' => $addressBookId,
641
+                    'cardUri' => $cardUri,
642
+                    'cardData' => $cardData]));
643
+        }
644
+
645
+        return '"' . $etag . '"';
646
+    }
647
+
648
+    /**
649
+     * Deletes a card
650
+     *
651
+     * @param mixed $addressBookId
652
+     * @param string $cardUri
653
+     * @return bool
654
+     */
655
+    function deleteCard($addressBookId, $cardUri) {
656
+        try {
657
+            $cardId = $this->getCardId($addressBookId, $cardUri);
658
+        } catch (\InvalidArgumentException $e) {
659
+            $cardId = null;
660
+        }
661
+        $query = $this->db->getQueryBuilder();
662
+        $ret = $query->delete('cards')
663
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
664
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
665
+            ->execute();
666
+
667
+        $this->addChange($addressBookId, $cardUri, 3);
668
+
669
+        if (!is_null($this->dispatcher)) {
670
+            $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard',
671
+                new GenericEvent(null, [
672
+                    'addressBookId' => $addressBookId,
673
+                    'cardUri' => $cardUri]));
674
+        }
675
+
676
+        if ($ret === 1) {
677
+            if ($cardId !== null) {
678
+                $this->purgeProperties($addressBookId, $cardId);
679
+            }
680
+            return true;
681
+        }
682
+
683
+        return false;
684
+    }
685
+
686
+    /**
687
+     * The getChanges method returns all the changes that have happened, since
688
+     * the specified syncToken in the specified address book.
689
+     *
690
+     * This function should return an array, such as the following:
691
+     *
692
+     * [
693
+     *   'syncToken' => 'The current synctoken',
694
+     *   'added'   => [
695
+     *      'new.txt',
696
+     *   ],
697
+     *   'modified'   => [
698
+     *      'modified.txt',
699
+     *   ],
700
+     *   'deleted' => [
701
+     *      'foo.php.bak',
702
+     *      'old.txt'
703
+     *   ]
704
+     * ];
705
+     *
706
+     * The returned syncToken property should reflect the *current* syncToken
707
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
708
+     * property. This is needed here too, to ensure the operation is atomic.
709
+     *
710
+     * If the $syncToken argument is specified as null, this is an initial
711
+     * sync, and all members should be reported.
712
+     *
713
+     * The modified property is an array of nodenames that have changed since
714
+     * the last token.
715
+     *
716
+     * The deleted property is an array with nodenames, that have been deleted
717
+     * from collection.
718
+     *
719
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
720
+     * 1, you only have to report changes that happened only directly in
721
+     * immediate descendants. If it's 2, it should also include changes from
722
+     * the nodes below the child collections. (grandchildren)
723
+     *
724
+     * The $limit argument allows a client to specify how many results should
725
+     * be returned at most. If the limit is not specified, it should be treated
726
+     * as infinite.
727
+     *
728
+     * If the limit (infinite or not) is higher than you're willing to return,
729
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
730
+     *
731
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
732
+     * return null.
733
+     *
734
+     * The limit is 'suggestive'. You are free to ignore it.
735
+     *
736
+     * @param string $addressBookId
737
+     * @param string $syncToken
738
+     * @param int $syncLevel
739
+     * @param int $limit
740
+     * @return array
741
+     */
742
+    function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
743
+        // Current synctoken
744
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
745
+        $stmt->execute([ $addressBookId ]);
746
+        $currentToken = $stmt->fetchColumn(0);
747
+
748
+        if (is_null($currentToken)) return null;
749
+
750
+        $result = [
751
+            'syncToken' => $currentToken,
752
+            'added'     => [],
753
+            'modified'  => [],
754
+            'deleted'   => [],
755
+        ];
756
+
757
+        if ($syncToken) {
758
+
759
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
760
+            if ($limit>0) {
761
+                $query .= " `LIMIT` " . (int)$limit;
762
+            }
763
+
764
+            // Fetching all changes
765
+            $stmt = $this->db->prepare($query);
766
+            $stmt->execute([$syncToken, $currentToken, $addressBookId]);
767
+
768
+            $changes = [];
769
+
770
+            // This loop ensures that any duplicates are overwritten, only the
771
+            // last change on a node is relevant.
772
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
773
+
774
+                $changes[$row['uri']] = $row['operation'];
775
+
776
+            }
777
+
778
+            foreach($changes as $uri => $operation) {
779
+
780
+                switch($operation) {
781
+                    case 1:
782
+                        $result['added'][] = $uri;
783
+                        break;
784
+                    case 2:
785
+                        $result['modified'][] = $uri;
786
+                        break;
787
+                    case 3:
788
+                        $result['deleted'][] = $uri;
789
+                        break;
790
+                }
791
+
792
+            }
793
+        } else {
794
+            // No synctoken supplied, this is the initial sync.
795
+            $query = "SELECT `uri` FROM `*PREFIX*cards` WHERE `addressbookid` = ?";
796
+            $stmt = $this->db->prepare($query);
797
+            $stmt->execute([$addressBookId]);
798
+
799
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
800
+        }
801
+        return $result;
802
+    }
803
+
804
+    /**
805
+     * Adds a change record to the addressbookchanges table.
806
+     *
807
+     * @param mixed $addressBookId
808
+     * @param string $objectUri
809
+     * @param int $operation 1 = add, 2 = modify, 3 = delete
810
+     * @return void
811
+     */
812
+    protected function addChange($addressBookId, $objectUri, $operation) {
813
+        $sql = 'INSERT INTO `*PREFIX*addressbookchanges`(`uri`, `synctoken`, `addressbookid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*addressbooks` WHERE `id` = ?';
814
+        $stmt = $this->db->prepare($sql);
815
+        $stmt->execute([
816
+            $objectUri,
817
+            $addressBookId,
818
+            $operation,
819
+            $addressBookId
820
+        ]);
821
+        $stmt = $this->db->prepare('UPDATE `*PREFIX*addressbooks` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
822
+        $stmt->execute([
823
+            $addressBookId
824
+        ]);
825
+    }
826
+
827
+    private function readBlob($cardData) {
828
+        if (is_resource($cardData)) {
829
+            return stream_get_contents($cardData);
830
+        }
831
+
832
+        return $cardData;
833
+    }
834
+
835
+    /**
836
+     * @param IShareable $shareable
837
+     * @param string[] $add
838
+     * @param string[] $remove
839
+     */
840
+    public function updateShares(IShareable $shareable, $add, $remove) {
841
+        $this->sharingBackend->updateShares($shareable, $add, $remove);
842
+    }
843
+
844
+    /**
845
+     * search contact
846
+     *
847
+     * @param int $addressBookId
848
+     * @param string $pattern which should match within the $searchProperties
849
+     * @param array $searchProperties defines the properties within the query pattern should match
850
+     * @return array an array of contacts which are arrays of key-value-pairs
851
+     */
852
+    public function search($addressBookId, $pattern, $searchProperties) {
853
+        $query = $this->db->getQueryBuilder();
854
+        $query2 = $this->db->getQueryBuilder();
855
+        $query2->selectDistinct('cp.cardid')->from($this->dbCardsPropertiesTable, 'cp');
856
+        foreach ($searchProperties as $property) {
857
+            $query2->orWhere(
858
+                $query2->expr()->andX(
859
+                    $query2->expr()->eq('cp.name', $query->createNamedParameter($property)),
860
+                    $query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%'))
861
+                )
862
+            );
863
+        }
864
+        $query2->andWhere($query2->expr()->eq('cp.addressbookid', $query->createNamedParameter($addressBookId)));
865
+
866
+        $query->select('c.carddata', 'c.uri')->from($this->dbCardsTable, 'c')
867
+            ->where($query->expr()->in('c.id', $query->createFunction($query2->getSQL())));
868
+
869
+        $result = $query->execute();
870
+        $cards = $result->fetchAll();
871
+
872
+        $result->closeCursor();
873
+
874
+        return array_map(function($array) {
875
+            $array['carddata'] = $this->readBlob($array['carddata']);
876
+            return $array;
877
+        }, $cards);
878
+    }
879
+
880
+    /**
881
+     * @param int $bookId
882
+     * @param string $name
883
+     * @return array
884
+     */
885
+    public function collectCardProperties($bookId, $name) {
886
+        $query = $this->db->getQueryBuilder();
887
+        $result = $query->selectDistinct('value')
888
+            ->from($this->dbCardsPropertiesTable)
889
+            ->where($query->expr()->eq('name', $query->createNamedParameter($name)))
890
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
891
+            ->execute();
892
+
893
+        $all = $result->fetchAll(PDO::FETCH_COLUMN);
894
+        $result->closeCursor();
895
+
896
+        return $all;
897
+    }
898
+
899
+    /**
900
+     * get URI from a given contact
901
+     *
902
+     * @param int $id
903
+     * @return string
904
+     */
905
+    public function getCardUri($id) {
906
+        $query = $this->db->getQueryBuilder();
907
+        $query->select('uri')->from($this->dbCardsTable)
908
+                ->where($query->expr()->eq('id', $query->createParameter('id')))
909
+                ->setParameter('id', $id);
910
+
911
+        $result = $query->execute();
912
+        $uri = $result->fetch();
913
+        $result->closeCursor();
914
+
915
+        if (!isset($uri['uri'])) {
916
+            throw new \InvalidArgumentException('Card does not exists: ' . $id);
917
+        }
918
+
919
+        return $uri['uri'];
920
+    }
921
+
922
+    /**
923
+     * return contact with the given URI
924
+     *
925
+     * @param int $addressBookId
926
+     * @param string $uri
927
+     * @returns array
928
+     */
929
+    public function getContact($addressBookId, $uri) {
930
+        $result = [];
931
+        $query = $this->db->getQueryBuilder();
932
+        $query->select('*')->from($this->dbCardsTable)
933
+                ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
934
+                ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
935
+        $queryResult = $query->execute();
936
+        $contact = $queryResult->fetch();
937
+        $queryResult->closeCursor();
938
+
939
+        if (is_array($contact)) {
940
+            $result = $contact;
941
+        }
942
+
943
+        return $result;
944
+    }
945
+
946
+    /**
947
+     * Returns the list of people whom this address book is shared with.
948
+     *
949
+     * Every element in this array should have the following properties:
950
+     *   * href - Often a mailto: address
951
+     *   * commonName - Optional, for example a first + last name
952
+     *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
953
+     *   * readOnly - boolean
954
+     *   * summary - Optional, a description for the share
955
+     *
956
+     * @return array
957
+     */
958
+    public function getShares($addressBookId) {
959
+        return $this->sharingBackend->getShares($addressBookId);
960
+    }
961
+
962
+    /**
963
+     * update properties table
964
+     *
965
+     * @param int $addressBookId
966
+     * @param string $cardUri
967
+     * @param string $vCardSerialized
968
+     */
969
+    protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
970
+        $cardId = $this->getCardId($addressBookId, $cardUri);
971
+        $vCard = $this->readCard($vCardSerialized);
972
+
973
+        $this->purgeProperties($addressBookId, $cardId);
974
+
975
+        $query = $this->db->getQueryBuilder();
976
+        $query->insert($this->dbCardsPropertiesTable)
977
+            ->values(
978
+                [
979
+                    'addressbookid' => $query->createNamedParameter($addressBookId),
980
+                    'cardid' => $query->createNamedParameter($cardId),
981
+                    'name' => $query->createParameter('name'),
982
+                    'value' => $query->createParameter('value'),
983
+                    'preferred' => $query->createParameter('preferred')
984
+                ]
985
+            );
986
+
987
+        foreach ($vCard->children() as $property) {
988
+            if(!in_array($property->name, self::$indexProperties)) {
989
+                continue;
990
+            }
991
+            $preferred = 0;
992
+            foreach($property->parameters as $parameter) {
993
+                if ($parameter->name == 'TYPE' && strtoupper($parameter->getValue()) == 'PREF') {
994
+                    $preferred = 1;
995
+                    break;
996
+                }
997
+            }
998
+            $query->setParameter('name', $property->name);
999
+            $query->setParameter('value', substr($property->getValue(), 0, 254));
1000
+            $query->setParameter('preferred', $preferred);
1001
+            $query->execute();
1002
+        }
1003
+    }
1004
+
1005
+    /**
1006
+     * read vCard data into a vCard object
1007
+     *
1008
+     * @param string $cardData
1009
+     * @return VCard
1010
+     */
1011
+    protected function readCard($cardData) {
1012
+        return  Reader::read($cardData);
1013
+    }
1014
+
1015
+    /**
1016
+     * delete all properties from a given card
1017
+     *
1018
+     * @param int $addressBookId
1019
+     * @param int $cardId
1020
+     */
1021
+    protected function purgeProperties($addressBookId, $cardId) {
1022
+        $query = $this->db->getQueryBuilder();
1023
+        $query->delete($this->dbCardsPropertiesTable)
1024
+            ->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
1025
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1026
+        $query->execute();
1027
+    }
1028
+
1029
+    /**
1030
+     * get ID from a given contact
1031
+     *
1032
+     * @param int $addressBookId
1033
+     * @param string $uri
1034
+     * @return int
1035
+     */
1036
+    protected function getCardId($addressBookId, $uri) {
1037
+        $query = $this->db->getQueryBuilder();
1038
+        $query->select('id')->from($this->dbCardsTable)
1039
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1040
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1041
+
1042
+        $result = $query->execute();
1043
+        $cardIds = $result->fetch();
1044
+        $result->closeCursor();
1045
+
1046
+        if (!isset($cardIds['id'])) {
1047
+            throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1048
+        }
1049
+
1050
+        return (int)$cardIds['id'];
1051
+    }
1052
+
1053
+    /**
1054
+     * For shared address books the sharee is set in the ACL of the address book
1055
+     * @param $addressBookId
1056
+     * @param $acl
1057
+     * @return array
1058
+     */
1059
+    public function applyShareAcl($addressBookId, $acl) {
1060
+        return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
1061
+    }
1062
+
1063
+    private function convertPrincipal($principalUri, $toV2) {
1064
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1065
+            list(, $name) = URLUtil::splitPath($principalUri);
1066
+            if ($toV2 === true) {
1067
+                return "principals/users/$name";
1068
+            }
1069
+            return "principals/$name";
1070
+        }
1071
+        return $principalUri;
1072
+    }
1073 1073
 }
Please login to merge, or discard this patch.
Spacing   +47 added lines, -47 removed lines patch added patch discarded remove patch
@@ -114,7 +114,7 @@  discard block
 block discarded – undo
114 114
 			->from('addressbooks')
115 115
 			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
116 116
 
117
-		return (int)$query->execute()->fetchColumn();
117
+		return (int) $query->execute()->fetchColumn();
118 118
 	}
119 119
 
120 120
 	/**
@@ -145,22 +145,22 @@  discard block
 block discarded – undo
145 145
 		$addressBooks = [];
146 146
 
147 147
 		$result = $query->execute();
148
-		while($row = $result->fetch()) {
148
+		while ($row = $result->fetch()) {
149 149
 			$addressBooks[$row['id']] = [
150 150
 				'id'  => $row['id'],
151 151
 				'uri' => $row['uri'],
152 152
 				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
153 153
 				'{DAV:}displayname' => $row['displayname'],
154
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
154
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
155 155
 				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
156
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
156
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
157 157
 			];
158 158
 		}
159 159
 		$result->closeCursor();
160 160
 
161 161
 		// query for shared calendars
162 162
 		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
163
-		$principals[]= $principalUri;
163
+		$principals[] = $principalUri;
164 164
 
165 165
 		$query = $this->db->getQueryBuilder();
166 166
 		$result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
@@ -172,21 +172,21 @@  discard block
 block discarded – undo
172 172
 			->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
173 173
 			->execute();
174 174
 
175
-		while($row = $result->fetch()) {
175
+		while ($row = $result->fetch()) {
176 176
 			list(, $name) = URLUtil::splitPath($row['principaluri']);
177
-			$uri = $row['uri'] . '_shared_by_' . $name;
178
-			$displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
177
+			$uri = $row['uri'].'_shared_by_'.$name;
178
+			$displayName = $row['displayname'].' ('.$this->getUserDisplayName($name).')';
179 179
 			if (!isset($addressBooks[$row['id']])) {
180 180
 				$addressBooks[$row['id']] = [
181 181
 					'id'  => $row['id'],
182 182
 					'uri' => $uri,
183 183
 					'principaluri' => $principalUri,
184 184
 					'{DAV:}displayname' => $displayName,
185
-					'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
185
+					'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
186 186
 					'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
187
-					'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
188
-					'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
189
-					'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
187
+					'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
188
+					'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $row['principaluri'],
189
+					'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
190 190
 				];
191 191
 			}
192 192
 		}
@@ -206,15 +206,15 @@  discard block
 block discarded – undo
206 206
 		$addressBooks = [];
207 207
 
208 208
 		$result = $query->execute();
209
-		while($row = $result->fetch()) {
209
+		while ($row = $result->fetch()) {
210 210
 			$addressBooks[$row['id']] = [
211 211
 				'id'  => $row['id'],
212 212
 				'uri' => $row['uri'],
213 213
 				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
214 214
 				'{DAV:}displayname' => $row['displayname'],
215
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
215
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
216 216
 				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
217
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
217
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
218 218
 			];
219 219
 		}
220 220
 		$result->closeCursor();
@@ -257,9 +257,9 @@  discard block
 block discarded – undo
257 257
 			'uri' => $row['uri'],
258 258
 			'principaluri' => $row['principaluri'],
259 259
 			'{DAV:}displayname' => $row['displayname'],
260
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
260
+			'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
261 261
 			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
262
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
262
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
263 263
 		];
264 264
 	}
265 265
 
@@ -287,9 +287,9 @@  discard block
 block discarded – undo
287 287
 				'uri' => $row['uri'],
288 288
 				'principaluri' => $row['principaluri'],
289 289
 				'{DAV:}displayname' => $row['displayname'],
290
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
290
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
291 291
 				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
292
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
292
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
293 293
 			];
294 294
 	}
295 295
 
@@ -312,19 +312,19 @@  discard block
 block discarded – undo
312 312
 	function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
313 313
 		$supportedProperties = [
314 314
 			'{DAV:}displayname',
315
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description',
315
+			'{'.Plugin::NS_CARDDAV.'}addressbook-description',
316 316
 		];
317 317
 
318 318
 		$propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
319 319
 
320 320
 			$updates = [];
321
-			foreach($mutations as $property=>$newValue) {
321
+			foreach ($mutations as $property=>$newValue) {
322 322
 
323
-				switch($property) {
323
+				switch ($property) {
324 324
 					case '{DAV:}displayname' :
325 325
 						$updates['displayname'] = $newValue;
326 326
 						break;
327
-					case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
327
+					case '{'.Plugin::NS_CARDDAV.'}addressbook-description' :
328 328
 						$updates['description'] = $newValue;
329 329
 						break;
330 330
 				}
@@ -332,7 +332,7 @@  discard block
 block discarded – undo
332 332
 			$query = $this->db->getQueryBuilder();
333 333
 			$query->update('addressbooks');
334 334
 
335
-			foreach($updates as $key=>$value) {
335
+			foreach ($updates as $key=>$value) {
336 336
 				$query->set($key, $query->createNamedParameter($value));
337 337
 			}
338 338
 			$query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
@@ -363,24 +363,24 @@  discard block
 block discarded – undo
363 363
 			'synctoken' => 1
364 364
 		];
365 365
 
366
-		foreach($properties as $property=>$newValue) {
366
+		foreach ($properties as $property=>$newValue) {
367 367
 
368
-			switch($property) {
368
+			switch ($property) {
369 369
 				case '{DAV:}displayname' :
370 370
 					$values['displayname'] = $newValue;
371 371
 					break;
372
-				case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
372
+				case '{'.Plugin::NS_CARDDAV.'}addressbook-description' :
373 373
 					$values['description'] = $newValue;
374 374
 					break;
375 375
 				default :
376
-					throw new BadRequest('Unknown property: ' . $property);
376
+					throw new BadRequest('Unknown property: '.$property);
377 377
 			}
378 378
 
379 379
 		}
380 380
 
381 381
 		// Fallback to make sure the displayname is set. Some clients may refuse
382 382
 		// to work with addressbooks not having a displayname.
383
-		if(is_null($values['displayname'])) {
383
+		if (is_null($values['displayname'])) {
384 384
 			$values['displayname'] = $url;
385 385
 		}
386 386
 
@@ -458,8 +458,8 @@  discard block
 block discarded – undo
458 458
 		$cards = [];
459 459
 
460 460
 		$result = $query->execute();
461
-		while($row = $result->fetch()) {
462
-			$row['etag'] = '"' . $row['etag'] . '"';
461
+		while ($row = $result->fetch()) {
462
+			$row['etag'] = '"'.$row['etag'].'"';
463 463
 			$row['carddata'] = $this->readBlob($row['carddata']);
464 464
 			$cards[] = $row;
465 465
 		}
@@ -493,7 +493,7 @@  discard block
 block discarded – undo
493 493
 		if (!$row) {
494 494
 			return false;
495 495
 		}
496
-		$row['etag'] = '"' . $row['etag'] . '"';
496
+		$row['etag'] = '"'.$row['etag'].'"';
497 497
 		$row['carddata'] = $this->readBlob($row['carddata']);
498 498
 
499 499
 		return $row;
@@ -530,7 +530,7 @@  discard block
 block discarded – undo
530 530
 			$result = $query->execute();
531 531
 
532 532
 			while ($row = $result->fetch()) {
533
-				$row['etag'] = '"' . $row['etag'] . '"';
533
+				$row['etag'] = '"'.$row['etag'].'"';
534 534
 				$row['carddata'] = $this->readBlob($row['carddata']);
535 535
 				$cards[] = $row;
536 536
 			}
@@ -590,7 +590,7 @@  discard block
 block discarded – undo
590 590
 					'cardData' => $cardData]));
591 591
 		}
592 592
 
593
-		return '"' . $etag . '"';
593
+		return '"'.$etag.'"';
594 594
 	}
595 595
 
596 596
 	/**
@@ -642,7 +642,7 @@  discard block
 block discarded – undo
642 642
 					'cardData' => $cardData]));
643 643
 		}
644 644
 
645
-		return '"' . $etag . '"';
645
+		return '"'.$etag.'"';
646 646
 	}
647 647
 
648 648
 	/**
@@ -742,7 +742,7 @@  discard block
 block discarded – undo
742 742
 	function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
743 743
 		// Current synctoken
744 744
 		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
745
-		$stmt->execute([ $addressBookId ]);
745
+		$stmt->execute([$addressBookId]);
746 746
 		$currentToken = $stmt->fetchColumn(0);
747 747
 
748 748
 		if (is_null($currentToken)) return null;
@@ -757,8 +757,8 @@  discard block
 block discarded – undo
757 757
 		if ($syncToken) {
758 758
 
759 759
 			$query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
760
-			if ($limit>0) {
761
-				$query .= " `LIMIT` " . (int)$limit;
760
+			if ($limit > 0) {
761
+				$query .= " `LIMIT` ".(int) $limit;
762 762
 			}
763 763
 
764 764
 			// Fetching all changes
@@ -769,15 +769,15 @@  discard block
 block discarded – undo
769 769
 
770 770
 			// This loop ensures that any duplicates are overwritten, only the
771 771
 			// last change on a node is relevant.
772
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
772
+			while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
773 773
 
774 774
 				$changes[$row['uri']] = $row['operation'];
775 775
 
776 776
 			}
777 777
 
778
-			foreach($changes as $uri => $operation) {
778
+			foreach ($changes as $uri => $operation) {
779 779
 
780
-				switch($operation) {
780
+				switch ($operation) {
781 781
 					case 1:
782 782
 						$result['added'][] = $uri;
783 783
 						break;
@@ -857,7 +857,7 @@  discard block
 block discarded – undo
857 857
 			$query2->orWhere(
858 858
 				$query2->expr()->andX(
859 859
 					$query2->expr()->eq('cp.name', $query->createNamedParameter($property)),
860
-					$query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%'))
860
+					$query2->expr()->ilike('cp.value', $query->createNamedParameter('%'.$this->db->escapeLikeParameter($pattern).'%'))
861 861
 				)
862 862
 			);
863 863
 		}
@@ -913,7 +913,7 @@  discard block
 block discarded – undo
913 913
 		$result->closeCursor();
914 914
 
915 915
 		if (!isset($uri['uri'])) {
916
-			throw new \InvalidArgumentException('Card does not exists: ' . $id);
916
+			throw new \InvalidArgumentException('Card does not exists: '.$id);
917 917
 		}
918 918
 
919 919
 		return $uri['uri'];
@@ -985,11 +985,11 @@  discard block
 block discarded – undo
985 985
 			);
986 986
 
987 987
 		foreach ($vCard->children() as $property) {
988
-			if(!in_array($property->name, self::$indexProperties)) {
988
+			if (!in_array($property->name, self::$indexProperties)) {
989 989
 				continue;
990 990
 			}
991 991
 			$preferred = 0;
992
-			foreach($property->parameters as $parameter) {
992
+			foreach ($property->parameters as $parameter) {
993 993
 				if ($parameter->name == 'TYPE' && strtoupper($parameter->getValue()) == 'PREF') {
994 994
 					$preferred = 1;
995 995
 					break;
@@ -1044,10 +1044,10 @@  discard block
 block discarded – undo
1044 1044
 		$result->closeCursor();
1045 1045
 
1046 1046
 		if (!isset($cardIds['id'])) {
1047
-			throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1047
+			throw new \InvalidArgumentException('Card does not exists: '.$uri);
1048 1048
 		}
1049 1049
 
1050
-		return (int)$cardIds['id'];
1050
+		return (int) $cardIds['id'];
1051 1051
 	}
1052 1052
 
1053 1053
 	/**
Please login to merge, or discard this patch.
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -745,7 +745,9 @@
 block discarded – undo
745 745
 		$stmt->execute([ $addressBookId ]);
746 746
 		$currentToken = $stmt->fetchColumn(0);
747 747
 
748
-		if (is_null($currentToken)) return null;
748
+		if (is_null($currentToken)) {
749
+		    return null;
750
+		}
749 751
 
750 752
 		$result = [
751 753
 			'syncToken' => $currentToken,
Please login to merge, or discard this patch.