Completed
Pull Request — master (#3233)
by Christoph
14:41
created
apps/theming/lib/Util.php 3 patches
Doc Comments   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -52,7 +52,7 @@  discard block
 block discarded – undo
52 52
 	/**
53 53
 	 * get color for on-page elements:
54 54
 	 * theme color by default, grey if theme color is to bright
55
-	 * @param $color
55
+	 * @param string $color
56 56
 	 * @return string
57 57
 	 */
58 58
 	public function elementColor($color) {
@@ -83,7 +83,7 @@  discard block
 block discarded – undo
83 83
 	}
84 84
 
85 85
 	/**
86
-	 * @param $color
86
+	 * @param string $color
87 87
 	 * @return string base64 encoded radio button svg
88 88
 	 */
89 89
 	public function generateRadioButton($color) {
@@ -152,8 +152,8 @@  discard block
 block discarded – undo
152 152
 	/**
153 153
 	 * replace default color with a custom one
154 154
 	 *
155
-	 * @param $svg string content of a svg file
156
-	 * @param $color string color to match
155
+	 * @param string $svg string content of a svg file
156
+	 * @param string $color string color to match
157 157
 	 * @return string
158 158
 	 */
159 159
 	public function colorizeSvg($svg, $color) {
Please login to merge, or discard this patch.
Indentation   +159 added lines, -159 removed lines patch added patch discarded remove patch
@@ -30,164 +30,164 @@
 block discarded – undo
30 30
 
31 31
 class Util {
32 32
 
33
-	/** @var IConfig */
34
-	private $config;
35
-
36
-	/** @var IRootFolder */
37
-	private $rootFolder;
38
-
39
-	/** @var IAppManager */
40
-	private $appManager;
41
-
42
-	/**
43
-	 * Util constructor.
44
-	 *
45
-	 * @param IConfig $config
46
-	 * @param IRootFolder $rootFolder
47
-	 * @param IAppManager $appManager
48
-	 */
49
-	public function __construct(IConfig $config, IRootFolder $rootFolder, IAppManager $appManager) {
50
-		$this->config = $config;
51
-		$this->rootFolder = $rootFolder;
52
-		$this->appManager = $appManager;
53
-	}
54
-
55
-	/**
56
-	 * @param string $color rgb color value
57
-	 * @return bool
58
-	 */
59
-	public function invertTextColor($color) {
60
-		$l = $this->calculateLuminance($color);
61
-		if($l>0.5) {
62
-			return true;
63
-		} else {
64
-			return false;
65
-		}
66
-	}
67
-
68
-	/**
69
-	 * get color for on-page elements:
70
-	 * theme color by default, grey if theme color is to bright
71
-	 * @param $color
72
-	 * @return string
73
-	 */
74
-	public function elementColor($color) {
75
-		$l = $this->calculateLuminance($color);
76
-		if($l>0.8) {
77
-			return '#555555';
78
-		} else {
79
-			return $color;
80
-		}
81
-	}
82
-
83
-	/**
84
-	 * @param string $color rgb color value
85
-	 * @return float
86
-	 */
87
-	public function calculateLuminance($color) {
88
-		$hex = preg_replace("/[^0-9A-Fa-f]/", '', $color);
89
-		if (strlen($hex) === 3) {
90
-			$hex = $hex{0} . $hex{0} . $hex{1} . $hex{1} . $hex{2} . $hex{2};
91
-		}
92
-		if (strlen($hex) !== 6) {
93
-			return 0;
94
-		}
95
-		$r = hexdec(substr($hex, 0, 2));
96
-		$g = hexdec(substr($hex, 2, 2));
97
-		$b = hexdec(substr($hex, 4, 2));
98
-		return (0.299 * $r + 0.587 * $g + 0.114 * $b)/255;
99
-	}
100
-
101
-	/**
102
-	 * @param $color
103
-	 * @return string base64 encoded radio button svg
104
-	 */
105
-	public function generateRadioButton($color) {
106
-		$radioButtonIcon = '<svg xmlns="http://www.w3.org/2000/svg" height="16" width="16">' .
107
-			'<path d="M8 1a7 7 0 0 0-7 7 7 7 0 0 0 7 7 7 7 0 0 0 7-7 7 7 0 0 0-7-7zm0 1a6 6 0 0 1 6 6 6 6 0 0 1-6 6 6 6 0 0 1-6-6 6 6 0 0 1 6-6zm0 2a4 4 0 1 0 0 8 4 4 0 0 0 0-8z" fill="'.$color.'"/></svg>';
108
-		return base64_encode($radioButtonIcon);
109
-	}
110
-
111
-
112
-	/**
113
-	 * @param $app string app name
114
-	 * @return string path to app icon / logo
115
-	 */
116
-	public function getAppIcon($app) {
117
-		$app = str_replace(array('\0', '/', '\\', '..'), '', $app);
118
-		try {
119
-			$appPath = $this->appManager->getAppPath($app);
120
-			$icon = $appPath . '/img/' . $app . '.svg';
121
-			if (file_exists($icon)) {
122
-				return $icon;
123
-			}
124
-			$icon = $appPath . '/img/app.svg';
125
-			if (file_exists($icon)) {
126
-				return $icon;
127
-			}
128
-		} catch (AppPathNotFoundException $e) {}
129
-
130
-		if($this->config->getAppValue('theming', 'logoMime', '') !== '' && $this->rootFolder->nodeExists('/themedinstancelogo')) {
131
-			return $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/themedinstancelogo';
132
-		}
133
-		return \OC::$SERVERROOT . '/core/img/logo.svg';
134
-	}
135
-
136
-	/**
137
-	 * @param $app string app name
138
-	 * @param $image string relative path to image in app folder
139
-	 * @return string|false absolute path to image
140
-	 */
141
-	public function getAppImage($app, $image) {
142
-		$app = str_replace(array('\0', '/', '\\', '..'), '', $app);
143
-		$image = str_replace(array('\0', '\\', '..'), '', $image);
144
-		if ($app === "core") {
145
-			$icon = \OC::$SERVERROOT . '/core/img/' . $image;
146
-			if (file_exists($icon)) {
147
-				return $icon;
148
-			}
149
-		}
150
-
151
-		try {
152
-			$appPath = $this->appManager->getAppPath($app);
153
-		} catch (AppPathNotFoundException $e) {
154
-			return false;
155
-		}
156
-
157
-		$icon = $appPath . '/img/' . $image;
158
-		if (file_exists($icon)) {
159
-			return $icon;
160
-		}
161
-		$icon = $appPath . '/img/' . $image . '.svg';
162
-		if (file_exists($icon)) {
163
-			return $icon;
164
-		}
165
-		$icon = $appPath . '/img/' . $image . '.png';
166
-		if (file_exists($icon)) {
167
-			return $icon;
168
-		}
169
-		$icon = $appPath . '/img/' . $image . '.gif';
170
-		if (file_exists($icon)) {
171
-			return $icon;
172
-		}
173
-		$icon = $appPath . '/img/' . $image . '.jpg';
174
-		if (file_exists($icon)) {
175
-			return $icon;
176
-		}
177
-
178
-		return false;
179
-	}
180
-
181
-	/**
182
-	 * replace default color with a custom one
183
-	 *
184
-	 * @param $svg string content of a svg file
185
-	 * @param $color string color to match
186
-	 * @return string
187
-	 */
188
-	public function colorizeSvg($svg, $color) {
189
-		$svg = preg_replace('/#0082c9/i', $color, $svg);
190
-		return $svg;
191
-	}
33
+    /** @var IConfig */
34
+    private $config;
35
+
36
+    /** @var IRootFolder */
37
+    private $rootFolder;
38
+
39
+    /** @var IAppManager */
40
+    private $appManager;
41
+
42
+    /**
43
+     * Util constructor.
44
+     *
45
+     * @param IConfig $config
46
+     * @param IRootFolder $rootFolder
47
+     * @param IAppManager $appManager
48
+     */
49
+    public function __construct(IConfig $config, IRootFolder $rootFolder, IAppManager $appManager) {
50
+        $this->config = $config;
51
+        $this->rootFolder = $rootFolder;
52
+        $this->appManager = $appManager;
53
+    }
54
+
55
+    /**
56
+     * @param string $color rgb color value
57
+     * @return bool
58
+     */
59
+    public function invertTextColor($color) {
60
+        $l = $this->calculateLuminance($color);
61
+        if($l>0.5) {
62
+            return true;
63
+        } else {
64
+            return false;
65
+        }
66
+    }
67
+
68
+    /**
69
+     * get color for on-page elements:
70
+     * theme color by default, grey if theme color is to bright
71
+     * @param $color
72
+     * @return string
73
+     */
74
+    public function elementColor($color) {
75
+        $l = $this->calculateLuminance($color);
76
+        if($l>0.8) {
77
+            return '#555555';
78
+        } else {
79
+            return $color;
80
+        }
81
+    }
82
+
83
+    /**
84
+     * @param string $color rgb color value
85
+     * @return float
86
+     */
87
+    public function calculateLuminance($color) {
88
+        $hex = preg_replace("/[^0-9A-Fa-f]/", '', $color);
89
+        if (strlen($hex) === 3) {
90
+            $hex = $hex{0} . $hex{0} . $hex{1} . $hex{1} . $hex{2} . $hex{2};
91
+        }
92
+        if (strlen($hex) !== 6) {
93
+            return 0;
94
+        }
95
+        $r = hexdec(substr($hex, 0, 2));
96
+        $g = hexdec(substr($hex, 2, 2));
97
+        $b = hexdec(substr($hex, 4, 2));
98
+        return (0.299 * $r + 0.587 * $g + 0.114 * $b)/255;
99
+    }
100
+
101
+    /**
102
+     * @param $color
103
+     * @return string base64 encoded radio button svg
104
+     */
105
+    public function generateRadioButton($color) {
106
+        $radioButtonIcon = '<svg xmlns="http://www.w3.org/2000/svg" height="16" width="16">' .
107
+            '<path d="M8 1a7 7 0 0 0-7 7 7 7 0 0 0 7 7 7 7 0 0 0 7-7 7 7 0 0 0-7-7zm0 1a6 6 0 0 1 6 6 6 6 0 0 1-6 6 6 6 0 0 1-6-6 6 6 0 0 1 6-6zm0 2a4 4 0 1 0 0 8 4 4 0 0 0 0-8z" fill="'.$color.'"/></svg>';
108
+        return base64_encode($radioButtonIcon);
109
+    }
110
+
111
+
112
+    /**
113
+     * @param $app string app name
114
+     * @return string path to app icon / logo
115
+     */
116
+    public function getAppIcon($app) {
117
+        $app = str_replace(array('\0', '/', '\\', '..'), '', $app);
118
+        try {
119
+            $appPath = $this->appManager->getAppPath($app);
120
+            $icon = $appPath . '/img/' . $app . '.svg';
121
+            if (file_exists($icon)) {
122
+                return $icon;
123
+            }
124
+            $icon = $appPath . '/img/app.svg';
125
+            if (file_exists($icon)) {
126
+                return $icon;
127
+            }
128
+        } catch (AppPathNotFoundException $e) {}
129
+
130
+        if($this->config->getAppValue('theming', 'logoMime', '') !== '' && $this->rootFolder->nodeExists('/themedinstancelogo')) {
131
+            return $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/themedinstancelogo';
132
+        }
133
+        return \OC::$SERVERROOT . '/core/img/logo.svg';
134
+    }
135
+
136
+    /**
137
+     * @param $app string app name
138
+     * @param $image string relative path to image in app folder
139
+     * @return string|false absolute path to image
140
+     */
141
+    public function getAppImage($app, $image) {
142
+        $app = str_replace(array('\0', '/', '\\', '..'), '', $app);
143
+        $image = str_replace(array('\0', '\\', '..'), '', $image);
144
+        if ($app === "core") {
145
+            $icon = \OC::$SERVERROOT . '/core/img/' . $image;
146
+            if (file_exists($icon)) {
147
+                return $icon;
148
+            }
149
+        }
150
+
151
+        try {
152
+            $appPath = $this->appManager->getAppPath($app);
153
+        } catch (AppPathNotFoundException $e) {
154
+            return false;
155
+        }
156
+
157
+        $icon = $appPath . '/img/' . $image;
158
+        if (file_exists($icon)) {
159
+            return $icon;
160
+        }
161
+        $icon = $appPath . '/img/' . $image . '.svg';
162
+        if (file_exists($icon)) {
163
+            return $icon;
164
+        }
165
+        $icon = $appPath . '/img/' . $image . '.png';
166
+        if (file_exists($icon)) {
167
+            return $icon;
168
+        }
169
+        $icon = $appPath . '/img/' . $image . '.gif';
170
+        if (file_exists($icon)) {
171
+            return $icon;
172
+        }
173
+        $icon = $appPath . '/img/' . $image . '.jpg';
174
+        if (file_exists($icon)) {
175
+            return $icon;
176
+        }
177
+
178
+        return false;
179
+    }
180
+
181
+    /**
182
+     * replace default color with a custom one
183
+     *
184
+     * @param $svg string content of a svg file
185
+     * @param $color string color to match
186
+     * @return string
187
+     */
188
+    public function colorizeSvg($svg, $color) {
189
+        $svg = preg_replace('/#0082c9/i', $color, $svg);
190
+        return $svg;
191
+    }
192 192
 
193 193
 }
Please login to merge, or discard this patch.
Spacing   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -58,7 +58,7 @@  discard block
 block discarded – undo
58 58
 	 */
59 59
 	public function invertTextColor($color) {
60 60
 		$l = $this->calculateLuminance($color);
61
-		if($l>0.5) {
61
+		if ($l > 0.5) {
62 62
 			return true;
63 63
 		} else {
64 64
 			return false;
@@ -73,7 +73,7 @@  discard block
 block discarded – undo
73 73
 	 */
74 74
 	public function elementColor($color) {
75 75
 		$l = $this->calculateLuminance($color);
76
-		if($l>0.8) {
76
+		if ($l > 0.8) {
77 77
 			return '#555555';
78 78
 		} else {
79 79
 			return $color;
@@ -87,7 +87,7 @@  discard block
 block discarded – undo
87 87
 	public function calculateLuminance($color) {
88 88
 		$hex = preg_replace("/[^0-9A-Fa-f]/", '', $color);
89 89
 		if (strlen($hex) === 3) {
90
-			$hex = $hex{0} . $hex{0} . $hex{1} . $hex{1} . $hex{2} . $hex{2};
90
+			$hex = $hex{0}.$hex{0}.$hex{1}.$hex{1}.$hex{2}.$hex{2};
91 91
 		}
92 92
 		if (strlen($hex) !== 6) {
93 93
 			return 0;
@@ -95,7 +95,7 @@  discard block
 block discarded – undo
95 95
 		$r = hexdec(substr($hex, 0, 2));
96 96
 		$g = hexdec(substr($hex, 2, 2));
97 97
 		$b = hexdec(substr($hex, 4, 2));
98
-		return (0.299 * $r + 0.587 * $g + 0.114 * $b)/255;
98
+		return (0.299 * $r + 0.587 * $g + 0.114 * $b) / 255;
99 99
 	}
100 100
 
101 101
 	/**
@@ -103,7 +103,7 @@  discard block
 block discarded – undo
103 103
 	 * @return string base64 encoded radio button svg
104 104
 	 */
105 105
 	public function generateRadioButton($color) {
106
-		$radioButtonIcon = '<svg xmlns="http://www.w3.org/2000/svg" height="16" width="16">' .
106
+		$radioButtonIcon = '<svg xmlns="http://www.w3.org/2000/svg" height="16" width="16">'.
107 107
 			'<path d="M8 1a7 7 0 0 0-7 7 7 7 0 0 0 7 7 7 7 0 0 0 7-7 7 7 0 0 0-7-7zm0 1a6 6 0 0 1 6 6 6 6 0 0 1-6 6 6 6 0 0 1-6-6 6 6 0 0 1 6-6zm0 2a4 4 0 1 0 0 8 4 4 0 0 0 0-8z" fill="'.$color.'"/></svg>';
108 108
 		return base64_encode($radioButtonIcon);
109 109
 	}
@@ -117,20 +117,20 @@  discard block
 block discarded – undo
117 117
 		$app = str_replace(array('\0', '/', '\\', '..'), '', $app);
118 118
 		try {
119 119
 			$appPath = $this->appManager->getAppPath($app);
120
-			$icon = $appPath . '/img/' . $app . '.svg';
120
+			$icon = $appPath.'/img/'.$app.'.svg';
121 121
 			if (file_exists($icon)) {
122 122
 				return $icon;
123 123
 			}
124
-			$icon = $appPath . '/img/app.svg';
124
+			$icon = $appPath.'/img/app.svg';
125 125
 			if (file_exists($icon)) {
126 126
 				return $icon;
127 127
 			}
128 128
 		} catch (AppPathNotFoundException $e) {}
129 129
 
130
-		if($this->config->getAppValue('theming', 'logoMime', '') !== '' && $this->rootFolder->nodeExists('/themedinstancelogo')) {
131
-			return $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/themedinstancelogo';
130
+		if ($this->config->getAppValue('theming', 'logoMime', '') !== '' && $this->rootFolder->nodeExists('/themedinstancelogo')) {
131
+			return $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data').'/themedinstancelogo';
132 132
 		}
133
-		return \OC::$SERVERROOT . '/core/img/logo.svg';
133
+		return \OC::$SERVERROOT.'/core/img/logo.svg';
134 134
 	}
135 135
 
136 136
 	/**
@@ -142,7 +142,7 @@  discard block
 block discarded – undo
142 142
 		$app = str_replace(array('\0', '/', '\\', '..'), '', $app);
143 143
 		$image = str_replace(array('\0', '\\', '..'), '', $image);
144 144
 		if ($app === "core") {
145
-			$icon = \OC::$SERVERROOT . '/core/img/' . $image;
145
+			$icon = \OC::$SERVERROOT.'/core/img/'.$image;
146 146
 			if (file_exists($icon)) {
147 147
 				return $icon;
148 148
 			}
@@ -154,23 +154,23 @@  discard block
 block discarded – undo
154 154
 			return false;
155 155
 		}
156 156
 
157
-		$icon = $appPath . '/img/' . $image;
157
+		$icon = $appPath.'/img/'.$image;
158 158
 		if (file_exists($icon)) {
159 159
 			return $icon;
160 160
 		}
161
-		$icon = $appPath . '/img/' . $image . '.svg';
161
+		$icon = $appPath.'/img/'.$image.'.svg';
162 162
 		if (file_exists($icon)) {
163 163
 			return $icon;
164 164
 		}
165
-		$icon = $appPath . '/img/' . $image . '.png';
165
+		$icon = $appPath.'/img/'.$image.'.png';
166 166
 		if (file_exists($icon)) {
167 167
 			return $icon;
168 168
 		}
169
-		$icon = $appPath . '/img/' . $image . '.gif';
169
+		$icon = $appPath.'/img/'.$image.'.gif';
170 170
 		if (file_exists($icon)) {
171 171
 			return $icon;
172 172
 		}
173
-		$icon = $appPath . '/img/' . $image . '.jpg';
173
+		$icon = $appPath.'/img/'.$image.'.jpg';
174 174
 		if (file_exists($icon)) {
175 175
 			return $icon;
176 176
 		}
Please login to merge, or discard this patch.
apps/files_external/lib/Service/DBConfigService.php 3 patches
Doc Comments   +16 added lines patch added patch discarded remove patch
@@ -89,6 +89,9 @@  discard block
 block discarded – undo
89 89
 		return $this->getMountsFromQuery($query);
90 90
 	}
91 91
 
92
+	/**
93
+	 * @param string $userId
94
+	 */
92 95
 	public function getMountsForUser($userId, $groupIds) {
93 96
 		$builder = $this->connection->getQueryBuilder();
94 97
 		$query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
@@ -125,6 +128,10 @@  discard block
 block discarded – undo
125 128
 		return $this->getMountsFromQuery($query);
126 129
 	}
127 130
 
131
+	/**
132
+	 * @param integer $type
133
+	 * @param string|null $value
134
+	 */
128 135
 	protected function getForQuery(IQueryBuilder $builder, $type, $value) {
129 136
 		$query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
130 137
 			->from('external_mounts', 'm')
@@ -332,6 +339,9 @@  discard block
 block discarded – undo
332 339
 		}
333 340
 	}
334 341
 
342
+	/**
343
+	 * @param integer $mountId
344
+	 */
335 345
 	public function addApplicable($mountId, $type, $value) {
336 346
 		$this->connection->insertIfNotExist('*PREFIX*external_applicable', [
337 347
 			'mount_id' => $mountId,
@@ -340,6 +350,9 @@  discard block
 block discarded – undo
340 350
 		], ['mount_id', 'type', 'value']);
341 351
 	}
342 352
 
353
+	/**
354
+	 * @param integer $mountId
355
+	 */
343 356
 	public function removeApplicable($mountId, $type, $value) {
344 357
 		$builder = $this->connection->getQueryBuilder();
345 358
 		$query = $builder->delete('external_applicable')
@@ -473,6 +486,9 @@  discard block
 block discarded – undo
473 486
 		return array_combine($keys, $values);
474 487
 	}
475 488
 
489
+	/**
490
+	 * @param string $value
491
+	 */
476 492
 	private function encryptValue($value) {
477 493
 		return $this->crypto->encrypt($value);
478 494
 	}
Please login to merge, or discard this patch.
Indentation   +452 added lines, -452 removed lines patch added patch discarded remove patch
@@ -32,456 +32,456 @@
 block discarded – undo
32 32
  * Stores the mount config in the database
33 33
  */
34 34
 class DBConfigService {
35
-	const MOUNT_TYPE_ADMIN = 1;
36
-	const MOUNT_TYPE_PERSONAl = 2;
37
-
38
-	const APPLICABLE_TYPE_GLOBAL = 1;
39
-	const APPLICABLE_TYPE_GROUP = 2;
40
-	const APPLICABLE_TYPE_USER = 3;
41
-
42
-	/**
43
-	 * @var IDBConnection
44
-	 */
45
-	private $connection;
46
-
47
-	/**
48
-	 * @var ICrypto
49
-	 */
50
-	private $crypto;
51
-
52
-	/**
53
-	 * DBConfigService constructor.
54
-	 *
55
-	 * @param IDBConnection $connection
56
-	 * @param ICrypto $crypto
57
-	 */
58
-	public function __construct(IDBConnection $connection, ICrypto $crypto) {
59
-		$this->connection = $connection;
60
-		$this->crypto = $crypto;
61
-	}
62
-
63
-	/**
64
-	 * @param int $mountId
65
-	 * @return array
66
-	 */
67
-	public function getMountById($mountId) {
68
-		$builder = $this->connection->getQueryBuilder();
69
-		$query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
70
-			->from('external_mounts', 'm')
71
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
72
-		$mounts = $this->getMountsFromQuery($query);
73
-		if (count($mounts) > 0) {
74
-			return $mounts[0];
75
-		} else {
76
-			return null;
77
-		}
78
-	}
79
-
80
-	/**
81
-	 * Get all configured mounts
82
-	 *
83
-	 * @return array
84
-	 */
85
-	public function getAllMounts() {
86
-		$builder = $this->connection->getQueryBuilder();
87
-		$query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
88
-			->from('external_mounts');
89
-		return $this->getMountsFromQuery($query);
90
-	}
91
-
92
-	public function getMountsForUser($userId, $groupIds) {
93
-		$builder = $this->connection->getQueryBuilder();
94
-		$query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
95
-			->from('external_mounts', 'm')
96
-			->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
97
-			->where($builder->expr()->orX(
98
-				$builder->expr()->andX( // global mounts
99
-					$builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_GLOBAL, IQueryBuilder::PARAM_INT)),
100
-					$builder->expr()->isNull('a.value')
101
-				),
102
-				$builder->expr()->andX( // mounts for user
103
-					$builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_USER, IQueryBuilder::PARAM_INT)),
104
-					$builder->expr()->eq('a.value', $builder->createNamedParameter($userId))
105
-				),
106
-				$builder->expr()->andX( // mounts for group
107
-					$builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_GROUP, IQueryBuilder::PARAM_INT)),
108
-					$builder->expr()->in('a.value', $builder->createNamedParameter($groupIds, IQueryBuilder::PARAM_INT_ARRAY))
109
-				)
110
-			));
111
-
112
-		return $this->getMountsFromQuery($query);
113
-	}
114
-
115
-	/**
116
-	 * Get admin defined mounts
117
-	 *
118
-	 * @return array
119
-	 */
120
-	public function getAdminMounts() {
121
-		$builder = $this->connection->getQueryBuilder();
122
-		$query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
123
-			->from('external_mounts')
124
-			->where($builder->expr()->eq('type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
125
-		return $this->getMountsFromQuery($query);
126
-	}
127
-
128
-	protected function getForQuery(IQueryBuilder $builder, $type, $value) {
129
-		$query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
130
-			->from('external_mounts', 'm')
131
-			->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
132
-			->where($builder->expr()->eq('a.type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)));
133
-
134
-		if (is_null($value)) {
135
-			$query = $query->andWhere($builder->expr()->isNull('a.value'));
136
-		} else {
137
-			$query = $query->andWhere($builder->expr()->eq('a.value', $builder->createNamedParameter($value)));
138
-		}
139
-
140
-		return $query;
141
-	}
142
-
143
-	/**
144
-	 * Get mounts by applicable
145
-	 *
146
-	 * @param int $type any of the self::APPLICABLE_TYPE_ constants
147
-	 * @param string|null $value user_id, group_id or null for global mounts
148
-	 * @return array
149
-	 */
150
-	public function getMountsFor($type, $value) {
151
-		$builder = $this->connection->getQueryBuilder();
152
-		$query = $this->getForQuery($builder, $type, $value);
153
-
154
-		return $this->getMountsFromQuery($query);
155
-	}
156
-
157
-	/**
158
-	 * Get admin defined mounts by applicable
159
-	 *
160
-	 * @param int $type any of the self::APPLICABLE_TYPE_ constants
161
-	 * @param string|null $value user_id, group_id or null for global mounts
162
-	 * @return array
163
-	 */
164
-	public function getAdminMountsFor($type, $value) {
165
-		$builder = $this->connection->getQueryBuilder();
166
-		$query = $this->getForQuery($builder, $type, $value);
167
-		$query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
168
-
169
-		return $this->getMountsFromQuery($query);
170
-	}
171
-
172
-	/**
173
-	 * Get admin defined mounts for multiple applicable
174
-	 *
175
-	 * @param int $type any of the self::APPLICABLE_TYPE_ constants
176
-	 * @param string[] $values user_ids or group_ids
177
-	 * @return array
178
-	 */
179
-	public function getAdminMountsForMultiple($type, array $values) {
180
-		$builder = $this->connection->getQueryBuilder();
181
-		$params = array_map(function ($value) use ($builder) {
182
-			return $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR);
183
-		}, $values);
184
-
185
-		$query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
186
-			->from('external_mounts', 'm')
187
-			->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
188
-			->where($builder->expr()->eq('a.type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)))
189
-			->andWhere($builder->expr()->in('a.value', $params));
190
-		$query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
191
-
192
-		return $this->getMountsFromQuery($query);
193
-	}
194
-
195
-	/**
196
-	 * Get user defined mounts by applicable
197
-	 *
198
-	 * @param int $type any of the self::APPLICABLE_TYPE_ constants
199
-	 * @param string|null $value user_id, group_id or null for global mounts
200
-	 * @return array
201
-	 */
202
-	public function getUserMountsFor($type, $value) {
203
-		$builder = $this->connection->getQueryBuilder();
204
-		$query = $this->getForQuery($builder, $type, $value);
205
-		$query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_PERSONAl, IQueryBuilder::PARAM_INT)));
206
-
207
-		return $this->getMountsFromQuery($query);
208
-	}
209
-
210
-	/**
211
-	 * Add a mount to the database
212
-	 *
213
-	 * @param string $mountPoint
214
-	 * @param string $storageBackend
215
-	 * @param string $authBackend
216
-	 * @param int $priority
217
-	 * @param int $type self::MOUNT_TYPE_ADMIN or self::MOUNT_TYPE_PERSONAL
218
-	 * @return int the id of the new mount
219
-	 */
220
-	public function addMount($mountPoint, $storageBackend, $authBackend, $priority, $type) {
221
-		if (!$priority) {
222
-			$priority = 100;
223
-		}
224
-		$builder = $this->connection->getQueryBuilder();
225
-		$query = $builder->insert('external_mounts')
226
-			->values([
227
-				'mount_point' => $builder->createNamedParameter($mountPoint, IQueryBuilder::PARAM_STR),
228
-				'storage_backend' => $builder->createNamedParameter($storageBackend, IQueryBuilder::PARAM_STR),
229
-				'auth_backend' => $builder->createNamedParameter($authBackend, IQueryBuilder::PARAM_STR),
230
-				'priority' => $builder->createNamedParameter($priority, IQueryBuilder::PARAM_INT),
231
-				'type' => $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)
232
-			]);
233
-		$query->execute();
234
-		return (int)$this->connection->lastInsertId('*PREFIX*external_mounts');
235
-	}
236
-
237
-	/**
238
-	 * Remove a mount from the database
239
-	 *
240
-	 * @param int $mountId
241
-	 */
242
-	public function removeMount($mountId) {
243
-		$builder = $this->connection->getQueryBuilder();
244
-		$query = $builder->delete('external_mounts')
245
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
246
-		$query->execute();
247
-
248
-		$query = $builder->delete('external_applicable')
249
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
250
-		$query->execute();
251
-
252
-		$query = $builder->delete('external_config')
253
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
254
-		$query->execute();
255
-
256
-		$query = $builder->delete('external_options')
257
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
258
-		$query->execute();
259
-	}
260
-
261
-	/**
262
-	 * @param int $mountId
263
-	 * @param string $newMountPoint
264
-	 */
265
-	public function setMountPoint($mountId, $newMountPoint) {
266
-		$builder = $this->connection->getQueryBuilder();
267
-
268
-		$query = $builder->update('external_mounts')
269
-			->set('mount_point', $builder->createNamedParameter($newMountPoint))
270
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
271
-
272
-		$query->execute();
273
-	}
274
-
275
-	/**
276
-	 * @param int $mountId
277
-	 * @param string $newAuthBackend
278
-	 */
279
-	public function setAuthBackend($mountId, $newAuthBackend) {
280
-		$builder = $this->connection->getQueryBuilder();
281
-
282
-		$query = $builder->update('external_mounts')
283
-			->set('auth_backend', $builder->createNamedParameter($newAuthBackend))
284
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
285
-
286
-		$query->execute();
287
-	}
288
-
289
-	/**
290
-	 * @param int $mountId
291
-	 * @param string $key
292
-	 * @param string $value
293
-	 */
294
-	public function setConfig($mountId, $key, $value) {
295
-		if ($key === 'password') {
296
-			$value = $this->encryptValue($value);
297
-		}
298
-		$count = $this->connection->insertIfNotExist('*PREFIX*external_config', [
299
-			'mount_id' => $mountId,
300
-			'key' => $key,
301
-			'value' => $value
302
-		], ['mount_id', 'key']);
303
-		if ($count === 0) {
304
-			$builder = $this->connection->getQueryBuilder();
305
-			$query = $builder->update('external_config')
306
-				->set('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR))
307
-				->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
308
-				->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)));
309
-			$query->execute();
310
-		}
311
-	}
312
-
313
-	/**
314
-	 * @param int $mountId
315
-	 * @param string $key
316
-	 * @param string $value
317
-	 */
318
-	public function setOption($mountId, $key, $value) {
319
-
320
-		$count = $this->connection->insertIfNotExist('*PREFIX*external_options', [
321
-			'mount_id' => $mountId,
322
-			'key' => $key,
323
-			'value' => json_encode($value)
324
-		], ['mount_id', 'key']);
325
-		if ($count === 0) {
326
-			$builder = $this->connection->getQueryBuilder();
327
-			$query = $builder->update('external_options')
328
-				->set('value', $builder->createNamedParameter(json_encode($value), IQueryBuilder::PARAM_STR))
329
-				->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
330
-				->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)));
331
-			$query->execute();
332
-		}
333
-	}
334
-
335
-	public function addApplicable($mountId, $type, $value) {
336
-		$this->connection->insertIfNotExist('*PREFIX*external_applicable', [
337
-			'mount_id' => $mountId,
338
-			'type' => $type,
339
-			'value' => $value
340
-		], ['mount_id', 'type', 'value']);
341
-	}
342
-
343
-	public function removeApplicable($mountId, $type, $value) {
344
-		$builder = $this->connection->getQueryBuilder();
345
-		$query = $builder->delete('external_applicable')
346
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
347
-			->andWhere($builder->expr()->eq('type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)));
348
-
349
-		if (is_null($value)) {
350
-			$query = $query->andWhere($builder->expr()->isNull('value'));
351
-		} else {
352
-			$query = $query->andWhere($builder->expr()->eq('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR)));
353
-		}
354
-
355
-		$query->execute();
356
-	}
357
-
358
-	private function getMountsFromQuery(IQueryBuilder $query) {
359
-		$result = $query->execute();
360
-		$mounts = $result->fetchAll();
361
-		$uniqueMounts = [];
362
-		foreach ($mounts as $mount) {
363
-			$id = $mount['mount_id'];
364
-			if (!isset($uniqueMounts[$id])) {
365
-				$uniqueMounts[$id] = $mount;
366
-			}
367
-		}
368
-		$uniqueMounts = array_values($uniqueMounts);
369
-
370
-		$mountIds = array_map(function ($mount) {
371
-			return $mount['mount_id'];
372
-		}, $uniqueMounts);
373
-		$mountIds = array_values(array_unique($mountIds));
374
-
375
-		$applicable = $this->getApplicableForMounts($mountIds);
376
-		$config = $this->getConfigForMounts($mountIds);
377
-		$options = $this->getOptionsForMounts($mountIds);
378
-
379
-		return array_map(function ($mount, $applicable, $config, $options) {
380
-			$mount['type'] = (int)$mount['type'];
381
-			$mount['priority'] = (int)$mount['priority'];
382
-			$mount['applicable'] = $applicable;
383
-			$mount['config'] = $config;
384
-			$mount['options'] = $options;
385
-			return $mount;
386
-		}, $uniqueMounts, $applicable, $config, $options);
387
-	}
388
-
389
-	/**
390
-	 * Get mount options from a table grouped by mount id
391
-	 *
392
-	 * @param string $table
393
-	 * @param string[] $fields
394
-	 * @param int[] $mountIds
395
-	 * @return array [$mountId => [['field1' => $value1, ...], ...], ...]
396
-	 */
397
-	private function selectForMounts($table, array $fields, array $mountIds) {
398
-		if (count($mountIds) === 0) {
399
-			return [];
400
-		}
401
-		$builder = $this->connection->getQueryBuilder();
402
-		$fields[] = 'mount_id';
403
-		$placeHolders = array_map(function ($id) use ($builder) {
404
-			return $builder->createPositionalParameter($id, IQueryBuilder::PARAM_INT);
405
-		}, $mountIds);
406
-		$query = $builder->select($fields)
407
-			->from($table)
408
-			->where($builder->expr()->in('mount_id', $placeHolders));
409
-		$rows = $query->execute()->fetchAll();
410
-
411
-		$result = [];
412
-		foreach ($mountIds as $mountId) {
413
-			$result[$mountId] = [];
414
-		}
415
-		foreach ($rows as $row) {
416
-			if (isset($row['type'])) {
417
-				$row['type'] = (int)$row['type'];
418
-			}
419
-			$result[$row['mount_id']][] = $row;
420
-		}
421
-		return $result;
422
-	}
423
-
424
-	/**
425
-	 * @param int[] $mountIds
426
-	 * @return array [$id => [['type' => $type, 'value' => $value], ...], ...]
427
-	 */
428
-	public function getApplicableForMounts($mountIds) {
429
-		return $this->selectForMounts('external_applicable', ['type', 'value'], $mountIds);
430
-	}
431
-
432
-	/**
433
-	 * @param int[] $mountIds
434
-	 * @return array [$id => ['key1' => $value1, ...], ...]
435
-	 */
436
-	public function getConfigForMounts($mountIds) {
437
-		$mountConfigs = $this->selectForMounts('external_config', ['key', 'value'], $mountIds);
438
-		return array_map([$this, 'createKeyValueMap'], $mountConfigs);
439
-	}
440
-
441
-	/**
442
-	 * @param int[] $mountIds
443
-	 * @return array [$id => ['key1' => $value1, ...], ...]
444
-	 */
445
-	public function getOptionsForMounts($mountIds) {
446
-		$mountOptions = $this->selectForMounts('external_options', ['key', 'value'], $mountIds);
447
-		$optionsMap = array_map([$this, 'createKeyValueMap'], $mountOptions);
448
-		return array_map(function (array $options) {
449
-			return array_map(function ($option) {
450
-				return json_decode($option);
451
-			}, $options);
452
-		}, $optionsMap);
453
-	}
454
-
455
-	/**
456
-	 * @param array $keyValuePairs [['key'=>$key, 'value=>$value], ...]
457
-	 * @return array ['key1' => $value1, ...]
458
-	 */
459
-	private function createKeyValueMap(array $keyValuePairs) {
460
-		$decryptedPairts = array_map(function ($pair) {
461
-			if ($pair['key'] === 'password') {
462
-				$pair['value'] = $this->decryptValue($pair['value']);
463
-			}
464
-			return $pair;
465
-		}, $keyValuePairs);
466
-		$keys = array_map(function ($pair) {
467
-			return $pair['key'];
468
-		}, $decryptedPairts);
469
-		$values = array_map(function ($pair) {
470
-			return $pair['value'];
471
-		}, $decryptedPairts);
472
-
473
-		return array_combine($keys, $values);
474
-	}
475
-
476
-	private function encryptValue($value) {
477
-		return $this->crypto->encrypt($value);
478
-	}
479
-
480
-	private function decryptValue($value) {
481
-		try {
482
-			return $this->crypto->decrypt($value);
483
-		} catch (\Exception $e) {
484
-			return $value;
485
-		}
486
-	}
35
+    const MOUNT_TYPE_ADMIN = 1;
36
+    const MOUNT_TYPE_PERSONAl = 2;
37
+
38
+    const APPLICABLE_TYPE_GLOBAL = 1;
39
+    const APPLICABLE_TYPE_GROUP = 2;
40
+    const APPLICABLE_TYPE_USER = 3;
41
+
42
+    /**
43
+     * @var IDBConnection
44
+     */
45
+    private $connection;
46
+
47
+    /**
48
+     * @var ICrypto
49
+     */
50
+    private $crypto;
51
+
52
+    /**
53
+     * DBConfigService constructor.
54
+     *
55
+     * @param IDBConnection $connection
56
+     * @param ICrypto $crypto
57
+     */
58
+    public function __construct(IDBConnection $connection, ICrypto $crypto) {
59
+        $this->connection = $connection;
60
+        $this->crypto = $crypto;
61
+    }
62
+
63
+    /**
64
+     * @param int $mountId
65
+     * @return array
66
+     */
67
+    public function getMountById($mountId) {
68
+        $builder = $this->connection->getQueryBuilder();
69
+        $query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
70
+            ->from('external_mounts', 'm')
71
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
72
+        $mounts = $this->getMountsFromQuery($query);
73
+        if (count($mounts) > 0) {
74
+            return $mounts[0];
75
+        } else {
76
+            return null;
77
+        }
78
+    }
79
+
80
+    /**
81
+     * Get all configured mounts
82
+     *
83
+     * @return array
84
+     */
85
+    public function getAllMounts() {
86
+        $builder = $this->connection->getQueryBuilder();
87
+        $query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
88
+            ->from('external_mounts');
89
+        return $this->getMountsFromQuery($query);
90
+    }
91
+
92
+    public function getMountsForUser($userId, $groupIds) {
93
+        $builder = $this->connection->getQueryBuilder();
94
+        $query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
95
+            ->from('external_mounts', 'm')
96
+            ->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
97
+            ->where($builder->expr()->orX(
98
+                $builder->expr()->andX( // global mounts
99
+                    $builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_GLOBAL, IQueryBuilder::PARAM_INT)),
100
+                    $builder->expr()->isNull('a.value')
101
+                ),
102
+                $builder->expr()->andX( // mounts for user
103
+                    $builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_USER, IQueryBuilder::PARAM_INT)),
104
+                    $builder->expr()->eq('a.value', $builder->createNamedParameter($userId))
105
+                ),
106
+                $builder->expr()->andX( // mounts for group
107
+                    $builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_GROUP, IQueryBuilder::PARAM_INT)),
108
+                    $builder->expr()->in('a.value', $builder->createNamedParameter($groupIds, IQueryBuilder::PARAM_INT_ARRAY))
109
+                )
110
+            ));
111
+
112
+        return $this->getMountsFromQuery($query);
113
+    }
114
+
115
+    /**
116
+     * Get admin defined mounts
117
+     *
118
+     * @return array
119
+     */
120
+    public function getAdminMounts() {
121
+        $builder = $this->connection->getQueryBuilder();
122
+        $query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
123
+            ->from('external_mounts')
124
+            ->where($builder->expr()->eq('type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
125
+        return $this->getMountsFromQuery($query);
126
+    }
127
+
128
+    protected function getForQuery(IQueryBuilder $builder, $type, $value) {
129
+        $query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
130
+            ->from('external_mounts', 'm')
131
+            ->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
132
+            ->where($builder->expr()->eq('a.type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)));
133
+
134
+        if (is_null($value)) {
135
+            $query = $query->andWhere($builder->expr()->isNull('a.value'));
136
+        } else {
137
+            $query = $query->andWhere($builder->expr()->eq('a.value', $builder->createNamedParameter($value)));
138
+        }
139
+
140
+        return $query;
141
+    }
142
+
143
+    /**
144
+     * Get mounts by applicable
145
+     *
146
+     * @param int $type any of the self::APPLICABLE_TYPE_ constants
147
+     * @param string|null $value user_id, group_id or null for global mounts
148
+     * @return array
149
+     */
150
+    public function getMountsFor($type, $value) {
151
+        $builder = $this->connection->getQueryBuilder();
152
+        $query = $this->getForQuery($builder, $type, $value);
153
+
154
+        return $this->getMountsFromQuery($query);
155
+    }
156
+
157
+    /**
158
+     * Get admin defined mounts by applicable
159
+     *
160
+     * @param int $type any of the self::APPLICABLE_TYPE_ constants
161
+     * @param string|null $value user_id, group_id or null for global mounts
162
+     * @return array
163
+     */
164
+    public function getAdminMountsFor($type, $value) {
165
+        $builder = $this->connection->getQueryBuilder();
166
+        $query = $this->getForQuery($builder, $type, $value);
167
+        $query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
168
+
169
+        return $this->getMountsFromQuery($query);
170
+    }
171
+
172
+    /**
173
+     * Get admin defined mounts for multiple applicable
174
+     *
175
+     * @param int $type any of the self::APPLICABLE_TYPE_ constants
176
+     * @param string[] $values user_ids or group_ids
177
+     * @return array
178
+     */
179
+    public function getAdminMountsForMultiple($type, array $values) {
180
+        $builder = $this->connection->getQueryBuilder();
181
+        $params = array_map(function ($value) use ($builder) {
182
+            return $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR);
183
+        }, $values);
184
+
185
+        $query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
186
+            ->from('external_mounts', 'm')
187
+            ->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
188
+            ->where($builder->expr()->eq('a.type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)))
189
+            ->andWhere($builder->expr()->in('a.value', $params));
190
+        $query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
191
+
192
+        return $this->getMountsFromQuery($query);
193
+    }
194
+
195
+    /**
196
+     * Get user defined mounts by applicable
197
+     *
198
+     * @param int $type any of the self::APPLICABLE_TYPE_ constants
199
+     * @param string|null $value user_id, group_id or null for global mounts
200
+     * @return array
201
+     */
202
+    public function getUserMountsFor($type, $value) {
203
+        $builder = $this->connection->getQueryBuilder();
204
+        $query = $this->getForQuery($builder, $type, $value);
205
+        $query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_PERSONAl, IQueryBuilder::PARAM_INT)));
206
+
207
+        return $this->getMountsFromQuery($query);
208
+    }
209
+
210
+    /**
211
+     * Add a mount to the database
212
+     *
213
+     * @param string $mountPoint
214
+     * @param string $storageBackend
215
+     * @param string $authBackend
216
+     * @param int $priority
217
+     * @param int $type self::MOUNT_TYPE_ADMIN or self::MOUNT_TYPE_PERSONAL
218
+     * @return int the id of the new mount
219
+     */
220
+    public function addMount($mountPoint, $storageBackend, $authBackend, $priority, $type) {
221
+        if (!$priority) {
222
+            $priority = 100;
223
+        }
224
+        $builder = $this->connection->getQueryBuilder();
225
+        $query = $builder->insert('external_mounts')
226
+            ->values([
227
+                'mount_point' => $builder->createNamedParameter($mountPoint, IQueryBuilder::PARAM_STR),
228
+                'storage_backend' => $builder->createNamedParameter($storageBackend, IQueryBuilder::PARAM_STR),
229
+                'auth_backend' => $builder->createNamedParameter($authBackend, IQueryBuilder::PARAM_STR),
230
+                'priority' => $builder->createNamedParameter($priority, IQueryBuilder::PARAM_INT),
231
+                'type' => $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)
232
+            ]);
233
+        $query->execute();
234
+        return (int)$this->connection->lastInsertId('*PREFIX*external_mounts');
235
+    }
236
+
237
+    /**
238
+     * Remove a mount from the database
239
+     *
240
+     * @param int $mountId
241
+     */
242
+    public function removeMount($mountId) {
243
+        $builder = $this->connection->getQueryBuilder();
244
+        $query = $builder->delete('external_mounts')
245
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
246
+        $query->execute();
247
+
248
+        $query = $builder->delete('external_applicable')
249
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
250
+        $query->execute();
251
+
252
+        $query = $builder->delete('external_config')
253
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
254
+        $query->execute();
255
+
256
+        $query = $builder->delete('external_options')
257
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
258
+        $query->execute();
259
+    }
260
+
261
+    /**
262
+     * @param int $mountId
263
+     * @param string $newMountPoint
264
+     */
265
+    public function setMountPoint($mountId, $newMountPoint) {
266
+        $builder = $this->connection->getQueryBuilder();
267
+
268
+        $query = $builder->update('external_mounts')
269
+            ->set('mount_point', $builder->createNamedParameter($newMountPoint))
270
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
271
+
272
+        $query->execute();
273
+    }
274
+
275
+    /**
276
+     * @param int $mountId
277
+     * @param string $newAuthBackend
278
+     */
279
+    public function setAuthBackend($mountId, $newAuthBackend) {
280
+        $builder = $this->connection->getQueryBuilder();
281
+
282
+        $query = $builder->update('external_mounts')
283
+            ->set('auth_backend', $builder->createNamedParameter($newAuthBackend))
284
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
285
+
286
+        $query->execute();
287
+    }
288
+
289
+    /**
290
+     * @param int $mountId
291
+     * @param string $key
292
+     * @param string $value
293
+     */
294
+    public function setConfig($mountId, $key, $value) {
295
+        if ($key === 'password') {
296
+            $value = $this->encryptValue($value);
297
+        }
298
+        $count = $this->connection->insertIfNotExist('*PREFIX*external_config', [
299
+            'mount_id' => $mountId,
300
+            'key' => $key,
301
+            'value' => $value
302
+        ], ['mount_id', 'key']);
303
+        if ($count === 0) {
304
+            $builder = $this->connection->getQueryBuilder();
305
+            $query = $builder->update('external_config')
306
+                ->set('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR))
307
+                ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
308
+                ->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)));
309
+            $query->execute();
310
+        }
311
+    }
312
+
313
+    /**
314
+     * @param int $mountId
315
+     * @param string $key
316
+     * @param string $value
317
+     */
318
+    public function setOption($mountId, $key, $value) {
319
+
320
+        $count = $this->connection->insertIfNotExist('*PREFIX*external_options', [
321
+            'mount_id' => $mountId,
322
+            'key' => $key,
323
+            'value' => json_encode($value)
324
+        ], ['mount_id', 'key']);
325
+        if ($count === 0) {
326
+            $builder = $this->connection->getQueryBuilder();
327
+            $query = $builder->update('external_options')
328
+                ->set('value', $builder->createNamedParameter(json_encode($value), IQueryBuilder::PARAM_STR))
329
+                ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
330
+                ->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)));
331
+            $query->execute();
332
+        }
333
+    }
334
+
335
+    public function addApplicable($mountId, $type, $value) {
336
+        $this->connection->insertIfNotExist('*PREFIX*external_applicable', [
337
+            'mount_id' => $mountId,
338
+            'type' => $type,
339
+            'value' => $value
340
+        ], ['mount_id', 'type', 'value']);
341
+    }
342
+
343
+    public function removeApplicable($mountId, $type, $value) {
344
+        $builder = $this->connection->getQueryBuilder();
345
+        $query = $builder->delete('external_applicable')
346
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
347
+            ->andWhere($builder->expr()->eq('type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)));
348
+
349
+        if (is_null($value)) {
350
+            $query = $query->andWhere($builder->expr()->isNull('value'));
351
+        } else {
352
+            $query = $query->andWhere($builder->expr()->eq('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR)));
353
+        }
354
+
355
+        $query->execute();
356
+    }
357
+
358
+    private function getMountsFromQuery(IQueryBuilder $query) {
359
+        $result = $query->execute();
360
+        $mounts = $result->fetchAll();
361
+        $uniqueMounts = [];
362
+        foreach ($mounts as $mount) {
363
+            $id = $mount['mount_id'];
364
+            if (!isset($uniqueMounts[$id])) {
365
+                $uniqueMounts[$id] = $mount;
366
+            }
367
+        }
368
+        $uniqueMounts = array_values($uniqueMounts);
369
+
370
+        $mountIds = array_map(function ($mount) {
371
+            return $mount['mount_id'];
372
+        }, $uniqueMounts);
373
+        $mountIds = array_values(array_unique($mountIds));
374
+
375
+        $applicable = $this->getApplicableForMounts($mountIds);
376
+        $config = $this->getConfigForMounts($mountIds);
377
+        $options = $this->getOptionsForMounts($mountIds);
378
+
379
+        return array_map(function ($mount, $applicable, $config, $options) {
380
+            $mount['type'] = (int)$mount['type'];
381
+            $mount['priority'] = (int)$mount['priority'];
382
+            $mount['applicable'] = $applicable;
383
+            $mount['config'] = $config;
384
+            $mount['options'] = $options;
385
+            return $mount;
386
+        }, $uniqueMounts, $applicable, $config, $options);
387
+    }
388
+
389
+    /**
390
+     * Get mount options from a table grouped by mount id
391
+     *
392
+     * @param string $table
393
+     * @param string[] $fields
394
+     * @param int[] $mountIds
395
+     * @return array [$mountId => [['field1' => $value1, ...], ...], ...]
396
+     */
397
+    private function selectForMounts($table, array $fields, array $mountIds) {
398
+        if (count($mountIds) === 0) {
399
+            return [];
400
+        }
401
+        $builder = $this->connection->getQueryBuilder();
402
+        $fields[] = 'mount_id';
403
+        $placeHolders = array_map(function ($id) use ($builder) {
404
+            return $builder->createPositionalParameter($id, IQueryBuilder::PARAM_INT);
405
+        }, $mountIds);
406
+        $query = $builder->select($fields)
407
+            ->from($table)
408
+            ->where($builder->expr()->in('mount_id', $placeHolders));
409
+        $rows = $query->execute()->fetchAll();
410
+
411
+        $result = [];
412
+        foreach ($mountIds as $mountId) {
413
+            $result[$mountId] = [];
414
+        }
415
+        foreach ($rows as $row) {
416
+            if (isset($row['type'])) {
417
+                $row['type'] = (int)$row['type'];
418
+            }
419
+            $result[$row['mount_id']][] = $row;
420
+        }
421
+        return $result;
422
+    }
423
+
424
+    /**
425
+     * @param int[] $mountIds
426
+     * @return array [$id => [['type' => $type, 'value' => $value], ...], ...]
427
+     */
428
+    public function getApplicableForMounts($mountIds) {
429
+        return $this->selectForMounts('external_applicable', ['type', 'value'], $mountIds);
430
+    }
431
+
432
+    /**
433
+     * @param int[] $mountIds
434
+     * @return array [$id => ['key1' => $value1, ...], ...]
435
+     */
436
+    public function getConfigForMounts($mountIds) {
437
+        $mountConfigs = $this->selectForMounts('external_config', ['key', 'value'], $mountIds);
438
+        return array_map([$this, 'createKeyValueMap'], $mountConfigs);
439
+    }
440
+
441
+    /**
442
+     * @param int[] $mountIds
443
+     * @return array [$id => ['key1' => $value1, ...], ...]
444
+     */
445
+    public function getOptionsForMounts($mountIds) {
446
+        $mountOptions = $this->selectForMounts('external_options', ['key', 'value'], $mountIds);
447
+        $optionsMap = array_map([$this, 'createKeyValueMap'], $mountOptions);
448
+        return array_map(function (array $options) {
449
+            return array_map(function ($option) {
450
+                return json_decode($option);
451
+            }, $options);
452
+        }, $optionsMap);
453
+    }
454
+
455
+    /**
456
+     * @param array $keyValuePairs [['key'=>$key, 'value=>$value], ...]
457
+     * @return array ['key1' => $value1, ...]
458
+     */
459
+    private function createKeyValueMap(array $keyValuePairs) {
460
+        $decryptedPairts = array_map(function ($pair) {
461
+            if ($pair['key'] === 'password') {
462
+                $pair['value'] = $this->decryptValue($pair['value']);
463
+            }
464
+            return $pair;
465
+        }, $keyValuePairs);
466
+        $keys = array_map(function ($pair) {
467
+            return $pair['key'];
468
+        }, $decryptedPairts);
469
+        $values = array_map(function ($pair) {
470
+            return $pair['value'];
471
+        }, $decryptedPairts);
472
+
473
+        return array_combine($keys, $values);
474
+    }
475
+
476
+    private function encryptValue($value) {
477
+        return $this->crypto->encrypt($value);
478
+    }
479
+
480
+    private function decryptValue($value) {
481
+        try {
482
+            return $this->crypto->decrypt($value);
483
+        } catch (\Exception $e) {
484
+            return $value;
485
+        }
486
+    }
487 487
 }
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
 	 */
179 179
 	public function getAdminMountsForMultiple($type, array $values) {
180 180
 		$builder = $this->connection->getQueryBuilder();
181
-		$params = array_map(function ($value) use ($builder) {
181
+		$params = array_map(function($value) use ($builder) {
182 182
 			return $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR);
183 183
 		}, $values);
184 184
 
@@ -231,7 +231,7 @@  discard block
 block discarded – undo
231 231
 				'type' => $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)
232 232
 			]);
233 233
 		$query->execute();
234
-		return (int)$this->connection->lastInsertId('*PREFIX*external_mounts');
234
+		return (int) $this->connection->lastInsertId('*PREFIX*external_mounts');
235 235
 	}
236 236
 
237 237
 	/**
@@ -367,7 +367,7 @@  discard block
 block discarded – undo
367 367
 		}
368 368
 		$uniqueMounts = array_values($uniqueMounts);
369 369
 
370
-		$mountIds = array_map(function ($mount) {
370
+		$mountIds = array_map(function($mount) {
371 371
 			return $mount['mount_id'];
372 372
 		}, $uniqueMounts);
373 373
 		$mountIds = array_values(array_unique($mountIds));
@@ -376,9 +376,9 @@  discard block
 block discarded – undo
376 376
 		$config = $this->getConfigForMounts($mountIds);
377 377
 		$options = $this->getOptionsForMounts($mountIds);
378 378
 
379
-		return array_map(function ($mount, $applicable, $config, $options) {
380
-			$mount['type'] = (int)$mount['type'];
381
-			$mount['priority'] = (int)$mount['priority'];
379
+		return array_map(function($mount, $applicable, $config, $options) {
380
+			$mount['type'] = (int) $mount['type'];
381
+			$mount['priority'] = (int) $mount['priority'];
382 382
 			$mount['applicable'] = $applicable;
383 383
 			$mount['config'] = $config;
384 384
 			$mount['options'] = $options;
@@ -400,7 +400,7 @@  discard block
 block discarded – undo
400 400
 		}
401 401
 		$builder = $this->connection->getQueryBuilder();
402 402
 		$fields[] = 'mount_id';
403
-		$placeHolders = array_map(function ($id) use ($builder) {
403
+		$placeHolders = array_map(function($id) use ($builder) {
404 404
 			return $builder->createPositionalParameter($id, IQueryBuilder::PARAM_INT);
405 405
 		}, $mountIds);
406 406
 		$query = $builder->select($fields)
@@ -414,7 +414,7 @@  discard block
 block discarded – undo
414 414
 		}
415 415
 		foreach ($rows as $row) {
416 416
 			if (isset($row['type'])) {
417
-				$row['type'] = (int)$row['type'];
417
+				$row['type'] = (int) $row['type'];
418 418
 			}
419 419
 			$result[$row['mount_id']][] = $row;
420 420
 		}
@@ -445,8 +445,8 @@  discard block
 block discarded – undo
445 445
 	public function getOptionsForMounts($mountIds) {
446 446
 		$mountOptions = $this->selectForMounts('external_options', ['key', 'value'], $mountIds);
447 447
 		$optionsMap = array_map([$this, 'createKeyValueMap'], $mountOptions);
448
-		return array_map(function (array $options) {
449
-			return array_map(function ($option) {
448
+		return array_map(function(array $options) {
449
+			return array_map(function($option) {
450 450
 				return json_decode($option);
451 451
 			}, $options);
452 452
 		}, $optionsMap);
@@ -457,16 +457,16 @@  discard block
 block discarded – undo
457 457
 	 * @return array ['key1' => $value1, ...]
458 458
 	 */
459 459
 	private function createKeyValueMap(array $keyValuePairs) {
460
-		$decryptedPairts = array_map(function ($pair) {
460
+		$decryptedPairts = array_map(function($pair) {
461 461
 			if ($pair['key'] === 'password') {
462 462
 				$pair['value'] = $this->decryptValue($pair['value']);
463 463
 			}
464 464
 			return $pair;
465 465
 		}, $keyValuePairs);
466
-		$keys = array_map(function ($pair) {
466
+		$keys = array_map(function($pair) {
467 467
 			return $pair['key'];
468 468
 		}, $decryptedPairts);
469
-		$values = array_map(function ($pair) {
469
+		$values = array_map(function($pair) {
470 470
 			return $pair['value'];
471 471
 		}, $decryptedPairts);
472 472
 
Please login to merge, or discard this patch.
apps/federation/lib/AppInfo/Application.php 3 patches
Unused Use Statements   -3 removed lines patch added patch discarded remove patch
@@ -24,16 +24,13 @@
 block discarded – undo
24 24
 
25 25
 namespace OCA\Federation\AppInfo;
26 26
 
27
-use OCA\Federation\API\OCSAuthAPI;
28 27
 use OCA\Federation\Controller\SettingsController;
29 28
 use OCA\Federation\DAV\FedAuth;
30 29
 use OCA\Federation\DbHandler;
31 30
 use OCA\Federation\Hooks;
32 31
 use OCA\Federation\Middleware\AddServerMiddleware;
33 32
 use OCA\Federation\SyncFederationAddressBooks;
34
-use OCA\Federation\SyncJob;
35 33
 use OCA\Federation\TrustedServers;
36
-use OCP\API;
37 34
 use OCP\App;
38 35
 use OCP\AppFramework\IAppContainer;
39 36
 use OCP\SabrePluginEvent;
Please login to merge, or discard this patch.
Indentation   +95 added lines, -95 removed lines patch added patch discarded remove patch
@@ -42,100 +42,100 @@
 block discarded – undo
42 42
 
43 43
 class Application extends \OCP\AppFramework\App {
44 44
 
45
-	/**
46
-	 * @param array $urlParams
47
-	 */
48
-	public function __construct($urlParams = array()) {
49
-		parent::__construct('federation', $urlParams);
50
-		$this->registerService();
51
-		$this->registerMiddleware();
52
-	}
53
-
54
-	private function registerService() {
55
-		$container = $this->getContainer();
56
-
57
-		$container->registerService('addServerMiddleware', function(IAppContainer $c) {
58
-			return new AddServerMiddleware(
59
-				$c->getAppName(),
60
-				\OC::$server->getL10N($c->getAppName()),
61
-				\OC::$server->getLogger()
62
-			);
63
-		});
64
-
65
-		$container->registerService('DbHandler', function(IAppContainer $c) {
66
-			return new DbHandler(
67
-				\OC::$server->getDatabaseConnection(),
68
-				\OC::$server->getL10N($c->getAppName())
69
-			);
70
-		});
71
-
72
-		$container->registerService('TrustedServers', function(IAppContainer $c) {
73
-			$server = $c->getServer();
74
-			return new TrustedServers(
75
-				$c->query('DbHandler'),
76
-				$server->getHTTPClientService(),
77
-				$server->getLogger(),
78
-				$server->getJobList(),
79
-				$server->getSecureRandom(),
80
-				$server->getConfig(),
81
-				$server->getEventDispatcher()
82
-			);
83
-		});
84
-
85
-		$container->registerService('SettingsController', function (IAppContainer $c) {
86
-			$server = $c->getServer();
87
-			return new SettingsController(
88
-				$c->getAppName(),
89
-				$server->getRequest(),
90
-				$server->getL10N($c->getAppName()),
91
-				$c->query('TrustedServers')
92
-			);
93
-		});
94
-
95
-	}
96
-
97
-	private function registerMiddleware() {
98
-		$container = $this->getContainer();
99
-		$container->registerMiddleware('addServerMiddleware');
100
-	}
101
-
102
-	/**
103
-	 * listen to federated_share_added hooks to auto-add new servers to the
104
-	 * list of trusted servers.
105
-	 */
106
-	public function registerHooks() {
107
-
108
-		$container = $this->getContainer();
109
-		$hooksManager = new Hooks($container->query('TrustedServers'));
110
-
111
-		Util::connectHook(
112
-				'OCP\Share',
113
-				'federated_share_added',
114
-				$hooksManager,
115
-				'addServerHook'
116
-		);
117
-
118
-		$dispatcher = $this->getContainer()->getServer()->getEventDispatcher();
119
-		$dispatcher->addListener('OCA\DAV\Connector\Sabre::authInit', function($event) use($container) {
120
-			if ($event instanceof SabrePluginEvent) {
121
-				$authPlugin = $event->getServer()->getPlugin('auth');
122
-				if ($authPlugin instanceof Plugin) {
123
-					$h = new DbHandler($container->getServer()->getDatabaseConnection(),
124
-							$container->getServer()->getL10N('federation')
125
-					);
126
-					$authPlugin->addBackend(new FedAuth($h));
127
-				}
128
-			}
129
-		});
130
-	}
131
-
132
-	/**
133
-	 * @return SyncFederationAddressBooks
134
-	 */
135
-	public function getSyncService() {
136
-		$syncService = \OC::$server->query('CardDAVSyncService');
137
-		$dbHandler = $this->getContainer()->query('DbHandler');
138
-		return new SyncFederationAddressBooks($dbHandler, $syncService);
139
-	}
45
+    /**
46
+     * @param array $urlParams
47
+     */
48
+    public function __construct($urlParams = array()) {
49
+        parent::__construct('federation', $urlParams);
50
+        $this->registerService();
51
+        $this->registerMiddleware();
52
+    }
53
+
54
+    private function registerService() {
55
+        $container = $this->getContainer();
56
+
57
+        $container->registerService('addServerMiddleware', function(IAppContainer $c) {
58
+            return new AddServerMiddleware(
59
+                $c->getAppName(),
60
+                \OC::$server->getL10N($c->getAppName()),
61
+                \OC::$server->getLogger()
62
+            );
63
+        });
64
+
65
+        $container->registerService('DbHandler', function(IAppContainer $c) {
66
+            return new DbHandler(
67
+                \OC::$server->getDatabaseConnection(),
68
+                \OC::$server->getL10N($c->getAppName())
69
+            );
70
+        });
71
+
72
+        $container->registerService('TrustedServers', function(IAppContainer $c) {
73
+            $server = $c->getServer();
74
+            return new TrustedServers(
75
+                $c->query('DbHandler'),
76
+                $server->getHTTPClientService(),
77
+                $server->getLogger(),
78
+                $server->getJobList(),
79
+                $server->getSecureRandom(),
80
+                $server->getConfig(),
81
+                $server->getEventDispatcher()
82
+            );
83
+        });
84
+
85
+        $container->registerService('SettingsController', function (IAppContainer $c) {
86
+            $server = $c->getServer();
87
+            return new SettingsController(
88
+                $c->getAppName(),
89
+                $server->getRequest(),
90
+                $server->getL10N($c->getAppName()),
91
+                $c->query('TrustedServers')
92
+            );
93
+        });
94
+
95
+    }
96
+
97
+    private function registerMiddleware() {
98
+        $container = $this->getContainer();
99
+        $container->registerMiddleware('addServerMiddleware');
100
+    }
101
+
102
+    /**
103
+     * listen to federated_share_added hooks to auto-add new servers to the
104
+     * list of trusted servers.
105
+     */
106
+    public function registerHooks() {
107
+
108
+        $container = $this->getContainer();
109
+        $hooksManager = new Hooks($container->query('TrustedServers'));
110
+
111
+        Util::connectHook(
112
+                'OCP\Share',
113
+                'federated_share_added',
114
+                $hooksManager,
115
+                'addServerHook'
116
+        );
117
+
118
+        $dispatcher = $this->getContainer()->getServer()->getEventDispatcher();
119
+        $dispatcher->addListener('OCA\DAV\Connector\Sabre::authInit', function($event) use($container) {
120
+            if ($event instanceof SabrePluginEvent) {
121
+                $authPlugin = $event->getServer()->getPlugin('auth');
122
+                if ($authPlugin instanceof Plugin) {
123
+                    $h = new DbHandler($container->getServer()->getDatabaseConnection(),
124
+                            $container->getServer()->getL10N('federation')
125
+                    );
126
+                    $authPlugin->addBackend(new FedAuth($h));
127
+                }
128
+            }
129
+        });
130
+    }
131
+
132
+    /**
133
+     * @return SyncFederationAddressBooks
134
+     */
135
+    public function getSyncService() {
136
+        $syncService = \OC::$server->query('CardDAVSyncService');
137
+        $dbHandler = $this->getContainer()->query('DbHandler');
138
+        return new SyncFederationAddressBooks($dbHandler, $syncService);
139
+    }
140 140
 
141 141
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -82,7 +82,7 @@
 block discarded – undo
82 82
 			);
83 83
 		});
84 84
 
85
-		$container->registerService('SettingsController', function (IAppContainer $c) {
85
+		$container->registerService('SettingsController', function(IAppContainer $c) {
86 86
 			$server = $c->getServer();
87 87
 			return new SettingsController(
88 88
 				$c->getAppName(),
Please login to merge, or discard this patch.
lib/private/AppFramework/OCS/BaseResponse.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@
 block discarded – undo
24 24
 	/**
25 25
 	 * BaseResponse constructor.
26 26
 	 *
27
-	 * @param DataResponse|null $dataResponse
27
+	 * @param DataResponse $dataResponse
28 28
 	 * @param string $format
29 29
 	 * @param string|null $statusMessage
30 30
 	 * @param int|null $itemsCount
Please login to merge, or discard this patch.
Indentation   +56 added lines, -56 removed lines patch added patch discarded remove patch
@@ -27,70 +27,70 @@
 block discarded – undo
27 27
 use OCP\AppFramework\Http\Response;
28 28
 
29 29
 abstract class BaseResponse extends Response   {
30
-	/** @var array */
31
-	protected $data;
30
+    /** @var array */
31
+    protected $data;
32 32
 
33
-	/** @var string */
34
-	protected $format;
33
+    /** @var string */
34
+    protected $format;
35 35
 
36
-	/** @var string */
37
-	protected $statusMessage;
36
+    /** @var string */
37
+    protected $statusMessage;
38 38
 
39
-	/** @var int */
40
-	protected $itemsCount;
39
+    /** @var int */
40
+    protected $itemsCount;
41 41
 
42
-	/** @var int */
43
-	protected $itemsPerPage;
42
+    /** @var int */
43
+    protected $itemsPerPage;
44 44
 
45
-	/**
46
-	 * BaseResponse constructor.
47
-	 *
48
-	 * @param DataResponse|null $dataResponse
49
-	 * @param string $format
50
-	 * @param string|null $statusMessage
51
-	 * @param int|null $itemsCount
52
-	 * @param int|null $itemsPerPage
53
-	 */
54
-	public function __construct(DataResponse $dataResponse,
55
-								$format = 'xml',
56
-								$statusMessage = null,
57
-								$itemsCount = null,
58
-								$itemsPerPage = null) {
59
-		$this->format = $format;
60
-		$this->statusMessage = $statusMessage;
61
-		$this->itemsCount = $itemsCount;
62
-		$this->itemsPerPage = $itemsPerPage;
45
+    /**
46
+     * BaseResponse constructor.
47
+     *
48
+     * @param DataResponse|null $dataResponse
49
+     * @param string $format
50
+     * @param string|null $statusMessage
51
+     * @param int|null $itemsCount
52
+     * @param int|null $itemsPerPage
53
+     */
54
+    public function __construct(DataResponse $dataResponse,
55
+                                $format = 'xml',
56
+                                $statusMessage = null,
57
+                                $itemsCount = null,
58
+                                $itemsPerPage = null) {
59
+        $this->format = $format;
60
+        $this->statusMessage = $statusMessage;
61
+        $this->itemsCount = $itemsCount;
62
+        $this->itemsPerPage = $itemsPerPage;
63 63
 
64
-		$this->data = $dataResponse->getData();
64
+        $this->data = $dataResponse->getData();
65 65
 
66
-		$this->setHeaders($dataResponse->getHeaders());
67
-		$this->setStatus($dataResponse->getStatus());
68
-		$this->setETag($dataResponse->getETag());
69
-		$this->setLastModified($dataResponse->getLastModified());
70
-		$this->setCookies($dataResponse->getCookies());
71
-		$this->setContentSecurityPolicy(new EmptyContentSecurityPolicy());
66
+        $this->setHeaders($dataResponse->getHeaders());
67
+        $this->setStatus($dataResponse->getStatus());
68
+        $this->setETag($dataResponse->getETag());
69
+        $this->setLastModified($dataResponse->getLastModified());
70
+        $this->setCookies($dataResponse->getCookies());
71
+        $this->setContentSecurityPolicy(new EmptyContentSecurityPolicy());
72 72
 
73
-		if ($format === 'json') {
74
-			$this->addHeader(
75
-				'Content-Type', 'application/json; charset=utf-8'
76
-			);
77
-		} else {
78
-			$this->addHeader(
79
-				'Content-Type', 'application/xml; charset=utf-8'
80
-			);
81
-		}
82
-	}
73
+        if ($format === 'json') {
74
+            $this->addHeader(
75
+                'Content-Type', 'application/json; charset=utf-8'
76
+            );
77
+        } else {
78
+            $this->addHeader(
79
+                'Content-Type', 'application/xml; charset=utf-8'
80
+            );
81
+        }
82
+    }
83 83
 
84
-	/**
85
-	 * @param string[] $meta
86
-	 * @return string
87
-	 */
88
-	protected function renderResult($meta) {
89
-		// TODO rewrite functions
90
-		return \OC_API::renderResult($this->format, $meta, $this->data);
91
-	}
84
+    /**
85
+     * @param string[] $meta
86
+     * @return string
87
+     */
88
+    protected function renderResult($meta) {
89
+        // TODO rewrite functions
90
+        return \OC_API::renderResult($this->format, $meta, $this->data);
91
+    }
92 92
 
93
-	public function getOCSStatus() {
94
-		return parent::getStatus();
95
-	}
93
+    public function getOCSStatus() {
94
+        return parent::getStatus();
95
+    }
96 96
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -26,7 +26,7 @@
 block discarded – undo
26 26
 use OCP\AppFramework\Http\EmptyContentSecurityPolicy;
27 27
 use OCP\AppFramework\Http\Response;
28 28
 
29
-abstract class BaseResponse extends Response   {
29
+abstract class BaseResponse extends Response {
30 30
 	/** @var array */
31 31
 	protected $data;
32 32
 
Please login to merge, or discard this patch.
lib/private/Server.php 3 patches
Doc Comments   +2 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1143,7 +1143,7 @@  discard block
 block discarded – undo
1143 1143
 	 * Get the certificate manager for the user
1144 1144
 	 *
1145 1145
 	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1146
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1146
+	 * @return null|CertificateManager | null if $uid is null and no user is logged in
1147 1147
 	 */
1148 1148
 	public function getCertificateManager($userId = '') {
1149 1149
 		if ($userId === '') {
@@ -1464,6 +1464,7 @@  discard block
 block discarded – undo
1464 1464
 	}
1465 1465
 
1466 1466
 	/**
1467
+	 * @param string $app
1467 1468
 	 * @return \OCP\Files\IAppData
1468 1469
 	 */
1469 1470
 	public function getAppDataDir($app) {
Please login to merge, or discard this patch.
Indentation   +1589 added lines, -1589 removed lines patch added patch discarded remove patch
@@ -118,1598 +118,1598 @@
 block discarded – undo
118 118
  * TODO: hookup all manager classes
119 119
  */
120 120
 class Server extends ServerContainer implements IServerContainer {
121
-	/** @var string */
122
-	private $webRoot;
123
-
124
-	/**
125
-	 * @param string $webRoot
126
-	 * @param \OC\Config $config
127
-	 */
128
-	public function __construct($webRoot, \OC\Config $config) {
129
-		parent::__construct();
130
-		$this->webRoot = $webRoot;
131
-
132
-		$this->registerService(\OCP\IServerContainer::class, function(IServerContainer $c) {
133
-			return $c;
134
-		});
135
-
136
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
137
-		$this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
138
-
139
-		$this->registerAlias(IActionFactory::class, ActionFactory::class);
140
-
141
-
142
-
143
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
144
-			return new PreviewManager(
145
-				$c->getConfig(),
146
-				$c->getRootFolder(),
147
-				$c->getAppDataDir('preview'),
148
-				$c->getEventDispatcher(),
149
-				$c->getSession()->get('user_id')
150
-			);
151
-		});
152
-		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
153
-
154
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
155
-			return new \OC\Preview\Watcher(
156
-				$c->getAppDataDir('preview')
157
-			);
158
-		});
159
-
160
-		$this->registerService('EncryptionManager', function (Server $c) {
161
-			$view = new View();
162
-			$util = new Encryption\Util(
163
-				$view,
164
-				$c->getUserManager(),
165
-				$c->getGroupManager(),
166
-				$c->getConfig()
167
-			);
168
-			return new Encryption\Manager(
169
-				$c->getConfig(),
170
-				$c->getLogger(),
171
-				$c->getL10N('core'),
172
-				new View(),
173
-				$util,
174
-				new ArrayCache()
175
-			);
176
-		});
177
-
178
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
179
-			$util = new Encryption\Util(
180
-				new View(),
181
-				$c->getUserManager(),
182
-				$c->getGroupManager(),
183
-				$c->getConfig()
184
-			);
185
-			return new Encryption\File($util);
186
-		});
187
-
188
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
189
-			$view = new View();
190
-			$util = new Encryption\Util(
191
-				$view,
192
-				$c->getUserManager(),
193
-				$c->getGroupManager(),
194
-				$c->getConfig()
195
-			);
196
-
197
-			return new Encryption\Keys\Storage($view, $util);
198
-		});
199
-		$this->registerService('TagMapper', function (Server $c) {
200
-			return new TagMapper($c->getDatabaseConnection());
201
-		});
202
-
203
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
204
-			$tagMapper = $c->query('TagMapper');
205
-			return new TagManager($tagMapper, $c->getUserSession());
206
-		});
207
-		$this->registerAlias('TagManager', \OCP\ITagManager::class);
208
-
209
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
210
-			$config = $c->getConfig();
211
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
212
-			/** @var \OC\SystemTag\ManagerFactory $factory */
213
-			$factory = new $factoryClass($this);
214
-			return $factory;
215
-		});
216
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
217
-			return $c->query('SystemTagManagerFactory')->getManager();
218
-		});
219
-		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
220
-
221
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
222
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
223
-		});
224
-		$this->registerService('RootFolder', function (Server $c) {
225
-			$manager = \OC\Files\Filesystem::getMountManager(null);
226
-			$view = new View();
227
-			$root = new Root(
228
-				$manager,
229
-				$view,
230
-				null,
231
-				$c->getUserMountCache(),
232
-				$this->getLogger(),
233
-				$this->getUserManager()
234
-			);
235
-			$connector = new HookConnector($root, $view);
236
-			$connector->viewToNode();
237
-
238
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
239
-			$previewConnector->connectWatcher();
240
-
241
-			return $root;
242
-		});
243
-		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
244
-
245
-		$this->registerService(\OCP\Files\IRootFolder::class, function(Server $c) {
246
-			return new LazyRoot(function() use ($c) {
247
-				return $c->query('RootFolder');
248
-			});
249
-		});
250
-		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
251
-
252
-		$this->registerService(\OCP\IUserManager::class, function (Server $c) {
253
-			$config = $c->getConfig();
254
-			return new \OC\User\Manager($config);
255
-		});
256
-		$this->registerAlias('UserManager', \OCP\IUserManager::class);
257
-
258
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
259
-			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
260
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
261
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
262
-			});
263
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
264
-				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
265
-			});
266
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
267
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
268
-			});
269
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
270
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
271
-			});
272
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
273
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
274
-			});
275
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
276
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
277
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
278
-				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
279
-			});
280
-			return $groupManager;
281
-		});
282
-		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
283
-
284
-		$this->registerService(Store::class, function(Server $c) {
285
-			$session = $c->getSession();
286
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
287
-				$tokenProvider = $c->query('OC\Authentication\Token\IProvider');
288
-			} else {
289
-				$tokenProvider = null;
290
-			}
291
-			$logger = $c->getLogger();
292
-			return new Store($session, $logger, $tokenProvider);
293
-		});
294
-		$this->registerAlias(IStore::class, Store::class);
295
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
296
-			$dbConnection = $c->getDatabaseConnection();
297
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
298
-		});
299
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
300
-			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
301
-			$crypto = $c->getCrypto();
302
-			$config = $c->getConfig();
303
-			$logger = $c->getLogger();
304
-			$timeFactory = new TimeFactory();
305
-			return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
306
-		});
307
-		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
308
-
309
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
310
-			$manager = $c->getUserManager();
311
-			$session = new \OC\Session\Memory('');
312
-			$timeFactory = new TimeFactory();
313
-			// Token providers might require a working database. This code
314
-			// might however be called when ownCloud is not yet setup.
315
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
316
-				$defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
317
-			} else {
318
-				$defaultTokenProvider = null;
319
-			}
320
-
321
-			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
322
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
323
-				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
324
-			});
325
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
326
-				/** @var $user \OC\User\User */
327
-				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
328
-			});
329
-			$userSession->listen('\OC\User', 'preDelete', function ($user) {
330
-				/** @var $user \OC\User\User */
331
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
332
-			});
333
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
334
-				/** @var $user \OC\User\User */
335
-				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
336
-			});
337
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
338
-				/** @var $user \OC\User\User */
339
-				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
340
-			});
341
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
342
-				/** @var $user \OC\User\User */
343
-				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
344
-			});
345
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
346
-				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
347
-			});
348
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
349
-				/** @var $user \OC\User\User */
350
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
351
-			});
352
-			$userSession->listen('\OC\User', 'logout', function () {
353
-				\OC_Hook::emit('OC_User', 'logout', array());
354
-			});
355
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value) {
356
-				/** @var $user \OC\User\User */
357
-				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value));
358
-			});
359
-			return $userSession;
360
-		});
361
-		$this->registerAlias('UserSession', \OCP\IUserSession::class);
362
-
363
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
364
-			return new \OC\Authentication\TwoFactorAuth\Manager($c->getAppManager(), $c->getSession(), $c->getConfig(), $c->getActivityManager(), $c->getLogger());
365
-		});
366
-
367
-		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
368
-		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
369
-
370
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
371
-			return new \OC\AllConfig(
372
-				$c->getSystemConfig()
373
-			);
374
-		});
375
-		$this->registerAlias('AllConfig', \OC\AllConfig::class);
376
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
377
-
378
-		$this->registerService('SystemConfig', function ($c) use ($config) {
379
-			return new \OC\SystemConfig($config);
380
-		});
381
-
382
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
383
-			return new \OC\AppConfig($c->getDatabaseConnection());
384
-		});
385
-		$this->registerAlias('AppConfig', \OC\AppConfig::class);
386
-		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
387
-
388
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
389
-			return new \OC\L10N\Factory(
390
-				$c->getConfig(),
391
-				$c->getRequest(),
392
-				$c->getUserSession(),
393
-				\OC::$SERVERROOT
394
-			);
395
-		});
396
-		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
397
-
398
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
399
-			$config = $c->getConfig();
400
-			$cacheFactory = $c->getMemCacheFactory();
401
-			return new \OC\URLGenerator(
402
-				$config,
403
-				$cacheFactory
404
-			);
405
-		});
406
-		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
407
-
408
-		$this->registerService('AppHelper', function ($c) {
409
-			return new \OC\AppHelper();
410
-		});
411
-		$this->registerService('AppFetcher', function ($c) {
412
-			return new AppFetcher(
413
-				$this->getAppDataDir('appstore'),
414
-				$this->getHTTPClientService(),
415
-				$this->query(TimeFactory::class),
416
-				$this->getConfig()
417
-			);
418
-		});
419
-		$this->registerService('CategoryFetcher', function ($c) {
420
-			return new CategoryFetcher(
421
-				$this->getAppDataDir('appstore'),
422
-				$this->getHTTPClientService(),
423
-				$this->query(TimeFactory::class),
424
-				$this->getConfig()
425
-			);
426
-		});
427
-
428
-		$this->registerService(\OCP\ICache::class, function ($c) {
429
-			return new Cache\File();
430
-		});
431
-		$this->registerAlias('UserCache', \OCP\ICache::class);
432
-
433
-		$this->registerService(Factory::class, function (Server $c) {
434
-			$config = $c->getConfig();
435
-
436
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
437
-				$v = \OC_App::getAppVersions();
438
-				$v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php'));
439
-				$version = implode(',', $v);
440
-				$instanceId = \OC_Util::getInstanceId();
441
-				$path = \OC::$SERVERROOT;
442
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . \OC::$WEBROOT);
443
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
444
-					$config->getSystemValue('memcache.local', null),
445
-					$config->getSystemValue('memcache.distributed', null),
446
-					$config->getSystemValue('memcache.locking', null)
447
-				);
448
-			}
449
-
450
-			return new \OC\Memcache\Factory('', $c->getLogger(),
451
-				'\\OC\\Memcache\\ArrayCache',
452
-				'\\OC\\Memcache\\ArrayCache',
453
-				'\\OC\\Memcache\\ArrayCache'
454
-			);
455
-		});
456
-		$this->registerAlias('MemCacheFactory', Factory::class);
457
-		$this->registerAlias(ICacheFactory::class, Factory::class);
458
-
459
-		$this->registerService('RedisFactory', function (Server $c) {
460
-			$systemConfig = $c->getSystemConfig();
461
-			return new RedisFactory($systemConfig);
462
-		});
463
-
464
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
465
-			return new \OC\Activity\Manager(
466
-				$c->getRequest(),
467
-				$c->getUserSession(),
468
-				$c->getConfig(),
469
-				$c->query(IValidator::class)
470
-			);
471
-		});
472
-		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
473
-
474
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
475
-			return new \OC\Activity\EventMerger(
476
-				$c->getL10N('lib')
477
-			);
478
-		});
479
-		$this->registerAlias(IValidator::class, Validator::class);
480
-
481
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
482
-			return new AvatarManager(
483
-				$c->getUserManager(),
484
-				$c->getAppDataDir('avatar'),
485
-				$c->getL10N('lib'),
486
-				$c->getLogger(),
487
-				$c->getConfig()
488
-			);
489
-		});
490
-		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
491
-
492
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
493
-			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
494
-			$logger = Log::getLogClass($logType);
495
-			call_user_func(array($logger, 'init'));
496
-
497
-			return new Log($logger);
498
-		});
499
-		$this->registerAlias('Logger', \OCP\ILogger::class);
500
-
501
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
502
-			$config = $c->getConfig();
503
-			return new \OC\BackgroundJob\JobList(
504
-				$c->getDatabaseConnection(),
505
-				$config,
506
-				new TimeFactory()
507
-			);
508
-		});
509
-		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
510
-
511
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
512
-			$cacheFactory = $c->getMemCacheFactory();
513
-			$logger = $c->getLogger();
514
-			if ($cacheFactory->isAvailable()) {
515
-				$router = new \OC\Route\CachingRouter($cacheFactory->create('route'), $logger);
516
-			} else {
517
-				$router = new \OC\Route\Router($logger);
518
-			}
519
-			return $router;
520
-		});
521
-		$this->registerAlias('Router', \OCP\Route\IRouter::class);
522
-
523
-		$this->registerService(\OCP\ISearch::class, function ($c) {
524
-			return new Search();
525
-		});
526
-		$this->registerAlias('Search', \OCP\ISearch::class);
527
-
528
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
529
-			return new SecureRandom();
530
-		});
531
-		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
532
-
533
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
534
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
535
-		});
536
-		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
537
-
538
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
539
-			return new Hasher($c->getConfig());
540
-		});
541
-		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
542
-
543
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
544
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
545
-		});
546
-		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
547
-
548
-		$this->registerService(IDBConnection::class, function (Server $c) {
549
-			$systemConfig = $c->getSystemConfig();
550
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
551
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
552
-			if (!$factory->isValidType($type)) {
553
-				throw new \OC\DatabaseException('Invalid database type');
554
-			}
555
-			$connectionParams = $factory->createConnectionParams();
556
-			$connection = $factory->getConnection($type, $connectionParams);
557
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
558
-			return $connection;
559
-		});
560
-		$this->registerAlias('DatabaseConnection', IDBConnection::class);
561
-
562
-		$this->registerService('HTTPHelper', function (Server $c) {
563
-			$config = $c->getConfig();
564
-			return new HTTPHelper(
565
-				$config,
566
-				$c->getHTTPClientService()
567
-			);
568
-		});
569
-
570
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
571
-			$user = \OC_User::getUser();
572
-			$uid = $user ? $user : null;
573
-			return new ClientService(
574
-				$c->getConfig(),
575
-				new \OC\Security\CertificateManager($uid, new View(), $c->getConfig(), $c->getLogger())
576
-			);
577
-		});
578
-		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
579
-
580
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
581
-			if ($c->getSystemConfig()->getValue('debug', false)) {
582
-				return new EventLogger();
583
-			} else {
584
-				return new NullEventLogger();
585
-			}
586
-		});
587
-		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
588
-
589
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
590
-			if ($c->getSystemConfig()->getValue('debug', false)) {
591
-				return new QueryLogger();
592
-			} else {
593
-				return new NullQueryLogger();
594
-			}
595
-		});
596
-		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
597
-
598
-		$this->registerService(TempManager::class, function (Server $c) {
599
-			return new TempManager(
600
-				$c->getLogger(),
601
-				$c->getConfig()
602
-			);
603
-		});
604
-		$this->registerAlias('TempManager', TempManager::class);
605
-		$this->registerAlias(ITempManager::class, TempManager::class);
606
-
607
-		$this->registerService(AppManager::class, function (Server $c) {
608
-			return new \OC\App\AppManager(
609
-				$c->getUserSession(),
610
-				$c->getAppConfig(),
611
-				$c->getGroupManager(),
612
-				$c->getMemCacheFactory(),
613
-				$c->getEventDispatcher()
614
-			);
615
-		});
616
-		$this->registerAlias('AppManager', AppManager::class);
617
-		$this->registerAlias(IAppManager::class, AppManager::class);
618
-
619
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
620
-			return new DateTimeZone(
621
-				$c->getConfig(),
622
-				$c->getSession()
623
-			);
624
-		});
625
-		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
626
-
627
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
628
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
629
-
630
-			return new DateTimeFormatter(
631
-				$c->getDateTimeZone()->getTimeZone(),
632
-				$c->getL10N('lib', $language)
633
-			);
634
-		});
635
-		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
636
-
637
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
638
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
639
-			$listener = new UserMountCacheListener($mountCache);
640
-			$listener->listen($c->getUserManager());
641
-			return $mountCache;
642
-		});
643
-		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
644
-
645
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
646
-			$loader = \OC\Files\Filesystem::getLoader();
647
-			$mountCache = $c->query('UserMountCache');
648
-			$manager =  new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
649
-
650
-			// builtin providers
651
-
652
-			$config = $c->getConfig();
653
-			$manager->registerProvider(new CacheMountProvider($config));
654
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
655
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
656
-
657
-			return $manager;
658
-		});
659
-		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
660
-
661
-		$this->registerService('IniWrapper', function ($c) {
662
-			return new IniGetWrapper();
663
-		});
664
-		$this->registerService('AsyncCommandBus', function (Server $c) {
665
-			$jobList = $c->getJobList();
666
-			return new AsyncBus($jobList);
667
-		});
668
-		$this->registerService('TrustedDomainHelper', function ($c) {
669
-			return new TrustedDomainHelper($this->getConfig());
670
-		});
671
-		$this->registerService('Throttler', function(Server $c) {
672
-			return new Throttler(
673
-				$c->getDatabaseConnection(),
674
-				new TimeFactory(),
675
-				$c->getLogger(),
676
-				$c->getConfig()
677
-			);
678
-		});
679
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
680
-			// IConfig and IAppManager requires a working database. This code
681
-			// might however be called when ownCloud is not yet setup.
682
-			if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
683
-				$config = $c->getConfig();
684
-				$appManager = $c->getAppManager();
685
-			} else {
686
-				$config = null;
687
-				$appManager = null;
688
-			}
689
-
690
-			return new Checker(
691
-					new EnvironmentHelper(),
692
-					new FileAccessHelper(),
693
-					new AppLocator(),
694
-					$config,
695
-					$c->getMemCacheFactory(),
696
-					$appManager,
697
-					$c->getTempManager()
698
-			);
699
-		});
700
-		$this->registerService(\OCP\IRequest::class, function ($c) {
701
-			if (isset($this['urlParams'])) {
702
-				$urlParams = $this['urlParams'];
703
-			} else {
704
-				$urlParams = [];
705
-			}
706
-
707
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
708
-				&& in_array('fakeinput', stream_get_wrappers())
709
-			) {
710
-				$stream = 'fakeinput://data';
711
-			} else {
712
-				$stream = 'php://input';
713
-			}
714
-
715
-			return new Request(
716
-				[
717
-					'get' => $_GET,
718
-					'post' => $_POST,
719
-					'files' => $_FILES,
720
-					'server' => $_SERVER,
721
-					'env' => $_ENV,
722
-					'cookies' => $_COOKIE,
723
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
724
-						? $_SERVER['REQUEST_METHOD']
725
-						: null,
726
-					'urlParams' => $urlParams,
727
-				],
728
-				$this->getSecureRandom(),
729
-				$this->getConfig(),
730
-				$this->getCsrfTokenManager(),
731
-				$stream
732
-			);
733
-		});
734
-		$this->registerAlias('Request', \OCP\IRequest::class);
735
-
736
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
737
-			return new Mailer(
738
-				$c->getConfig(),
739
-				$c->getLogger(),
740
-				$c->getThemingDefaults()
741
-			);
742
-		});
743
-		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
744
-
745
-		$this->registerService('LDAPProvider', function(Server $c) {
746
-			$config = $c->getConfig();
747
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
748
-			if(is_null($factoryClass)) {
749
-				throw new \Exception('ldapProviderFactory not set');
750
-			}
751
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
752
-			$factory = new $factoryClass($this);
753
-			return $factory->getLDAPProvider();
754
-		});
755
-		$this->registerService('LockingProvider', function (Server $c) {
756
-			$ini = $c->getIniWrapper();
757
-			$config = $c->getConfig();
758
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
759
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
760
-				/** @var \OC\Memcache\Factory $memcacheFactory */
761
-				$memcacheFactory = $c->getMemCacheFactory();
762
-				$memcache = $memcacheFactory->createLocking('lock');
763
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
764
-					return new MemcacheLockingProvider($memcache, $ttl);
765
-				}
766
-				return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
767
-			}
768
-			return new NoopLockingProvider();
769
-		});
770
-
771
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
772
-			return new \OC\Files\Mount\Manager();
773
-		});
774
-		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
775
-
776
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
777
-			return new \OC\Files\Type\Detection(
778
-				$c->getURLGenerator(),
779
-				\OC::$configDir,
780
-				\OC::$SERVERROOT . '/resources/config/'
781
-			);
782
-		});
783
-		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
784
-
785
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
786
-			return new \OC\Files\Type\Loader(
787
-				$c->getDatabaseConnection()
788
-			);
789
-		});
790
-		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
791
-
792
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
793
-			return new Manager(
794
-				$c->query(IValidator::class)
795
-			);
796
-		});
797
-		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
798
-
799
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
800
-			$manager = new \OC\CapabilitiesManager($c->getLogger());
801
-			$manager->registerCapability(function () use ($c) {
802
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
803
-			});
804
-			return $manager;
805
-		});
806
-		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
807
-
808
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function(Server $c) {
809
-			$config = $c->getConfig();
810
-			$factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
811
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
812
-			$factory = new $factoryClass($this);
813
-			return $factory->getManager();
814
-		});
815
-		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
816
-
817
-		$this->registerService('ThemingDefaults', function(Server $c) {
818
-			/*
121
+    /** @var string */
122
+    private $webRoot;
123
+
124
+    /**
125
+     * @param string $webRoot
126
+     * @param \OC\Config $config
127
+     */
128
+    public function __construct($webRoot, \OC\Config $config) {
129
+        parent::__construct();
130
+        $this->webRoot = $webRoot;
131
+
132
+        $this->registerService(\OCP\IServerContainer::class, function(IServerContainer $c) {
133
+            return $c;
134
+        });
135
+
136
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
137
+        $this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
138
+
139
+        $this->registerAlias(IActionFactory::class, ActionFactory::class);
140
+
141
+
142
+
143
+        $this->registerService(\OCP\IPreview::class, function (Server $c) {
144
+            return new PreviewManager(
145
+                $c->getConfig(),
146
+                $c->getRootFolder(),
147
+                $c->getAppDataDir('preview'),
148
+                $c->getEventDispatcher(),
149
+                $c->getSession()->get('user_id')
150
+            );
151
+        });
152
+        $this->registerAlias('PreviewManager', \OCP\IPreview::class);
153
+
154
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
155
+            return new \OC\Preview\Watcher(
156
+                $c->getAppDataDir('preview')
157
+            );
158
+        });
159
+
160
+        $this->registerService('EncryptionManager', function (Server $c) {
161
+            $view = new View();
162
+            $util = new Encryption\Util(
163
+                $view,
164
+                $c->getUserManager(),
165
+                $c->getGroupManager(),
166
+                $c->getConfig()
167
+            );
168
+            return new Encryption\Manager(
169
+                $c->getConfig(),
170
+                $c->getLogger(),
171
+                $c->getL10N('core'),
172
+                new View(),
173
+                $util,
174
+                new ArrayCache()
175
+            );
176
+        });
177
+
178
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
179
+            $util = new Encryption\Util(
180
+                new View(),
181
+                $c->getUserManager(),
182
+                $c->getGroupManager(),
183
+                $c->getConfig()
184
+            );
185
+            return new Encryption\File($util);
186
+        });
187
+
188
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
189
+            $view = new View();
190
+            $util = new Encryption\Util(
191
+                $view,
192
+                $c->getUserManager(),
193
+                $c->getGroupManager(),
194
+                $c->getConfig()
195
+            );
196
+
197
+            return new Encryption\Keys\Storage($view, $util);
198
+        });
199
+        $this->registerService('TagMapper', function (Server $c) {
200
+            return new TagMapper($c->getDatabaseConnection());
201
+        });
202
+
203
+        $this->registerService(\OCP\ITagManager::class, function (Server $c) {
204
+            $tagMapper = $c->query('TagMapper');
205
+            return new TagManager($tagMapper, $c->getUserSession());
206
+        });
207
+        $this->registerAlias('TagManager', \OCP\ITagManager::class);
208
+
209
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
210
+            $config = $c->getConfig();
211
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
212
+            /** @var \OC\SystemTag\ManagerFactory $factory */
213
+            $factory = new $factoryClass($this);
214
+            return $factory;
215
+        });
216
+        $this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
217
+            return $c->query('SystemTagManagerFactory')->getManager();
218
+        });
219
+        $this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
220
+
221
+        $this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
222
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
223
+        });
224
+        $this->registerService('RootFolder', function (Server $c) {
225
+            $manager = \OC\Files\Filesystem::getMountManager(null);
226
+            $view = new View();
227
+            $root = new Root(
228
+                $manager,
229
+                $view,
230
+                null,
231
+                $c->getUserMountCache(),
232
+                $this->getLogger(),
233
+                $this->getUserManager()
234
+            );
235
+            $connector = new HookConnector($root, $view);
236
+            $connector->viewToNode();
237
+
238
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
239
+            $previewConnector->connectWatcher();
240
+
241
+            return $root;
242
+        });
243
+        $this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
244
+
245
+        $this->registerService(\OCP\Files\IRootFolder::class, function(Server $c) {
246
+            return new LazyRoot(function() use ($c) {
247
+                return $c->query('RootFolder');
248
+            });
249
+        });
250
+        $this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
251
+
252
+        $this->registerService(\OCP\IUserManager::class, function (Server $c) {
253
+            $config = $c->getConfig();
254
+            return new \OC\User\Manager($config);
255
+        });
256
+        $this->registerAlias('UserManager', \OCP\IUserManager::class);
257
+
258
+        $this->registerService(\OCP\IGroupManager::class, function (Server $c) {
259
+            $groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
260
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
261
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
262
+            });
263
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
264
+                \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
265
+            });
266
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
267
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
268
+            });
269
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
270
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
271
+            });
272
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
273
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
274
+            });
275
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
276
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
277
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
278
+                \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
279
+            });
280
+            return $groupManager;
281
+        });
282
+        $this->registerAlias('GroupManager', \OCP\IGroupManager::class);
283
+
284
+        $this->registerService(Store::class, function(Server $c) {
285
+            $session = $c->getSession();
286
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
287
+                $tokenProvider = $c->query('OC\Authentication\Token\IProvider');
288
+            } else {
289
+                $tokenProvider = null;
290
+            }
291
+            $logger = $c->getLogger();
292
+            return new Store($session, $logger, $tokenProvider);
293
+        });
294
+        $this->registerAlias(IStore::class, Store::class);
295
+        $this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
296
+            $dbConnection = $c->getDatabaseConnection();
297
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
298
+        });
299
+        $this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
300
+            $mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
301
+            $crypto = $c->getCrypto();
302
+            $config = $c->getConfig();
303
+            $logger = $c->getLogger();
304
+            $timeFactory = new TimeFactory();
305
+            return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
306
+        });
307
+        $this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
308
+
309
+        $this->registerService(\OCP\IUserSession::class, function (Server $c) {
310
+            $manager = $c->getUserManager();
311
+            $session = new \OC\Session\Memory('');
312
+            $timeFactory = new TimeFactory();
313
+            // Token providers might require a working database. This code
314
+            // might however be called when ownCloud is not yet setup.
315
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
316
+                $defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
317
+            } else {
318
+                $defaultTokenProvider = null;
319
+            }
320
+
321
+            $userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
322
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
323
+                \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
324
+            });
325
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
326
+                /** @var $user \OC\User\User */
327
+                \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
328
+            });
329
+            $userSession->listen('\OC\User', 'preDelete', function ($user) {
330
+                /** @var $user \OC\User\User */
331
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
332
+            });
333
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
334
+                /** @var $user \OC\User\User */
335
+                \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
336
+            });
337
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
338
+                /** @var $user \OC\User\User */
339
+                \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
340
+            });
341
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
342
+                /** @var $user \OC\User\User */
343
+                \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
344
+            });
345
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
346
+                \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
347
+            });
348
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
349
+                /** @var $user \OC\User\User */
350
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
351
+            });
352
+            $userSession->listen('\OC\User', 'logout', function () {
353
+                \OC_Hook::emit('OC_User', 'logout', array());
354
+            });
355
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value) {
356
+                /** @var $user \OC\User\User */
357
+                \OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value));
358
+            });
359
+            return $userSession;
360
+        });
361
+        $this->registerAlias('UserSession', \OCP\IUserSession::class);
362
+
363
+        $this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
364
+            return new \OC\Authentication\TwoFactorAuth\Manager($c->getAppManager(), $c->getSession(), $c->getConfig(), $c->getActivityManager(), $c->getLogger());
365
+        });
366
+
367
+        $this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
368
+        $this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
369
+
370
+        $this->registerService(\OC\AllConfig::class, function (Server $c) {
371
+            return new \OC\AllConfig(
372
+                $c->getSystemConfig()
373
+            );
374
+        });
375
+        $this->registerAlias('AllConfig', \OC\AllConfig::class);
376
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
377
+
378
+        $this->registerService('SystemConfig', function ($c) use ($config) {
379
+            return new \OC\SystemConfig($config);
380
+        });
381
+
382
+        $this->registerService(\OC\AppConfig::class, function (Server $c) {
383
+            return new \OC\AppConfig($c->getDatabaseConnection());
384
+        });
385
+        $this->registerAlias('AppConfig', \OC\AppConfig::class);
386
+        $this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
387
+
388
+        $this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
389
+            return new \OC\L10N\Factory(
390
+                $c->getConfig(),
391
+                $c->getRequest(),
392
+                $c->getUserSession(),
393
+                \OC::$SERVERROOT
394
+            );
395
+        });
396
+        $this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
397
+
398
+        $this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
399
+            $config = $c->getConfig();
400
+            $cacheFactory = $c->getMemCacheFactory();
401
+            return new \OC\URLGenerator(
402
+                $config,
403
+                $cacheFactory
404
+            );
405
+        });
406
+        $this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
407
+
408
+        $this->registerService('AppHelper', function ($c) {
409
+            return new \OC\AppHelper();
410
+        });
411
+        $this->registerService('AppFetcher', function ($c) {
412
+            return new AppFetcher(
413
+                $this->getAppDataDir('appstore'),
414
+                $this->getHTTPClientService(),
415
+                $this->query(TimeFactory::class),
416
+                $this->getConfig()
417
+            );
418
+        });
419
+        $this->registerService('CategoryFetcher', function ($c) {
420
+            return new CategoryFetcher(
421
+                $this->getAppDataDir('appstore'),
422
+                $this->getHTTPClientService(),
423
+                $this->query(TimeFactory::class),
424
+                $this->getConfig()
425
+            );
426
+        });
427
+
428
+        $this->registerService(\OCP\ICache::class, function ($c) {
429
+            return new Cache\File();
430
+        });
431
+        $this->registerAlias('UserCache', \OCP\ICache::class);
432
+
433
+        $this->registerService(Factory::class, function (Server $c) {
434
+            $config = $c->getConfig();
435
+
436
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
437
+                $v = \OC_App::getAppVersions();
438
+                $v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php'));
439
+                $version = implode(',', $v);
440
+                $instanceId = \OC_Util::getInstanceId();
441
+                $path = \OC::$SERVERROOT;
442
+                $prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . \OC::$WEBROOT);
443
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
444
+                    $config->getSystemValue('memcache.local', null),
445
+                    $config->getSystemValue('memcache.distributed', null),
446
+                    $config->getSystemValue('memcache.locking', null)
447
+                );
448
+            }
449
+
450
+            return new \OC\Memcache\Factory('', $c->getLogger(),
451
+                '\\OC\\Memcache\\ArrayCache',
452
+                '\\OC\\Memcache\\ArrayCache',
453
+                '\\OC\\Memcache\\ArrayCache'
454
+            );
455
+        });
456
+        $this->registerAlias('MemCacheFactory', Factory::class);
457
+        $this->registerAlias(ICacheFactory::class, Factory::class);
458
+
459
+        $this->registerService('RedisFactory', function (Server $c) {
460
+            $systemConfig = $c->getSystemConfig();
461
+            return new RedisFactory($systemConfig);
462
+        });
463
+
464
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
465
+            return new \OC\Activity\Manager(
466
+                $c->getRequest(),
467
+                $c->getUserSession(),
468
+                $c->getConfig(),
469
+                $c->query(IValidator::class)
470
+            );
471
+        });
472
+        $this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
473
+
474
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
475
+            return new \OC\Activity\EventMerger(
476
+                $c->getL10N('lib')
477
+            );
478
+        });
479
+        $this->registerAlias(IValidator::class, Validator::class);
480
+
481
+        $this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
482
+            return new AvatarManager(
483
+                $c->getUserManager(),
484
+                $c->getAppDataDir('avatar'),
485
+                $c->getL10N('lib'),
486
+                $c->getLogger(),
487
+                $c->getConfig()
488
+            );
489
+        });
490
+        $this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
491
+
492
+        $this->registerService(\OCP\ILogger::class, function (Server $c) {
493
+            $logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
494
+            $logger = Log::getLogClass($logType);
495
+            call_user_func(array($logger, 'init'));
496
+
497
+            return new Log($logger);
498
+        });
499
+        $this->registerAlias('Logger', \OCP\ILogger::class);
500
+
501
+        $this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
502
+            $config = $c->getConfig();
503
+            return new \OC\BackgroundJob\JobList(
504
+                $c->getDatabaseConnection(),
505
+                $config,
506
+                new TimeFactory()
507
+            );
508
+        });
509
+        $this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
510
+
511
+        $this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
512
+            $cacheFactory = $c->getMemCacheFactory();
513
+            $logger = $c->getLogger();
514
+            if ($cacheFactory->isAvailable()) {
515
+                $router = new \OC\Route\CachingRouter($cacheFactory->create('route'), $logger);
516
+            } else {
517
+                $router = new \OC\Route\Router($logger);
518
+            }
519
+            return $router;
520
+        });
521
+        $this->registerAlias('Router', \OCP\Route\IRouter::class);
522
+
523
+        $this->registerService(\OCP\ISearch::class, function ($c) {
524
+            return new Search();
525
+        });
526
+        $this->registerAlias('Search', \OCP\ISearch::class);
527
+
528
+        $this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
529
+            return new SecureRandom();
530
+        });
531
+        $this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
532
+
533
+        $this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
534
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
535
+        });
536
+        $this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
537
+
538
+        $this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
539
+            return new Hasher($c->getConfig());
540
+        });
541
+        $this->registerAlias('Hasher', \OCP\Security\IHasher::class);
542
+
543
+        $this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
544
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
545
+        });
546
+        $this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
547
+
548
+        $this->registerService(IDBConnection::class, function (Server $c) {
549
+            $systemConfig = $c->getSystemConfig();
550
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
551
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
552
+            if (!$factory->isValidType($type)) {
553
+                throw new \OC\DatabaseException('Invalid database type');
554
+            }
555
+            $connectionParams = $factory->createConnectionParams();
556
+            $connection = $factory->getConnection($type, $connectionParams);
557
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
558
+            return $connection;
559
+        });
560
+        $this->registerAlias('DatabaseConnection', IDBConnection::class);
561
+
562
+        $this->registerService('HTTPHelper', function (Server $c) {
563
+            $config = $c->getConfig();
564
+            return new HTTPHelper(
565
+                $config,
566
+                $c->getHTTPClientService()
567
+            );
568
+        });
569
+
570
+        $this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
571
+            $user = \OC_User::getUser();
572
+            $uid = $user ? $user : null;
573
+            return new ClientService(
574
+                $c->getConfig(),
575
+                new \OC\Security\CertificateManager($uid, new View(), $c->getConfig(), $c->getLogger())
576
+            );
577
+        });
578
+        $this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
579
+
580
+        $this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
581
+            if ($c->getSystemConfig()->getValue('debug', false)) {
582
+                return new EventLogger();
583
+            } else {
584
+                return new NullEventLogger();
585
+            }
586
+        });
587
+        $this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
588
+
589
+        $this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
590
+            if ($c->getSystemConfig()->getValue('debug', false)) {
591
+                return new QueryLogger();
592
+            } else {
593
+                return new NullQueryLogger();
594
+            }
595
+        });
596
+        $this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
597
+
598
+        $this->registerService(TempManager::class, function (Server $c) {
599
+            return new TempManager(
600
+                $c->getLogger(),
601
+                $c->getConfig()
602
+            );
603
+        });
604
+        $this->registerAlias('TempManager', TempManager::class);
605
+        $this->registerAlias(ITempManager::class, TempManager::class);
606
+
607
+        $this->registerService(AppManager::class, function (Server $c) {
608
+            return new \OC\App\AppManager(
609
+                $c->getUserSession(),
610
+                $c->getAppConfig(),
611
+                $c->getGroupManager(),
612
+                $c->getMemCacheFactory(),
613
+                $c->getEventDispatcher()
614
+            );
615
+        });
616
+        $this->registerAlias('AppManager', AppManager::class);
617
+        $this->registerAlias(IAppManager::class, AppManager::class);
618
+
619
+        $this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
620
+            return new DateTimeZone(
621
+                $c->getConfig(),
622
+                $c->getSession()
623
+            );
624
+        });
625
+        $this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
626
+
627
+        $this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
628
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
629
+
630
+            return new DateTimeFormatter(
631
+                $c->getDateTimeZone()->getTimeZone(),
632
+                $c->getL10N('lib', $language)
633
+            );
634
+        });
635
+        $this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
636
+
637
+        $this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
638
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
639
+            $listener = new UserMountCacheListener($mountCache);
640
+            $listener->listen($c->getUserManager());
641
+            return $mountCache;
642
+        });
643
+        $this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
644
+
645
+        $this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
646
+            $loader = \OC\Files\Filesystem::getLoader();
647
+            $mountCache = $c->query('UserMountCache');
648
+            $manager =  new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
649
+
650
+            // builtin providers
651
+
652
+            $config = $c->getConfig();
653
+            $manager->registerProvider(new CacheMountProvider($config));
654
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
655
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
656
+
657
+            return $manager;
658
+        });
659
+        $this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
660
+
661
+        $this->registerService('IniWrapper', function ($c) {
662
+            return new IniGetWrapper();
663
+        });
664
+        $this->registerService('AsyncCommandBus', function (Server $c) {
665
+            $jobList = $c->getJobList();
666
+            return new AsyncBus($jobList);
667
+        });
668
+        $this->registerService('TrustedDomainHelper', function ($c) {
669
+            return new TrustedDomainHelper($this->getConfig());
670
+        });
671
+        $this->registerService('Throttler', function(Server $c) {
672
+            return new Throttler(
673
+                $c->getDatabaseConnection(),
674
+                new TimeFactory(),
675
+                $c->getLogger(),
676
+                $c->getConfig()
677
+            );
678
+        });
679
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
680
+            // IConfig and IAppManager requires a working database. This code
681
+            // might however be called when ownCloud is not yet setup.
682
+            if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
683
+                $config = $c->getConfig();
684
+                $appManager = $c->getAppManager();
685
+            } else {
686
+                $config = null;
687
+                $appManager = null;
688
+            }
689
+
690
+            return new Checker(
691
+                    new EnvironmentHelper(),
692
+                    new FileAccessHelper(),
693
+                    new AppLocator(),
694
+                    $config,
695
+                    $c->getMemCacheFactory(),
696
+                    $appManager,
697
+                    $c->getTempManager()
698
+            );
699
+        });
700
+        $this->registerService(\OCP\IRequest::class, function ($c) {
701
+            if (isset($this['urlParams'])) {
702
+                $urlParams = $this['urlParams'];
703
+            } else {
704
+                $urlParams = [];
705
+            }
706
+
707
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
708
+                && in_array('fakeinput', stream_get_wrappers())
709
+            ) {
710
+                $stream = 'fakeinput://data';
711
+            } else {
712
+                $stream = 'php://input';
713
+            }
714
+
715
+            return new Request(
716
+                [
717
+                    'get' => $_GET,
718
+                    'post' => $_POST,
719
+                    'files' => $_FILES,
720
+                    'server' => $_SERVER,
721
+                    'env' => $_ENV,
722
+                    'cookies' => $_COOKIE,
723
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
724
+                        ? $_SERVER['REQUEST_METHOD']
725
+                        : null,
726
+                    'urlParams' => $urlParams,
727
+                ],
728
+                $this->getSecureRandom(),
729
+                $this->getConfig(),
730
+                $this->getCsrfTokenManager(),
731
+                $stream
732
+            );
733
+        });
734
+        $this->registerAlias('Request', \OCP\IRequest::class);
735
+
736
+        $this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
737
+            return new Mailer(
738
+                $c->getConfig(),
739
+                $c->getLogger(),
740
+                $c->getThemingDefaults()
741
+            );
742
+        });
743
+        $this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
744
+
745
+        $this->registerService('LDAPProvider', function(Server $c) {
746
+            $config = $c->getConfig();
747
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
748
+            if(is_null($factoryClass)) {
749
+                throw new \Exception('ldapProviderFactory not set');
750
+            }
751
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
752
+            $factory = new $factoryClass($this);
753
+            return $factory->getLDAPProvider();
754
+        });
755
+        $this->registerService('LockingProvider', function (Server $c) {
756
+            $ini = $c->getIniWrapper();
757
+            $config = $c->getConfig();
758
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
759
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
760
+                /** @var \OC\Memcache\Factory $memcacheFactory */
761
+                $memcacheFactory = $c->getMemCacheFactory();
762
+                $memcache = $memcacheFactory->createLocking('lock');
763
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
764
+                    return new MemcacheLockingProvider($memcache, $ttl);
765
+                }
766
+                return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
767
+            }
768
+            return new NoopLockingProvider();
769
+        });
770
+
771
+        $this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
772
+            return new \OC\Files\Mount\Manager();
773
+        });
774
+        $this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
775
+
776
+        $this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
777
+            return new \OC\Files\Type\Detection(
778
+                $c->getURLGenerator(),
779
+                \OC::$configDir,
780
+                \OC::$SERVERROOT . '/resources/config/'
781
+            );
782
+        });
783
+        $this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
784
+
785
+        $this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
786
+            return new \OC\Files\Type\Loader(
787
+                $c->getDatabaseConnection()
788
+            );
789
+        });
790
+        $this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
791
+
792
+        $this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
793
+            return new Manager(
794
+                $c->query(IValidator::class)
795
+            );
796
+        });
797
+        $this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
798
+
799
+        $this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
800
+            $manager = new \OC\CapabilitiesManager($c->getLogger());
801
+            $manager->registerCapability(function () use ($c) {
802
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
803
+            });
804
+            return $manager;
805
+        });
806
+        $this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
807
+
808
+        $this->registerService(\OCP\Comments\ICommentsManager::class, function(Server $c) {
809
+            $config = $c->getConfig();
810
+            $factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
811
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
812
+            $factory = new $factoryClass($this);
813
+            return $factory->getManager();
814
+        });
815
+        $this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
816
+
817
+        $this->registerService('ThemingDefaults', function(Server $c) {
818
+            /*
819 819
 			 * Dark magic for autoloader.
820 820
 			 * If we do a class_exists it will try to load the class which will
821 821
 			 * make composer cache the result. Resulting in errors when enabling
822 822
 			 * the theming app.
823 823
 			 */
824
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
825
-			if (isset($prefixes['OCA\\Theming\\'])) {
826
-				$classExists = true;
827
-			} else {
828
-				$classExists = false;
829
-			}
830
-
831
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming')) {
832
-				return new ThemingDefaults(
833
-					$c->getConfig(),
834
-					$c->getL10N('theming'),
835
-					$c->getURLGenerator(),
836
-					new \OC_Defaults(),
837
-					$c->getAppDataDir('theming'),
838
-					$c->getMemCacheFactory()
839
-				);
840
-			}
841
-			return new \OC_Defaults();
842
-		});
843
-		$this->registerService(EventDispatcher::class, function () {
844
-			return new EventDispatcher();
845
-		});
846
-		$this->registerAlias('EventDispatcher', EventDispatcher::class);
847
-		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
848
-
849
-		$this->registerService('CryptoWrapper', function (Server $c) {
850
-			// FIXME: Instantiiated here due to cyclic dependency
851
-			$request = new Request(
852
-				[
853
-					'get' => $_GET,
854
-					'post' => $_POST,
855
-					'files' => $_FILES,
856
-					'server' => $_SERVER,
857
-					'env' => $_ENV,
858
-					'cookies' => $_COOKIE,
859
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
860
-						? $_SERVER['REQUEST_METHOD']
861
-						: null,
862
-				],
863
-				$c->getSecureRandom(),
864
-				$c->getConfig()
865
-			);
866
-
867
-			return new CryptoWrapper(
868
-				$c->getConfig(),
869
-				$c->getCrypto(),
870
-				$c->getSecureRandom(),
871
-				$request
872
-			);
873
-		});
874
-		$this->registerService('CsrfTokenManager', function (Server $c) {
875
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
876
-
877
-			return new CsrfTokenManager(
878
-				$tokenGenerator,
879
-				$c->query(SessionStorage::class)
880
-			);
881
-		});
882
-		$this->registerService(SessionStorage::class, function (Server $c) {
883
-			return new SessionStorage($c->getSession());
884
-		});
885
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
886
-			return new ContentSecurityPolicyManager();
887
-		});
888
-		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
889
-
890
-		$this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
891
-			return new ContentSecurityPolicyNonceManager(
892
-				$c->getCsrfTokenManager(),
893
-				$c->getRequest()
894
-			);
895
-		});
896
-
897
-		$this->registerService(\OCP\Share\IManager::class, function(Server $c) {
898
-			$config = $c->getConfig();
899
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
900
-			/** @var \OCP\Share\IProviderFactory $factory */
901
-			$factory = new $factoryClass($this);
902
-
903
-			$manager = new \OC\Share20\Manager(
904
-				$c->getLogger(),
905
-				$c->getConfig(),
906
-				$c->getSecureRandom(),
907
-				$c->getHasher(),
908
-				$c->getMountManager(),
909
-				$c->getGroupManager(),
910
-				$c->getL10N('core'),
911
-				$factory,
912
-				$c->getUserManager(),
913
-				$c->getLazyRootFolder(),
914
-				$c->getEventDispatcher()
915
-			);
916
-
917
-			return $manager;
918
-		});
919
-		$this->registerAlias('ShareManager', \OCP\Share\IManager::class);
920
-
921
-		$this->registerService('SettingsManager', function(Server $c) {
922
-			$manager = new \OC\Settings\Manager(
923
-				$c->getLogger(),
924
-				$c->getDatabaseConnection(),
925
-				$c->getL10N('lib'),
926
-				$c->getConfig(),
927
-				$c->getEncryptionManager(),
928
-				$c->getUserManager(),
929
-				$c->getLockingProvider(),
930
-				$c->getRequest(),
931
-				new \OC\Settings\Mapper($c->getDatabaseConnection()),
932
-				$c->getURLGenerator()
933
-			);
934
-			return $manager;
935
-		});
936
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
937
-			return new \OC\Files\AppData\Factory(
938
-				$c->getRootFolder(),
939
-				$c->getSystemConfig()
940
-			);
941
-		});
942
-
943
-		$this->registerService('LockdownManager', function (Server $c) {
944
-			return new LockdownManager(function() use ($c) {
945
-				return $c->getSession();
946
-			});
947
-		});
948
-
949
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
950
-			return new CloudIdManager();
951
-		});
952
-
953
-		/* To trick DI since we don't extend the DIContainer here */
954
-		$this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
955
-			return new CleanPreviewsBackgroundJob(
956
-				$c->getRootFolder(),
957
-				$c->getLogger(),
958
-				$c->getJobList(),
959
-				new TimeFactory()
960
-			);
961
-		});
962
-
963
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
964
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
965
-
966
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
967
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
968
-
969
-		$this->registerService(\OCP\ISession::class, function(SimpleContainer $c) {
970
-			return $c->query(\OCP\IUserSession::class)->getSession();
971
-		});
972
-	}
973
-
974
-	/**
975
-	 * @return \OCP\Contacts\IManager
976
-	 */
977
-	public function getContactsManager() {
978
-		return $this->query('ContactsManager');
979
-	}
980
-
981
-	/**
982
-	 * @return \OC\Encryption\Manager
983
-	 */
984
-	public function getEncryptionManager() {
985
-		return $this->query('EncryptionManager');
986
-	}
987
-
988
-	/**
989
-	 * @return \OC\Encryption\File
990
-	 */
991
-	public function getEncryptionFilesHelper() {
992
-		return $this->query('EncryptionFileHelper');
993
-	}
994
-
995
-	/**
996
-	 * @return \OCP\Encryption\Keys\IStorage
997
-	 */
998
-	public function getEncryptionKeyStorage() {
999
-		return $this->query('EncryptionKeyStorage');
1000
-	}
1001
-
1002
-	/**
1003
-	 * The current request object holding all information about the request
1004
-	 * currently being processed is returned from this method.
1005
-	 * In case the current execution was not initiated by a web request null is returned
1006
-	 *
1007
-	 * @return \OCP\IRequest
1008
-	 */
1009
-	public function getRequest() {
1010
-		return $this->query('Request');
1011
-	}
1012
-
1013
-	/**
1014
-	 * Returns the preview manager which can create preview images for a given file
1015
-	 *
1016
-	 * @return \OCP\IPreview
1017
-	 */
1018
-	public function getPreviewManager() {
1019
-		return $this->query('PreviewManager');
1020
-	}
1021
-
1022
-	/**
1023
-	 * Returns the tag manager which can get and set tags for different object types
1024
-	 *
1025
-	 * @see \OCP\ITagManager::load()
1026
-	 * @return \OCP\ITagManager
1027
-	 */
1028
-	public function getTagManager() {
1029
-		return $this->query('TagManager');
1030
-	}
1031
-
1032
-	/**
1033
-	 * Returns the system-tag manager
1034
-	 *
1035
-	 * @return \OCP\SystemTag\ISystemTagManager
1036
-	 *
1037
-	 * @since 9.0.0
1038
-	 */
1039
-	public function getSystemTagManager() {
1040
-		return $this->query('SystemTagManager');
1041
-	}
1042
-
1043
-	/**
1044
-	 * Returns the system-tag object mapper
1045
-	 *
1046
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
1047
-	 *
1048
-	 * @since 9.0.0
1049
-	 */
1050
-	public function getSystemTagObjectMapper() {
1051
-		return $this->query('SystemTagObjectMapper');
1052
-	}
1053
-
1054
-	/**
1055
-	 * Returns the avatar manager, used for avatar functionality
1056
-	 *
1057
-	 * @return \OCP\IAvatarManager
1058
-	 */
1059
-	public function getAvatarManager() {
1060
-		return $this->query('AvatarManager');
1061
-	}
1062
-
1063
-	/**
1064
-	 * Returns the root folder of ownCloud's data directory
1065
-	 *
1066
-	 * @return \OCP\Files\IRootFolder
1067
-	 */
1068
-	public function getRootFolder() {
1069
-		return $this->query('LazyRootFolder');
1070
-	}
1071
-
1072
-	/**
1073
-	 * Returns the root folder of ownCloud's data directory
1074
-	 * This is the lazy variant so this gets only initialized once it
1075
-	 * is actually used.
1076
-	 *
1077
-	 * @return \OCP\Files\IRootFolder
1078
-	 */
1079
-	public function getLazyRootFolder() {
1080
-		return $this->query('LazyRootFolder');
1081
-	}
1082
-
1083
-	/**
1084
-	 * Returns a view to ownCloud's files folder
1085
-	 *
1086
-	 * @param string $userId user ID
1087
-	 * @return \OCP\Files\Folder|null
1088
-	 */
1089
-	public function getUserFolder($userId = null) {
1090
-		if ($userId === null) {
1091
-			$user = $this->getUserSession()->getUser();
1092
-			if (!$user) {
1093
-				return null;
1094
-			}
1095
-			$userId = $user->getUID();
1096
-		}
1097
-		$root = $this->getRootFolder();
1098
-		return $root->getUserFolder($userId);
1099
-	}
1100
-
1101
-	/**
1102
-	 * Returns an app-specific view in ownClouds data directory
1103
-	 *
1104
-	 * @return \OCP\Files\Folder
1105
-	 * @deprecated since 9.2.0 use IAppData
1106
-	 */
1107
-	public function getAppFolder() {
1108
-		$dir = '/' . \OC_App::getCurrentApp();
1109
-		$root = $this->getRootFolder();
1110
-		if (!$root->nodeExists($dir)) {
1111
-			$folder = $root->newFolder($dir);
1112
-		} else {
1113
-			$folder = $root->get($dir);
1114
-		}
1115
-		return $folder;
1116
-	}
1117
-
1118
-	/**
1119
-	 * @return \OC\User\Manager
1120
-	 */
1121
-	public function getUserManager() {
1122
-		return $this->query('UserManager');
1123
-	}
1124
-
1125
-	/**
1126
-	 * @return \OC\Group\Manager
1127
-	 */
1128
-	public function getGroupManager() {
1129
-		return $this->query('GroupManager');
1130
-	}
1131
-
1132
-	/**
1133
-	 * @return \OC\User\Session
1134
-	 */
1135
-	public function getUserSession() {
1136
-		return $this->query('UserSession');
1137
-	}
1138
-
1139
-	/**
1140
-	 * @return \OCP\ISession
1141
-	 */
1142
-	public function getSession() {
1143
-		return $this->query('UserSession')->getSession();
1144
-	}
1145
-
1146
-	/**
1147
-	 * @param \OCP\ISession $session
1148
-	 */
1149
-	public function setSession(\OCP\ISession $session) {
1150
-		$this->query(SessionStorage::class)->setSession($session);
1151
-		$this->query('UserSession')->setSession($session);
1152
-		$this->query(Store::class)->setSession($session);
1153
-	}
1154
-
1155
-	/**
1156
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1157
-	 */
1158
-	public function getTwoFactorAuthManager() {
1159
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1160
-	}
1161
-
1162
-	/**
1163
-	 * @return \OC\NavigationManager
1164
-	 */
1165
-	public function getNavigationManager() {
1166
-		return $this->query('NavigationManager');
1167
-	}
1168
-
1169
-	/**
1170
-	 * @return \OCP\IConfig
1171
-	 */
1172
-	public function getConfig() {
1173
-		return $this->query('AllConfig');
1174
-	}
1175
-
1176
-	/**
1177
-	 * @internal For internal use only
1178
-	 * @return \OC\SystemConfig
1179
-	 */
1180
-	public function getSystemConfig() {
1181
-		return $this->query('SystemConfig');
1182
-	}
1183
-
1184
-	/**
1185
-	 * Returns the app config manager
1186
-	 *
1187
-	 * @return \OCP\IAppConfig
1188
-	 */
1189
-	public function getAppConfig() {
1190
-		return $this->query('AppConfig');
1191
-	}
1192
-
1193
-	/**
1194
-	 * @return \OCP\L10N\IFactory
1195
-	 */
1196
-	public function getL10NFactory() {
1197
-		return $this->query('L10NFactory');
1198
-	}
1199
-
1200
-	/**
1201
-	 * get an L10N instance
1202
-	 *
1203
-	 * @param string $app appid
1204
-	 * @param string $lang
1205
-	 * @return IL10N
1206
-	 */
1207
-	public function getL10N($app, $lang = null) {
1208
-		return $this->getL10NFactory()->get($app, $lang);
1209
-	}
1210
-
1211
-	/**
1212
-	 * @return \OCP\IURLGenerator
1213
-	 */
1214
-	public function getURLGenerator() {
1215
-		return $this->query('URLGenerator');
1216
-	}
1217
-
1218
-	/**
1219
-	 * @return \OCP\IHelper
1220
-	 */
1221
-	public function getHelper() {
1222
-		return $this->query('AppHelper');
1223
-	}
1224
-
1225
-	/**
1226
-	 * @return AppFetcher
1227
-	 */
1228
-	public function getAppFetcher() {
1229
-		return $this->query('AppFetcher');
1230
-	}
1231
-
1232
-	/**
1233
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1234
-	 * getMemCacheFactory() instead.
1235
-	 *
1236
-	 * @return \OCP\ICache
1237
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1238
-	 */
1239
-	public function getCache() {
1240
-		return $this->query('UserCache');
1241
-	}
1242
-
1243
-	/**
1244
-	 * Returns an \OCP\CacheFactory instance
1245
-	 *
1246
-	 * @return \OCP\ICacheFactory
1247
-	 */
1248
-	public function getMemCacheFactory() {
1249
-		return $this->query('MemCacheFactory');
1250
-	}
1251
-
1252
-	/**
1253
-	 * Returns an \OC\RedisFactory instance
1254
-	 *
1255
-	 * @return \OC\RedisFactory
1256
-	 */
1257
-	public function getGetRedisFactory() {
1258
-		return $this->query('RedisFactory');
1259
-	}
1260
-
1261
-
1262
-	/**
1263
-	 * Returns the current session
1264
-	 *
1265
-	 * @return \OCP\IDBConnection
1266
-	 */
1267
-	public function getDatabaseConnection() {
1268
-		return $this->query('DatabaseConnection');
1269
-	}
1270
-
1271
-	/**
1272
-	 * Returns the activity manager
1273
-	 *
1274
-	 * @return \OCP\Activity\IManager
1275
-	 */
1276
-	public function getActivityManager() {
1277
-		return $this->query('ActivityManager');
1278
-	}
1279
-
1280
-	/**
1281
-	 * Returns an job list for controlling background jobs
1282
-	 *
1283
-	 * @return \OCP\BackgroundJob\IJobList
1284
-	 */
1285
-	public function getJobList() {
1286
-		return $this->query('JobList');
1287
-	}
1288
-
1289
-	/**
1290
-	 * Returns a logger instance
1291
-	 *
1292
-	 * @return \OCP\ILogger
1293
-	 */
1294
-	public function getLogger() {
1295
-		return $this->query('Logger');
1296
-	}
1297
-
1298
-	/**
1299
-	 * Returns a router for generating and matching urls
1300
-	 *
1301
-	 * @return \OCP\Route\IRouter
1302
-	 */
1303
-	public function getRouter() {
1304
-		return $this->query('Router');
1305
-	}
1306
-
1307
-	/**
1308
-	 * Returns a search instance
1309
-	 *
1310
-	 * @return \OCP\ISearch
1311
-	 */
1312
-	public function getSearch() {
1313
-		return $this->query('Search');
1314
-	}
1315
-
1316
-	/**
1317
-	 * Returns a SecureRandom instance
1318
-	 *
1319
-	 * @return \OCP\Security\ISecureRandom
1320
-	 */
1321
-	public function getSecureRandom() {
1322
-		return $this->query('SecureRandom');
1323
-	}
1324
-
1325
-	/**
1326
-	 * Returns a Crypto instance
1327
-	 *
1328
-	 * @return \OCP\Security\ICrypto
1329
-	 */
1330
-	public function getCrypto() {
1331
-		return $this->query('Crypto');
1332
-	}
1333
-
1334
-	/**
1335
-	 * Returns a Hasher instance
1336
-	 *
1337
-	 * @return \OCP\Security\IHasher
1338
-	 */
1339
-	public function getHasher() {
1340
-		return $this->query('Hasher');
1341
-	}
1342
-
1343
-	/**
1344
-	 * Returns a CredentialsManager instance
1345
-	 *
1346
-	 * @return \OCP\Security\ICredentialsManager
1347
-	 */
1348
-	public function getCredentialsManager() {
1349
-		return $this->query('CredentialsManager');
1350
-	}
1351
-
1352
-	/**
1353
-	 * Returns an instance of the HTTP helper class
1354
-	 *
1355
-	 * @deprecated Use getHTTPClientService()
1356
-	 * @return \OC\HTTPHelper
1357
-	 */
1358
-	public function getHTTPHelper() {
1359
-		return $this->query('HTTPHelper');
1360
-	}
1361
-
1362
-	/**
1363
-	 * Get the certificate manager for the user
1364
-	 *
1365
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1366
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1367
-	 */
1368
-	public function getCertificateManager($userId = '') {
1369
-		if ($userId === '') {
1370
-			$userSession = $this->getUserSession();
1371
-			$user = $userSession->getUser();
1372
-			if (is_null($user)) {
1373
-				return null;
1374
-			}
1375
-			$userId = $user->getUID();
1376
-		}
1377
-		return new CertificateManager($userId, new View(), $this->getConfig(), $this->getLogger());
1378
-	}
1379
-
1380
-	/**
1381
-	 * Returns an instance of the HTTP client service
1382
-	 *
1383
-	 * @return \OCP\Http\Client\IClientService
1384
-	 */
1385
-	public function getHTTPClientService() {
1386
-		return $this->query('HttpClientService');
1387
-	}
1388
-
1389
-	/**
1390
-	 * Create a new event source
1391
-	 *
1392
-	 * @return \OCP\IEventSource
1393
-	 */
1394
-	public function createEventSource() {
1395
-		return new \OC_EventSource();
1396
-	}
1397
-
1398
-	/**
1399
-	 * Get the active event logger
1400
-	 *
1401
-	 * The returned logger only logs data when debug mode is enabled
1402
-	 *
1403
-	 * @return \OCP\Diagnostics\IEventLogger
1404
-	 */
1405
-	public function getEventLogger() {
1406
-		return $this->query('EventLogger');
1407
-	}
1408
-
1409
-	/**
1410
-	 * Get the active query logger
1411
-	 *
1412
-	 * The returned logger only logs data when debug mode is enabled
1413
-	 *
1414
-	 * @return \OCP\Diagnostics\IQueryLogger
1415
-	 */
1416
-	public function getQueryLogger() {
1417
-		return $this->query('QueryLogger');
1418
-	}
1419
-
1420
-	/**
1421
-	 * Get the manager for temporary files and folders
1422
-	 *
1423
-	 * @return \OCP\ITempManager
1424
-	 */
1425
-	public function getTempManager() {
1426
-		return $this->query('TempManager');
1427
-	}
1428
-
1429
-	/**
1430
-	 * Get the app manager
1431
-	 *
1432
-	 * @return \OCP\App\IAppManager
1433
-	 */
1434
-	public function getAppManager() {
1435
-		return $this->query('AppManager');
1436
-	}
1437
-
1438
-	/**
1439
-	 * Creates a new mailer
1440
-	 *
1441
-	 * @return \OCP\Mail\IMailer
1442
-	 */
1443
-	public function getMailer() {
1444
-		return $this->query('Mailer');
1445
-	}
1446
-
1447
-	/**
1448
-	 * Get the webroot
1449
-	 *
1450
-	 * @return string
1451
-	 */
1452
-	public function getWebRoot() {
1453
-		return $this->webRoot;
1454
-	}
1455
-
1456
-	/**
1457
-	 * @return \OC\OCSClient
1458
-	 */
1459
-	public function getOcsClient() {
1460
-		return $this->query('OcsClient');
1461
-	}
1462
-
1463
-	/**
1464
-	 * @return \OCP\IDateTimeZone
1465
-	 */
1466
-	public function getDateTimeZone() {
1467
-		return $this->query('DateTimeZone');
1468
-	}
1469
-
1470
-	/**
1471
-	 * @return \OCP\IDateTimeFormatter
1472
-	 */
1473
-	public function getDateTimeFormatter() {
1474
-		return $this->query('DateTimeFormatter');
1475
-	}
1476
-
1477
-	/**
1478
-	 * @return \OCP\Files\Config\IMountProviderCollection
1479
-	 */
1480
-	public function getMountProviderCollection() {
1481
-		return $this->query('MountConfigManager');
1482
-	}
1483
-
1484
-	/**
1485
-	 * Get the IniWrapper
1486
-	 *
1487
-	 * @return IniGetWrapper
1488
-	 */
1489
-	public function getIniWrapper() {
1490
-		return $this->query('IniWrapper');
1491
-	}
1492
-
1493
-	/**
1494
-	 * @return \OCP\Command\IBus
1495
-	 */
1496
-	public function getCommandBus() {
1497
-		return $this->query('AsyncCommandBus');
1498
-	}
1499
-
1500
-	/**
1501
-	 * Get the trusted domain helper
1502
-	 *
1503
-	 * @return TrustedDomainHelper
1504
-	 */
1505
-	public function getTrustedDomainHelper() {
1506
-		return $this->query('TrustedDomainHelper');
1507
-	}
1508
-
1509
-	/**
1510
-	 * Get the locking provider
1511
-	 *
1512
-	 * @return \OCP\Lock\ILockingProvider
1513
-	 * @since 8.1.0
1514
-	 */
1515
-	public function getLockingProvider() {
1516
-		return $this->query('LockingProvider');
1517
-	}
1518
-
1519
-	/**
1520
-	 * @return \OCP\Files\Mount\IMountManager
1521
-	 **/
1522
-	function getMountManager() {
1523
-		return $this->query('MountManager');
1524
-	}
1525
-
1526
-	/** @return \OCP\Files\Config\IUserMountCache */
1527
-	function getUserMountCache() {
1528
-		return $this->query('UserMountCache');
1529
-	}
1530
-
1531
-	/**
1532
-	 * Get the MimeTypeDetector
1533
-	 *
1534
-	 * @return \OCP\Files\IMimeTypeDetector
1535
-	 */
1536
-	public function getMimeTypeDetector() {
1537
-		return $this->query('MimeTypeDetector');
1538
-	}
1539
-
1540
-	/**
1541
-	 * Get the MimeTypeLoader
1542
-	 *
1543
-	 * @return \OCP\Files\IMimeTypeLoader
1544
-	 */
1545
-	public function getMimeTypeLoader() {
1546
-		return $this->query('MimeTypeLoader');
1547
-	}
1548
-
1549
-	/**
1550
-	 * Get the manager of all the capabilities
1551
-	 *
1552
-	 * @return \OC\CapabilitiesManager
1553
-	 */
1554
-	public function getCapabilitiesManager() {
1555
-		return $this->query('CapabilitiesManager');
1556
-	}
1557
-
1558
-	/**
1559
-	 * Get the EventDispatcher
1560
-	 *
1561
-	 * @return EventDispatcherInterface
1562
-	 * @since 8.2.0
1563
-	 */
1564
-	public function getEventDispatcher() {
1565
-		return $this->query('EventDispatcher');
1566
-	}
1567
-
1568
-	/**
1569
-	 * Get the Notification Manager
1570
-	 *
1571
-	 * @return \OCP\Notification\IManager
1572
-	 * @since 8.2.0
1573
-	 */
1574
-	public function getNotificationManager() {
1575
-		return $this->query('NotificationManager');
1576
-	}
1577
-
1578
-	/**
1579
-	 * @return \OCP\Comments\ICommentsManager
1580
-	 */
1581
-	public function getCommentsManager() {
1582
-		return $this->query('CommentsManager');
1583
-	}
1584
-
1585
-	/**
1586
-	 * @return \OCA\Theming\ThemingDefaults
1587
-	 */
1588
-	public function getThemingDefaults() {
1589
-		return $this->query('ThemingDefaults');
1590
-	}
1591
-
1592
-	/**
1593
-	 * @return \OC\IntegrityCheck\Checker
1594
-	 */
1595
-	public function getIntegrityCodeChecker() {
1596
-		return $this->query('IntegrityCodeChecker');
1597
-	}
1598
-
1599
-	/**
1600
-	 * @return \OC\Session\CryptoWrapper
1601
-	 */
1602
-	public function getSessionCryptoWrapper() {
1603
-		return $this->query('CryptoWrapper');
1604
-	}
1605
-
1606
-	/**
1607
-	 * @return CsrfTokenManager
1608
-	 */
1609
-	public function getCsrfTokenManager() {
1610
-		return $this->query('CsrfTokenManager');
1611
-	}
1612
-
1613
-	/**
1614
-	 * @return Throttler
1615
-	 */
1616
-	public function getBruteForceThrottler() {
1617
-		return $this->query('Throttler');
1618
-	}
1619
-
1620
-	/**
1621
-	 * @return IContentSecurityPolicyManager
1622
-	 */
1623
-	public function getContentSecurityPolicyManager() {
1624
-		return $this->query('ContentSecurityPolicyManager');
1625
-	}
1626
-
1627
-	/**
1628
-	 * @return ContentSecurityPolicyNonceManager
1629
-	 */
1630
-	public function getContentSecurityPolicyNonceManager() {
1631
-		return $this->query('ContentSecurityPolicyNonceManager');
1632
-	}
1633
-
1634
-	/**
1635
-	 * Not a public API as of 8.2, wait for 9.0
1636
-	 *
1637
-	 * @return \OCA\Files_External\Service\BackendService
1638
-	 */
1639
-	public function getStoragesBackendService() {
1640
-		return $this->query('OCA\\Files_External\\Service\\BackendService');
1641
-	}
1642
-
1643
-	/**
1644
-	 * Not a public API as of 8.2, wait for 9.0
1645
-	 *
1646
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1647
-	 */
1648
-	public function getGlobalStoragesService() {
1649
-		return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1650
-	}
1651
-
1652
-	/**
1653
-	 * Not a public API as of 8.2, wait for 9.0
1654
-	 *
1655
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1656
-	 */
1657
-	public function getUserGlobalStoragesService() {
1658
-		return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1659
-	}
1660
-
1661
-	/**
1662
-	 * Not a public API as of 8.2, wait for 9.0
1663
-	 *
1664
-	 * @return \OCA\Files_External\Service\UserStoragesService
1665
-	 */
1666
-	public function getUserStoragesService() {
1667
-		return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1668
-	}
1669
-
1670
-	/**
1671
-	 * @return \OCP\Share\IManager
1672
-	 */
1673
-	public function getShareManager() {
1674
-		return $this->query('ShareManager');
1675
-	}
1676
-
1677
-	/**
1678
-	 * Returns the LDAP Provider
1679
-	 *
1680
-	 * @return \OCP\LDAP\ILDAPProvider
1681
-	 */
1682
-	public function getLDAPProvider() {
1683
-		return $this->query('LDAPProvider');
1684
-	}
1685
-
1686
-	/**
1687
-	 * @return \OCP\Settings\IManager
1688
-	 */
1689
-	public function getSettingsManager() {
1690
-		return $this->query('SettingsManager');
1691
-	}
1692
-
1693
-	/**
1694
-	 * @return \OCP\Files\IAppData
1695
-	 */
1696
-	public function getAppDataDir($app) {
1697
-		/** @var \OC\Files\AppData\Factory $factory */
1698
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
1699
-		return $factory->get($app);
1700
-	}
1701
-
1702
-	/**
1703
-	 * @return \OCP\Lockdown\ILockdownManager
1704
-	 */
1705
-	public function getLockdownManager() {
1706
-		return $this->query('LockdownManager');
1707
-	}
1708
-
1709
-	/**
1710
-	 * @return \OCP\Federation\ICloudIdManager
1711
-	 */
1712
-	public function getCloudIdManager() {
1713
-		return $this->query(ICloudIdManager::class);
1714
-	}
824
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
825
+            if (isset($prefixes['OCA\\Theming\\'])) {
826
+                $classExists = true;
827
+            } else {
828
+                $classExists = false;
829
+            }
830
+
831
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming')) {
832
+                return new ThemingDefaults(
833
+                    $c->getConfig(),
834
+                    $c->getL10N('theming'),
835
+                    $c->getURLGenerator(),
836
+                    new \OC_Defaults(),
837
+                    $c->getAppDataDir('theming'),
838
+                    $c->getMemCacheFactory()
839
+                );
840
+            }
841
+            return new \OC_Defaults();
842
+        });
843
+        $this->registerService(EventDispatcher::class, function () {
844
+            return new EventDispatcher();
845
+        });
846
+        $this->registerAlias('EventDispatcher', EventDispatcher::class);
847
+        $this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
848
+
849
+        $this->registerService('CryptoWrapper', function (Server $c) {
850
+            // FIXME: Instantiiated here due to cyclic dependency
851
+            $request = new Request(
852
+                [
853
+                    'get' => $_GET,
854
+                    'post' => $_POST,
855
+                    'files' => $_FILES,
856
+                    'server' => $_SERVER,
857
+                    'env' => $_ENV,
858
+                    'cookies' => $_COOKIE,
859
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
860
+                        ? $_SERVER['REQUEST_METHOD']
861
+                        : null,
862
+                ],
863
+                $c->getSecureRandom(),
864
+                $c->getConfig()
865
+            );
866
+
867
+            return new CryptoWrapper(
868
+                $c->getConfig(),
869
+                $c->getCrypto(),
870
+                $c->getSecureRandom(),
871
+                $request
872
+            );
873
+        });
874
+        $this->registerService('CsrfTokenManager', function (Server $c) {
875
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
876
+
877
+            return new CsrfTokenManager(
878
+                $tokenGenerator,
879
+                $c->query(SessionStorage::class)
880
+            );
881
+        });
882
+        $this->registerService(SessionStorage::class, function (Server $c) {
883
+            return new SessionStorage($c->getSession());
884
+        });
885
+        $this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
886
+            return new ContentSecurityPolicyManager();
887
+        });
888
+        $this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
889
+
890
+        $this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
891
+            return new ContentSecurityPolicyNonceManager(
892
+                $c->getCsrfTokenManager(),
893
+                $c->getRequest()
894
+            );
895
+        });
896
+
897
+        $this->registerService(\OCP\Share\IManager::class, function(Server $c) {
898
+            $config = $c->getConfig();
899
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
900
+            /** @var \OCP\Share\IProviderFactory $factory */
901
+            $factory = new $factoryClass($this);
902
+
903
+            $manager = new \OC\Share20\Manager(
904
+                $c->getLogger(),
905
+                $c->getConfig(),
906
+                $c->getSecureRandom(),
907
+                $c->getHasher(),
908
+                $c->getMountManager(),
909
+                $c->getGroupManager(),
910
+                $c->getL10N('core'),
911
+                $factory,
912
+                $c->getUserManager(),
913
+                $c->getLazyRootFolder(),
914
+                $c->getEventDispatcher()
915
+            );
916
+
917
+            return $manager;
918
+        });
919
+        $this->registerAlias('ShareManager', \OCP\Share\IManager::class);
920
+
921
+        $this->registerService('SettingsManager', function(Server $c) {
922
+            $manager = new \OC\Settings\Manager(
923
+                $c->getLogger(),
924
+                $c->getDatabaseConnection(),
925
+                $c->getL10N('lib'),
926
+                $c->getConfig(),
927
+                $c->getEncryptionManager(),
928
+                $c->getUserManager(),
929
+                $c->getLockingProvider(),
930
+                $c->getRequest(),
931
+                new \OC\Settings\Mapper($c->getDatabaseConnection()),
932
+                $c->getURLGenerator()
933
+            );
934
+            return $manager;
935
+        });
936
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
937
+            return new \OC\Files\AppData\Factory(
938
+                $c->getRootFolder(),
939
+                $c->getSystemConfig()
940
+            );
941
+        });
942
+
943
+        $this->registerService('LockdownManager', function (Server $c) {
944
+            return new LockdownManager(function() use ($c) {
945
+                return $c->getSession();
946
+            });
947
+        });
948
+
949
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
950
+            return new CloudIdManager();
951
+        });
952
+
953
+        /* To trick DI since we don't extend the DIContainer here */
954
+        $this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
955
+            return new CleanPreviewsBackgroundJob(
956
+                $c->getRootFolder(),
957
+                $c->getLogger(),
958
+                $c->getJobList(),
959
+                new TimeFactory()
960
+            );
961
+        });
962
+
963
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
964
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
965
+
966
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
967
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
968
+
969
+        $this->registerService(\OCP\ISession::class, function(SimpleContainer $c) {
970
+            return $c->query(\OCP\IUserSession::class)->getSession();
971
+        });
972
+    }
973
+
974
+    /**
975
+     * @return \OCP\Contacts\IManager
976
+     */
977
+    public function getContactsManager() {
978
+        return $this->query('ContactsManager');
979
+    }
980
+
981
+    /**
982
+     * @return \OC\Encryption\Manager
983
+     */
984
+    public function getEncryptionManager() {
985
+        return $this->query('EncryptionManager');
986
+    }
987
+
988
+    /**
989
+     * @return \OC\Encryption\File
990
+     */
991
+    public function getEncryptionFilesHelper() {
992
+        return $this->query('EncryptionFileHelper');
993
+    }
994
+
995
+    /**
996
+     * @return \OCP\Encryption\Keys\IStorage
997
+     */
998
+    public function getEncryptionKeyStorage() {
999
+        return $this->query('EncryptionKeyStorage');
1000
+    }
1001
+
1002
+    /**
1003
+     * The current request object holding all information about the request
1004
+     * currently being processed is returned from this method.
1005
+     * In case the current execution was not initiated by a web request null is returned
1006
+     *
1007
+     * @return \OCP\IRequest
1008
+     */
1009
+    public function getRequest() {
1010
+        return $this->query('Request');
1011
+    }
1012
+
1013
+    /**
1014
+     * Returns the preview manager which can create preview images for a given file
1015
+     *
1016
+     * @return \OCP\IPreview
1017
+     */
1018
+    public function getPreviewManager() {
1019
+        return $this->query('PreviewManager');
1020
+    }
1021
+
1022
+    /**
1023
+     * Returns the tag manager which can get and set tags for different object types
1024
+     *
1025
+     * @see \OCP\ITagManager::load()
1026
+     * @return \OCP\ITagManager
1027
+     */
1028
+    public function getTagManager() {
1029
+        return $this->query('TagManager');
1030
+    }
1031
+
1032
+    /**
1033
+     * Returns the system-tag manager
1034
+     *
1035
+     * @return \OCP\SystemTag\ISystemTagManager
1036
+     *
1037
+     * @since 9.0.0
1038
+     */
1039
+    public function getSystemTagManager() {
1040
+        return $this->query('SystemTagManager');
1041
+    }
1042
+
1043
+    /**
1044
+     * Returns the system-tag object mapper
1045
+     *
1046
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
1047
+     *
1048
+     * @since 9.0.0
1049
+     */
1050
+    public function getSystemTagObjectMapper() {
1051
+        return $this->query('SystemTagObjectMapper');
1052
+    }
1053
+
1054
+    /**
1055
+     * Returns the avatar manager, used for avatar functionality
1056
+     *
1057
+     * @return \OCP\IAvatarManager
1058
+     */
1059
+    public function getAvatarManager() {
1060
+        return $this->query('AvatarManager');
1061
+    }
1062
+
1063
+    /**
1064
+     * Returns the root folder of ownCloud's data directory
1065
+     *
1066
+     * @return \OCP\Files\IRootFolder
1067
+     */
1068
+    public function getRootFolder() {
1069
+        return $this->query('LazyRootFolder');
1070
+    }
1071
+
1072
+    /**
1073
+     * Returns the root folder of ownCloud's data directory
1074
+     * This is the lazy variant so this gets only initialized once it
1075
+     * is actually used.
1076
+     *
1077
+     * @return \OCP\Files\IRootFolder
1078
+     */
1079
+    public function getLazyRootFolder() {
1080
+        return $this->query('LazyRootFolder');
1081
+    }
1082
+
1083
+    /**
1084
+     * Returns a view to ownCloud's files folder
1085
+     *
1086
+     * @param string $userId user ID
1087
+     * @return \OCP\Files\Folder|null
1088
+     */
1089
+    public function getUserFolder($userId = null) {
1090
+        if ($userId === null) {
1091
+            $user = $this->getUserSession()->getUser();
1092
+            if (!$user) {
1093
+                return null;
1094
+            }
1095
+            $userId = $user->getUID();
1096
+        }
1097
+        $root = $this->getRootFolder();
1098
+        return $root->getUserFolder($userId);
1099
+    }
1100
+
1101
+    /**
1102
+     * Returns an app-specific view in ownClouds data directory
1103
+     *
1104
+     * @return \OCP\Files\Folder
1105
+     * @deprecated since 9.2.0 use IAppData
1106
+     */
1107
+    public function getAppFolder() {
1108
+        $dir = '/' . \OC_App::getCurrentApp();
1109
+        $root = $this->getRootFolder();
1110
+        if (!$root->nodeExists($dir)) {
1111
+            $folder = $root->newFolder($dir);
1112
+        } else {
1113
+            $folder = $root->get($dir);
1114
+        }
1115
+        return $folder;
1116
+    }
1117
+
1118
+    /**
1119
+     * @return \OC\User\Manager
1120
+     */
1121
+    public function getUserManager() {
1122
+        return $this->query('UserManager');
1123
+    }
1124
+
1125
+    /**
1126
+     * @return \OC\Group\Manager
1127
+     */
1128
+    public function getGroupManager() {
1129
+        return $this->query('GroupManager');
1130
+    }
1131
+
1132
+    /**
1133
+     * @return \OC\User\Session
1134
+     */
1135
+    public function getUserSession() {
1136
+        return $this->query('UserSession');
1137
+    }
1138
+
1139
+    /**
1140
+     * @return \OCP\ISession
1141
+     */
1142
+    public function getSession() {
1143
+        return $this->query('UserSession')->getSession();
1144
+    }
1145
+
1146
+    /**
1147
+     * @param \OCP\ISession $session
1148
+     */
1149
+    public function setSession(\OCP\ISession $session) {
1150
+        $this->query(SessionStorage::class)->setSession($session);
1151
+        $this->query('UserSession')->setSession($session);
1152
+        $this->query(Store::class)->setSession($session);
1153
+    }
1154
+
1155
+    /**
1156
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1157
+     */
1158
+    public function getTwoFactorAuthManager() {
1159
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1160
+    }
1161
+
1162
+    /**
1163
+     * @return \OC\NavigationManager
1164
+     */
1165
+    public function getNavigationManager() {
1166
+        return $this->query('NavigationManager');
1167
+    }
1168
+
1169
+    /**
1170
+     * @return \OCP\IConfig
1171
+     */
1172
+    public function getConfig() {
1173
+        return $this->query('AllConfig');
1174
+    }
1175
+
1176
+    /**
1177
+     * @internal For internal use only
1178
+     * @return \OC\SystemConfig
1179
+     */
1180
+    public function getSystemConfig() {
1181
+        return $this->query('SystemConfig');
1182
+    }
1183
+
1184
+    /**
1185
+     * Returns the app config manager
1186
+     *
1187
+     * @return \OCP\IAppConfig
1188
+     */
1189
+    public function getAppConfig() {
1190
+        return $this->query('AppConfig');
1191
+    }
1192
+
1193
+    /**
1194
+     * @return \OCP\L10N\IFactory
1195
+     */
1196
+    public function getL10NFactory() {
1197
+        return $this->query('L10NFactory');
1198
+    }
1199
+
1200
+    /**
1201
+     * get an L10N instance
1202
+     *
1203
+     * @param string $app appid
1204
+     * @param string $lang
1205
+     * @return IL10N
1206
+     */
1207
+    public function getL10N($app, $lang = null) {
1208
+        return $this->getL10NFactory()->get($app, $lang);
1209
+    }
1210
+
1211
+    /**
1212
+     * @return \OCP\IURLGenerator
1213
+     */
1214
+    public function getURLGenerator() {
1215
+        return $this->query('URLGenerator');
1216
+    }
1217
+
1218
+    /**
1219
+     * @return \OCP\IHelper
1220
+     */
1221
+    public function getHelper() {
1222
+        return $this->query('AppHelper');
1223
+    }
1224
+
1225
+    /**
1226
+     * @return AppFetcher
1227
+     */
1228
+    public function getAppFetcher() {
1229
+        return $this->query('AppFetcher');
1230
+    }
1231
+
1232
+    /**
1233
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1234
+     * getMemCacheFactory() instead.
1235
+     *
1236
+     * @return \OCP\ICache
1237
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1238
+     */
1239
+    public function getCache() {
1240
+        return $this->query('UserCache');
1241
+    }
1242
+
1243
+    /**
1244
+     * Returns an \OCP\CacheFactory instance
1245
+     *
1246
+     * @return \OCP\ICacheFactory
1247
+     */
1248
+    public function getMemCacheFactory() {
1249
+        return $this->query('MemCacheFactory');
1250
+    }
1251
+
1252
+    /**
1253
+     * Returns an \OC\RedisFactory instance
1254
+     *
1255
+     * @return \OC\RedisFactory
1256
+     */
1257
+    public function getGetRedisFactory() {
1258
+        return $this->query('RedisFactory');
1259
+    }
1260
+
1261
+
1262
+    /**
1263
+     * Returns the current session
1264
+     *
1265
+     * @return \OCP\IDBConnection
1266
+     */
1267
+    public function getDatabaseConnection() {
1268
+        return $this->query('DatabaseConnection');
1269
+    }
1270
+
1271
+    /**
1272
+     * Returns the activity manager
1273
+     *
1274
+     * @return \OCP\Activity\IManager
1275
+     */
1276
+    public function getActivityManager() {
1277
+        return $this->query('ActivityManager');
1278
+    }
1279
+
1280
+    /**
1281
+     * Returns an job list for controlling background jobs
1282
+     *
1283
+     * @return \OCP\BackgroundJob\IJobList
1284
+     */
1285
+    public function getJobList() {
1286
+        return $this->query('JobList');
1287
+    }
1288
+
1289
+    /**
1290
+     * Returns a logger instance
1291
+     *
1292
+     * @return \OCP\ILogger
1293
+     */
1294
+    public function getLogger() {
1295
+        return $this->query('Logger');
1296
+    }
1297
+
1298
+    /**
1299
+     * Returns a router for generating and matching urls
1300
+     *
1301
+     * @return \OCP\Route\IRouter
1302
+     */
1303
+    public function getRouter() {
1304
+        return $this->query('Router');
1305
+    }
1306
+
1307
+    /**
1308
+     * Returns a search instance
1309
+     *
1310
+     * @return \OCP\ISearch
1311
+     */
1312
+    public function getSearch() {
1313
+        return $this->query('Search');
1314
+    }
1315
+
1316
+    /**
1317
+     * Returns a SecureRandom instance
1318
+     *
1319
+     * @return \OCP\Security\ISecureRandom
1320
+     */
1321
+    public function getSecureRandom() {
1322
+        return $this->query('SecureRandom');
1323
+    }
1324
+
1325
+    /**
1326
+     * Returns a Crypto instance
1327
+     *
1328
+     * @return \OCP\Security\ICrypto
1329
+     */
1330
+    public function getCrypto() {
1331
+        return $this->query('Crypto');
1332
+    }
1333
+
1334
+    /**
1335
+     * Returns a Hasher instance
1336
+     *
1337
+     * @return \OCP\Security\IHasher
1338
+     */
1339
+    public function getHasher() {
1340
+        return $this->query('Hasher');
1341
+    }
1342
+
1343
+    /**
1344
+     * Returns a CredentialsManager instance
1345
+     *
1346
+     * @return \OCP\Security\ICredentialsManager
1347
+     */
1348
+    public function getCredentialsManager() {
1349
+        return $this->query('CredentialsManager');
1350
+    }
1351
+
1352
+    /**
1353
+     * Returns an instance of the HTTP helper class
1354
+     *
1355
+     * @deprecated Use getHTTPClientService()
1356
+     * @return \OC\HTTPHelper
1357
+     */
1358
+    public function getHTTPHelper() {
1359
+        return $this->query('HTTPHelper');
1360
+    }
1361
+
1362
+    /**
1363
+     * Get the certificate manager for the user
1364
+     *
1365
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1366
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1367
+     */
1368
+    public function getCertificateManager($userId = '') {
1369
+        if ($userId === '') {
1370
+            $userSession = $this->getUserSession();
1371
+            $user = $userSession->getUser();
1372
+            if (is_null($user)) {
1373
+                return null;
1374
+            }
1375
+            $userId = $user->getUID();
1376
+        }
1377
+        return new CertificateManager($userId, new View(), $this->getConfig(), $this->getLogger());
1378
+    }
1379
+
1380
+    /**
1381
+     * Returns an instance of the HTTP client service
1382
+     *
1383
+     * @return \OCP\Http\Client\IClientService
1384
+     */
1385
+    public function getHTTPClientService() {
1386
+        return $this->query('HttpClientService');
1387
+    }
1388
+
1389
+    /**
1390
+     * Create a new event source
1391
+     *
1392
+     * @return \OCP\IEventSource
1393
+     */
1394
+    public function createEventSource() {
1395
+        return new \OC_EventSource();
1396
+    }
1397
+
1398
+    /**
1399
+     * Get the active event logger
1400
+     *
1401
+     * The returned logger only logs data when debug mode is enabled
1402
+     *
1403
+     * @return \OCP\Diagnostics\IEventLogger
1404
+     */
1405
+    public function getEventLogger() {
1406
+        return $this->query('EventLogger');
1407
+    }
1408
+
1409
+    /**
1410
+     * Get the active query logger
1411
+     *
1412
+     * The returned logger only logs data when debug mode is enabled
1413
+     *
1414
+     * @return \OCP\Diagnostics\IQueryLogger
1415
+     */
1416
+    public function getQueryLogger() {
1417
+        return $this->query('QueryLogger');
1418
+    }
1419
+
1420
+    /**
1421
+     * Get the manager for temporary files and folders
1422
+     *
1423
+     * @return \OCP\ITempManager
1424
+     */
1425
+    public function getTempManager() {
1426
+        return $this->query('TempManager');
1427
+    }
1428
+
1429
+    /**
1430
+     * Get the app manager
1431
+     *
1432
+     * @return \OCP\App\IAppManager
1433
+     */
1434
+    public function getAppManager() {
1435
+        return $this->query('AppManager');
1436
+    }
1437
+
1438
+    /**
1439
+     * Creates a new mailer
1440
+     *
1441
+     * @return \OCP\Mail\IMailer
1442
+     */
1443
+    public function getMailer() {
1444
+        return $this->query('Mailer');
1445
+    }
1446
+
1447
+    /**
1448
+     * Get the webroot
1449
+     *
1450
+     * @return string
1451
+     */
1452
+    public function getWebRoot() {
1453
+        return $this->webRoot;
1454
+    }
1455
+
1456
+    /**
1457
+     * @return \OC\OCSClient
1458
+     */
1459
+    public function getOcsClient() {
1460
+        return $this->query('OcsClient');
1461
+    }
1462
+
1463
+    /**
1464
+     * @return \OCP\IDateTimeZone
1465
+     */
1466
+    public function getDateTimeZone() {
1467
+        return $this->query('DateTimeZone');
1468
+    }
1469
+
1470
+    /**
1471
+     * @return \OCP\IDateTimeFormatter
1472
+     */
1473
+    public function getDateTimeFormatter() {
1474
+        return $this->query('DateTimeFormatter');
1475
+    }
1476
+
1477
+    /**
1478
+     * @return \OCP\Files\Config\IMountProviderCollection
1479
+     */
1480
+    public function getMountProviderCollection() {
1481
+        return $this->query('MountConfigManager');
1482
+    }
1483
+
1484
+    /**
1485
+     * Get the IniWrapper
1486
+     *
1487
+     * @return IniGetWrapper
1488
+     */
1489
+    public function getIniWrapper() {
1490
+        return $this->query('IniWrapper');
1491
+    }
1492
+
1493
+    /**
1494
+     * @return \OCP\Command\IBus
1495
+     */
1496
+    public function getCommandBus() {
1497
+        return $this->query('AsyncCommandBus');
1498
+    }
1499
+
1500
+    /**
1501
+     * Get the trusted domain helper
1502
+     *
1503
+     * @return TrustedDomainHelper
1504
+     */
1505
+    public function getTrustedDomainHelper() {
1506
+        return $this->query('TrustedDomainHelper');
1507
+    }
1508
+
1509
+    /**
1510
+     * Get the locking provider
1511
+     *
1512
+     * @return \OCP\Lock\ILockingProvider
1513
+     * @since 8.1.0
1514
+     */
1515
+    public function getLockingProvider() {
1516
+        return $this->query('LockingProvider');
1517
+    }
1518
+
1519
+    /**
1520
+     * @return \OCP\Files\Mount\IMountManager
1521
+     **/
1522
+    function getMountManager() {
1523
+        return $this->query('MountManager');
1524
+    }
1525
+
1526
+    /** @return \OCP\Files\Config\IUserMountCache */
1527
+    function getUserMountCache() {
1528
+        return $this->query('UserMountCache');
1529
+    }
1530
+
1531
+    /**
1532
+     * Get the MimeTypeDetector
1533
+     *
1534
+     * @return \OCP\Files\IMimeTypeDetector
1535
+     */
1536
+    public function getMimeTypeDetector() {
1537
+        return $this->query('MimeTypeDetector');
1538
+    }
1539
+
1540
+    /**
1541
+     * Get the MimeTypeLoader
1542
+     *
1543
+     * @return \OCP\Files\IMimeTypeLoader
1544
+     */
1545
+    public function getMimeTypeLoader() {
1546
+        return $this->query('MimeTypeLoader');
1547
+    }
1548
+
1549
+    /**
1550
+     * Get the manager of all the capabilities
1551
+     *
1552
+     * @return \OC\CapabilitiesManager
1553
+     */
1554
+    public function getCapabilitiesManager() {
1555
+        return $this->query('CapabilitiesManager');
1556
+    }
1557
+
1558
+    /**
1559
+     * Get the EventDispatcher
1560
+     *
1561
+     * @return EventDispatcherInterface
1562
+     * @since 8.2.0
1563
+     */
1564
+    public function getEventDispatcher() {
1565
+        return $this->query('EventDispatcher');
1566
+    }
1567
+
1568
+    /**
1569
+     * Get the Notification Manager
1570
+     *
1571
+     * @return \OCP\Notification\IManager
1572
+     * @since 8.2.0
1573
+     */
1574
+    public function getNotificationManager() {
1575
+        return $this->query('NotificationManager');
1576
+    }
1577
+
1578
+    /**
1579
+     * @return \OCP\Comments\ICommentsManager
1580
+     */
1581
+    public function getCommentsManager() {
1582
+        return $this->query('CommentsManager');
1583
+    }
1584
+
1585
+    /**
1586
+     * @return \OCA\Theming\ThemingDefaults
1587
+     */
1588
+    public function getThemingDefaults() {
1589
+        return $this->query('ThemingDefaults');
1590
+    }
1591
+
1592
+    /**
1593
+     * @return \OC\IntegrityCheck\Checker
1594
+     */
1595
+    public function getIntegrityCodeChecker() {
1596
+        return $this->query('IntegrityCodeChecker');
1597
+    }
1598
+
1599
+    /**
1600
+     * @return \OC\Session\CryptoWrapper
1601
+     */
1602
+    public function getSessionCryptoWrapper() {
1603
+        return $this->query('CryptoWrapper');
1604
+    }
1605
+
1606
+    /**
1607
+     * @return CsrfTokenManager
1608
+     */
1609
+    public function getCsrfTokenManager() {
1610
+        return $this->query('CsrfTokenManager');
1611
+    }
1612
+
1613
+    /**
1614
+     * @return Throttler
1615
+     */
1616
+    public function getBruteForceThrottler() {
1617
+        return $this->query('Throttler');
1618
+    }
1619
+
1620
+    /**
1621
+     * @return IContentSecurityPolicyManager
1622
+     */
1623
+    public function getContentSecurityPolicyManager() {
1624
+        return $this->query('ContentSecurityPolicyManager');
1625
+    }
1626
+
1627
+    /**
1628
+     * @return ContentSecurityPolicyNonceManager
1629
+     */
1630
+    public function getContentSecurityPolicyNonceManager() {
1631
+        return $this->query('ContentSecurityPolicyNonceManager');
1632
+    }
1633
+
1634
+    /**
1635
+     * Not a public API as of 8.2, wait for 9.0
1636
+     *
1637
+     * @return \OCA\Files_External\Service\BackendService
1638
+     */
1639
+    public function getStoragesBackendService() {
1640
+        return $this->query('OCA\\Files_External\\Service\\BackendService');
1641
+    }
1642
+
1643
+    /**
1644
+     * Not a public API as of 8.2, wait for 9.0
1645
+     *
1646
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1647
+     */
1648
+    public function getGlobalStoragesService() {
1649
+        return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1650
+    }
1651
+
1652
+    /**
1653
+     * Not a public API as of 8.2, wait for 9.0
1654
+     *
1655
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1656
+     */
1657
+    public function getUserGlobalStoragesService() {
1658
+        return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1659
+    }
1660
+
1661
+    /**
1662
+     * Not a public API as of 8.2, wait for 9.0
1663
+     *
1664
+     * @return \OCA\Files_External\Service\UserStoragesService
1665
+     */
1666
+    public function getUserStoragesService() {
1667
+        return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1668
+    }
1669
+
1670
+    /**
1671
+     * @return \OCP\Share\IManager
1672
+     */
1673
+    public function getShareManager() {
1674
+        return $this->query('ShareManager');
1675
+    }
1676
+
1677
+    /**
1678
+     * Returns the LDAP Provider
1679
+     *
1680
+     * @return \OCP\LDAP\ILDAPProvider
1681
+     */
1682
+    public function getLDAPProvider() {
1683
+        return $this->query('LDAPProvider');
1684
+    }
1685
+
1686
+    /**
1687
+     * @return \OCP\Settings\IManager
1688
+     */
1689
+    public function getSettingsManager() {
1690
+        return $this->query('SettingsManager');
1691
+    }
1692
+
1693
+    /**
1694
+     * @return \OCP\Files\IAppData
1695
+     */
1696
+    public function getAppDataDir($app) {
1697
+        /** @var \OC\Files\AppData\Factory $factory */
1698
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
1699
+        return $factory->get($app);
1700
+    }
1701
+
1702
+    /**
1703
+     * @return \OCP\Lockdown\ILockdownManager
1704
+     */
1705
+    public function getLockdownManager() {
1706
+        return $this->query('LockdownManager');
1707
+    }
1708
+
1709
+    /**
1710
+     * @return \OCP\Federation\ICloudIdManager
1711
+     */
1712
+    public function getCloudIdManager() {
1713
+        return $this->query(ICloudIdManager::class);
1714
+    }
1715 1715
 }
Please login to merge, or discard this patch.
Spacing   +95 added lines, -95 removed lines patch added patch discarded remove patch
@@ -140,7 +140,7 @@  discard block
 block discarded – undo
140 140
 
141 141
 
142 142
 
143
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
143
+		$this->registerService(\OCP\IPreview::class, function(Server $c) {
144 144
 			return new PreviewManager(
145 145
 				$c->getConfig(),
146 146
 				$c->getRootFolder(),
@@ -151,13 +151,13 @@  discard block
 block discarded – undo
151 151
 		});
152 152
 		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
153 153
 
154
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
154
+		$this->registerService(\OC\Preview\Watcher::class, function(Server $c) {
155 155
 			return new \OC\Preview\Watcher(
156 156
 				$c->getAppDataDir('preview')
157 157
 			);
158 158
 		});
159 159
 
160
-		$this->registerService('EncryptionManager', function (Server $c) {
160
+		$this->registerService('EncryptionManager', function(Server $c) {
161 161
 			$view = new View();
162 162
 			$util = new Encryption\Util(
163 163
 				$view,
@@ -175,7 +175,7 @@  discard block
 block discarded – undo
175 175
 			);
176 176
 		});
177 177
 
178
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
178
+		$this->registerService('EncryptionFileHelper', function(Server $c) {
179 179
 			$util = new Encryption\Util(
180 180
 				new View(),
181 181
 				$c->getUserManager(),
@@ -185,7 +185,7 @@  discard block
 block discarded – undo
185 185
 			return new Encryption\File($util);
186 186
 		});
187 187
 
188
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
188
+		$this->registerService('EncryptionKeyStorage', function(Server $c) {
189 189
 			$view = new View();
190 190
 			$util = new Encryption\Util(
191 191
 				$view,
@@ -196,32 +196,32 @@  discard block
 block discarded – undo
196 196
 
197 197
 			return new Encryption\Keys\Storage($view, $util);
198 198
 		});
199
-		$this->registerService('TagMapper', function (Server $c) {
199
+		$this->registerService('TagMapper', function(Server $c) {
200 200
 			return new TagMapper($c->getDatabaseConnection());
201 201
 		});
202 202
 
203
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
203
+		$this->registerService(\OCP\ITagManager::class, function(Server $c) {
204 204
 			$tagMapper = $c->query('TagMapper');
205 205
 			return new TagManager($tagMapper, $c->getUserSession());
206 206
 		});
207 207
 		$this->registerAlias('TagManager', \OCP\ITagManager::class);
208 208
 
209
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
209
+		$this->registerService('SystemTagManagerFactory', function(Server $c) {
210 210
 			$config = $c->getConfig();
211 211
 			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
212 212
 			/** @var \OC\SystemTag\ManagerFactory $factory */
213 213
 			$factory = new $factoryClass($this);
214 214
 			return $factory;
215 215
 		});
216
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
216
+		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function(Server $c) {
217 217
 			return $c->query('SystemTagManagerFactory')->getManager();
218 218
 		});
219 219
 		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
220 220
 
221
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
221
+		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function(Server $c) {
222 222
 			return $c->query('SystemTagManagerFactory')->getObjectMapper();
223 223
 		});
224
-		$this->registerService('RootFolder', function (Server $c) {
224
+		$this->registerService('RootFolder', function(Server $c) {
225 225
 			$manager = \OC\Files\Filesystem::getMountManager(null);
226 226
 			$view = new View();
227 227
 			$root = new Root(
@@ -249,30 +249,30 @@  discard block
 block discarded – undo
249 249
 		});
250 250
 		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
251 251
 
252
-		$this->registerService(\OCP\IUserManager::class, function (Server $c) {
252
+		$this->registerService(\OCP\IUserManager::class, function(Server $c) {
253 253
 			$config = $c->getConfig();
254 254
 			return new \OC\User\Manager($config);
255 255
 		});
256 256
 		$this->registerAlias('UserManager', \OCP\IUserManager::class);
257 257
 
258
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
258
+		$this->registerService(\OCP\IGroupManager::class, function(Server $c) {
259 259
 			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
260
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
260
+			$groupManager->listen('\OC\Group', 'preCreate', function($gid) {
261 261
 				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
262 262
 			});
263
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
263
+			$groupManager->listen('\OC\Group', 'postCreate', function(\OC\Group\Group $gid) {
264 264
 				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
265 265
 			});
266
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
266
+			$groupManager->listen('\OC\Group', 'preDelete', function(\OC\Group\Group $group) {
267 267
 				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
268 268
 			});
269
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
269
+			$groupManager->listen('\OC\Group', 'postDelete', function(\OC\Group\Group $group) {
270 270
 				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
271 271
 			});
272
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
272
+			$groupManager->listen('\OC\Group', 'preAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
273 273
 				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
274 274
 			});
275
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
275
+			$groupManager->listen('\OC\Group', 'postAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
276 276
 				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
277 277
 				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
278 278
 				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
@@ -292,11 +292,11 @@  discard block
 block discarded – undo
292 292
 			return new Store($session, $logger, $tokenProvider);
293 293
 		});
294 294
 		$this->registerAlias(IStore::class, Store::class);
295
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
295
+		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function(Server $c) {
296 296
 			$dbConnection = $c->getDatabaseConnection();
297 297
 			return new Authentication\Token\DefaultTokenMapper($dbConnection);
298 298
 		});
299
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
299
+		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function(Server $c) {
300 300
 			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
301 301
 			$crypto = $c->getCrypto();
302 302
 			$config = $c->getConfig();
@@ -306,7 +306,7 @@  discard block
 block discarded – undo
306 306
 		});
307 307
 		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
308 308
 
309
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
309
+		$this->registerService(\OCP\IUserSession::class, function(Server $c) {
310 310
 			$manager = $c->getUserManager();
311 311
 			$session = new \OC\Session\Memory('');
312 312
 			$timeFactory = new TimeFactory();
@@ -319,40 +319,40 @@  discard block
 block discarded – undo
319 319
 			}
320 320
 
321 321
 			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
322
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
322
+			$userSession->listen('\OC\User', 'preCreateUser', function($uid, $password) {
323 323
 				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
324 324
 			});
325
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
325
+			$userSession->listen('\OC\User', 'postCreateUser', function($user, $password) {
326 326
 				/** @var $user \OC\User\User */
327 327
 				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
328 328
 			});
329
-			$userSession->listen('\OC\User', 'preDelete', function ($user) {
329
+			$userSession->listen('\OC\User', 'preDelete', function($user) {
330 330
 				/** @var $user \OC\User\User */
331 331
 				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
332 332
 			});
333
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
333
+			$userSession->listen('\OC\User', 'postDelete', function($user) {
334 334
 				/** @var $user \OC\User\User */
335 335
 				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
336 336
 			});
337
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
337
+			$userSession->listen('\OC\User', 'preSetPassword', function($user, $password, $recoveryPassword) {
338 338
 				/** @var $user \OC\User\User */
339 339
 				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
340 340
 			});
341
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
341
+			$userSession->listen('\OC\User', 'postSetPassword', function($user, $password, $recoveryPassword) {
342 342
 				/** @var $user \OC\User\User */
343 343
 				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
344 344
 			});
345
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
345
+			$userSession->listen('\OC\User', 'preLogin', function($uid, $password) {
346 346
 				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
347 347
 			});
348
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
348
+			$userSession->listen('\OC\User', 'postLogin', function($user, $password) {
349 349
 				/** @var $user \OC\User\User */
350 350
 				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
351 351
 			});
352
-			$userSession->listen('\OC\User', 'logout', function () {
352
+			$userSession->listen('\OC\User', 'logout', function() {
353 353
 				\OC_Hook::emit('OC_User', 'logout', array());
354 354
 			});
355
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value) {
355
+			$userSession->listen('\OC\User', 'changeUser', function($user, $feature, $value) {
356 356
 				/** @var $user \OC\User\User */
357 357
 				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value));
358 358
 			});
@@ -360,14 +360,14 @@  discard block
 block discarded – undo
360 360
 		});
361 361
 		$this->registerAlias('UserSession', \OCP\IUserSession::class);
362 362
 
363
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
363
+		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function(Server $c) {
364 364
 			return new \OC\Authentication\TwoFactorAuth\Manager($c->getAppManager(), $c->getSession(), $c->getConfig(), $c->getActivityManager(), $c->getLogger());
365 365
 		});
366 366
 
367 367
 		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
368 368
 		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
369 369
 
370
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
370
+		$this->registerService(\OC\AllConfig::class, function(Server $c) {
371 371
 			return new \OC\AllConfig(
372 372
 				$c->getSystemConfig()
373 373
 			);
@@ -375,17 +375,17 @@  discard block
 block discarded – undo
375 375
 		$this->registerAlias('AllConfig', \OC\AllConfig::class);
376 376
 		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
377 377
 
378
-		$this->registerService('SystemConfig', function ($c) use ($config) {
378
+		$this->registerService('SystemConfig', function($c) use ($config) {
379 379
 			return new \OC\SystemConfig($config);
380 380
 		});
381 381
 
382
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
382
+		$this->registerService(\OC\AppConfig::class, function(Server $c) {
383 383
 			return new \OC\AppConfig($c->getDatabaseConnection());
384 384
 		});
385 385
 		$this->registerAlias('AppConfig', \OC\AppConfig::class);
386 386
 		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
387 387
 
388
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
388
+		$this->registerService(\OCP\L10N\IFactory::class, function(Server $c) {
389 389
 			return new \OC\L10N\Factory(
390 390
 				$c->getConfig(),
391 391
 				$c->getRequest(),
@@ -395,7 +395,7 @@  discard block
 block discarded – undo
395 395
 		});
396 396
 		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
397 397
 
398
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
398
+		$this->registerService(\OCP\IURLGenerator::class, function(Server $c) {
399 399
 			$config = $c->getConfig();
400 400
 			$cacheFactory = $c->getMemCacheFactory();
401 401
 			return new \OC\URLGenerator(
@@ -405,10 +405,10 @@  discard block
 block discarded – undo
405 405
 		});
406 406
 		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
407 407
 
408
-		$this->registerService('AppHelper', function ($c) {
408
+		$this->registerService('AppHelper', function($c) {
409 409
 			return new \OC\AppHelper();
410 410
 		});
411
-		$this->registerService('AppFetcher', function ($c) {
411
+		$this->registerService('AppFetcher', function($c) {
412 412
 			return new AppFetcher(
413 413
 				$this->getAppDataDir('appstore'),
414 414
 				$this->getHTTPClientService(),
@@ -416,7 +416,7 @@  discard block
 block discarded – undo
416 416
 				$this->getConfig()
417 417
 			);
418 418
 		});
419
-		$this->registerService('CategoryFetcher', function ($c) {
419
+		$this->registerService('CategoryFetcher', function($c) {
420 420
 			return new CategoryFetcher(
421 421
 				$this->getAppDataDir('appstore'),
422 422
 				$this->getHTTPClientService(),
@@ -425,21 +425,21 @@  discard block
 block discarded – undo
425 425
 			);
426 426
 		});
427 427
 
428
-		$this->registerService(\OCP\ICache::class, function ($c) {
428
+		$this->registerService(\OCP\ICache::class, function($c) {
429 429
 			return new Cache\File();
430 430
 		});
431 431
 		$this->registerAlias('UserCache', \OCP\ICache::class);
432 432
 
433
-		$this->registerService(Factory::class, function (Server $c) {
433
+		$this->registerService(Factory::class, function(Server $c) {
434 434
 			$config = $c->getConfig();
435 435
 
436 436
 			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
437 437
 				$v = \OC_App::getAppVersions();
438
-				$v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php'));
438
+				$v['core'] = md5(file_get_contents(\OC::$SERVERROOT.'/version.php'));
439 439
 				$version = implode(',', $v);
440 440
 				$instanceId = \OC_Util::getInstanceId();
441 441
 				$path = \OC::$SERVERROOT;
442
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . \OC::$WEBROOT);
442
+				$prefix = md5($instanceId.'-'.$version.'-'.$path.'-'.\OC::$WEBROOT);
443 443
 				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
444 444
 					$config->getSystemValue('memcache.local', null),
445 445
 					$config->getSystemValue('memcache.distributed', null),
@@ -456,12 +456,12 @@  discard block
 block discarded – undo
456 456
 		$this->registerAlias('MemCacheFactory', Factory::class);
457 457
 		$this->registerAlias(ICacheFactory::class, Factory::class);
458 458
 
459
-		$this->registerService('RedisFactory', function (Server $c) {
459
+		$this->registerService('RedisFactory', function(Server $c) {
460 460
 			$systemConfig = $c->getSystemConfig();
461 461
 			return new RedisFactory($systemConfig);
462 462
 		});
463 463
 
464
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
464
+		$this->registerService(\OCP\Activity\IManager::class, function(Server $c) {
465 465
 			return new \OC\Activity\Manager(
466 466
 				$c->getRequest(),
467 467
 				$c->getUserSession(),
@@ -471,14 +471,14 @@  discard block
 block discarded – undo
471 471
 		});
472 472
 		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
473 473
 
474
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
474
+		$this->registerService(\OCP\Activity\IEventMerger::class, function(Server $c) {
475 475
 			return new \OC\Activity\EventMerger(
476 476
 				$c->getL10N('lib')
477 477
 			);
478 478
 		});
479 479
 		$this->registerAlias(IValidator::class, Validator::class);
480 480
 
481
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
481
+		$this->registerService(\OCP\IAvatarManager::class, function(Server $c) {
482 482
 			return new AvatarManager(
483 483
 				$c->getUserManager(),
484 484
 				$c->getAppDataDir('avatar'),
@@ -489,7 +489,7 @@  discard block
 block discarded – undo
489 489
 		});
490 490
 		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
491 491
 
492
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
492
+		$this->registerService(\OCP\ILogger::class, function(Server $c) {
493 493
 			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
494 494
 			$logger = Log::getLogClass($logType);
495 495
 			call_user_func(array($logger, 'init'));
@@ -498,7 +498,7 @@  discard block
 block discarded – undo
498 498
 		});
499 499
 		$this->registerAlias('Logger', \OCP\ILogger::class);
500 500
 
501
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
501
+		$this->registerService(\OCP\BackgroundJob\IJobList::class, function(Server $c) {
502 502
 			$config = $c->getConfig();
503 503
 			return new \OC\BackgroundJob\JobList(
504 504
 				$c->getDatabaseConnection(),
@@ -508,7 +508,7 @@  discard block
 block discarded – undo
508 508
 		});
509 509
 		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
510 510
 
511
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
511
+		$this->registerService(\OCP\Route\IRouter::class, function(Server $c) {
512 512
 			$cacheFactory = $c->getMemCacheFactory();
513 513
 			$logger = $c->getLogger();
514 514
 			if ($cacheFactory->isAvailable()) {
@@ -520,32 +520,32 @@  discard block
 block discarded – undo
520 520
 		});
521 521
 		$this->registerAlias('Router', \OCP\Route\IRouter::class);
522 522
 
523
-		$this->registerService(\OCP\ISearch::class, function ($c) {
523
+		$this->registerService(\OCP\ISearch::class, function($c) {
524 524
 			return new Search();
525 525
 		});
526 526
 		$this->registerAlias('Search', \OCP\ISearch::class);
527 527
 
528
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
528
+		$this->registerService(\OCP\Security\ISecureRandom::class, function($c) {
529 529
 			return new SecureRandom();
530 530
 		});
531 531
 		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
532 532
 
533
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
533
+		$this->registerService(\OCP\Security\ICrypto::class, function(Server $c) {
534 534
 			return new Crypto($c->getConfig(), $c->getSecureRandom());
535 535
 		});
536 536
 		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
537 537
 
538
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
538
+		$this->registerService(\OCP\Security\IHasher::class, function(Server $c) {
539 539
 			return new Hasher($c->getConfig());
540 540
 		});
541 541
 		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
542 542
 
543
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
543
+		$this->registerService(\OCP\Security\ICredentialsManager::class, function(Server $c) {
544 544
 			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
545 545
 		});
546 546
 		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
547 547
 
548
-		$this->registerService(IDBConnection::class, function (Server $c) {
548
+		$this->registerService(IDBConnection::class, function(Server $c) {
549 549
 			$systemConfig = $c->getSystemConfig();
550 550
 			$factory = new \OC\DB\ConnectionFactory($systemConfig);
551 551
 			$type = $systemConfig->getValue('dbtype', 'sqlite');
@@ -559,7 +559,7 @@  discard block
 block discarded – undo
559 559
 		});
560 560
 		$this->registerAlias('DatabaseConnection', IDBConnection::class);
561 561
 
562
-		$this->registerService('HTTPHelper', function (Server $c) {
562
+		$this->registerService('HTTPHelper', function(Server $c) {
563 563
 			$config = $c->getConfig();
564 564
 			return new HTTPHelper(
565 565
 				$config,
@@ -567,7 +567,7 @@  discard block
 block discarded – undo
567 567
 			);
568 568
 		});
569 569
 
570
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
570
+		$this->registerService(\OCP\Http\Client\IClientService::class, function(Server $c) {
571 571
 			$user = \OC_User::getUser();
572 572
 			$uid = $user ? $user : null;
573 573
 			return new ClientService(
@@ -577,7 +577,7 @@  discard block
 block discarded – undo
577 577
 		});
578 578
 		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
579 579
 
580
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
580
+		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function(Server $c) {
581 581
 			if ($c->getSystemConfig()->getValue('debug', false)) {
582 582
 				return new EventLogger();
583 583
 			} else {
@@ -586,7 +586,7 @@  discard block
 block discarded – undo
586 586
 		});
587 587
 		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
588 588
 
589
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
589
+		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function(Server $c) {
590 590
 			if ($c->getSystemConfig()->getValue('debug', false)) {
591 591
 				return new QueryLogger();
592 592
 			} else {
@@ -595,7 +595,7 @@  discard block
 block discarded – undo
595 595
 		});
596 596
 		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
597 597
 
598
-		$this->registerService(TempManager::class, function (Server $c) {
598
+		$this->registerService(TempManager::class, function(Server $c) {
599 599
 			return new TempManager(
600 600
 				$c->getLogger(),
601 601
 				$c->getConfig()
@@ -604,7 +604,7 @@  discard block
 block discarded – undo
604 604
 		$this->registerAlias('TempManager', TempManager::class);
605 605
 		$this->registerAlias(ITempManager::class, TempManager::class);
606 606
 
607
-		$this->registerService(AppManager::class, function (Server $c) {
607
+		$this->registerService(AppManager::class, function(Server $c) {
608 608
 			return new \OC\App\AppManager(
609 609
 				$c->getUserSession(),
610 610
 				$c->getAppConfig(),
@@ -616,7 +616,7 @@  discard block
 block discarded – undo
616 616
 		$this->registerAlias('AppManager', AppManager::class);
617 617
 		$this->registerAlias(IAppManager::class, AppManager::class);
618 618
 
619
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
619
+		$this->registerService(\OCP\IDateTimeZone::class, function(Server $c) {
620 620
 			return new DateTimeZone(
621 621
 				$c->getConfig(),
622 622
 				$c->getSession()
@@ -624,7 +624,7 @@  discard block
 block discarded – undo
624 624
 		});
625 625
 		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
626 626
 
627
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
627
+		$this->registerService(\OCP\IDateTimeFormatter::class, function(Server $c) {
628 628
 			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
629 629
 
630 630
 			return new DateTimeFormatter(
@@ -634,7 +634,7 @@  discard block
 block discarded – undo
634 634
 		});
635 635
 		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
636 636
 
637
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
637
+		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function(Server $c) {
638 638
 			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
639 639
 			$listener = new UserMountCacheListener($mountCache);
640 640
 			$listener->listen($c->getUserManager());
@@ -642,10 +642,10 @@  discard block
 block discarded – undo
642 642
 		});
643 643
 		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
644 644
 
645
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
645
+		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function(Server $c) {
646 646
 			$loader = \OC\Files\Filesystem::getLoader();
647 647
 			$mountCache = $c->query('UserMountCache');
648
-			$manager =  new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
648
+			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
649 649
 
650 650
 			// builtin providers
651 651
 
@@ -658,14 +658,14 @@  discard block
 block discarded – undo
658 658
 		});
659 659
 		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
660 660
 
661
-		$this->registerService('IniWrapper', function ($c) {
661
+		$this->registerService('IniWrapper', function($c) {
662 662
 			return new IniGetWrapper();
663 663
 		});
664
-		$this->registerService('AsyncCommandBus', function (Server $c) {
664
+		$this->registerService('AsyncCommandBus', function(Server $c) {
665 665
 			$jobList = $c->getJobList();
666 666
 			return new AsyncBus($jobList);
667 667
 		});
668
-		$this->registerService('TrustedDomainHelper', function ($c) {
668
+		$this->registerService('TrustedDomainHelper', function($c) {
669 669
 			return new TrustedDomainHelper($this->getConfig());
670 670
 		});
671 671
 		$this->registerService('Throttler', function(Server $c) {
@@ -676,10 +676,10 @@  discard block
 block discarded – undo
676 676
 				$c->getConfig()
677 677
 			);
678 678
 		});
679
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
679
+		$this->registerService('IntegrityCodeChecker', function(Server $c) {
680 680
 			// IConfig and IAppManager requires a working database. This code
681 681
 			// might however be called when ownCloud is not yet setup.
682
-			if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
682
+			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
683 683
 				$config = $c->getConfig();
684 684
 				$appManager = $c->getAppManager();
685 685
 			} else {
@@ -697,7 +697,7 @@  discard block
 block discarded – undo
697 697
 					$c->getTempManager()
698 698
 			);
699 699
 		});
700
-		$this->registerService(\OCP\IRequest::class, function ($c) {
700
+		$this->registerService(\OCP\IRequest::class, function($c) {
701 701
 			if (isset($this['urlParams'])) {
702 702
 				$urlParams = $this['urlParams'];
703 703
 			} else {
@@ -733,7 +733,7 @@  discard block
 block discarded – undo
733 733
 		});
734 734
 		$this->registerAlias('Request', \OCP\IRequest::class);
735 735
 
736
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
736
+		$this->registerService(\OCP\Mail\IMailer::class, function(Server $c) {
737 737
 			return new Mailer(
738 738
 				$c->getConfig(),
739 739
 				$c->getLogger(),
@@ -745,14 +745,14 @@  discard block
 block discarded – undo
745 745
 		$this->registerService('LDAPProvider', function(Server $c) {
746 746
 			$config = $c->getConfig();
747 747
 			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
748
-			if(is_null($factoryClass)) {
748
+			if (is_null($factoryClass)) {
749 749
 				throw new \Exception('ldapProviderFactory not set');
750 750
 			}
751 751
 			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
752 752
 			$factory = new $factoryClass($this);
753 753
 			return $factory->getLDAPProvider();
754 754
 		});
755
-		$this->registerService('LockingProvider', function (Server $c) {
755
+		$this->registerService('LockingProvider', function(Server $c) {
756 756
 			$ini = $c->getIniWrapper();
757 757
 			$config = $c->getConfig();
758 758
 			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
@@ -768,37 +768,37 @@  discard block
 block discarded – undo
768 768
 			return new NoopLockingProvider();
769 769
 		});
770 770
 
771
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
771
+		$this->registerService(\OCP\Files\Mount\IMountManager::class, function() {
772 772
 			return new \OC\Files\Mount\Manager();
773 773
 		});
774 774
 		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
775 775
 
776
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
776
+		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function(Server $c) {
777 777
 			return new \OC\Files\Type\Detection(
778 778
 				$c->getURLGenerator(),
779 779
 				\OC::$configDir,
780
-				\OC::$SERVERROOT . '/resources/config/'
780
+				\OC::$SERVERROOT.'/resources/config/'
781 781
 			);
782 782
 		});
783 783
 		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
784 784
 
785
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
785
+		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function(Server $c) {
786 786
 			return new \OC\Files\Type\Loader(
787 787
 				$c->getDatabaseConnection()
788 788
 			);
789 789
 		});
790 790
 		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
791 791
 
792
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
792
+		$this->registerService(\OCP\Notification\IManager::class, function(Server $c) {
793 793
 			return new Manager(
794 794
 				$c->query(IValidator::class)
795 795
 			);
796 796
 		});
797 797
 		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
798 798
 
799
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
799
+		$this->registerService(\OC\CapabilitiesManager::class, function(Server $c) {
800 800
 			$manager = new \OC\CapabilitiesManager($c->getLogger());
801
-			$manager->registerCapability(function () use ($c) {
801
+			$manager->registerCapability(function() use ($c) {
802 802
 				return new \OC\OCS\CoreCapabilities($c->getConfig());
803 803
 			});
804 804
 			return $manager;
@@ -840,13 +840,13 @@  discard block
 block discarded – undo
840 840
 			}
841 841
 			return new \OC_Defaults();
842 842
 		});
843
-		$this->registerService(EventDispatcher::class, function () {
843
+		$this->registerService(EventDispatcher::class, function() {
844 844
 			return new EventDispatcher();
845 845
 		});
846 846
 		$this->registerAlias('EventDispatcher', EventDispatcher::class);
847 847
 		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
848 848
 
849
-		$this->registerService('CryptoWrapper', function (Server $c) {
849
+		$this->registerService('CryptoWrapper', function(Server $c) {
850 850
 			// FIXME: Instantiiated here due to cyclic dependency
851 851
 			$request = new Request(
852 852
 				[
@@ -871,7 +871,7 @@  discard block
 block discarded – undo
871 871
 				$request
872 872
 			);
873 873
 		});
874
-		$this->registerService('CsrfTokenManager', function (Server $c) {
874
+		$this->registerService('CsrfTokenManager', function(Server $c) {
875 875
 			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
876 876
 
877 877
 			return new CsrfTokenManager(
@@ -879,10 +879,10 @@  discard block
 block discarded – undo
879 879
 				$c->query(SessionStorage::class)
880 880
 			);
881 881
 		});
882
-		$this->registerService(SessionStorage::class, function (Server $c) {
882
+		$this->registerService(SessionStorage::class, function(Server $c) {
883 883
 			return new SessionStorage($c->getSession());
884 884
 		});
885
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
885
+		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function(Server $c) {
886 886
 			return new ContentSecurityPolicyManager();
887 887
 		});
888 888
 		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
@@ -933,25 +933,25 @@  discard block
 block discarded – undo
933 933
 			);
934 934
 			return $manager;
935 935
 		});
936
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
936
+		$this->registerService(\OC\Files\AppData\Factory::class, function(Server $c) {
937 937
 			return new \OC\Files\AppData\Factory(
938 938
 				$c->getRootFolder(),
939 939
 				$c->getSystemConfig()
940 940
 			);
941 941
 		});
942 942
 
943
-		$this->registerService('LockdownManager', function (Server $c) {
943
+		$this->registerService('LockdownManager', function(Server $c) {
944 944
 			return new LockdownManager(function() use ($c) {
945 945
 				return $c->getSession();
946 946
 			});
947 947
 		});
948 948
 
949
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
949
+		$this->registerService(ICloudIdManager::class, function(Server $c) {
950 950
 			return new CloudIdManager();
951 951
 		});
952 952
 
953 953
 		/* To trick DI since we don't extend the DIContainer here */
954
-		$this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
954
+		$this->registerService(CleanPreviewsBackgroundJob::class, function(Server $c) {
955 955
 			return new CleanPreviewsBackgroundJob(
956 956
 				$c->getRootFolder(),
957 957
 				$c->getLogger(),
@@ -1105,7 +1105,7 @@  discard block
 block discarded – undo
1105 1105
 	 * @deprecated since 9.2.0 use IAppData
1106 1106
 	 */
1107 1107
 	public function getAppFolder() {
1108
-		$dir = '/' . \OC_App::getCurrentApp();
1108
+		$dir = '/'.\OC_App::getCurrentApp();
1109 1109
 		$root = $this->getRootFolder();
1110 1110
 		if (!$root->nodeExists($dir)) {
1111 1111
 			$folder = $root->newFolder($dir);
Please login to merge, or discard this patch.
lib/public/AppFramework/Http/Response.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -226,7 +226,7 @@  discard block
 block discarded – undo
226 226
 
227 227
 	/**
228 228
 	 * By default renders no output
229
-	 * @return null
229
+	 * @return string
230 230
 	 * @since 6.0.0
231 231
 	 */
232 232
 	public function render() {
@@ -259,7 +259,7 @@  discard block
 block discarded – undo
259 259
 
260 260
 	/**
261 261
 	 * Get the currently used Content-Security-Policy
262
-	 * @return EmptyContentSecurityPolicy|null Used Content-Security-Policy or null if
262
+	 * @return ContentSecurityPolicy|null Used Content-Security-Policy or null if
263 263
 	 *                                    none specified.
264 264
 	 * @since 8.1.0
265 265
 	 */
Please login to merge, or discard this patch.
Indentation   +279 added lines, -279 removed lines patch added patch discarded remove patch
@@ -42,285 +42,285 @@
 block discarded – undo
42 42
  */
43 43
 class Response {
44 44
 
45
-	/**
46
-	 * Headers - defaults to ['Cache-Control' => 'no-cache, no-store, must-revalidate']
47
-	 * @var array
48
-	 */
49
-	private $headers = array(
50
-		'Cache-Control' => 'no-cache, no-store, must-revalidate'
51
-	);
52
-
53
-
54
-	/**
55
-	 * Cookies that will be need to be constructed as header
56
-	 * @var array
57
-	 */
58
-	private $cookies = array();
59
-
60
-
61
-	/**
62
-	 * HTTP status code - defaults to STATUS OK
63
-	 * @var int
64
-	 */
65
-	private $status = Http::STATUS_OK;
66
-
67
-
68
-	/**
69
-	 * Last modified date
70
-	 * @var \DateTime
71
-	 */
72
-	private $lastModified;
73
-
74
-
75
-	/**
76
-	 * ETag
77
-	 * @var string
78
-	 */
79
-	private $ETag;
80
-
81
-	/** @var ContentSecurityPolicy|null Used Content-Security-Policy */
82
-	private $contentSecurityPolicy = null;
83
-
84
-
85
-	/**
86
-	 * Caches the response
87
-	 * @param int $cacheSeconds the amount of seconds that should be cached
88
-	 * if 0 then caching will be disabled
89
-	 * @return $this
90
-	 * @since 6.0.0 - return value was added in 7.0.0
91
-	 */
92
-	public function cacheFor($cacheSeconds) {
93
-
94
-		if($cacheSeconds > 0) {
95
-			$this->addHeader('Cache-Control', 'max-age=' . $cacheSeconds . ', must-revalidate');
96
-		} else {
97
-			$this->addHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
98
-		}
99
-
100
-		return $this;
101
-	}
102
-
103
-	/**
104
-	 * Adds a new cookie to the response
105
-	 * @param string $name The name of the cookie
106
-	 * @param string $value The value of the cookie
107
-	 * @param \DateTime|null $expireDate Date on that the cookie should expire, if set
108
-	 * 									to null cookie will be considered as session
109
-	 * 									cookie.
110
-	 * @return $this
111
-	 * @since 8.0.0
112
-	 */
113
-	public function addCookie($name, $value, \DateTime $expireDate = null) {
114
-		$this->cookies[$name] = array('value' => $value, 'expireDate' => $expireDate);
115
-		return $this;
116
-	}
117
-
118
-
119
-	/**
120
-	 * Set the specified cookies
121
-	 * @param array $cookies array('foo' => array('value' => 'bar', 'expire' => null))
122
-	 * @return $this
123
-	 * @since 8.0.0
124
-	 */
125
-	public function setCookies(array $cookies) {
126
-		$this->cookies = $cookies;
127
-		return $this;
128
-	}
129
-
130
-
131
-	/**
132
-	 * Invalidates the specified cookie
133
-	 * @param string $name
134
-	 * @return $this
135
-	 * @since 8.0.0
136
-	 */
137
-	public function invalidateCookie($name) {
138
-		$this->addCookie($name, 'expired', new \DateTime('1971-01-01 00:00'));
139
-		return $this;
140
-	}
141
-
142
-	/**
143
-	 * Invalidates the specified cookies
144
-	 * @param array $cookieNames array('foo', 'bar')
145
-	 * @return $this
146
-	 * @since 8.0.0
147
-	 */
148
-	public function invalidateCookies(array $cookieNames) {
149
-		foreach($cookieNames as $cookieName) {
150
-			$this->invalidateCookie($cookieName);
151
-		}
152
-		return $this;
153
-	}
154
-
155
-	/**
156
-	 * Returns the cookies
157
-	 * @return array
158
-	 * @since 8.0.0
159
-	 */
160
-	public function getCookies() {
161
-		return $this->cookies;
162
-	}
163
-
164
-	/**
165
-	 * Adds a new header to the response that will be called before the render
166
-	 * function
167
-	 * @param string $name The name of the HTTP header
168
-	 * @param string $value The value, null will delete it
169
-	 * @return $this
170
-	 * @since 6.0.0 - return value was added in 7.0.0
171
-	 */
172
-	public function addHeader($name, $value) {
173
-		$name = trim($name);  // always remove leading and trailing whitespace
174
-		                      // to be able to reliably check for security
175
-		                      // headers
176
-
177
-		if(is_null($value)) {
178
-			unset($this->headers[$name]);
179
-		} else {
180
-			$this->headers[$name] = $value;
181
-		}
182
-
183
-		return $this;
184
-	}
185
-
186
-
187
-	/**
188
-	 * Set the headers
189
-	 * @param array $headers value header pairs
190
-	 * @return $this
191
-	 * @since 8.0.0
192
-	 */
193
-	public function setHeaders(array $headers) {
194
-		$this->headers = $headers;
195
-
196
-		return $this;
197
-	}
198
-
199
-
200
-	/**
201
-	 * Returns the set headers
202
-	 * @return array the headers
203
-	 * @since 6.0.0
204
-	 */
205
-	public function getHeaders() {
206
-		$mergeWith = [];
207
-
208
-		if($this->lastModified) {
209
-			$mergeWith['Last-Modified'] =
210
-				$this->lastModified->format(\DateTime::RFC2822);
211
-		}
212
-
213
-		// Build Content-Security-Policy and use default if none has been specified
214
-		if(is_null($this->contentSecurityPolicy)) {
215
-			$this->setContentSecurityPolicy(new ContentSecurityPolicy());
216
-		}
217
-		$this->headers['Content-Security-Policy'] = $this->contentSecurityPolicy->buildPolicy();
218
-
219
-		if($this->ETag) {
220
-			$mergeWith['ETag'] = '"' . $this->ETag . '"';
221
-		}
222
-
223
-		return array_merge($mergeWith, $this->headers);
224
-	}
225
-
226
-
227
-	/**
228
-	 * By default renders no output
229
-	 * @return null
230
-	 * @since 6.0.0
231
-	 */
232
-	public function render() {
233
-		return null;
234
-	}
235
-
236
-
237
-	/**
238
-	 * Set response status
239
-	 * @param int $status a HTTP status code, see also the STATUS constants
240
-	 * @return Response Reference to this object
241
-	 * @since 6.0.0 - return value was added in 7.0.0
242
-	 */
243
-	public function setStatus($status) {
244
-		$this->status = $status;
245
-
246
-		return $this;
247
-	}
248
-
249
-	/**
250
-	 * Set a Content-Security-Policy
251
-	 * @param EmptyContentSecurityPolicy $csp Policy to set for the response object
252
-	 * @return $this
253
-	 * @since 8.1.0
254
-	 */
255
-	public function setContentSecurityPolicy(EmptyContentSecurityPolicy $csp) {
256
-		$this->contentSecurityPolicy = $csp;
257
-		return $this;
258
-	}
259
-
260
-	/**
261
-	 * Get the currently used Content-Security-Policy
262
-	 * @return EmptyContentSecurityPolicy|null Used Content-Security-Policy or null if
263
-	 *                                    none specified.
264
-	 * @since 8.1.0
265
-	 */
266
-	public function getContentSecurityPolicy() {
267
-		return $this->contentSecurityPolicy;
268
-	}
269
-
270
-
271
-	/**
272
-	 * Get response status
273
-	 * @since 6.0.0
274
-	 */
275
-	public function getStatus() {
276
-		return $this->status;
277
-	}
278
-
279
-
280
-	/**
281
-	 * Get the ETag
282
-	 * @return string the etag
283
-	 * @since 6.0.0
284
-	 */
285
-	public function getETag() {
286
-		return $this->ETag;
287
-	}
288
-
289
-
290
-	/**
291
-	 * Get "last modified" date
292
-	 * @return \DateTime RFC2822 formatted last modified date
293
-	 * @since 6.0.0
294
-	 */
295
-	public function getLastModified() {
296
-		return $this->lastModified;
297
-	}
298
-
299
-
300
-	/**
301
-	 * Set the ETag
302
-	 * @param string $ETag
303
-	 * @return Response Reference to this object
304
-	 * @since 6.0.0 - return value was added in 7.0.0
305
-	 */
306
-	public function setETag($ETag) {
307
-		$this->ETag = $ETag;
308
-
309
-		return $this;
310
-	}
311
-
312
-
313
-	/**
314
-	 * Set "last modified" date
315
-	 * @param \DateTime $lastModified
316
-	 * @return Response Reference to this object
317
-	 * @since 6.0.0 - return value was added in 7.0.0
318
-	 */
319
-	public function setLastModified($lastModified) {
320
-		$this->lastModified = $lastModified;
321
-
322
-		return $this;
323
-	}
45
+    /**
46
+     * Headers - defaults to ['Cache-Control' => 'no-cache, no-store, must-revalidate']
47
+     * @var array
48
+     */
49
+    private $headers = array(
50
+        'Cache-Control' => 'no-cache, no-store, must-revalidate'
51
+    );
52
+
53
+
54
+    /**
55
+     * Cookies that will be need to be constructed as header
56
+     * @var array
57
+     */
58
+    private $cookies = array();
59
+
60
+
61
+    /**
62
+     * HTTP status code - defaults to STATUS OK
63
+     * @var int
64
+     */
65
+    private $status = Http::STATUS_OK;
66
+
67
+
68
+    /**
69
+     * Last modified date
70
+     * @var \DateTime
71
+     */
72
+    private $lastModified;
73
+
74
+
75
+    /**
76
+     * ETag
77
+     * @var string
78
+     */
79
+    private $ETag;
80
+
81
+    /** @var ContentSecurityPolicy|null Used Content-Security-Policy */
82
+    private $contentSecurityPolicy = null;
83
+
84
+
85
+    /**
86
+     * Caches the response
87
+     * @param int $cacheSeconds the amount of seconds that should be cached
88
+     * if 0 then caching will be disabled
89
+     * @return $this
90
+     * @since 6.0.0 - return value was added in 7.0.0
91
+     */
92
+    public function cacheFor($cacheSeconds) {
93
+
94
+        if($cacheSeconds > 0) {
95
+            $this->addHeader('Cache-Control', 'max-age=' . $cacheSeconds . ', must-revalidate');
96
+        } else {
97
+            $this->addHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
98
+        }
99
+
100
+        return $this;
101
+    }
102
+
103
+    /**
104
+     * Adds a new cookie to the response
105
+     * @param string $name The name of the cookie
106
+     * @param string $value The value of the cookie
107
+     * @param \DateTime|null $expireDate Date on that the cookie should expire, if set
108
+     * 									to null cookie will be considered as session
109
+     * 									cookie.
110
+     * @return $this
111
+     * @since 8.0.0
112
+     */
113
+    public function addCookie($name, $value, \DateTime $expireDate = null) {
114
+        $this->cookies[$name] = array('value' => $value, 'expireDate' => $expireDate);
115
+        return $this;
116
+    }
117
+
118
+
119
+    /**
120
+     * Set the specified cookies
121
+     * @param array $cookies array('foo' => array('value' => 'bar', 'expire' => null))
122
+     * @return $this
123
+     * @since 8.0.0
124
+     */
125
+    public function setCookies(array $cookies) {
126
+        $this->cookies = $cookies;
127
+        return $this;
128
+    }
129
+
130
+
131
+    /**
132
+     * Invalidates the specified cookie
133
+     * @param string $name
134
+     * @return $this
135
+     * @since 8.0.0
136
+     */
137
+    public function invalidateCookie($name) {
138
+        $this->addCookie($name, 'expired', new \DateTime('1971-01-01 00:00'));
139
+        return $this;
140
+    }
141
+
142
+    /**
143
+     * Invalidates the specified cookies
144
+     * @param array $cookieNames array('foo', 'bar')
145
+     * @return $this
146
+     * @since 8.0.0
147
+     */
148
+    public function invalidateCookies(array $cookieNames) {
149
+        foreach($cookieNames as $cookieName) {
150
+            $this->invalidateCookie($cookieName);
151
+        }
152
+        return $this;
153
+    }
154
+
155
+    /**
156
+     * Returns the cookies
157
+     * @return array
158
+     * @since 8.0.0
159
+     */
160
+    public function getCookies() {
161
+        return $this->cookies;
162
+    }
163
+
164
+    /**
165
+     * Adds a new header to the response that will be called before the render
166
+     * function
167
+     * @param string $name The name of the HTTP header
168
+     * @param string $value The value, null will delete it
169
+     * @return $this
170
+     * @since 6.0.0 - return value was added in 7.0.0
171
+     */
172
+    public function addHeader($name, $value) {
173
+        $name = trim($name);  // always remove leading and trailing whitespace
174
+                                // to be able to reliably check for security
175
+                                // headers
176
+
177
+        if(is_null($value)) {
178
+            unset($this->headers[$name]);
179
+        } else {
180
+            $this->headers[$name] = $value;
181
+        }
182
+
183
+        return $this;
184
+    }
185
+
186
+
187
+    /**
188
+     * Set the headers
189
+     * @param array $headers value header pairs
190
+     * @return $this
191
+     * @since 8.0.0
192
+     */
193
+    public function setHeaders(array $headers) {
194
+        $this->headers = $headers;
195
+
196
+        return $this;
197
+    }
198
+
199
+
200
+    /**
201
+     * Returns the set headers
202
+     * @return array the headers
203
+     * @since 6.0.0
204
+     */
205
+    public function getHeaders() {
206
+        $mergeWith = [];
207
+
208
+        if($this->lastModified) {
209
+            $mergeWith['Last-Modified'] =
210
+                $this->lastModified->format(\DateTime::RFC2822);
211
+        }
212
+
213
+        // Build Content-Security-Policy and use default if none has been specified
214
+        if(is_null($this->contentSecurityPolicy)) {
215
+            $this->setContentSecurityPolicy(new ContentSecurityPolicy());
216
+        }
217
+        $this->headers['Content-Security-Policy'] = $this->contentSecurityPolicy->buildPolicy();
218
+
219
+        if($this->ETag) {
220
+            $mergeWith['ETag'] = '"' . $this->ETag . '"';
221
+        }
222
+
223
+        return array_merge($mergeWith, $this->headers);
224
+    }
225
+
226
+
227
+    /**
228
+     * By default renders no output
229
+     * @return null
230
+     * @since 6.0.0
231
+     */
232
+    public function render() {
233
+        return null;
234
+    }
235
+
236
+
237
+    /**
238
+     * Set response status
239
+     * @param int $status a HTTP status code, see also the STATUS constants
240
+     * @return Response Reference to this object
241
+     * @since 6.0.0 - return value was added in 7.0.0
242
+     */
243
+    public function setStatus($status) {
244
+        $this->status = $status;
245
+
246
+        return $this;
247
+    }
248
+
249
+    /**
250
+     * Set a Content-Security-Policy
251
+     * @param EmptyContentSecurityPolicy $csp Policy to set for the response object
252
+     * @return $this
253
+     * @since 8.1.0
254
+     */
255
+    public function setContentSecurityPolicy(EmptyContentSecurityPolicy $csp) {
256
+        $this->contentSecurityPolicy = $csp;
257
+        return $this;
258
+    }
259
+
260
+    /**
261
+     * Get the currently used Content-Security-Policy
262
+     * @return EmptyContentSecurityPolicy|null Used Content-Security-Policy or null if
263
+     *                                    none specified.
264
+     * @since 8.1.0
265
+     */
266
+    public function getContentSecurityPolicy() {
267
+        return $this->contentSecurityPolicy;
268
+    }
269
+
270
+
271
+    /**
272
+     * Get response status
273
+     * @since 6.0.0
274
+     */
275
+    public function getStatus() {
276
+        return $this->status;
277
+    }
278
+
279
+
280
+    /**
281
+     * Get the ETag
282
+     * @return string the etag
283
+     * @since 6.0.0
284
+     */
285
+    public function getETag() {
286
+        return $this->ETag;
287
+    }
288
+
289
+
290
+    /**
291
+     * Get "last modified" date
292
+     * @return \DateTime RFC2822 formatted last modified date
293
+     * @since 6.0.0
294
+     */
295
+    public function getLastModified() {
296
+        return $this->lastModified;
297
+    }
298
+
299
+
300
+    /**
301
+     * Set the ETag
302
+     * @param string $ETag
303
+     * @return Response Reference to this object
304
+     * @since 6.0.0 - return value was added in 7.0.0
305
+     */
306
+    public function setETag($ETag) {
307
+        $this->ETag = $ETag;
308
+
309
+        return $this;
310
+    }
311
+
312
+
313
+    /**
314
+     * Set "last modified" date
315
+     * @param \DateTime $lastModified
316
+     * @return Response Reference to this object
317
+     * @since 6.0.0 - return value was added in 7.0.0
318
+     */
319
+    public function setLastModified($lastModified) {
320
+        $this->lastModified = $lastModified;
321
+
322
+        return $this;
323
+    }
324 324
 
325 325
 
326 326
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -91,8 +91,8 @@  discard block
 block discarded – undo
91 91
 	 */
92 92
 	public function cacheFor($cacheSeconds) {
93 93
 
94
-		if($cacheSeconds > 0) {
95
-			$this->addHeader('Cache-Control', 'max-age=' . $cacheSeconds . ', must-revalidate');
94
+		if ($cacheSeconds > 0) {
95
+			$this->addHeader('Cache-Control', 'max-age='.$cacheSeconds.', must-revalidate');
96 96
 		} else {
97 97
 			$this->addHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
98 98
 		}
@@ -146,7 +146,7 @@  discard block
 block discarded – undo
146 146
 	 * @since 8.0.0
147 147
 	 */
148 148
 	public function invalidateCookies(array $cookieNames) {
149
-		foreach($cookieNames as $cookieName) {
149
+		foreach ($cookieNames as $cookieName) {
150 150
 			$this->invalidateCookie($cookieName);
151 151
 		}
152 152
 		return $this;
@@ -170,11 +170,11 @@  discard block
 block discarded – undo
170 170
 	 * @since 6.0.0 - return value was added in 7.0.0
171 171
 	 */
172 172
 	public function addHeader($name, $value) {
173
-		$name = trim($name);  // always remove leading and trailing whitespace
173
+		$name = trim($name); // always remove leading and trailing whitespace
174 174
 		                      // to be able to reliably check for security
175 175
 		                      // headers
176 176
 
177
-		if(is_null($value)) {
177
+		if (is_null($value)) {
178 178
 			unset($this->headers[$name]);
179 179
 		} else {
180 180
 			$this->headers[$name] = $value;
@@ -205,19 +205,19 @@  discard block
 block discarded – undo
205 205
 	public function getHeaders() {
206 206
 		$mergeWith = [];
207 207
 
208
-		if($this->lastModified) {
208
+		if ($this->lastModified) {
209 209
 			$mergeWith['Last-Modified'] =
210 210
 				$this->lastModified->format(\DateTime::RFC2822);
211 211
 		}
212 212
 
213 213
 		// Build Content-Security-Policy and use default if none has been specified
214
-		if(is_null($this->contentSecurityPolicy)) {
214
+		if (is_null($this->contentSecurityPolicy)) {
215 215
 			$this->setContentSecurityPolicy(new ContentSecurityPolicy());
216 216
 		}
217 217
 		$this->headers['Content-Security-Policy'] = $this->contentSecurityPolicy->buildPolicy();
218 218
 
219
-		if($this->ETag) {
220
-			$mergeWith['ETag'] = '"' . $this->ETag . '"';
219
+		if ($this->ETag) {
220
+			$mergeWith['ETag'] = '"'.$this->ETag.'"';
221 221
 		}
222 222
 
223 223
 		return array_merge($mergeWith, $this->headers);
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Publishing/PublishPlugin.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -134,7 +134,7 @@
 block discarded – undo
134 134
 	 * @param RequestInterface $request
135 135
 	 * @param ResponseInterface $response
136 136
 	 *
137
-	 * @return void|bool
137
+	 * @return null|false
138 138
 	 */
139 139
 	public function httpPost(RequestInterface $request, ResponseInterface $response) {
140 140
 		$path = $request->getPath();
Please login to merge, or discard this patch.
Indentation   +189 added lines, -189 removed lines patch added patch discarded remove patch
@@ -34,194 +34,194 @@
 block discarded – undo
34 34
 use OCP\IConfig;
35 35
 
36 36
 class PublishPlugin extends ServerPlugin {
37
-	const NS_CALENDARSERVER = 'http://calendarserver.org/ns/';
38
-
39
-	/**
40
-	 * Reference to SabreDAV server object.
41
-	 *
42
-	 * @var \Sabre\DAV\Server
43
-	 */
44
-	protected $server;
45
-
46
-	/**
47
-	 * Config instance to get instance secret.
48
-	 *
49
-	 * @var IConfig
50
-	 */
51
-	protected $config;
52
-
53
-	/**
54
-	 * URL Generator for absolute URLs.
55
-	 *
56
-	 * @var IURLGenerator
57
-	 */
58
-	protected $urlGenerator;
59
-
60
-	/**
61
-	 * PublishPlugin constructor.
62
-	 *
63
-	 * @param IConfig $config
64
-	 * @param IURLGenerator $urlGenerator
65
-	 */
66
-	public function __construct(IConfig $config, IURLGenerator $urlGenerator) {
67
-		$this->config = $config;
68
-		$this->urlGenerator = $urlGenerator;
69
-	}
70
-
71
-	/**
72
-	 * This method should return a list of server-features.
73
-	 *
74
-	 * This is for example 'versioning' and is added to the DAV: header
75
-	 * in an OPTIONS response.
76
-	 *
77
-	 * @return string[]
78
-	 */
79
-	public function getFeatures() {
80
-		// May have to be changed to be detected
81
-		return ['oc-calendar-publishing', 'calendarserver-sharing'];
82
-	}
83
-
84
-	/**
85
-	 * Returns a plugin name.
86
-	 *
87
-	 * Using this name other plugins will be able to access other plugins
88
-	 * using Sabre\DAV\Server::getPlugin
89
-	 *
90
-	 * @return string
91
-	 */
92
-	public function getPluginName()	{
93
-		return 'oc-calendar-publishing';
94
-	}
95
-
96
-	/**
97
-	 * This initializes the plugin.
98
-	 *
99
-	 * This function is called by Sabre\DAV\Server, after
100
-	 * addPlugin is called.
101
-	 *
102
-	 * This method should set up the required event subscriptions.
103
-	 *
104
-	 * @param Server $server
105
-	 */
106
-	public function initialize(Server $server) {
107
-		$this->server = $server;
108
-
109
-		$this->server->on('method:POST', [$this, 'httpPost']);
110
-		$this->server->on('propFind',    [$this, 'propFind']);
111
-	}
112
-
113
-	public function propFind(PropFind $propFind, INode $node) {
114
-		if ($node instanceof Calendar) {
115
-			$propFind->handle('{'.self::NS_CALENDARSERVER.'}publish-url', function () use ($node) {
116
-				if ($node->getPublishStatus()) {
117
-					// We return the publish-url only if the calendar is published.
118
-					$token = $node->getPublishStatus();
119
-					$publishUrl = $this->urlGenerator->getAbsoluteURL($this->server->getBaseUri().'public-calendars/').$token;
120
-
121
-					return new Publisher($publishUrl, true);
122
-				}
123
-			});
124
-
125
-			$propFind->handle('{'.self::NS_CALENDARSERVER.'}allowed-sharing-modes', function() use ($node) {
126
-				return new AllowedSharingModes(!$node->isSubscription(), !$node->isSubscription());
127
-			});
128
-		}
129
-	}
130
-
131
-	/**
132
-	 * We intercept this to handle POST requests on calendars.
133
-	 *
134
-	 * @param RequestInterface $request
135
-	 * @param ResponseInterface $response
136
-	 *
137
-	 * @return void|bool
138
-	 */
139
-	public function httpPost(RequestInterface $request, ResponseInterface $response) {
140
-		$path = $request->getPath();
141
-
142
-		// Only handling xml
143
-		$contentType = $request->getHeader('Content-Type');
144
-		if (strpos($contentType, 'application/xml') === false && strpos($contentType, 'text/xml') === false) {
145
-			return;
146
-		}
147
-
148
-		// Making sure the node exists
149
-		try {
150
-			$node = $this->server->tree->getNodeForPath($path);
151
-		} catch (NotFound $e) {
152
-			return;
153
-		}
154
-
155
-		$requestBody = $request->getBodyAsString();
156
-
157
-		// If this request handler could not deal with this POST request, it
158
-		// will return 'null' and other plugins get a chance to handle the
159
-		// request.
160
-		//
161
-		// However, we already requested the full body. This is a problem,
162
-		// because a body can only be read once. This is why we preemptively
163
-		// re-populated the request body with the existing data.
164
-		$request->setBody($requestBody);
165
-
166
-		$this->server->xml->parse($requestBody, $request->getUrl(), $documentType);
167
-
168
-		switch ($documentType) {
169
-
170
-			case '{'.self::NS_CALENDARSERVER.'}publish-calendar' :
171
-
172
-			// We can only deal with IShareableCalendar objects
173
-			if (!$node instanceof Calendar) {
174
-				return;
175
-			}
176
-			$this->server->transactionType = 'post-publish-calendar';
177
-
178
-			// Getting ACL info
179
-			$acl = $this->server->getPlugin('acl');
180
-
181
-			// If there's no ACL support, we allow everything
182
-			if ($acl) {
183
-				$acl->checkPrivileges($path, '{DAV:}write');
184
-			}
185
-
186
-			$node->setPublishStatus(true);
187
-
188
-			// iCloud sends back the 202, so we will too.
189
-			$response->setStatus(202);
190
-
191
-			// Adding this because sending a response body may cause issues,
192
-			// and I wanted some type of indicator the response was handled.
193
-			$response->setHeader('X-Sabre-Status', 'everything-went-well');
194
-
195
-			// Breaking the event chain
196
-			return false;
197
-
198
-			case '{'.self::NS_CALENDARSERVER.'}unpublish-calendar' :
199
-
200
-			// We can only deal with IShareableCalendar objects
201
-			if (!$node instanceof Calendar) {
202
-				return;
203
-			}
204
-			$this->server->transactionType = 'post-unpublish-calendar';
205
-
206
-			// Getting ACL info
207
-			$acl = $this->server->getPlugin('acl');
208
-
209
-			// If there's no ACL support, we allow everything
210
-			if ($acl) {
211
-				$acl->checkPrivileges($path, '{DAV:}write');
212
-			}
213
-
214
-			$node->setPublishStatus(false);
215
-
216
-			$response->setStatus(200);
217
-
218
-			// Adding this because sending a response body may cause issues,
219
-			// and I wanted some type of indicator the response was handled.
220
-			$response->setHeader('X-Sabre-Status', 'everything-went-well');
221
-
222
-			// Breaking the event chain
223
-			return false;
37
+    const NS_CALENDARSERVER = 'http://calendarserver.org/ns/';
38
+
39
+    /**
40
+     * Reference to SabreDAV server object.
41
+     *
42
+     * @var \Sabre\DAV\Server
43
+     */
44
+    protected $server;
45
+
46
+    /**
47
+     * Config instance to get instance secret.
48
+     *
49
+     * @var IConfig
50
+     */
51
+    protected $config;
52
+
53
+    /**
54
+     * URL Generator for absolute URLs.
55
+     *
56
+     * @var IURLGenerator
57
+     */
58
+    protected $urlGenerator;
59
+
60
+    /**
61
+     * PublishPlugin constructor.
62
+     *
63
+     * @param IConfig $config
64
+     * @param IURLGenerator $urlGenerator
65
+     */
66
+    public function __construct(IConfig $config, IURLGenerator $urlGenerator) {
67
+        $this->config = $config;
68
+        $this->urlGenerator = $urlGenerator;
69
+    }
70
+
71
+    /**
72
+     * This method should return a list of server-features.
73
+     *
74
+     * This is for example 'versioning' and is added to the DAV: header
75
+     * in an OPTIONS response.
76
+     *
77
+     * @return string[]
78
+     */
79
+    public function getFeatures() {
80
+        // May have to be changed to be detected
81
+        return ['oc-calendar-publishing', 'calendarserver-sharing'];
82
+    }
83
+
84
+    /**
85
+     * Returns a plugin name.
86
+     *
87
+     * Using this name other plugins will be able to access other plugins
88
+     * using Sabre\DAV\Server::getPlugin
89
+     *
90
+     * @return string
91
+     */
92
+    public function getPluginName()	{
93
+        return 'oc-calendar-publishing';
94
+    }
95
+
96
+    /**
97
+     * This initializes the plugin.
98
+     *
99
+     * This function is called by Sabre\DAV\Server, after
100
+     * addPlugin is called.
101
+     *
102
+     * This method should set up the required event subscriptions.
103
+     *
104
+     * @param Server $server
105
+     */
106
+    public function initialize(Server $server) {
107
+        $this->server = $server;
108
+
109
+        $this->server->on('method:POST', [$this, 'httpPost']);
110
+        $this->server->on('propFind',    [$this, 'propFind']);
111
+    }
112
+
113
+    public function propFind(PropFind $propFind, INode $node) {
114
+        if ($node instanceof Calendar) {
115
+            $propFind->handle('{'.self::NS_CALENDARSERVER.'}publish-url', function () use ($node) {
116
+                if ($node->getPublishStatus()) {
117
+                    // We return the publish-url only if the calendar is published.
118
+                    $token = $node->getPublishStatus();
119
+                    $publishUrl = $this->urlGenerator->getAbsoluteURL($this->server->getBaseUri().'public-calendars/').$token;
120
+
121
+                    return new Publisher($publishUrl, true);
122
+                }
123
+            });
124
+
125
+            $propFind->handle('{'.self::NS_CALENDARSERVER.'}allowed-sharing-modes', function() use ($node) {
126
+                return new AllowedSharingModes(!$node->isSubscription(), !$node->isSubscription());
127
+            });
128
+        }
129
+    }
130
+
131
+    /**
132
+     * We intercept this to handle POST requests on calendars.
133
+     *
134
+     * @param RequestInterface $request
135
+     * @param ResponseInterface $response
136
+     *
137
+     * @return void|bool
138
+     */
139
+    public function httpPost(RequestInterface $request, ResponseInterface $response) {
140
+        $path = $request->getPath();
141
+
142
+        // Only handling xml
143
+        $contentType = $request->getHeader('Content-Type');
144
+        if (strpos($contentType, 'application/xml') === false && strpos($contentType, 'text/xml') === false) {
145
+            return;
146
+        }
147
+
148
+        // Making sure the node exists
149
+        try {
150
+            $node = $this->server->tree->getNodeForPath($path);
151
+        } catch (NotFound $e) {
152
+            return;
153
+        }
154
+
155
+        $requestBody = $request->getBodyAsString();
156
+
157
+        // If this request handler could not deal with this POST request, it
158
+        // will return 'null' and other plugins get a chance to handle the
159
+        // request.
160
+        //
161
+        // However, we already requested the full body. This is a problem,
162
+        // because a body can only be read once. This is why we preemptively
163
+        // re-populated the request body with the existing data.
164
+        $request->setBody($requestBody);
165
+
166
+        $this->server->xml->parse($requestBody, $request->getUrl(), $documentType);
167
+
168
+        switch ($documentType) {
169
+
170
+            case '{'.self::NS_CALENDARSERVER.'}publish-calendar' :
171
+
172
+            // We can only deal with IShareableCalendar objects
173
+            if (!$node instanceof Calendar) {
174
+                return;
175
+            }
176
+            $this->server->transactionType = 'post-publish-calendar';
177
+
178
+            // Getting ACL info
179
+            $acl = $this->server->getPlugin('acl');
180
+
181
+            // If there's no ACL support, we allow everything
182
+            if ($acl) {
183
+                $acl->checkPrivileges($path, '{DAV:}write');
184
+            }
185
+
186
+            $node->setPublishStatus(true);
187
+
188
+            // iCloud sends back the 202, so we will too.
189
+            $response->setStatus(202);
190
+
191
+            // Adding this because sending a response body may cause issues,
192
+            // and I wanted some type of indicator the response was handled.
193
+            $response->setHeader('X-Sabre-Status', 'everything-went-well');
194
+
195
+            // Breaking the event chain
196
+            return false;
197
+
198
+            case '{'.self::NS_CALENDARSERVER.'}unpublish-calendar' :
199
+
200
+            // We can only deal with IShareableCalendar objects
201
+            if (!$node instanceof Calendar) {
202
+                return;
203
+            }
204
+            $this->server->transactionType = 'post-unpublish-calendar';
205
+
206
+            // Getting ACL info
207
+            $acl = $this->server->getPlugin('acl');
208
+
209
+            // If there's no ACL support, we allow everything
210
+            if ($acl) {
211
+                $acl->checkPrivileges($path, '{DAV:}write');
212
+            }
213
+
214
+            $node->setPublishStatus(false);
215
+
216
+            $response->setStatus(200);
217
+
218
+            // Adding this because sending a response body may cause issues,
219
+            // and I wanted some type of indicator the response was handled.
220
+            $response->setHeader('X-Sabre-Status', 'everything-went-well');
221
+
222
+            // Breaking the event chain
223
+            return false;
224 224
 
225
-		}
226
-	}
225
+        }
226
+    }
227 227
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -89,7 +89,7 @@  discard block
 block discarded – undo
89 89
 	 *
90 90
 	 * @return string
91 91
 	 */
92
-	public function getPluginName()	{
92
+	public function getPluginName() {
93 93
 		return 'oc-calendar-publishing';
94 94
 	}
95 95
 
@@ -107,12 +107,12 @@  discard block
 block discarded – undo
107 107
 		$this->server = $server;
108 108
 
109 109
 		$this->server->on('method:POST', [$this, 'httpPost']);
110
-		$this->server->on('propFind',    [$this, 'propFind']);
110
+		$this->server->on('propFind', [$this, 'propFind']);
111 111
 	}
112 112
 
113 113
 	public function propFind(PropFind $propFind, INode $node) {
114 114
 		if ($node instanceof Calendar) {
115
-			$propFind->handle('{'.self::NS_CALENDARSERVER.'}publish-url', function () use ($node) {
115
+			$propFind->handle('{'.self::NS_CALENDARSERVER.'}publish-url', function() use ($node) {
116 116
 				if ($node->getPublishStatus()) {
117 117
 					// We return the publish-url only if the calendar is published.
118 118
 					$token = $node->getPublishStatus();
Please login to merge, or discard this patch.
apps/dav/lib/CardDAV/AddressBookRoot.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -30,7 +30,7 @@
 block discarded – undo
30 30
 
31 31
 	/**
32 32
 	 * @param \Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend
33
-	 * @param \Sabre\CardDAV\Backend\BackendInterface $carddavBackend
33
+	 * @param CardDavBackend $carddavBackend
34 34
 	 * @param string $principalPrefix
35 35
 	 */
36 36
 	public function __construct(\Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend, \Sabre\CardDAV\Backend\BackendInterface $carddavBackend, $principalPrefix = 'principals') {
Please login to merge, or discard this patch.
Indentation   +33 added lines, -33 removed lines patch added patch discarded remove patch
@@ -25,46 +25,46 @@
 block discarded – undo
25 25
 
26 26
 class AddressBookRoot extends \Sabre\CardDAV\AddressBookRoot {
27 27
 
28
-	/** @var IL10N */
29
-	protected $l10n;
28
+    /** @var IL10N */
29
+    protected $l10n;
30 30
 
31
-	/**
32
-	 * @param \Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend
33
-	 * @param \Sabre\CardDAV\Backend\BackendInterface $carddavBackend
34
-	 * @param string $principalPrefix
35
-	 */
36
-	public function __construct(\Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend, \Sabre\CardDAV\Backend\BackendInterface $carddavBackend, $principalPrefix = 'principals') {
37
-		parent::__construct($principalBackend, $carddavBackend, $principalPrefix);
38
-		$this->l10n = \OC::$server->getL10N('dav');
39
-	}
31
+    /**
32
+     * @param \Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend
33
+     * @param \Sabre\CardDAV\Backend\BackendInterface $carddavBackend
34
+     * @param string $principalPrefix
35
+     */
36
+    public function __construct(\Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend, \Sabre\CardDAV\Backend\BackendInterface $carddavBackend, $principalPrefix = 'principals') {
37
+        parent::__construct($principalBackend, $carddavBackend, $principalPrefix);
38
+        $this->l10n = \OC::$server->getL10N('dav');
39
+    }
40 40
 
41
-	/**
42
-	 * This method returns a node for a principal.
43
-	 *
44
-	 * The passed array contains principal information, and is guaranteed to
45
-	 * at least contain a uri item. Other properties may or may not be
46
-	 * supplied by the authentication backend.
47
-	 *
48
-	 * @param array $principal
49
-	 * @return \Sabre\DAV\INode
50
-	 */
51
-	function getChildForPrincipal(array $principal) {
41
+    /**
42
+     * This method returns a node for a principal.
43
+     *
44
+     * The passed array contains principal information, and is guaranteed to
45
+     * at least contain a uri item. Other properties may or may not be
46
+     * supplied by the authentication backend.
47
+     *
48
+     * @param array $principal
49
+     * @return \Sabre\DAV\INode
50
+     */
51
+    function getChildForPrincipal(array $principal) {
52 52
 
53
-		return new UserAddressBooks($this->carddavBackend, $principal['uri'], $this->l10n);
53
+        return new UserAddressBooks($this->carddavBackend, $principal['uri'], $this->l10n);
54 54
 
55
-	}
55
+    }
56 56
 
57
-	function getName() {
57
+    function getName() {
58 58
 
59
-		if ($this->principalPrefix === 'principals') {
60
-			return parent::getName();
61
-		}
62
-		// Grabbing all the components of the principal path.
63
-		$parts = explode('/', $this->principalPrefix);
59
+        if ($this->principalPrefix === 'principals') {
60
+            return parent::getName();
61
+        }
62
+        // Grabbing all the components of the principal path.
63
+        $parts = explode('/', $this->principalPrefix);
64 64
 
65
-		// We are only interested in the second part.
66
-		return $parts[1];
65
+        // We are only interested in the second part.
66
+        return $parts[1];
67 67
 
68
-	}
68
+    }
69 69
 
70 70
 }
Please login to merge, or discard this patch.
lib/private/Share20/DefaultShareProvider.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -770,7 +770,7 @@
 block discarded – undo
770 770
 
771 771
 	/**
772 772
 	 * @param Share[] $shares
773
-	 * @param $userId
773
+	 * @param string $userId
774 774
 	 * @return Share[] The updates shares if no update is found for a share return the original
775 775
 	 */
776 776
 	private function resolveGroupShares($shares, $userId) {
Please login to merge, or discard this patch.
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -24,7 +24,6 @@
 block discarded – undo
24 24
 namespace OC\Share20;
25 25
 
26 26
 use OC\Files\Cache\Cache;
27
-use OC\Files\Cache\CacheEntry;
28 27
 use OCP\Files\File;
29 28
 use OCP\Files\Folder;
30 29
 use OCP\Share\IShareProvider;
Please login to merge, or discard this patch.
Spacing   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -285,7 +285,7 @@  discard block
 block discarded – undo
285 285
 			->orderBy('id');
286 286
 
287 287
 		$cursor = $qb->execute();
288
-		while($data = $cursor->fetch()) {
288
+		while ($data = $cursor->fetch()) {
289 289
 			$children[] = $this->createShare($data);
290 290
 		}
291 291
 		$cursor->closeCursor();
@@ -330,7 +330,7 @@  discard block
 block discarded – undo
330 330
 			$user = $this->userManager->get($recipient);
331 331
 
332 332
 			if (is_null($group)) {
333
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
333
+				throw new ProviderException('Group "'.$share->getSharedWith().'" does not exist');
334 334
 			}
335 335
 
336 336
 			if (!$group->inGroup($user)) {
@@ -490,7 +490,7 @@  discard block
 block discarded – undo
490 490
 			);
491 491
 		}
492 492
 
493
-		$qb->innerJoin('s', 'filecache' ,'f', 's.file_source = f.fileid');
493
+		$qb->innerJoin('s', 'filecache', 'f', 's.file_source = f.fileid');
494 494
 		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
495 495
 
496 496
 		$qb->orderBy('id');
@@ -546,7 +546,7 @@  discard block
 block discarded – undo
546 546
 
547 547
 		$cursor = $qb->execute();
548 548
 		$shares = [];
549
-		while($data = $cursor->fetch()) {
549
+		while ($data = $cursor->fetch()) {
550 550
 			$shares[] = $this->createShare($data);
551 551
 		}
552 552
 		$cursor->closeCursor();
@@ -625,7 +625,7 @@  discard block
 block discarded – undo
625 625
 			->execute();
626 626
 
627 627
 		$shares = [];
628
-		while($data = $cursor->fetch()) {
628
+		while ($data = $cursor->fetch()) {
629 629
 			$shares[] = $this->createShare($data);
630 630
 		}
631 631
 		$cursor->closeCursor();
@@ -696,7 +696,7 @@  discard block
 block discarded – undo
696 696
 
697 697
 			$cursor = $qb->execute();
698 698
 
699
-			while($data = $cursor->fetch()) {
699
+			while ($data = $cursor->fetch()) {
700 700
 				if ($this->isAccessibleResult($data)) {
701 701
 					$shares[] = $this->createShare($data);
702 702
 				}
@@ -711,7 +711,7 @@  discard block
 block discarded – undo
711 711
 			$shares2 = [];
712 712
 
713 713
 			$start = 0;
714
-			while(true) {
714
+			while (true) {
715 715
 				$groups = array_slice($allGroups, $start, 100);
716 716
 				$start += 100;
717 717
 
@@ -754,7 +754,7 @@  discard block
 block discarded – undo
754 754
 					));
755 755
 
756 756
 				$cursor = $qb->execute();
757
-				while($data = $cursor->fetch()) {
757
+				while ($data = $cursor->fetch()) {
758 758
 					if ($offset > 0) {
759 759
 						$offset--;
760 760
 						continue;
@@ -823,14 +823,14 @@  discard block
 block discarded – undo
823 823
 	 */
824 824
 	private function createShare($data) {
825 825
 		$share = new Share($this->rootFolder, $this->userManager);
826
-		$share->setId((int)$data['id'])
827
-			->setShareType((int)$data['share_type'])
828
-			->setPermissions((int)$data['permissions'])
826
+		$share->setId((int) $data['id'])
827
+			->setShareType((int) $data['share_type'])
828
+			->setPermissions((int) $data['permissions'])
829 829
 			->setTarget($data['file_target'])
830
-			->setMailSend((bool)$data['mail_send']);
830
+			->setMailSend((bool) $data['mail_send']);
831 831
 
832 832
 		$shareTime = new \DateTime();
833
-		$shareTime->setTimestamp((int)$data['stime']);
833
+		$shareTime->setTimestamp((int) $data['stime']);
834 834
 		$share->setShareTime($shareTime);
835 835
 
836 836
 		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
@@ -845,7 +845,7 @@  discard block
 block discarded – undo
845 845
 		$share->setSharedBy($data['uid_initiator']);
846 846
 		$share->setShareOwner($data['uid_owner']);
847 847
 
848
-		$share->setNodeId((int)$data['file_source']);
848
+		$share->setNodeId((int) $data['file_source']);
849 849
 		$share->setNodeType($data['item_type']);
850 850
 
851 851
 		if ($data['expiration'] !== null) {
@@ -856,7 +856,7 @@  discard block
 block discarded – undo
856 856
 		if (isset($data['f_permissions'])) {
857 857
 			$entryData = $data;
858 858
 			$entryData['permissions'] = $entryData['f_permissions'];
859
-			$entryData['parent'] = $entryData['f_parent'];;
859
+			$entryData['parent'] = $entryData['f_parent']; ;
860 860
 			$share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
861 861
 				\OC::$server->getMimeTypeLoader()));
862 862
 		}
@@ -875,7 +875,7 @@  discard block
 block discarded – undo
875 875
 		$result = [];
876 876
 
877 877
 		$start = 0;
878
-		while(true) {
878
+		while (true) {
879 879
 			/** @var Share[] $shareSlice */
880 880
 			$shareSlice = array_slice($shares, $start, 100);
881 881
 			$start += 100;
@@ -890,7 +890,7 @@  discard block
 block discarded – undo
890 890
 			$shareMap = [];
891 891
 
892 892
 			foreach ($shareSlice as $share) {
893
-				$ids[] = (int)$share->getId();
893
+				$ids[] = (int) $share->getId();
894 894
 				$shareMap[$share->getId()] = $share;
895 895
 			}
896 896
 
@@ -907,8 +907,8 @@  discard block
 block discarded – undo
907 907
 
908 908
 			$stmt = $query->execute();
909 909
 
910
-			while($data = $stmt->fetch()) {
911
-				$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
910
+			while ($data = $stmt->fetch()) {
911
+				$shareMap[$data['parent']]->setPermissions((int) $data['permissions']);
912 912
 				$shareMap[$data['parent']]->setTarget($data['file_target']);
913 913
 			}
914 914
 
@@ -1005,8 +1005,8 @@  discard block
 block discarded – undo
1005 1005
 
1006 1006
 		$cursor = $qb->execute();
1007 1007
 		$ids = [];
1008
-		while($row = $cursor->fetch()) {
1009
-			$ids[] = (int)$row['id'];
1008
+		while ($row = $cursor->fetch()) {
1009
+			$ids[] = (int) $row['id'];
1010 1010
 		}
1011 1011
 		$cursor->closeCursor();
1012 1012
 
@@ -1048,8 +1048,8 @@  discard block
 block discarded – undo
1048 1048
 
1049 1049
 		$cursor = $qb->execute();
1050 1050
 		$ids = [];
1051
-		while($row = $cursor->fetch()) {
1052
-			$ids[] = (int)$row['id'];
1051
+		while ($row = $cursor->fetch()) {
1052
+			$ids[] = (int) $row['id'];
1053 1053
 		}
1054 1054
 		$cursor->closeCursor();
1055 1055
 
Please login to merge, or discard this patch.
Indentation   +990 added lines, -990 removed lines patch added patch discarded remove patch
@@ -47,1027 +47,1027 @@
 block discarded – undo
47 47
  */
48 48
 class DefaultShareProvider implements IShareProvider {
49 49
 
50
-	// Special share type for user modified group shares
51
-	const SHARE_TYPE_USERGROUP = 2;
52
-
53
-	/** @var IDBConnection */
54
-	private $dbConn;
55
-
56
-	/** @var IUserManager */
57
-	private $userManager;
58
-
59
-	/** @var IGroupManager */
60
-	private $groupManager;
61
-
62
-	/** @var IRootFolder */
63
-	private $rootFolder;
64
-
65
-	/**
66
-	 * DefaultShareProvider constructor.
67
-	 *
68
-	 * @param IDBConnection $connection
69
-	 * @param IUserManager $userManager
70
-	 * @param IGroupManager $groupManager
71
-	 * @param IRootFolder $rootFolder
72
-	 */
73
-	public function __construct(
74
-			IDBConnection $connection,
75
-			IUserManager $userManager,
76
-			IGroupManager $groupManager,
77
-			IRootFolder $rootFolder) {
78
-		$this->dbConn = $connection;
79
-		$this->userManager = $userManager;
80
-		$this->groupManager = $groupManager;
81
-		$this->rootFolder = $rootFolder;
82
-	}
83
-
84
-	/**
85
-	 * Return the identifier of this provider.
86
-	 *
87
-	 * @return string Containing only [a-zA-Z0-9]
88
-	 */
89
-	public function identifier() {
90
-		return 'ocinternal';
91
-	}
92
-
93
-	/**
94
-	 * Share a path
95
-	 *
96
-	 * @param \OCP\Share\IShare $share
97
-	 * @return \OCP\Share\IShare The share object
98
-	 * @throws ShareNotFound
99
-	 * @throws \Exception
100
-	 */
101
-	public function create(\OCP\Share\IShare $share) {
102
-		$qb = $this->dbConn->getQueryBuilder();
103
-
104
-		$qb->insert('share');
105
-		$qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
106
-
107
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
108
-			//Set the UID of the user we share with
109
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
110
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
111
-			//Set the GID of the group we share with
112
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
113
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
114
-			//Set the token of the share
115
-			$qb->setValue('token', $qb->createNamedParameter($share->getToken()));
116
-
117
-			//If a password is set store it
118
-			if ($share->getPassword() !== null) {
119
-				$qb->setValue('password', $qb->createNamedParameter($share->getPassword()));
120
-			}
121
-
122
-			//If an expiration date is set store it
123
-			if ($share->getExpirationDate() !== null) {
124
-				$qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
125
-			}
126
-
127
-			if (method_exists($share, 'getParent')) {
128
-				$qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
129
-			}
130
-		} else {
131
-			throw new \Exception('invalid share type!');
132
-		}
133
-
134
-		// Set what is shares
135
-		$qb->setValue('item_type', $qb->createParameter('itemType'));
136
-		if ($share->getNode() instanceof \OCP\Files\File) {
137
-			$qb->setParameter('itemType', 'file');
138
-		} else {
139
-			$qb->setParameter('itemType', 'folder');
140
-		}
141
-
142
-		// Set the file id
143
-		$qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
144
-		$qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
145
-
146
-		// set the permissions
147
-		$qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
148
-
149
-		// Set who created this share
150
-		$qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
151
-
152
-		// Set who is the owner of this file/folder (and this the owner of the share)
153
-		$qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
154
-
155
-		// Set the file target
156
-		$qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
157
-
158
-		// Set the time this share was created
159
-		$qb->setValue('stime', $qb->createNamedParameter(time()));
160
-
161
-		// insert the data and fetch the id of the share
162
-		$this->dbConn->beginTransaction();
163
-		$qb->execute();
164
-		$id = $this->dbConn->lastInsertId('*PREFIX*share');
165
-
166
-		// Now fetch the inserted share and create a complete share object
167
-		$qb = $this->dbConn->getQueryBuilder();
168
-		$qb->select('*')
169
-			->from('share')
170
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
171
-
172
-		$cursor = $qb->execute();
173
-		$data = $cursor->fetch();
174
-		$this->dbConn->commit();
175
-		$cursor->closeCursor();
176
-
177
-		if ($data === false) {
178
-			throw new ShareNotFound();
179
-		}
180
-
181
-		$share = $this->createShare($data);
182
-		return $share;
183
-	}
184
-
185
-	/**
186
-	 * Update a share
187
-	 *
188
-	 * @param \OCP\Share\IShare $share
189
-	 * @return \OCP\Share\IShare The share object
190
-	 */
191
-	public function update(\OCP\Share\IShare $share) {
192
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
193
-			/*
50
+    // Special share type for user modified group shares
51
+    const SHARE_TYPE_USERGROUP = 2;
52
+
53
+    /** @var IDBConnection */
54
+    private $dbConn;
55
+
56
+    /** @var IUserManager */
57
+    private $userManager;
58
+
59
+    /** @var IGroupManager */
60
+    private $groupManager;
61
+
62
+    /** @var IRootFolder */
63
+    private $rootFolder;
64
+
65
+    /**
66
+     * DefaultShareProvider constructor.
67
+     *
68
+     * @param IDBConnection $connection
69
+     * @param IUserManager $userManager
70
+     * @param IGroupManager $groupManager
71
+     * @param IRootFolder $rootFolder
72
+     */
73
+    public function __construct(
74
+            IDBConnection $connection,
75
+            IUserManager $userManager,
76
+            IGroupManager $groupManager,
77
+            IRootFolder $rootFolder) {
78
+        $this->dbConn = $connection;
79
+        $this->userManager = $userManager;
80
+        $this->groupManager = $groupManager;
81
+        $this->rootFolder = $rootFolder;
82
+    }
83
+
84
+    /**
85
+     * Return the identifier of this provider.
86
+     *
87
+     * @return string Containing only [a-zA-Z0-9]
88
+     */
89
+    public function identifier() {
90
+        return 'ocinternal';
91
+    }
92
+
93
+    /**
94
+     * Share a path
95
+     *
96
+     * @param \OCP\Share\IShare $share
97
+     * @return \OCP\Share\IShare The share object
98
+     * @throws ShareNotFound
99
+     * @throws \Exception
100
+     */
101
+    public function create(\OCP\Share\IShare $share) {
102
+        $qb = $this->dbConn->getQueryBuilder();
103
+
104
+        $qb->insert('share');
105
+        $qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
106
+
107
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
108
+            //Set the UID of the user we share with
109
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
110
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
111
+            //Set the GID of the group we share with
112
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
113
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
114
+            //Set the token of the share
115
+            $qb->setValue('token', $qb->createNamedParameter($share->getToken()));
116
+
117
+            //If a password is set store it
118
+            if ($share->getPassword() !== null) {
119
+                $qb->setValue('password', $qb->createNamedParameter($share->getPassword()));
120
+            }
121
+
122
+            //If an expiration date is set store it
123
+            if ($share->getExpirationDate() !== null) {
124
+                $qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
125
+            }
126
+
127
+            if (method_exists($share, 'getParent')) {
128
+                $qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
129
+            }
130
+        } else {
131
+            throw new \Exception('invalid share type!');
132
+        }
133
+
134
+        // Set what is shares
135
+        $qb->setValue('item_type', $qb->createParameter('itemType'));
136
+        if ($share->getNode() instanceof \OCP\Files\File) {
137
+            $qb->setParameter('itemType', 'file');
138
+        } else {
139
+            $qb->setParameter('itemType', 'folder');
140
+        }
141
+
142
+        // Set the file id
143
+        $qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
144
+        $qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
145
+
146
+        // set the permissions
147
+        $qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
148
+
149
+        // Set who created this share
150
+        $qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
151
+
152
+        // Set who is the owner of this file/folder (and this the owner of the share)
153
+        $qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
154
+
155
+        // Set the file target
156
+        $qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
157
+
158
+        // Set the time this share was created
159
+        $qb->setValue('stime', $qb->createNamedParameter(time()));
160
+
161
+        // insert the data and fetch the id of the share
162
+        $this->dbConn->beginTransaction();
163
+        $qb->execute();
164
+        $id = $this->dbConn->lastInsertId('*PREFIX*share');
165
+
166
+        // Now fetch the inserted share and create a complete share object
167
+        $qb = $this->dbConn->getQueryBuilder();
168
+        $qb->select('*')
169
+            ->from('share')
170
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
171
+
172
+        $cursor = $qb->execute();
173
+        $data = $cursor->fetch();
174
+        $this->dbConn->commit();
175
+        $cursor->closeCursor();
176
+
177
+        if ($data === false) {
178
+            throw new ShareNotFound();
179
+        }
180
+
181
+        $share = $this->createShare($data);
182
+        return $share;
183
+    }
184
+
185
+    /**
186
+     * Update a share
187
+     *
188
+     * @param \OCP\Share\IShare $share
189
+     * @return \OCP\Share\IShare The share object
190
+     */
191
+    public function update(\OCP\Share\IShare $share) {
192
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
193
+            /*
194 194
 			 * We allow updating the recipient on user shares.
195 195
 			 */
196
-			$qb = $this->dbConn->getQueryBuilder();
197
-			$qb->update('share')
198
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
199
-				->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
200
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
201
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
202
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
203
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
204
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
205
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
206
-				->execute();
207
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
208
-			$qb = $this->dbConn->getQueryBuilder();
209
-			$qb->update('share')
210
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
211
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
212
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
213
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
214
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
215
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
216
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
217
-				->execute();
218
-
219
-			/*
196
+            $qb = $this->dbConn->getQueryBuilder();
197
+            $qb->update('share')
198
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
199
+                ->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
200
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
201
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
202
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
203
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
204
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
205
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
206
+                ->execute();
207
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
208
+            $qb = $this->dbConn->getQueryBuilder();
209
+            $qb->update('share')
210
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
211
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
212
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
213
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
214
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
215
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
216
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
217
+                ->execute();
218
+
219
+            /*
220 220
 			 * Update all user defined group shares
221 221
 			 */
222
-			$qb = $this->dbConn->getQueryBuilder();
223
-			$qb->update('share')
224
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
225
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
226
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
227
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
228
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
229
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
230
-				->execute();
231
-
232
-			/*
222
+            $qb = $this->dbConn->getQueryBuilder();
223
+            $qb->update('share')
224
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
225
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
226
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
227
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
228
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
229
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
230
+                ->execute();
231
+
232
+            /*
233 233
 			 * Now update the permissions for all children that have not set it to 0
234 234
 			 */
235
-			$qb = $this->dbConn->getQueryBuilder();
236
-			$qb->update('share')
237
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
238
-				->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
239
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
240
-				->execute();
241
-
242
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
243
-			$qb = $this->dbConn->getQueryBuilder();
244
-			$qb->update('share')
245
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
246
-				->set('password', $qb->createNamedParameter($share->getPassword()))
247
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
248
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
249
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
250
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
251
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
252
-				->set('token', $qb->createNamedParameter($share->getToken()))
253
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
254
-				->execute();
255
-		}
256
-
257
-		return $share;
258
-	}
259
-
260
-	/**
261
-	 * Get all children of this share
262
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
263
-	 *
264
-	 * @param \OCP\Share\IShare $parent
265
-	 * @return \OCP\Share\IShare[]
266
-	 */
267
-	public function getChildren(\OCP\Share\IShare $parent) {
268
-		$children = [];
269
-
270
-		$qb = $this->dbConn->getQueryBuilder();
271
-		$qb->select('*')
272
-			->from('share')
273
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
274
-			->andWhere(
275
-				$qb->expr()->in(
276
-					'share_type',
277
-					$qb->createNamedParameter([
278
-						\OCP\Share::SHARE_TYPE_USER,
279
-						\OCP\Share::SHARE_TYPE_GROUP,
280
-						\OCP\Share::SHARE_TYPE_LINK,
281
-					], IQueryBuilder::PARAM_INT_ARRAY)
282
-				)
283
-			)
284
-			->andWhere($qb->expr()->orX(
285
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
286
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
287
-			))
288
-			->orderBy('id');
289
-
290
-		$cursor = $qb->execute();
291
-		while($data = $cursor->fetch()) {
292
-			$children[] = $this->createShare($data);
293
-		}
294
-		$cursor->closeCursor();
295
-
296
-		return $children;
297
-	}
298
-
299
-	/**
300
-	 * Delete a share
301
-	 *
302
-	 * @param \OCP\Share\IShare $share
303
-	 */
304
-	public function delete(\OCP\Share\IShare $share) {
305
-		$qb = $this->dbConn->getQueryBuilder();
306
-		$qb->delete('share')
307
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
308
-
309
-		/*
235
+            $qb = $this->dbConn->getQueryBuilder();
236
+            $qb->update('share')
237
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
238
+                ->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
239
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
240
+                ->execute();
241
+
242
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
243
+            $qb = $this->dbConn->getQueryBuilder();
244
+            $qb->update('share')
245
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
246
+                ->set('password', $qb->createNamedParameter($share->getPassword()))
247
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
248
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
249
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
250
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
251
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
252
+                ->set('token', $qb->createNamedParameter($share->getToken()))
253
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
254
+                ->execute();
255
+        }
256
+
257
+        return $share;
258
+    }
259
+
260
+    /**
261
+     * Get all children of this share
262
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
263
+     *
264
+     * @param \OCP\Share\IShare $parent
265
+     * @return \OCP\Share\IShare[]
266
+     */
267
+    public function getChildren(\OCP\Share\IShare $parent) {
268
+        $children = [];
269
+
270
+        $qb = $this->dbConn->getQueryBuilder();
271
+        $qb->select('*')
272
+            ->from('share')
273
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
274
+            ->andWhere(
275
+                $qb->expr()->in(
276
+                    'share_type',
277
+                    $qb->createNamedParameter([
278
+                        \OCP\Share::SHARE_TYPE_USER,
279
+                        \OCP\Share::SHARE_TYPE_GROUP,
280
+                        \OCP\Share::SHARE_TYPE_LINK,
281
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
282
+                )
283
+            )
284
+            ->andWhere($qb->expr()->orX(
285
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
286
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
287
+            ))
288
+            ->orderBy('id');
289
+
290
+        $cursor = $qb->execute();
291
+        while($data = $cursor->fetch()) {
292
+            $children[] = $this->createShare($data);
293
+        }
294
+        $cursor->closeCursor();
295
+
296
+        return $children;
297
+    }
298
+
299
+    /**
300
+     * Delete a share
301
+     *
302
+     * @param \OCP\Share\IShare $share
303
+     */
304
+    public function delete(\OCP\Share\IShare $share) {
305
+        $qb = $this->dbConn->getQueryBuilder();
306
+        $qb->delete('share')
307
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
308
+
309
+        /*
310 310
 		 * If the share is a group share delete all possible
311 311
 		 * user defined groups shares.
312 312
 		 */
313
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
314
-			$qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
315
-		}
316
-
317
-		$qb->execute();
318
-	}
319
-
320
-	/**
321
-	 * Unshare a share from the recipient. If this is a group share
322
-	 * this means we need a special entry in the share db.
323
-	 *
324
-	 * @param \OCP\Share\IShare $share
325
-	 * @param string $recipient UserId of recipient
326
-	 * @throws BackendError
327
-	 * @throws ProviderException
328
-	 */
329
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
330
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
331
-
332
-			$group = $this->groupManager->get($share->getSharedWith());
333
-			$user = $this->userManager->get($recipient);
334
-
335
-			if (is_null($group)) {
336
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
337
-			}
338
-
339
-			if (!$group->inGroup($user)) {
340
-				throw new ProviderException('Recipient not in receiving group');
341
-			}
342
-
343
-			// Try to fetch user specific share
344
-			$qb = $this->dbConn->getQueryBuilder();
345
-			$stmt = $qb->select('*')
346
-				->from('share')
347
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
348
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
349
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
350
-				->andWhere($qb->expr()->orX(
351
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
352
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
353
-				))
354
-				->execute();
355
-
356
-			$data = $stmt->fetch();
357
-
358
-			/*
313
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
314
+            $qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
315
+        }
316
+
317
+        $qb->execute();
318
+    }
319
+
320
+    /**
321
+     * Unshare a share from the recipient. If this is a group share
322
+     * this means we need a special entry in the share db.
323
+     *
324
+     * @param \OCP\Share\IShare $share
325
+     * @param string $recipient UserId of recipient
326
+     * @throws BackendError
327
+     * @throws ProviderException
328
+     */
329
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
330
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
331
+
332
+            $group = $this->groupManager->get($share->getSharedWith());
333
+            $user = $this->userManager->get($recipient);
334
+
335
+            if (is_null($group)) {
336
+                throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
337
+            }
338
+
339
+            if (!$group->inGroup($user)) {
340
+                throw new ProviderException('Recipient not in receiving group');
341
+            }
342
+
343
+            // Try to fetch user specific share
344
+            $qb = $this->dbConn->getQueryBuilder();
345
+            $stmt = $qb->select('*')
346
+                ->from('share')
347
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
348
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
349
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
350
+                ->andWhere($qb->expr()->orX(
351
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
352
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
353
+                ))
354
+                ->execute();
355
+
356
+            $data = $stmt->fetch();
357
+
358
+            /*
359 359
 			 * Check if there already is a user specific group share.
360 360
 			 * If there is update it (if required).
361 361
 			 */
362
-			if ($data === false) {
363
-				$qb = $this->dbConn->getQueryBuilder();
364
-
365
-				$type = $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder';
366
-
367
-				//Insert new share
368
-				$qb->insert('share')
369
-					->values([
370
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
371
-						'share_with' => $qb->createNamedParameter($recipient),
372
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
373
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
374
-						'parent' => $qb->createNamedParameter($share->getId()),
375
-						'item_type' => $qb->createNamedParameter($type),
376
-						'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
377
-						'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
378
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
379
-						'permissions' => $qb->createNamedParameter(0),
380
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
381
-					])->execute();
382
-
383
-			} else if ($data['permissions'] !== 0) {
384
-
385
-				// Update existing usergroup share
386
-				$qb = $this->dbConn->getQueryBuilder();
387
-				$qb->update('share')
388
-					->set('permissions', $qb->createNamedParameter(0))
389
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
390
-					->execute();
391
-			}
392
-
393
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
394
-
395
-			if ($share->getSharedWith() !== $recipient) {
396
-				throw new ProviderException('Recipient does not match');
397
-			}
398
-
399
-			// We can just delete user and link shares
400
-			$this->delete($share);
401
-		} else {
402
-			throw new ProviderException('Invalid shareType');
403
-		}
404
-	}
405
-
406
-	/**
407
-	 * @inheritdoc
408
-	 */
409
-	public function move(\OCP\Share\IShare $share, $recipient) {
410
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
411
-			// Just update the target
412
-			$qb = $this->dbConn->getQueryBuilder();
413
-			$qb->update('share')
414
-				->set('file_target', $qb->createNamedParameter($share->getTarget()))
415
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
416
-				->execute();
417
-
418
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
419
-
420
-			// Check if there is a usergroup share
421
-			$qb = $this->dbConn->getQueryBuilder();
422
-			$stmt = $qb->select('id')
423
-				->from('share')
424
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
425
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
426
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
427
-				->andWhere($qb->expr()->orX(
428
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
429
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
430
-				))
431
-				->setMaxResults(1)
432
-				->execute();
433
-
434
-			$data = $stmt->fetch();
435
-			$stmt->closeCursor();
436
-
437
-			if ($data === false) {
438
-				// No usergroup share yet. Create one.
439
-				$qb = $this->dbConn->getQueryBuilder();
440
-				$qb->insert('share')
441
-					->values([
442
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
443
-						'share_with' => $qb->createNamedParameter($recipient),
444
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
445
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
446
-						'parent' => $qb->createNamedParameter($share->getId()),
447
-						'item_type' => $qb->createNamedParameter($share->getNode() instanceof File ? 'file' : 'folder'),
448
-						'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
449
-						'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
450
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
451
-						'permissions' => $qb->createNamedParameter($share->getPermissions()),
452
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
453
-					])->execute();
454
-			} else {
455
-				// Already a usergroup share. Update it.
456
-				$qb = $this->dbConn->getQueryBuilder();
457
-				$qb->update('share')
458
-					->set('file_target', $qb->createNamedParameter($share->getTarget()))
459
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
460
-					->execute();
461
-			}
462
-		}
463
-
464
-		return $share;
465
-	}
466
-
467
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
468
-		$qb = $this->dbConn->getQueryBuilder();
469
-		$qb->select('*')
470
-			->from('share', 's')
471
-			->andWhere($qb->expr()->orX(
472
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
473
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
474
-			));
475
-
476
-		$qb->andWhere($qb->expr()->orX(
477
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
478
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
479
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
480
-		));
481
-
482
-		/**
483
-		 * Reshares for this user are shares where they are the owner.
484
-		 */
485
-		if ($reshares === false) {
486
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
487
-		} else {
488
-			$qb->andWhere(
489
-				$qb->expr()->orX(
490
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
491
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
492
-				)
493
-			);
494
-		}
495
-
496
-		$qb->innerJoin('s', 'filecache' ,'f', 's.file_source = f.fileid');
497
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
498
-
499
-		$qb->orderBy('id');
500
-
501
-		$cursor = $qb->execute();
502
-		$shares = [];
503
-		while ($data = $cursor->fetch()) {
504
-			$shares[$data['fileid']][] = $this->createShare($data);
505
-		}
506
-		$cursor->closeCursor();
507
-
508
-		return $shares;
509
-	}
510
-
511
-	/**
512
-	 * @inheritdoc
513
-	 */
514
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
515
-		$qb = $this->dbConn->getQueryBuilder();
516
-		$qb->select('*')
517
-			->from('share')
518
-			->andWhere($qb->expr()->orX(
519
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
520
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
521
-			));
522
-
523
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
524
-
525
-		/**
526
-		 * Reshares for this user are shares where they are the owner.
527
-		 */
528
-		if ($reshares === false) {
529
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
530
-		} else {
531
-			$qb->andWhere(
532
-				$qb->expr()->orX(
533
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
534
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
535
-				)
536
-			);
537
-		}
538
-
539
-		if ($node !== null) {
540
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
541
-		}
542
-
543
-		if ($limit !== -1) {
544
-			$qb->setMaxResults($limit);
545
-		}
546
-
547
-		$qb->setFirstResult($offset);
548
-		$qb->orderBy('id');
549
-
550
-		$cursor = $qb->execute();
551
-		$shares = [];
552
-		while($data = $cursor->fetch()) {
553
-			$shares[] = $this->createShare($data);
554
-		}
555
-		$cursor->closeCursor();
556
-
557
-		return $shares;
558
-	}
559
-
560
-	/**
561
-	 * @inheritdoc
562
-	 */
563
-	public function getShareById($id, $recipientId = null) {
564
-		$qb = $this->dbConn->getQueryBuilder();
565
-
566
-		$qb->select('*')
567
-			->from('share')
568
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
569
-			->andWhere(
570
-				$qb->expr()->in(
571
-					'share_type',
572
-					$qb->createNamedParameter([
573
-						\OCP\Share::SHARE_TYPE_USER,
574
-						\OCP\Share::SHARE_TYPE_GROUP,
575
-						\OCP\Share::SHARE_TYPE_LINK,
576
-					], IQueryBuilder::PARAM_INT_ARRAY)
577
-				)
578
-			)
579
-			->andWhere($qb->expr()->orX(
580
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
581
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
582
-			));
583
-
584
-		$cursor = $qb->execute();
585
-		$data = $cursor->fetch();
586
-		$cursor->closeCursor();
587
-
588
-		if ($data === false) {
589
-			throw new ShareNotFound();
590
-		}
591
-
592
-		try {
593
-			$share = $this->createShare($data);
594
-		} catch (InvalidShare $e) {
595
-			throw new ShareNotFound();
596
-		}
597
-
598
-		// If the recipient is set for a group share resolve to that user
599
-		if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
600
-			$share = $this->resolveGroupShares([$share], $recipientId)[0];
601
-		}
602
-
603
-		return $share;
604
-	}
605
-
606
-	/**
607
-	 * Get shares for a given path
608
-	 *
609
-	 * @param \OCP\Files\Node $path
610
-	 * @return \OCP\Share\IShare[]
611
-	 */
612
-	public function getSharesByPath(Node $path) {
613
-		$qb = $this->dbConn->getQueryBuilder();
614
-
615
-		$cursor = $qb->select('*')
616
-			->from('share')
617
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
618
-			->andWhere(
619
-				$qb->expr()->orX(
620
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
621
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
622
-				)
623
-			)
624
-			->andWhere($qb->expr()->orX(
625
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
626
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
627
-			))
628
-			->execute();
629
-
630
-		$shares = [];
631
-		while($data = $cursor->fetch()) {
632
-			$shares[] = $this->createShare($data);
633
-		}
634
-		$cursor->closeCursor();
635
-
636
-		return $shares;
637
-	}
638
-
639
-	/**
640
-	 * Returns whether the given database result can be interpreted as
641
-	 * a share with accessible file (not trashed, not deleted)
642
-	 */
643
-	private function isAccessibleResult($data) {
644
-		// exclude shares leading to deleted file entries
645
-		if ($data['fileid'] === null) {
646
-			return false;
647
-		}
648
-
649
-		// exclude shares leading to trashbin on home storages
650
-		$pathSections = explode('/', $data['path'], 2);
651
-		// FIXME: would not detect rare md5'd home storage case properly
652
-		if ($pathSections[0] !== 'files'
653
-		    	&& in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
654
-			return false;
655
-		}
656
-		return true;
657
-	}
658
-
659
-	/**
660
-	 * @inheritdoc
661
-	 */
662
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
663
-		/** @var Share[] $shares */
664
-		$shares = [];
665
-
666
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
667
-			//Get shares directly with this user
668
-			$qb = $this->dbConn->getQueryBuilder();
669
-			$qb->select('s.*',
670
-				'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
671
-				'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
672
-				'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
673
-			)
674
-				->selectAlias('st.id', 'storage_string_id')
675
-				->from('share', 's')
676
-				->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
677
-				->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
678
-
679
-			// Order by id
680
-			$qb->orderBy('s.id');
681
-
682
-			// Set limit and offset
683
-			if ($limit !== -1) {
684
-				$qb->setMaxResults($limit);
685
-			}
686
-			$qb->setFirstResult($offset);
687
-
688
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
689
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
690
-				->andWhere($qb->expr()->orX(
691
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
692
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
693
-				));
694
-
695
-			// Filter by node if provided
696
-			if ($node !== null) {
697
-				$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
698
-			}
699
-
700
-			$cursor = $qb->execute();
701
-
702
-			while($data = $cursor->fetch()) {
703
-				if ($this->isAccessibleResult($data)) {
704
-					$shares[] = $this->createShare($data);
705
-				}
706
-			}
707
-			$cursor->closeCursor();
708
-
709
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
710
-			$user = $this->userManager->get($userId);
711
-			$allGroups = $this->groupManager->getUserGroups($user);
712
-
713
-			/** @var Share[] $shares2 */
714
-			$shares2 = [];
715
-
716
-			$start = 0;
717
-			while(true) {
718
-				$groups = array_slice($allGroups, $start, 100);
719
-				$start += 100;
720
-
721
-				if ($groups === []) {
722
-					break;
723
-				}
724
-
725
-				$qb = $this->dbConn->getQueryBuilder();
726
-				$qb->select('s.*',
727
-					'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
728
-					'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
729
-					'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
730
-				)
731
-					->selectAlias('st.id', 'storage_string_id')
732
-					->from('share', 's')
733
-					->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
734
-					->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
735
-					->orderBy('s.id')
736
-					->setFirstResult(0);
737
-
738
-				if ($limit !== -1) {
739
-					$qb->setMaxResults($limit - count($shares));
740
-				}
741
-
742
-				// Filter by node if provided
743
-				if ($node !== null) {
744
-					$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
745
-				}
746
-
747
-				$groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
748
-
749
-				$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
750
-					->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
751
-						$groups,
752
-						IQueryBuilder::PARAM_STR_ARRAY
753
-					)))
754
-					->andWhere($qb->expr()->orX(
755
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
756
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
757
-					));
758
-
759
-				$cursor = $qb->execute();
760
-				while($data = $cursor->fetch()) {
761
-					if ($offset > 0) {
762
-						$offset--;
763
-						continue;
764
-					}
765
-
766
-					if ($this->isAccessibleResult($data)) {
767
-						$shares2[] = $this->createShare($data);
768
-					}
769
-				}
770
-				$cursor->closeCursor();
771
-			}
772
-
773
-			/*
362
+            if ($data === false) {
363
+                $qb = $this->dbConn->getQueryBuilder();
364
+
365
+                $type = $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder';
366
+
367
+                //Insert new share
368
+                $qb->insert('share')
369
+                    ->values([
370
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
371
+                        'share_with' => $qb->createNamedParameter($recipient),
372
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
373
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
374
+                        'parent' => $qb->createNamedParameter($share->getId()),
375
+                        'item_type' => $qb->createNamedParameter($type),
376
+                        'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
377
+                        'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
378
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
379
+                        'permissions' => $qb->createNamedParameter(0),
380
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
381
+                    ])->execute();
382
+
383
+            } else if ($data['permissions'] !== 0) {
384
+
385
+                // Update existing usergroup share
386
+                $qb = $this->dbConn->getQueryBuilder();
387
+                $qb->update('share')
388
+                    ->set('permissions', $qb->createNamedParameter(0))
389
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
390
+                    ->execute();
391
+            }
392
+
393
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
394
+
395
+            if ($share->getSharedWith() !== $recipient) {
396
+                throw new ProviderException('Recipient does not match');
397
+            }
398
+
399
+            // We can just delete user and link shares
400
+            $this->delete($share);
401
+        } else {
402
+            throw new ProviderException('Invalid shareType');
403
+        }
404
+    }
405
+
406
+    /**
407
+     * @inheritdoc
408
+     */
409
+    public function move(\OCP\Share\IShare $share, $recipient) {
410
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
411
+            // Just update the target
412
+            $qb = $this->dbConn->getQueryBuilder();
413
+            $qb->update('share')
414
+                ->set('file_target', $qb->createNamedParameter($share->getTarget()))
415
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
416
+                ->execute();
417
+
418
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
419
+
420
+            // Check if there is a usergroup share
421
+            $qb = $this->dbConn->getQueryBuilder();
422
+            $stmt = $qb->select('id')
423
+                ->from('share')
424
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
425
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
426
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
427
+                ->andWhere($qb->expr()->orX(
428
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
429
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
430
+                ))
431
+                ->setMaxResults(1)
432
+                ->execute();
433
+
434
+            $data = $stmt->fetch();
435
+            $stmt->closeCursor();
436
+
437
+            if ($data === false) {
438
+                // No usergroup share yet. Create one.
439
+                $qb = $this->dbConn->getQueryBuilder();
440
+                $qb->insert('share')
441
+                    ->values([
442
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
443
+                        'share_with' => $qb->createNamedParameter($recipient),
444
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
445
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
446
+                        'parent' => $qb->createNamedParameter($share->getId()),
447
+                        'item_type' => $qb->createNamedParameter($share->getNode() instanceof File ? 'file' : 'folder'),
448
+                        'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
449
+                        'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
450
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
451
+                        'permissions' => $qb->createNamedParameter($share->getPermissions()),
452
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
453
+                    ])->execute();
454
+            } else {
455
+                // Already a usergroup share. Update it.
456
+                $qb = $this->dbConn->getQueryBuilder();
457
+                $qb->update('share')
458
+                    ->set('file_target', $qb->createNamedParameter($share->getTarget()))
459
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
460
+                    ->execute();
461
+            }
462
+        }
463
+
464
+        return $share;
465
+    }
466
+
467
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
468
+        $qb = $this->dbConn->getQueryBuilder();
469
+        $qb->select('*')
470
+            ->from('share', 's')
471
+            ->andWhere($qb->expr()->orX(
472
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
473
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
474
+            ));
475
+
476
+        $qb->andWhere($qb->expr()->orX(
477
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
478
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
479
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
480
+        ));
481
+
482
+        /**
483
+         * Reshares for this user are shares where they are the owner.
484
+         */
485
+        if ($reshares === false) {
486
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
487
+        } else {
488
+            $qb->andWhere(
489
+                $qb->expr()->orX(
490
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
491
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
492
+                )
493
+            );
494
+        }
495
+
496
+        $qb->innerJoin('s', 'filecache' ,'f', 's.file_source = f.fileid');
497
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
498
+
499
+        $qb->orderBy('id');
500
+
501
+        $cursor = $qb->execute();
502
+        $shares = [];
503
+        while ($data = $cursor->fetch()) {
504
+            $shares[$data['fileid']][] = $this->createShare($data);
505
+        }
506
+        $cursor->closeCursor();
507
+
508
+        return $shares;
509
+    }
510
+
511
+    /**
512
+     * @inheritdoc
513
+     */
514
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
515
+        $qb = $this->dbConn->getQueryBuilder();
516
+        $qb->select('*')
517
+            ->from('share')
518
+            ->andWhere($qb->expr()->orX(
519
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
520
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
521
+            ));
522
+
523
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
524
+
525
+        /**
526
+         * Reshares for this user are shares where they are the owner.
527
+         */
528
+        if ($reshares === false) {
529
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
530
+        } else {
531
+            $qb->andWhere(
532
+                $qb->expr()->orX(
533
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
534
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
535
+                )
536
+            );
537
+        }
538
+
539
+        if ($node !== null) {
540
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
541
+        }
542
+
543
+        if ($limit !== -1) {
544
+            $qb->setMaxResults($limit);
545
+        }
546
+
547
+        $qb->setFirstResult($offset);
548
+        $qb->orderBy('id');
549
+
550
+        $cursor = $qb->execute();
551
+        $shares = [];
552
+        while($data = $cursor->fetch()) {
553
+            $shares[] = $this->createShare($data);
554
+        }
555
+        $cursor->closeCursor();
556
+
557
+        return $shares;
558
+    }
559
+
560
+    /**
561
+     * @inheritdoc
562
+     */
563
+    public function getShareById($id, $recipientId = null) {
564
+        $qb = $this->dbConn->getQueryBuilder();
565
+
566
+        $qb->select('*')
567
+            ->from('share')
568
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
569
+            ->andWhere(
570
+                $qb->expr()->in(
571
+                    'share_type',
572
+                    $qb->createNamedParameter([
573
+                        \OCP\Share::SHARE_TYPE_USER,
574
+                        \OCP\Share::SHARE_TYPE_GROUP,
575
+                        \OCP\Share::SHARE_TYPE_LINK,
576
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
577
+                )
578
+            )
579
+            ->andWhere($qb->expr()->orX(
580
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
581
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
582
+            ));
583
+
584
+        $cursor = $qb->execute();
585
+        $data = $cursor->fetch();
586
+        $cursor->closeCursor();
587
+
588
+        if ($data === false) {
589
+            throw new ShareNotFound();
590
+        }
591
+
592
+        try {
593
+            $share = $this->createShare($data);
594
+        } catch (InvalidShare $e) {
595
+            throw new ShareNotFound();
596
+        }
597
+
598
+        // If the recipient is set for a group share resolve to that user
599
+        if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
600
+            $share = $this->resolveGroupShares([$share], $recipientId)[0];
601
+        }
602
+
603
+        return $share;
604
+    }
605
+
606
+    /**
607
+     * Get shares for a given path
608
+     *
609
+     * @param \OCP\Files\Node $path
610
+     * @return \OCP\Share\IShare[]
611
+     */
612
+    public function getSharesByPath(Node $path) {
613
+        $qb = $this->dbConn->getQueryBuilder();
614
+
615
+        $cursor = $qb->select('*')
616
+            ->from('share')
617
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
618
+            ->andWhere(
619
+                $qb->expr()->orX(
620
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
621
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
622
+                )
623
+            )
624
+            ->andWhere($qb->expr()->orX(
625
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
626
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
627
+            ))
628
+            ->execute();
629
+
630
+        $shares = [];
631
+        while($data = $cursor->fetch()) {
632
+            $shares[] = $this->createShare($data);
633
+        }
634
+        $cursor->closeCursor();
635
+
636
+        return $shares;
637
+    }
638
+
639
+    /**
640
+     * Returns whether the given database result can be interpreted as
641
+     * a share with accessible file (not trashed, not deleted)
642
+     */
643
+    private function isAccessibleResult($data) {
644
+        // exclude shares leading to deleted file entries
645
+        if ($data['fileid'] === null) {
646
+            return false;
647
+        }
648
+
649
+        // exclude shares leading to trashbin on home storages
650
+        $pathSections = explode('/', $data['path'], 2);
651
+        // FIXME: would not detect rare md5'd home storage case properly
652
+        if ($pathSections[0] !== 'files'
653
+                && in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
654
+            return false;
655
+        }
656
+        return true;
657
+    }
658
+
659
+    /**
660
+     * @inheritdoc
661
+     */
662
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
663
+        /** @var Share[] $shares */
664
+        $shares = [];
665
+
666
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
667
+            //Get shares directly with this user
668
+            $qb = $this->dbConn->getQueryBuilder();
669
+            $qb->select('s.*',
670
+                'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
671
+                'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
672
+                'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
673
+            )
674
+                ->selectAlias('st.id', 'storage_string_id')
675
+                ->from('share', 's')
676
+                ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
677
+                ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
678
+
679
+            // Order by id
680
+            $qb->orderBy('s.id');
681
+
682
+            // Set limit and offset
683
+            if ($limit !== -1) {
684
+                $qb->setMaxResults($limit);
685
+            }
686
+            $qb->setFirstResult($offset);
687
+
688
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
689
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
690
+                ->andWhere($qb->expr()->orX(
691
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
692
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
693
+                ));
694
+
695
+            // Filter by node if provided
696
+            if ($node !== null) {
697
+                $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
698
+            }
699
+
700
+            $cursor = $qb->execute();
701
+
702
+            while($data = $cursor->fetch()) {
703
+                if ($this->isAccessibleResult($data)) {
704
+                    $shares[] = $this->createShare($data);
705
+                }
706
+            }
707
+            $cursor->closeCursor();
708
+
709
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
710
+            $user = $this->userManager->get($userId);
711
+            $allGroups = $this->groupManager->getUserGroups($user);
712
+
713
+            /** @var Share[] $shares2 */
714
+            $shares2 = [];
715
+
716
+            $start = 0;
717
+            while(true) {
718
+                $groups = array_slice($allGroups, $start, 100);
719
+                $start += 100;
720
+
721
+                if ($groups === []) {
722
+                    break;
723
+                }
724
+
725
+                $qb = $this->dbConn->getQueryBuilder();
726
+                $qb->select('s.*',
727
+                    'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
728
+                    'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
729
+                    'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
730
+                )
731
+                    ->selectAlias('st.id', 'storage_string_id')
732
+                    ->from('share', 's')
733
+                    ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
734
+                    ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
735
+                    ->orderBy('s.id')
736
+                    ->setFirstResult(0);
737
+
738
+                if ($limit !== -1) {
739
+                    $qb->setMaxResults($limit - count($shares));
740
+                }
741
+
742
+                // Filter by node if provided
743
+                if ($node !== null) {
744
+                    $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
745
+                }
746
+
747
+                $groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
748
+
749
+                $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
750
+                    ->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
751
+                        $groups,
752
+                        IQueryBuilder::PARAM_STR_ARRAY
753
+                    )))
754
+                    ->andWhere($qb->expr()->orX(
755
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
756
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
757
+                    ));
758
+
759
+                $cursor = $qb->execute();
760
+                while($data = $cursor->fetch()) {
761
+                    if ($offset > 0) {
762
+                        $offset--;
763
+                        continue;
764
+                    }
765
+
766
+                    if ($this->isAccessibleResult($data)) {
767
+                        $shares2[] = $this->createShare($data);
768
+                    }
769
+                }
770
+                $cursor->closeCursor();
771
+            }
772
+
773
+            /*
774 774
  			 * Resolve all group shares to user specific shares
775 775
  			 */
776
-			$shares = $this->resolveGroupShares($shares2, $userId);
777
-		} else {
778
-			throw new BackendError('Invalid backend');
779
-		}
780
-
781
-
782
-		return $shares;
783
-	}
784
-
785
-	/**
786
-	 * Get a share by token
787
-	 *
788
-	 * @param string $token
789
-	 * @return \OCP\Share\IShare
790
-	 * @throws ShareNotFound
791
-	 */
792
-	public function getShareByToken($token) {
793
-		$qb = $this->dbConn->getQueryBuilder();
794
-
795
-		$cursor = $qb->select('*')
796
-			->from('share')
797
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
798
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
799
-			->andWhere($qb->expr()->orX(
800
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
801
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
802
-			))
803
-			->execute();
804
-
805
-		$data = $cursor->fetch();
806
-
807
-		if ($data === false) {
808
-			throw new ShareNotFound();
809
-		}
810
-
811
-		try {
812
-			$share = $this->createShare($data);
813
-		} catch (InvalidShare $e) {
814
-			throw new ShareNotFound();
815
-		}
816
-
817
-		return $share;
818
-	}
819
-
820
-	/**
821
-	 * Create a share object from an database row
822
-	 *
823
-	 * @param mixed[] $data
824
-	 * @return \OCP\Share\IShare
825
-	 * @throws InvalidShare
826
-	 */
827
-	private function createShare($data) {
828
-		$share = new Share($this->rootFolder, $this->userManager);
829
-		$share->setId((int)$data['id'])
830
-			->setShareType((int)$data['share_type'])
831
-			->setPermissions((int)$data['permissions'])
832
-			->setTarget($data['file_target'])
833
-			->setMailSend((bool)$data['mail_send']);
834
-
835
-		$shareTime = new \DateTime();
836
-		$shareTime->setTimestamp((int)$data['stime']);
837
-		$share->setShareTime($shareTime);
838
-
839
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
840
-			$share->setSharedWith($data['share_with']);
841
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
842
-			$share->setSharedWith($data['share_with']);
843
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
844
-			$share->setPassword($data['password']);
845
-			$share->setToken($data['token']);
846
-		}
847
-
848
-		$share->setSharedBy($data['uid_initiator']);
849
-		$share->setShareOwner($data['uid_owner']);
850
-
851
-		$share->setNodeId((int)$data['file_source']);
852
-		$share->setNodeType($data['item_type']);
853
-
854
-		if ($data['expiration'] !== null) {
855
-			$expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
856
-			$share->setExpirationDate($expiration);
857
-		}
858
-
859
-		if (isset($data['f_permissions'])) {
860
-			$entryData = $data;
861
-			$entryData['permissions'] = $entryData['f_permissions'];
862
-			$entryData['parent'] = $entryData['f_parent'];;
863
-			$share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
864
-				\OC::$server->getMimeTypeLoader()));
865
-		}
866
-
867
-		$share->setProviderId($this->identifier());
868
-
869
-		return $share;
870
-	}
871
-
872
-	/**
873
-	 * @param Share[] $shares
874
-	 * @param $userId
875
-	 * @return Share[] The updates shares if no update is found for a share return the original
876
-	 */
877
-	private function resolveGroupShares($shares, $userId) {
878
-		$result = [];
879
-
880
-		$start = 0;
881
-		while(true) {
882
-			/** @var Share[] $shareSlice */
883
-			$shareSlice = array_slice($shares, $start, 100);
884
-			$start += 100;
885
-
886
-			if ($shareSlice === []) {
887
-				break;
888
-			}
889
-
890
-			/** @var int[] $ids */
891
-			$ids = [];
892
-			/** @var Share[] $shareMap */
893
-			$shareMap = [];
894
-
895
-			foreach ($shareSlice as $share) {
896
-				$ids[] = (int)$share->getId();
897
-				$shareMap[$share->getId()] = $share;
898
-			}
899
-
900
-			$qb = $this->dbConn->getQueryBuilder();
901
-
902
-			$query = $qb->select('*')
903
-				->from('share')
904
-				->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
905
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
906
-				->andWhere($qb->expr()->orX(
907
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
908
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
909
-				));
910
-
911
-			$stmt = $query->execute();
912
-
913
-			while($data = $stmt->fetch()) {
914
-				$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
915
-				$shareMap[$data['parent']]->setTarget($data['file_target']);
916
-			}
917
-
918
-			$stmt->closeCursor();
919
-
920
-			foreach ($shareMap as $share) {
921
-				$result[] = $share;
922
-			}
923
-		}
924
-
925
-		return $result;
926
-	}
927
-
928
-	/**
929
-	 * A user is deleted from the system
930
-	 * So clean up the relevant shares.
931
-	 *
932
-	 * @param string $uid
933
-	 * @param int $shareType
934
-	 */
935
-	public function userDeleted($uid, $shareType) {
936
-		$qb = $this->dbConn->getQueryBuilder();
937
-
938
-		$qb->delete('share');
939
-
940
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
941
-			/*
776
+            $shares = $this->resolveGroupShares($shares2, $userId);
777
+        } else {
778
+            throw new BackendError('Invalid backend');
779
+        }
780
+
781
+
782
+        return $shares;
783
+    }
784
+
785
+    /**
786
+     * Get a share by token
787
+     *
788
+     * @param string $token
789
+     * @return \OCP\Share\IShare
790
+     * @throws ShareNotFound
791
+     */
792
+    public function getShareByToken($token) {
793
+        $qb = $this->dbConn->getQueryBuilder();
794
+
795
+        $cursor = $qb->select('*')
796
+            ->from('share')
797
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
798
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
799
+            ->andWhere($qb->expr()->orX(
800
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
801
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
802
+            ))
803
+            ->execute();
804
+
805
+        $data = $cursor->fetch();
806
+
807
+        if ($data === false) {
808
+            throw new ShareNotFound();
809
+        }
810
+
811
+        try {
812
+            $share = $this->createShare($data);
813
+        } catch (InvalidShare $e) {
814
+            throw new ShareNotFound();
815
+        }
816
+
817
+        return $share;
818
+    }
819
+
820
+    /**
821
+     * Create a share object from an database row
822
+     *
823
+     * @param mixed[] $data
824
+     * @return \OCP\Share\IShare
825
+     * @throws InvalidShare
826
+     */
827
+    private function createShare($data) {
828
+        $share = new Share($this->rootFolder, $this->userManager);
829
+        $share->setId((int)$data['id'])
830
+            ->setShareType((int)$data['share_type'])
831
+            ->setPermissions((int)$data['permissions'])
832
+            ->setTarget($data['file_target'])
833
+            ->setMailSend((bool)$data['mail_send']);
834
+
835
+        $shareTime = new \DateTime();
836
+        $shareTime->setTimestamp((int)$data['stime']);
837
+        $share->setShareTime($shareTime);
838
+
839
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
840
+            $share->setSharedWith($data['share_with']);
841
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
842
+            $share->setSharedWith($data['share_with']);
843
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
844
+            $share->setPassword($data['password']);
845
+            $share->setToken($data['token']);
846
+        }
847
+
848
+        $share->setSharedBy($data['uid_initiator']);
849
+        $share->setShareOwner($data['uid_owner']);
850
+
851
+        $share->setNodeId((int)$data['file_source']);
852
+        $share->setNodeType($data['item_type']);
853
+
854
+        if ($data['expiration'] !== null) {
855
+            $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
856
+            $share->setExpirationDate($expiration);
857
+        }
858
+
859
+        if (isset($data['f_permissions'])) {
860
+            $entryData = $data;
861
+            $entryData['permissions'] = $entryData['f_permissions'];
862
+            $entryData['parent'] = $entryData['f_parent'];;
863
+            $share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
864
+                \OC::$server->getMimeTypeLoader()));
865
+        }
866
+
867
+        $share->setProviderId($this->identifier());
868
+
869
+        return $share;
870
+    }
871
+
872
+    /**
873
+     * @param Share[] $shares
874
+     * @param $userId
875
+     * @return Share[] The updates shares if no update is found for a share return the original
876
+     */
877
+    private function resolveGroupShares($shares, $userId) {
878
+        $result = [];
879
+
880
+        $start = 0;
881
+        while(true) {
882
+            /** @var Share[] $shareSlice */
883
+            $shareSlice = array_slice($shares, $start, 100);
884
+            $start += 100;
885
+
886
+            if ($shareSlice === []) {
887
+                break;
888
+            }
889
+
890
+            /** @var int[] $ids */
891
+            $ids = [];
892
+            /** @var Share[] $shareMap */
893
+            $shareMap = [];
894
+
895
+            foreach ($shareSlice as $share) {
896
+                $ids[] = (int)$share->getId();
897
+                $shareMap[$share->getId()] = $share;
898
+            }
899
+
900
+            $qb = $this->dbConn->getQueryBuilder();
901
+
902
+            $query = $qb->select('*')
903
+                ->from('share')
904
+                ->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
905
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
906
+                ->andWhere($qb->expr()->orX(
907
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
908
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
909
+                ));
910
+
911
+            $stmt = $query->execute();
912
+
913
+            while($data = $stmt->fetch()) {
914
+                $shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
915
+                $shareMap[$data['parent']]->setTarget($data['file_target']);
916
+            }
917
+
918
+            $stmt->closeCursor();
919
+
920
+            foreach ($shareMap as $share) {
921
+                $result[] = $share;
922
+            }
923
+        }
924
+
925
+        return $result;
926
+    }
927
+
928
+    /**
929
+     * A user is deleted from the system
930
+     * So clean up the relevant shares.
931
+     *
932
+     * @param string $uid
933
+     * @param int $shareType
934
+     */
935
+    public function userDeleted($uid, $shareType) {
936
+        $qb = $this->dbConn->getQueryBuilder();
937
+
938
+        $qb->delete('share');
939
+
940
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
941
+            /*
942 942
 			 * Delete all user shares that are owned by this user
943 943
 			 * or that are received by this user
944 944
 			 */
945 945
 
946
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
946
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
947 947
 
948
-			$qb->andWhere(
949
-				$qb->expr()->orX(
950
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
951
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
952
-				)
953
-			);
954
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
955
-			/*
948
+            $qb->andWhere(
949
+                $qb->expr()->orX(
950
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
951
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
952
+                )
953
+            );
954
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
955
+            /*
956 956
 			 * Delete all group shares that are owned by this user
957 957
 			 * Or special user group shares that are received by this user
958 958
 			 */
959
-			$qb->where(
960
-				$qb->expr()->andX(
961
-					$qb->expr()->orX(
962
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
963
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
964
-					),
965
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
966
-				)
967
-			);
968
-
969
-			$qb->orWhere(
970
-				$qb->expr()->andX(
971
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
972
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
973
-				)
974
-			);
975
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
976
-			/*
959
+            $qb->where(
960
+                $qb->expr()->andX(
961
+                    $qb->expr()->orX(
962
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
963
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
964
+                    ),
965
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
966
+                )
967
+            );
968
+
969
+            $qb->orWhere(
970
+                $qb->expr()->andX(
971
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
972
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
973
+                )
974
+            );
975
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
976
+            /*
977 977
 			 * Delete all link shares owned by this user.
978 978
 			 * And all link shares initiated by this user (until #22327 is in)
979 979
 			 */
980
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
981
-
982
-			$qb->andWhere(
983
-				$qb->expr()->orX(
984
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
985
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
986
-				)
987
-			);
988
-		}
989
-
990
-		$qb->execute();
991
-	}
992
-
993
-	/**
994
-	 * Delete all shares received by this group. As well as any custom group
995
-	 * shares for group members.
996
-	 *
997
-	 * @param string $gid
998
-	 */
999
-	public function groupDeleted($gid) {
1000
-		/*
980
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
981
+
982
+            $qb->andWhere(
983
+                $qb->expr()->orX(
984
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
985
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
986
+                )
987
+            );
988
+        }
989
+
990
+        $qb->execute();
991
+    }
992
+
993
+    /**
994
+     * Delete all shares received by this group. As well as any custom group
995
+     * shares for group members.
996
+     *
997
+     * @param string $gid
998
+     */
999
+    public function groupDeleted($gid) {
1000
+        /*
1001 1001
 		 * First delete all custom group shares for group members
1002 1002
 		 */
1003
-		$qb = $this->dbConn->getQueryBuilder();
1004
-		$qb->select('id')
1005
-			->from('share')
1006
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1007
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1008
-
1009
-		$cursor = $qb->execute();
1010
-		$ids = [];
1011
-		while($row = $cursor->fetch()) {
1012
-			$ids[] = (int)$row['id'];
1013
-		}
1014
-		$cursor->closeCursor();
1015
-
1016
-		if (!empty($ids)) {
1017
-			$chunks = array_chunk($ids, 100);
1018
-			foreach ($chunks as $chunk) {
1019
-				$qb->delete('share')
1020
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1021
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1022
-				$qb->execute();
1023
-			}
1024
-		}
1025
-
1026
-		/*
1003
+        $qb = $this->dbConn->getQueryBuilder();
1004
+        $qb->select('id')
1005
+            ->from('share')
1006
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1007
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1008
+
1009
+        $cursor = $qb->execute();
1010
+        $ids = [];
1011
+        while($row = $cursor->fetch()) {
1012
+            $ids[] = (int)$row['id'];
1013
+        }
1014
+        $cursor->closeCursor();
1015
+
1016
+        if (!empty($ids)) {
1017
+            $chunks = array_chunk($ids, 100);
1018
+            foreach ($chunks as $chunk) {
1019
+                $qb->delete('share')
1020
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1021
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1022
+                $qb->execute();
1023
+            }
1024
+        }
1025
+
1026
+        /*
1027 1027
 		 * Now delete all the group shares
1028 1028
 		 */
1029
-		$qb = $this->dbConn->getQueryBuilder();
1030
-		$qb->delete('share')
1031
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1032
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1033
-		$qb->execute();
1034
-	}
1035
-
1036
-	/**
1037
-	 * Delete custom group shares to this group for this user
1038
-	 *
1039
-	 * @param string $uid
1040
-	 * @param string $gid
1041
-	 */
1042
-	public function userDeletedFromGroup($uid, $gid) {
1043
-		/*
1029
+        $qb = $this->dbConn->getQueryBuilder();
1030
+        $qb->delete('share')
1031
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1032
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1033
+        $qb->execute();
1034
+    }
1035
+
1036
+    /**
1037
+     * Delete custom group shares to this group for this user
1038
+     *
1039
+     * @param string $uid
1040
+     * @param string $gid
1041
+     */
1042
+    public function userDeletedFromGroup($uid, $gid) {
1043
+        /*
1044 1044
 		 * Get all group shares
1045 1045
 		 */
1046
-		$qb = $this->dbConn->getQueryBuilder();
1047
-		$qb->select('id')
1048
-			->from('share')
1049
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1050
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1051
-
1052
-		$cursor = $qb->execute();
1053
-		$ids = [];
1054
-		while($row = $cursor->fetch()) {
1055
-			$ids[] = (int)$row['id'];
1056
-		}
1057
-		$cursor->closeCursor();
1058
-
1059
-		if (!empty($ids)) {
1060
-			$chunks = array_chunk($ids, 100);
1061
-			foreach ($chunks as $chunk) {
1062
-				/*
1046
+        $qb = $this->dbConn->getQueryBuilder();
1047
+        $qb->select('id')
1048
+            ->from('share')
1049
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1050
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1051
+
1052
+        $cursor = $qb->execute();
1053
+        $ids = [];
1054
+        while($row = $cursor->fetch()) {
1055
+            $ids[] = (int)$row['id'];
1056
+        }
1057
+        $cursor->closeCursor();
1058
+
1059
+        if (!empty($ids)) {
1060
+            $chunks = array_chunk($ids, 100);
1061
+            foreach ($chunks as $chunk) {
1062
+                /*
1063 1063
 				 * Delete all special shares wit this users for the found group shares
1064 1064
 				 */
1065
-				$qb->delete('share')
1066
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1067
-					->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1068
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1069
-				$qb->execute();
1070
-			}
1071
-		}
1072
-	}
1065
+                $qb->delete('share')
1066
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1067
+                    ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1068
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1069
+                $qb->execute();
1070
+            }
1071
+        }
1072
+    }
1073 1073
 }
Please login to merge, or discard this patch.