Completed
Push — master ( 445cce...52a994 )
by John
20:56
created
lib/public/AppFramework/Db/Entity.php 1 patch
Indentation   +290 added lines, -290 removed lines patch added patch discarded remove patch
@@ -19,294 +19,294 @@
 block discarded – undo
19 19
  * @psalm-consistent-constructor
20 20
  */
21 21
 abstract class Entity {
22
-	/** @var int $id */
23
-	public $id = null;
24
-
25
-	private array $_updatedFields = [];
26
-	/** @var array<string, \OCP\DB\Types::*> */
27
-	private array $_fieldTypes = ['id' => 'integer'];
28
-
29
-	/**
30
-	 * Simple alternative constructor for building entities from a request
31
-	 * @param array $params the array which was obtained via $this->params('key')
32
-	 *                      in the controller
33
-	 * @since 7.0.0
34
-	 */
35
-	public static function fromParams(array $params): static {
36
-		$instance = new static();
37
-
38
-		foreach ($params as $key => $value) {
39
-			$method = 'set' . ucfirst($key);
40
-			$instance->$method($value);
41
-		}
42
-
43
-		return $instance;
44
-	}
45
-
46
-
47
-	/**
48
-	 * Maps the keys of the row array to the attributes
49
-	 * @param array $row the row to map onto the entity
50
-	 * @since 7.0.0
51
-	 */
52
-	public static function fromRow(array $row): static {
53
-		$instance = new static();
54
-
55
-		foreach ($row as $key => $value) {
56
-			$prop = $instance->columnToProperty($key);
57
-			$instance->setter($prop, [$value]);
58
-		}
59
-
60
-		$instance->resetUpdatedFields();
61
-
62
-		return $instance;
63
-	}
64
-
65
-
66
-	/**
67
-	 * @return array<string, \OCP\DB\Types::*> with attribute and type
68
-	 * @since 7.0.0
69
-	 */
70
-	public function getFieldTypes(): array {
71
-		return $this->_fieldTypes;
72
-	}
73
-
74
-
75
-	/**
76
-	 * Marks the entity as clean needed for setting the id after the insertion
77
-	 * @since 7.0.0
78
-	 */
79
-	public function resetUpdatedFields(): void {
80
-		$this->_updatedFields = [];
81
-	}
82
-
83
-	/**
84
-	 * Generic setter for properties
85
-	 *
86
-	 * @throws \InvalidArgumentException
87
-	 * @since 7.0.0
88
-	 *
89
-	 */
90
-	protected function setter(string $name, array $args): void {
91
-		// setters should only work for existing attributes
92
-		if (!property_exists($this, $name)) {
93
-			throw new \BadFunctionCallException($name . ' is not a valid attribute');
94
-		}
95
-
96
-		if ($args[0] === $this->$name) {
97
-			return;
98
-		}
99
-		$this->markFieldUpdated($name);
100
-
101
-		// if type definition exists, cast to correct type
102
-		if ($args[0] !== null && array_key_exists($name, $this->_fieldTypes)) {
103
-			$type = $this->_fieldTypes[$name];
104
-			if ($type === Types::BLOB) {
105
-				// (B)LOB is treated as string when we read from the DB
106
-				if (is_resource($args[0])) {
107
-					$args[0] = stream_get_contents($args[0]);
108
-				}
109
-				$type = Types::STRING;
110
-			}
111
-
112
-			switch ($type) {
113
-				case Types::BIGINT:
114
-				case Types::SMALLINT:
115
-					settype($args[0], Types::INTEGER);
116
-					break;
117
-				case Types::BINARY:
118
-				case Types::DECIMAL:
119
-				case Types::TEXT:
120
-					settype($args[0], Types::STRING);
121
-					break;
122
-				case Types::TIME:
123
-				case Types::DATE:
124
-				case Types::DATETIME:
125
-				case Types::DATETIME_TZ:
126
-					if (!$args[0] instanceof \DateTime) {
127
-						$args[0] = new \DateTime($args[0]);
128
-					}
129
-					break;
130
-				case Types::TIME_IMMUTABLE:
131
-				case Types::DATE_IMMUTABLE:
132
-				case Types::DATETIME_IMMUTABLE:
133
-				case Types::DATETIME_TZ_IMMUTABLE:
134
-					if (!$args[0] instanceof \DateTimeImmutable) {
135
-						$args[0] = new \DateTimeImmutable($args[0]);
136
-					}
137
-					break;
138
-				case Types::JSON:
139
-					if (!is_array($args[0])) {
140
-						$args[0] = json_decode($args[0], true);
141
-					}
142
-					break;
143
-				default:
144
-					settype($args[0], $type);
145
-			}
146
-		}
147
-		$this->$name = $args[0];
148
-
149
-	}
150
-
151
-	/**
152
-	 * Generic getter for properties
153
-	 * @since 7.0.0
154
-	 */
155
-	protected function getter(string $name): mixed {
156
-		// getters should only work for existing attributes
157
-		if (property_exists($this, $name)) {
158
-			return $this->$name;
159
-		} else {
160
-			throw new \BadFunctionCallException($name
161
-				. ' is not a valid attribute');
162
-		}
163
-	}
164
-
165
-
166
-	/**
167
-	 * Each time a setter is called, push the part after set
168
-	 * into an array: for instance setId will save Id in the
169
-	 * updated fields array so it can be easily used to create the
170
-	 * getter method
171
-	 * @since 7.0.0
172
-	 */
173
-	public function __call(string $methodName, array $args) {
174
-		if (str_starts_with($methodName, 'set')) {
175
-			$this->setter(lcfirst(substr($methodName, 3)), $args);
176
-		} elseif (str_starts_with($methodName, 'get')) {
177
-			return $this->getter(lcfirst(substr($methodName, 3)));
178
-		} elseif ($this->isGetterForBoolProperty($methodName)) {
179
-			return $this->getter(lcfirst(substr($methodName, 2)));
180
-		} else {
181
-			throw new \BadFunctionCallException($methodName
182
-				. ' does not exist');
183
-		}
184
-	}
185
-
186
-	/**
187
-	 * @param string $methodName
188
-	 * @return bool
189
-	 * @since 18.0.0
190
-	 */
191
-	protected function isGetterForBoolProperty(string $methodName): bool {
192
-		if (str_starts_with($methodName, 'is')) {
193
-			$fieldName = lcfirst(substr($methodName, 2));
194
-			return isset($this->_fieldTypes[$fieldName]) && str_starts_with($this->_fieldTypes[$fieldName], 'bool');
195
-		}
196
-		return false;
197
-	}
198
-
199
-	/**
200
-	 * Mark am attribute as updated
201
-	 * @param string $attribute the name of the attribute
202
-	 * @since 7.0.0
203
-	 */
204
-	protected function markFieldUpdated(string $attribute): void {
205
-		$this->_updatedFields[$attribute] = true;
206
-	}
207
-
208
-
209
-	/**
210
-	 * Transform a database columnname to a property
211
-	 *
212
-	 * @param string $columnName the name of the column
213
-	 * @return string the property name
214
-	 * @since 7.0.0
215
-	 */
216
-	public function columnToProperty(string $columnName) {
217
-		$parts = explode('_', $columnName);
218
-		$property = '';
219
-
220
-		foreach ($parts as $part) {
221
-			if ($property === '') {
222
-				$property = $part;
223
-			} else {
224
-				$property .= ucfirst($part);
225
-			}
226
-		}
227
-
228
-		return $property;
229
-	}
230
-
231
-
232
-	/**
233
-	 * Transform a property to a database column name
234
-	 *
235
-	 * @param string $property the name of the property
236
-	 * @return string the column name
237
-	 * @since 7.0.0
238
-	 */
239
-	public function propertyToColumn(string $property): string {
240
-		$parts = preg_split('/(?=[A-Z])/', $property);
241
-
242
-		$column = '';
243
-		foreach ($parts as $part) {
244
-			if ($column === '') {
245
-				$column = $part;
246
-			} else {
247
-				$column .= '_' . lcfirst($part);
248
-			}
249
-		}
250
-
251
-		return $column;
252
-	}
253
-
254
-
255
-	/**
256
-	 * @return array array of updated fields for update query
257
-	 * @since 7.0.0
258
-	 */
259
-	public function getUpdatedFields(): array {
260
-		return $this->_updatedFields;
261
-	}
262
-
263
-
264
-	/**
265
-	 * Adds type information for a field so that it's automatically cast to
266
-	 * that value once its being returned from the database
267
-	 *
268
-	 * @param string $fieldName the name of the attribute
269
-	 * @param \OCP\DB\Types::* $type the type which will be used to match a cast
270
-	 * @since 31.0.0 Parameter $type is now restricted to {@see \OCP\DB\Types} constants. The formerly accidentally supported types 'int'|'bool'|'double' are mapped to Types::INTEGER|Types::BOOLEAN|Types::FLOAT accordingly.
271
-	 * @since 7.0.0
272
-	 */
273
-	protected function addType(string $fieldName, string $type): void {
274
-		/** @psalm-suppress TypeDoesNotContainType */
275
-		if (in_array($type, ['bool', 'double', 'int', 'array', 'object'], true)) {
276
-			// Mapping legacy strings to the actual types
277
-			$type = match ($type) {
278
-				'int' => Types::INTEGER,
279
-				'bool' => Types::BOOLEAN,
280
-				'double' => Types::FLOAT,
281
-				'array',
282
-				'object' => Types::STRING,
283
-			};
284
-		}
285
-
286
-		$this->_fieldTypes[$fieldName] = $type;
287
-	}
288
-
289
-
290
-	/**
291
-	 * Slugify the value of a given attribute
292
-	 * Warning: This doesn't result in a unique value
293
-	 *
294
-	 * @param string $attributeName the name of the attribute, which value should be slugified
295
-	 * @return string slugified value
296
-	 * @since 7.0.0
297
-	 * @deprecated 24.0.0
298
-	 */
299
-	public function slugify(string $attributeName): string {
300
-		// toSlug should only work for existing attributes
301
-		if (property_exists($this, $attributeName)) {
302
-			$value = $this->$attributeName;
303
-			// replace everything except alphanumeric with a single '-'
304
-			$value = preg_replace('/[^A-Za-z0-9]+/', '-', $value);
305
-			$value = strtolower($value);
306
-			// trim '-'
307
-			return trim($value, '-');
308
-		}
309
-
310
-		throw new \BadFunctionCallException($attributeName . ' is not a valid attribute');
311
-	}
22
+    /** @var int $id */
23
+    public $id = null;
24
+
25
+    private array $_updatedFields = [];
26
+    /** @var array<string, \OCP\DB\Types::*> */
27
+    private array $_fieldTypes = ['id' => 'integer'];
28
+
29
+    /**
30
+     * Simple alternative constructor for building entities from a request
31
+     * @param array $params the array which was obtained via $this->params('key')
32
+     *                      in the controller
33
+     * @since 7.0.0
34
+     */
35
+    public static function fromParams(array $params): static {
36
+        $instance = new static();
37
+
38
+        foreach ($params as $key => $value) {
39
+            $method = 'set' . ucfirst($key);
40
+            $instance->$method($value);
41
+        }
42
+
43
+        return $instance;
44
+    }
45
+
46
+
47
+    /**
48
+     * Maps the keys of the row array to the attributes
49
+     * @param array $row the row to map onto the entity
50
+     * @since 7.0.0
51
+     */
52
+    public static function fromRow(array $row): static {
53
+        $instance = new static();
54
+
55
+        foreach ($row as $key => $value) {
56
+            $prop = $instance->columnToProperty($key);
57
+            $instance->setter($prop, [$value]);
58
+        }
59
+
60
+        $instance->resetUpdatedFields();
61
+
62
+        return $instance;
63
+    }
64
+
65
+
66
+    /**
67
+     * @return array<string, \OCP\DB\Types::*> with attribute and type
68
+     * @since 7.0.0
69
+     */
70
+    public function getFieldTypes(): array {
71
+        return $this->_fieldTypes;
72
+    }
73
+
74
+
75
+    /**
76
+     * Marks the entity as clean needed for setting the id after the insertion
77
+     * @since 7.0.0
78
+     */
79
+    public function resetUpdatedFields(): void {
80
+        $this->_updatedFields = [];
81
+    }
82
+
83
+    /**
84
+     * Generic setter for properties
85
+     *
86
+     * @throws \InvalidArgumentException
87
+     * @since 7.0.0
88
+     *
89
+     */
90
+    protected function setter(string $name, array $args): void {
91
+        // setters should only work for existing attributes
92
+        if (!property_exists($this, $name)) {
93
+            throw new \BadFunctionCallException($name . ' is not a valid attribute');
94
+        }
95
+
96
+        if ($args[0] === $this->$name) {
97
+            return;
98
+        }
99
+        $this->markFieldUpdated($name);
100
+
101
+        // if type definition exists, cast to correct type
102
+        if ($args[0] !== null && array_key_exists($name, $this->_fieldTypes)) {
103
+            $type = $this->_fieldTypes[$name];
104
+            if ($type === Types::BLOB) {
105
+                // (B)LOB is treated as string when we read from the DB
106
+                if (is_resource($args[0])) {
107
+                    $args[0] = stream_get_contents($args[0]);
108
+                }
109
+                $type = Types::STRING;
110
+            }
111
+
112
+            switch ($type) {
113
+                case Types::BIGINT:
114
+                case Types::SMALLINT:
115
+                    settype($args[0], Types::INTEGER);
116
+                    break;
117
+                case Types::BINARY:
118
+                case Types::DECIMAL:
119
+                case Types::TEXT:
120
+                    settype($args[0], Types::STRING);
121
+                    break;
122
+                case Types::TIME:
123
+                case Types::DATE:
124
+                case Types::DATETIME:
125
+                case Types::DATETIME_TZ:
126
+                    if (!$args[0] instanceof \DateTime) {
127
+                        $args[0] = new \DateTime($args[0]);
128
+                    }
129
+                    break;
130
+                case Types::TIME_IMMUTABLE:
131
+                case Types::DATE_IMMUTABLE:
132
+                case Types::DATETIME_IMMUTABLE:
133
+                case Types::DATETIME_TZ_IMMUTABLE:
134
+                    if (!$args[0] instanceof \DateTimeImmutable) {
135
+                        $args[0] = new \DateTimeImmutable($args[0]);
136
+                    }
137
+                    break;
138
+                case Types::JSON:
139
+                    if (!is_array($args[0])) {
140
+                        $args[0] = json_decode($args[0], true);
141
+                    }
142
+                    break;
143
+                default:
144
+                    settype($args[0], $type);
145
+            }
146
+        }
147
+        $this->$name = $args[0];
148
+
149
+    }
150
+
151
+    /**
152
+     * Generic getter for properties
153
+     * @since 7.0.0
154
+     */
155
+    protected function getter(string $name): mixed {
156
+        // getters should only work for existing attributes
157
+        if (property_exists($this, $name)) {
158
+            return $this->$name;
159
+        } else {
160
+            throw new \BadFunctionCallException($name
161
+                . ' is not a valid attribute');
162
+        }
163
+    }
164
+
165
+
166
+    /**
167
+     * Each time a setter is called, push the part after set
168
+     * into an array: for instance setId will save Id in the
169
+     * updated fields array so it can be easily used to create the
170
+     * getter method
171
+     * @since 7.0.0
172
+     */
173
+    public function __call(string $methodName, array $args) {
174
+        if (str_starts_with($methodName, 'set')) {
175
+            $this->setter(lcfirst(substr($methodName, 3)), $args);
176
+        } elseif (str_starts_with($methodName, 'get')) {
177
+            return $this->getter(lcfirst(substr($methodName, 3)));
178
+        } elseif ($this->isGetterForBoolProperty($methodName)) {
179
+            return $this->getter(lcfirst(substr($methodName, 2)));
180
+        } else {
181
+            throw new \BadFunctionCallException($methodName
182
+                . ' does not exist');
183
+        }
184
+    }
185
+
186
+    /**
187
+     * @param string $methodName
188
+     * @return bool
189
+     * @since 18.0.0
190
+     */
191
+    protected function isGetterForBoolProperty(string $methodName): bool {
192
+        if (str_starts_with($methodName, 'is')) {
193
+            $fieldName = lcfirst(substr($methodName, 2));
194
+            return isset($this->_fieldTypes[$fieldName]) && str_starts_with($this->_fieldTypes[$fieldName], 'bool');
195
+        }
196
+        return false;
197
+    }
198
+
199
+    /**
200
+     * Mark am attribute as updated
201
+     * @param string $attribute the name of the attribute
202
+     * @since 7.0.0
203
+     */
204
+    protected function markFieldUpdated(string $attribute): void {
205
+        $this->_updatedFields[$attribute] = true;
206
+    }
207
+
208
+
209
+    /**
210
+     * Transform a database columnname to a property
211
+     *
212
+     * @param string $columnName the name of the column
213
+     * @return string the property name
214
+     * @since 7.0.0
215
+     */
216
+    public function columnToProperty(string $columnName) {
217
+        $parts = explode('_', $columnName);
218
+        $property = '';
219
+
220
+        foreach ($parts as $part) {
221
+            if ($property === '') {
222
+                $property = $part;
223
+            } else {
224
+                $property .= ucfirst($part);
225
+            }
226
+        }
227
+
228
+        return $property;
229
+    }
230
+
231
+
232
+    /**
233
+     * Transform a property to a database column name
234
+     *
235
+     * @param string $property the name of the property
236
+     * @return string the column name
237
+     * @since 7.0.0
238
+     */
239
+    public function propertyToColumn(string $property): string {
240
+        $parts = preg_split('/(?=[A-Z])/', $property);
241
+
242
+        $column = '';
243
+        foreach ($parts as $part) {
244
+            if ($column === '') {
245
+                $column = $part;
246
+            } else {
247
+                $column .= '_' . lcfirst($part);
248
+            }
249
+        }
250
+
251
+        return $column;
252
+    }
253
+
254
+
255
+    /**
256
+     * @return array array of updated fields for update query
257
+     * @since 7.0.0
258
+     */
259
+    public function getUpdatedFields(): array {
260
+        return $this->_updatedFields;
261
+    }
262
+
263
+
264
+    /**
265
+     * Adds type information for a field so that it's automatically cast to
266
+     * that value once its being returned from the database
267
+     *
268
+     * @param string $fieldName the name of the attribute
269
+     * @param \OCP\DB\Types::* $type the type which will be used to match a cast
270
+     * @since 31.0.0 Parameter $type is now restricted to {@see \OCP\DB\Types} constants. The formerly accidentally supported types 'int'|'bool'|'double' are mapped to Types::INTEGER|Types::BOOLEAN|Types::FLOAT accordingly.
271
+     * @since 7.0.0
272
+     */
273
+    protected function addType(string $fieldName, string $type): void {
274
+        /** @psalm-suppress TypeDoesNotContainType */
275
+        if (in_array($type, ['bool', 'double', 'int', 'array', 'object'], true)) {
276
+            // Mapping legacy strings to the actual types
277
+            $type = match ($type) {
278
+                'int' => Types::INTEGER,
279
+                'bool' => Types::BOOLEAN,
280
+                'double' => Types::FLOAT,
281
+                'array',
282
+                'object' => Types::STRING,
283
+            };
284
+        }
285
+
286
+        $this->_fieldTypes[$fieldName] = $type;
287
+    }
288
+
289
+
290
+    /**
291
+     * Slugify the value of a given attribute
292
+     * Warning: This doesn't result in a unique value
293
+     *
294
+     * @param string $attributeName the name of the attribute, which value should be slugified
295
+     * @return string slugified value
296
+     * @since 7.0.0
297
+     * @deprecated 24.0.0
298
+     */
299
+    public function slugify(string $attributeName): string {
300
+        // toSlug should only work for existing attributes
301
+        if (property_exists($this, $attributeName)) {
302
+            $value = $this->$attributeName;
303
+            // replace everything except alphanumeric with a single '-'
304
+            $value = preg_replace('/[^A-Za-z0-9]+/', '-', $value);
305
+            $value = strtolower($value);
306
+            // trim '-'
307
+            return trim($value, '-');
308
+        }
309
+
310
+        throw new \BadFunctionCallException($attributeName . ' is not a valid attribute');
311
+    }
312 312
 }
Please login to merge, or discard this patch.
lib/public/DB/ISchemaWrapper.php 1 patch
Indentation   +69 added lines, -69 removed lines patch added patch discarded remove patch
@@ -20,81 +20,81 @@
 block discarded – undo
20 20
  * @since 13.0.0
21 21
  */
22 22
 interface ISchemaWrapper {
23
-	/**
24
-	 * @param string $tableName
25
-	 *
26
-	 * @return \Doctrine\DBAL\Schema\Table
27
-	 * @throws \Doctrine\DBAL\Schema\SchemaException
28
-	 * @since 13.0.0
29
-	 */
30
-	public function getTable($tableName);
23
+    /**
24
+     * @param string $tableName
25
+     *
26
+     * @return \Doctrine\DBAL\Schema\Table
27
+     * @throws \Doctrine\DBAL\Schema\SchemaException
28
+     * @since 13.0.0
29
+     */
30
+    public function getTable($tableName);
31 31
 
32
-	/**
33
-	 * Does this schema have a table with the given name?
34
-	 *
35
-	 * @param string $tableName Prefix is automatically prepended
36
-	 *
37
-	 * @return boolean
38
-	 * @since 13.0.0
39
-	 */
40
-	public function hasTable($tableName);
32
+    /**
33
+     * Does this schema have a table with the given name?
34
+     *
35
+     * @param string $tableName Prefix is automatically prepended
36
+     *
37
+     * @return boolean
38
+     * @since 13.0.0
39
+     */
40
+    public function hasTable($tableName);
41 41
 
42
-	/**
43
-	 * Creates a new table.
44
-	 *
45
-	 * @param string $tableName Prefix is automatically prepended
46
-	 * @return \Doctrine\DBAL\Schema\Table
47
-	 * @since 13.0.0
48
-	 */
49
-	public function createTable($tableName);
42
+    /**
43
+     * Creates a new table.
44
+     *
45
+     * @param string $tableName Prefix is automatically prepended
46
+     * @return \Doctrine\DBAL\Schema\Table
47
+     * @since 13.0.0
48
+     */
49
+    public function createTable($tableName);
50 50
 
51
-	/**
52
-	 * Drops a table from the schema.
53
-	 *
54
-	 * @param string $tableName Prefix is automatically prepended
55
-	 * @return \Doctrine\DBAL\Schema\Schema
56
-	 * @since 13.0.0
57
-	 */
58
-	public function dropTable($tableName);
51
+    /**
52
+     * Drops a table from the schema.
53
+     *
54
+     * @param string $tableName Prefix is automatically prepended
55
+     * @return \Doctrine\DBAL\Schema\Schema
56
+     * @since 13.0.0
57
+     */
58
+    public function dropTable($tableName);
59 59
 
60
-	/**
61
-	 * Gets all tables of this schema.
62
-	 *
63
-	 * @return \Doctrine\DBAL\Schema\Table[]
64
-	 * @since 13.0.0
65
-	 */
66
-	public function getTables();
60
+    /**
61
+     * Gets all tables of this schema.
62
+     *
63
+     * @return \Doctrine\DBAL\Schema\Table[]
64
+     * @since 13.0.0
65
+     */
66
+    public function getTables();
67 67
 
68
-	/**
69
-	 * Gets all table names, prefixed with table prefix
70
-	 *
71
-	 * @return array
72
-	 * @since 13.0.0
73
-	 */
74
-	public function getTableNames();
68
+    /**
69
+     * Gets all table names, prefixed with table prefix
70
+     *
71
+     * @return array
72
+     * @since 13.0.0
73
+     */
74
+    public function getTableNames();
75 75
 
76
-	/**
77
-	 * Gets all table names
78
-	 *
79
-	 * @return array
80
-	 * @since 13.0.0
81
-	 */
82
-	public function getTableNamesWithoutPrefix();
76
+    /**
77
+     * Gets all table names
78
+     *
79
+     * @return array
80
+     * @since 13.0.0
81
+     */
82
+    public function getTableNamesWithoutPrefix();
83 83
 
84
-	/**
85
-	 * Gets the DatabasePlatform for the database.
86
-	 *
87
-	 * @return AbstractPlatform
88
-	 *
89
-	 * @throws Exception
90
-	 * @since 23.0.0
91
-	 */
92
-	public function getDatabasePlatform();
84
+    /**
85
+     * Gets the DatabasePlatform for the database.
86
+     *
87
+     * @return AbstractPlatform
88
+     *
89
+     * @throws Exception
90
+     * @since 23.0.0
91
+     */
92
+    public function getDatabasePlatform();
93 93
 
94
-	/**
95
-	 * Drop autoincrement from an existing table of the database.
96
-	 *
97
-	 * @since 33.0.0
98
-	 */
99
-	public function dropAutoincrementColumn(string $table, string $column): void;
94
+    /**
95
+     * Drop autoincrement from an existing table of the database.
96
+     *
97
+     * @since 33.0.0
98
+     */
99
+    public function dropAutoincrementColumn(string $table, string $column): void;
100 100
 }
Please login to merge, or discard this patch.
lib/public/Snowflake/IGenerator.php 1 patch
Indentation   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -27,20 +27,20 @@
 block discarded – undo
27 27
 #[Consumable(since: '33.0.0')]
28 28
 interface IGenerator {
29 29
 
30
-	/**
31
-	 * Offset applied on timestamps to keep it short
32
-	 * Start from 2025-10-01 at 00:00:00
33
-	 *
34
-	 * @since 33.0
35
-	 */
36
-	public const TS_OFFSET = 1759276800;
30
+    /**
31
+     * Offset applied on timestamps to keep it short
32
+     * Start from 2025-10-01 at 00:00:00
33
+     *
34
+     * @since 33.0
35
+     */
36
+    public const TS_OFFSET = 1759276800;
37 37
 
38
-	/**
39
-	 * Get a new Snowflake ID.
40
-	 *
41
-	 * Each call to this method is guaranteed to return a different ID.
42
-	 *
43
-	 * @since 33.0
44
-	 */
45
-	public function nextId(): string;
38
+    /**
39
+     * Get a new Snowflake ID.
40
+     *
41
+     * Each call to this method is guaranteed to return a different ID.
42
+     *
43
+     * @since 33.0
44
+     */
45
+    public function nextId(): string;
46 46
 }
Please login to merge, or discard this patch.
lib/public/Snowflake/IDecoder.php 1 patch
Indentation   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -19,17 +19,17 @@
 block discarded – undo
19 19
  */
20 20
 #[Consumable(since: '33.0.0')]
21 21
 interface IDecoder {
22
-	/**
23
-	 * Decode information contained into Snowflake ID
24
-	 *
25
-	 * It includes:
26
-	 *  - server ID: identify server on which ID was generated
27
-	 *  - sequence ID: sequence number (number of snowflakes generated in the same second)
28
-	 *  - createdAt: timestamp at which ID was generated
29
-	 *  - isCli: if ID was generated using CLI or not
30
-	 *
31
-	 * @return array{createdAt: \DateTimeImmutable, serverId: int<0,1023>, sequenceId: int<0,4095>, isCli: bool, seconds: positive-int, milliseconds: int<0,999>}
32
-	 * @since 33.0
33
-	 */
34
-	public function decode(string $snowflakeId): array;
22
+    /**
23
+     * Decode information contained into Snowflake ID
24
+     *
25
+     * It includes:
26
+     *  - server ID: identify server on which ID was generated
27
+     *  - sequence ID: sequence number (number of snowflakes generated in the same second)
28
+     *  - createdAt: timestamp at which ID was generated
29
+     *  - isCli: if ID was generated using CLI or not
30
+     *
31
+     * @return array{createdAt: \DateTimeImmutable, serverId: int<0,1023>, sequenceId: int<0,4095>, isCli: bool, seconds: positive-int, milliseconds: int<0,999>}
32
+     * @since 33.0
33
+     */
34
+    public function decode(string $snowflakeId): array;
35 35
 }
Please login to merge, or discard this patch.
lib/private/Server.php 1 patch
Indentation   +1369 added lines, -1369 removed lines patch added patch discarded remove patch
@@ -253,1415 +253,1415 @@
 block discarded – undo
253 253
  * TODO: hookup all manager classes
254 254
  */
255 255
 class Server extends ServerContainer implements IServerContainer {
256
-	/** @var string */
257
-	private $webRoot;
258
-
259
-	/**
260
-	 * @param string $webRoot
261
-	 * @param \OC\Config $config
262
-	 */
263
-	public function __construct($webRoot, \OC\Config $config) {
264
-		parent::__construct();
265
-		$this->webRoot = $webRoot;
266
-
267
-		// To find out if we are running from CLI or not
268
-		$this->registerParameter('isCLI', \OC::$CLI);
269
-		$this->registerParameter('serverRoot', \OC::$SERVERROOT);
270
-
271
-		$this->registerService(ContainerInterface::class, function (ContainerInterface $c) {
272
-			return $c;
273
-		});
274
-		$this->registerDeprecatedAlias(\OCP\IServerContainer::class, ContainerInterface::class);
275
-
276
-		$this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
277
-
278
-		$this->registerAlias(\OCP\Calendar\Resource\IManager::class, \OC\Calendar\Resource\Manager::class);
279
-
280
-		$this->registerAlias(\OCP\Calendar\Room\IManager::class, \OC\Calendar\Room\Manager::class);
281
-
282
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
283
-
284
-		$this->registerAlias(\OCP\ContextChat\IContentManager::class, \OC\ContextChat\ContentManager::class);
285
-
286
-		$this->registerAlias(\OCP\DirectEditing\IManager::class, \OC\DirectEditing\Manager::class);
287
-		$this->registerAlias(ITemplateManager::class, TemplateManager::class);
288
-		$this->registerAlias(\OCP\Template\ITemplateManager::class, \OC\Template\TemplateManager::class);
289
-
290
-		$this->registerAlias(IActionFactory::class, ActionFactory::class);
291
-
292
-		$this->registerService(View::class, function (Server $c) {
293
-			return new View();
294
-		}, false);
295
-
296
-		$this->registerService(IPreview::class, function (ContainerInterface $c) {
297
-			return new PreviewManager(
298
-				$c->get(\OCP\IConfig::class),
299
-				$c->get(IRootFolder::class),
300
-				$c->get(IEventDispatcher::class),
301
-				$c->get(GeneratorHelper::class),
302
-				$c->get(ISession::class)->get('user_id'),
303
-				$c->get(Coordinator::class),
304
-				$c->get(IServerContainer::class),
305
-				$c->get(IBinaryFinder::class),
306
-				$c->get(IMagickSupport::class)
307
-			);
308
-		});
309
-		$this->registerAlias(IMimeIconProvider::class, MimeIconProvider::class);
310
-
311
-		$this->registerService(Watcher::class, function (ContainerInterface $c): Watcher {
312
-			return new Watcher(
313
-				$c->get(\OC\Preview\Storage\StorageFactory::class),
314
-				$c->get(PreviewMapper::class),
315
-				$c->get(IDBConnection::class),
316
-			);
317
-		});
318
-
319
-		$this->registerService(IProfiler::class, function (Server $c) {
320
-			return new Profiler($c->get(SystemConfig::class));
321
-		});
322
-
323
-		$this->registerService(Encryption\Manager::class, function (Server $c): Encryption\Manager {
324
-			$view = new View();
325
-			$util = new Encryption\Util(
326
-				$view,
327
-				$c->get(IUserManager::class),
328
-				$c->get(IGroupManager::class),
329
-				$c->get(\OCP\IConfig::class)
330
-			);
331
-			return new Encryption\Manager(
332
-				$c->get(\OCP\IConfig::class),
333
-				$c->get(LoggerInterface::class),
334
-				$c->getL10N('core'),
335
-				new View(),
336
-				$util,
337
-				new ArrayCache()
338
-			);
339
-		});
340
-		$this->registerAlias(\OCP\Encryption\IManager::class, Encryption\Manager::class);
341
-
342
-		$this->registerService(IFile::class, function (ContainerInterface $c) {
343
-			$util = new Encryption\Util(
344
-				new View(),
345
-				$c->get(IUserManager::class),
346
-				$c->get(IGroupManager::class),
347
-				$c->get(\OCP\IConfig::class)
348
-			);
349
-			return new Encryption\File(
350
-				$util,
351
-				$c->get(IRootFolder::class),
352
-				$c->get(\OCP\Share\IManager::class)
353
-			);
354
-		});
355
-
356
-		$this->registerService(IStorage::class, function (ContainerInterface $c) {
357
-			$view = new View();
358
-			$util = new Encryption\Util(
359
-				$view,
360
-				$c->get(IUserManager::class),
361
-				$c->get(IGroupManager::class),
362
-				$c->get(\OCP\IConfig::class)
363
-			);
364
-
365
-			return new Encryption\Keys\Storage(
366
-				$view,
367
-				$util,
368
-				$c->get(ICrypto::class),
369
-				$c->get(\OCP\IConfig::class)
370
-			);
371
-		});
372
-
373
-		$this->registerAlias(\OCP\ITagManager::class, TagManager::class);
374
-
375
-		$this->registerService('SystemTagManagerFactory', function (ContainerInterface $c) {
376
-			/** @var \OCP\IConfig $config */
377
-			$config = $c->get(\OCP\IConfig::class);
378
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
379
-			return new $factoryClass($this);
380
-		});
381
-		$this->registerService(ISystemTagManager::class, function (ContainerInterface $c) {
382
-			return $c->get('SystemTagManagerFactory')->getManager();
383
-		});
384
-		/** @deprecated 19.0.0 */
385
-		$this->registerDeprecatedAlias('SystemTagManager', ISystemTagManager::class);
386
-
387
-		$this->registerService(ISystemTagObjectMapper::class, function (ContainerInterface $c) {
388
-			return $c->get('SystemTagManagerFactory')->getObjectMapper();
389
-		});
390
-		$this->registerAlias(IFileAccess::class, FileAccess::class);
391
-		$this->registerService('RootFolder', function (ContainerInterface $c) {
392
-			$manager = \OC\Files\Filesystem::getMountManager();
393
-			$view = new View();
394
-			/** @var IUserSession $userSession */
395
-			$userSession = $c->get(IUserSession::class);
396
-			$root = new Root(
397
-				$manager,
398
-				$view,
399
-				$userSession->getUser(),
400
-				$c->get(IUserMountCache::class),
401
-				$this->get(LoggerInterface::class),
402
-				$this->get(IUserManager::class),
403
-				$this->get(IEventDispatcher::class),
404
-				$this->get(ICacheFactory::class),
405
-				$this->get(IAppConfig::class),
406
-			);
407
-
408
-			$previewConnector = new \OC\Preview\WatcherConnector(
409
-				$root,
410
-				$c->get(SystemConfig::class),
411
-				$this->get(IEventDispatcher::class)
412
-			);
413
-			$previewConnector->connectWatcher();
414
-
415
-			return $root;
416
-		});
417
-		$this->registerService(HookConnector::class, function (ContainerInterface $c) {
418
-			return new HookConnector(
419
-				$c->get(IRootFolder::class),
420
-				new View(),
421
-				$c->get(IEventDispatcher::class),
422
-				$c->get(LoggerInterface::class)
423
-			);
424
-		});
425
-
426
-		$this->registerService(IRootFolder::class, function (ContainerInterface $c) {
427
-			return new LazyRoot(function () use ($c) {
428
-				return $c->get('RootFolder');
429
-			});
430
-		});
431
-
432
-		$this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
433
-
434
-		$this->registerService(DisplayNameCache::class, function (ContainerInterface $c) {
435
-			return $c->get(\OC\User\Manager::class)->getDisplayNameCache();
436
-		});
437
-
438
-		$this->registerService(\OCP\IGroupManager::class, function (ContainerInterface $c) {
439
-			$groupManager = new \OC\Group\Manager(
440
-				$this->get(IUserManager::class),
441
-				$this->get(IEventDispatcher::class),
442
-				$this->get(LoggerInterface::class),
443
-				$this->get(ICacheFactory::class),
444
-				$this->get(IRemoteAddress::class),
445
-			);
446
-			return $groupManager;
447
-		});
448
-
449
-		$this->registerService(Store::class, function (ContainerInterface $c) {
450
-			$session = $c->get(ISession::class);
451
-			if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
452
-				$tokenProvider = $c->get(IProvider::class);
453
-			} else {
454
-				$tokenProvider = null;
455
-			}
456
-			$logger = $c->get(LoggerInterface::class);
457
-			$crypto = $c->get(ICrypto::class);
458
-			return new Store($session, $logger, $crypto, $tokenProvider);
459
-		});
460
-		$this->registerAlias(IStore::class, Store::class);
461
-		$this->registerAlias(IProvider::class, Authentication\Token\Manager::class);
462
-		$this->registerAlias(OCPIProvider::class, Authentication\Token\Manager::class);
463
-
464
-		$this->registerService(\OC\User\Session::class, function (Server $c) {
465
-			$manager = $c->get(IUserManager::class);
466
-			$session = new \OC\Session\Memory();
467
-			$timeFactory = new TimeFactory();
468
-			// Token providers might require a working database. This code
469
-			// might however be called when Nextcloud is not yet setup.
470
-			if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
471
-				$provider = $c->get(IProvider::class);
472
-			} else {
473
-				$provider = null;
474
-			}
475
-
476
-			$userSession = new \OC\User\Session(
477
-				$manager,
478
-				$session,
479
-				$timeFactory,
480
-				$provider,
481
-				$c->get(\OCP\IConfig::class),
482
-				$c->get(ISecureRandom::class),
483
-				$c->get('LockdownManager'),
484
-				$c->get(LoggerInterface::class),
485
-				$c->get(IEventDispatcher::class),
486
-			);
487
-			/** @deprecated 21.0.0 use BeforeUserCreatedEvent event with the IEventDispatcher instead */
488
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
489
-				\OC_Hook::emit('OC_User', 'pre_createUser', ['run' => true, 'uid' => $uid, 'password' => $password]);
490
-			});
491
-			/** @deprecated 21.0.0 use UserCreatedEvent event with the IEventDispatcher instead */
492
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
493
-				/** @var \OC\User\User $user */
494
-				\OC_Hook::emit('OC_User', 'post_createUser', ['uid' => $user->getUID(), 'password' => $password]);
495
-			});
496
-			/** @deprecated 21.0.0 use BeforeUserDeletedEvent event with the IEventDispatcher instead */
497
-			$userSession->listen('\OC\User', 'preDelete', function ($user) {
498
-				/** @var \OC\User\User $user */
499
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', ['run' => true, 'uid' => $user->getUID()]);
500
-			});
501
-			/** @deprecated 21.0.0 use UserDeletedEvent event with the IEventDispatcher instead */
502
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
503
-				/** @var \OC\User\User $user */
504
-				\OC_Hook::emit('OC_User', 'post_deleteUser', ['uid' => $user->getUID()]);
505
-			});
506
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
507
-				/** @var \OC\User\User $user */
508
-				\OC_Hook::emit('OC_User', 'pre_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
509
-			});
510
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
511
-				/** @var \OC\User\User $user */
512
-				\OC_Hook::emit('OC_User', 'post_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
513
-			});
514
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
515
-				\OC_Hook::emit('OC_User', 'pre_login', ['run' => true, 'uid' => $uid, 'password' => $password]);
516
-
517
-				/** @var IEventDispatcher $dispatcher */
518
-				$dispatcher = $this->get(IEventDispatcher::class);
519
-				$dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password));
520
-			});
521
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $loginName, $password, $isTokenLogin) {
522
-				/** @var \OC\User\User $user */
523
-				\OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'loginName' => $loginName, 'password' => $password, 'isTokenLogin' => $isTokenLogin]);
524
-
525
-				/** @var IEventDispatcher $dispatcher */
526
-				$dispatcher = $this->get(IEventDispatcher::class);
527
-				$dispatcher->dispatchTyped(new UserLoggedInEvent($user, $loginName, $password, $isTokenLogin));
528
-			});
529
-			$userSession->listen('\OC\User', 'preRememberedLogin', function ($uid) {
530
-				/** @var IEventDispatcher $dispatcher */
531
-				$dispatcher = $this->get(IEventDispatcher::class);
532
-				$dispatcher->dispatchTyped(new BeforeUserLoggedInWithCookieEvent($uid));
533
-			});
534
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
535
-				/** @var \OC\User\User $user */
536
-				\OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password]);
537
-
538
-				/** @var IEventDispatcher $dispatcher */
539
-				$dispatcher = $this->get(IEventDispatcher::class);
540
-				$dispatcher->dispatchTyped(new UserLoggedInWithCookieEvent($user, $password));
541
-			});
542
-			$userSession->listen('\OC\User', 'logout', function ($user) {
543
-				\OC_Hook::emit('OC_User', 'logout', []);
544
-
545
-				/** @var IEventDispatcher $dispatcher */
546
-				$dispatcher = $this->get(IEventDispatcher::class);
547
-				$dispatcher->dispatchTyped(new BeforeUserLoggedOutEvent($user));
548
-			});
549
-			$userSession->listen('\OC\User', 'postLogout', function ($user) {
550
-				/** @var IEventDispatcher $dispatcher */
551
-				$dispatcher = $this->get(IEventDispatcher::class);
552
-				$dispatcher->dispatchTyped(new UserLoggedOutEvent($user));
553
-			});
554
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
555
-				/** @var \OC\User\User $user */
556
-				\OC_Hook::emit('OC_User', 'changeUser', ['run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue]);
557
-			});
558
-			return $userSession;
559
-		});
560
-		$this->registerAlias(\OCP\IUserSession::class, \OC\User\Session::class);
561
-
562
-		$this->registerAlias(\OCP\Authentication\TwoFactorAuth\IRegistry::class, \OC\Authentication\TwoFactorAuth\Registry::class);
563
-
564
-		$this->registerAlias(INavigationManager::class, \OC\NavigationManager::class);
565
-
566
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
567
-
568
-		$this->registerService(\OC\SystemConfig::class, function ($c) use ($config) {
569
-			return new \OC\SystemConfig($config);
570
-		});
571
-
572
-		$this->registerAlias(IAppConfig::class, \OC\AppConfig::class);
573
-		$this->registerAlias(IUserConfig::class, \OC\Config\UserConfig::class);
574
-		$this->registerAlias(IAppManager::class, AppManager::class);
575
-
576
-		$this->registerService(IFactory::class, function (Server $c) {
577
-			return new \OC\L10N\Factory(
578
-				$c->get(\OCP\IConfig::class),
579
-				$c->getRequest(),
580
-				$c->get(IUserSession::class),
581
-				$c->get(ICacheFactory::class),
582
-				\OC::$SERVERROOT,
583
-				$c->get(IAppManager::class),
584
-			);
585
-		});
586
-
587
-		$this->registerAlias(IURLGenerator::class, URLGenerator::class);
588
-
589
-		$this->registerAlias(ICache::class, Cache\File::class);
590
-		$this->registerService(Factory::class, function (Server $c) {
591
-			$profiler = $c->get(IProfiler::class);
592
-			$logger = $c->get(LoggerInterface::class);
593
-			$serverVersion = $c->get(ServerVersion::class);
594
-			/** @var SystemConfig $config */
595
-			$config = $c->get(SystemConfig::class);
596
-			if (!$config->getValue('installed', false) || (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
597
-				return new \OC\Memcache\Factory(
598
-					$logger,
599
-					$profiler,
600
-					$serverVersion,
601
-					ArrayCache::class,
602
-					ArrayCache::class,
603
-					ArrayCache::class
604
-				);
605
-			}
606
-
607
-			return new \OC\Memcache\Factory(
608
-				$logger,
609
-				$profiler,
610
-				$serverVersion,
611
-				/** @psalm-taint-escape callable */
612
-				$config->getValue('memcache.local', null),
613
-				/** @psalm-taint-escape callable */
614
-				$config->getValue('memcache.distributed', null),
615
-				/** @psalm-taint-escape callable */
616
-				$config->getValue('memcache.locking', null),
617
-				/** @psalm-taint-escape callable */
618
-				$config->getValue('redis_log_file')
619
-			);
620
-		});
621
-		$this->registerAlias(ICacheFactory::class, Factory::class);
622
-
623
-		$this->registerService('RedisFactory', function (Server $c) {
624
-			$systemConfig = $c->get(SystemConfig::class);
625
-			return new RedisFactory($systemConfig, $c->get(IEventLogger::class));
626
-		});
627
-
628
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
629
-			$l10n = $this->get(IFactory::class)->get('lib');
630
-			return new \OC\Activity\Manager(
631
-				$c->getRequest(),
632
-				$c->get(IUserSession::class),
633
-				$c->get(\OCP\IConfig::class),
634
-				$c->get(IValidator::class),
635
-				$c->get(IRichTextFormatter::class),
636
-				$l10n,
637
-				$c->get(ITimeFactory::class),
638
-			);
639
-		});
640
-
641
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
642
-			return new \OC\Activity\EventMerger(
643
-				$c->getL10N('lib')
644
-			);
645
-		});
646
-		$this->registerAlias(IValidator::class, Validator::class);
647
-
648
-		$this->registerService(AvatarManager::class, function (Server $c) {
649
-			return new AvatarManager(
650
-				$c->get(IUserSession::class),
651
-				$c->get(\OC\User\Manager::class),
652
-				$c->getAppDataDir('avatar'),
653
-				$c->getL10N('lib'),
654
-				$c->get(LoggerInterface::class),
655
-				$c->get(\OCP\IConfig::class),
656
-				$c->get(IAccountManager::class),
657
-				$c->get(KnownUserService::class)
658
-			);
659
-		});
660
-
661
-		$this->registerAlias(IAvatarManager::class, AvatarManager::class);
662
-
663
-		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
664
-		$this->registerAlias(\OCP\Support\Subscription\IRegistry::class, \OC\Support\Subscription\Registry::class);
665
-		$this->registerAlias(\OCP\Support\Subscription\IAssertion::class, \OC\Support\Subscription\Assertion::class);
666
-
667
-		/** Only used by the PsrLoggerAdapter should not be used by apps */
668
-		$this->registerService(\OC\Log::class, function (Server $c) {
669
-			$logType = $c->get(AllConfig::class)->getSystemValue('log_type', 'file');
670
-			$factory = new LogFactory($c, $this->get(SystemConfig::class));
671
-			$logger = $factory->get($logType);
672
-			$registry = $c->get(\OCP\Support\CrashReport\IRegistry::class);
673
-
674
-			return new Log($logger, $this->get(SystemConfig::class), crashReporters: $registry);
675
-		});
676
-		// PSR-3 logger
677
-		$this->registerAlias(LoggerInterface::class, PsrLoggerAdapter::class);
678
-
679
-		$this->registerService(ILogFactory::class, function (Server $c) {
680
-			return new LogFactory($c, $this->get(SystemConfig::class));
681
-		});
682
-
683
-		$this->registerAlias(IJobList::class, \OC\BackgroundJob\JobList::class);
684
-
685
-		$this->registerService(Router::class, function (Server $c) {
686
-			$cacheFactory = $c->get(ICacheFactory::class);
687
-			if ($cacheFactory->isLocalCacheAvailable()) {
688
-				$router = $c->resolve(CachingRouter::class);
689
-			} else {
690
-				$router = $c->resolve(Router::class);
691
-			}
692
-			return $router;
693
-		});
694
-		$this->registerAlias(IRouter::class, Router::class);
695
-
696
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
697
-			$config = $c->get(\OCP\IConfig::class);
698
-			if (ltrim($config->getSystemValueString('memcache.distributed', ''), '\\') === \OC\Memcache\Redis::class) {
699
-				$backend = new \OC\Security\RateLimiting\Backend\MemoryCacheBackend(
700
-					$c->get(AllConfig::class),
701
-					$this->get(ICacheFactory::class),
702
-					new \OC\AppFramework\Utility\TimeFactory()
703
-				);
704
-			} else {
705
-				$backend = new \OC\Security\RateLimiting\Backend\DatabaseBackend(
706
-					$c->get(AllConfig::class),
707
-					$c->get(IDBConnection::class),
708
-					new \OC\AppFramework\Utility\TimeFactory()
709
-				);
710
-			}
711
-
712
-			return $backend;
713
-		});
714
-
715
-		$this->registerAlias(\OCP\Security\ISecureRandom::class, SecureRandom::class);
716
-		$this->registerAlias(\OCP\Security\IRemoteHostValidator::class, \OC\Security\RemoteHostValidator::class);
717
-		$this->registerAlias(IVerificationToken::class, VerificationToken::class);
718
-
719
-		$this->registerAlias(ICrypto::class, Crypto::class);
720
-
721
-		$this->registerAlias(IHasher::class, Hasher::class);
722
-
723
-		$this->registerAlias(ICredentialsManager::class, CredentialsManager::class);
724
-
725
-		$this->registerAlias(IDBConnection::class, ConnectionAdapter::class);
726
-		$this->registerService(Connection::class, function (Server $c) {
727
-			$systemConfig = $c->get(SystemConfig::class);
728
-			$factory = new \OC\DB\ConnectionFactory($systemConfig, $c->get(ICacheFactory::class));
729
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
730
-			if (!$factory->isValidType($type)) {
731
-				throw new \OC\DatabaseException('Invalid database type');
732
-			}
733
-			$connection = $factory->getConnection($type, []);
734
-			return $connection;
735
-		});
736
-
737
-		$this->registerAlias(ICertificateManager::class, CertificateManager::class);
738
-		$this->registerAlias(IClientService::class, ClientService::class);
739
-		$this->registerService(NegativeDnsCache::class, function (ContainerInterface $c) {
740
-			return new NegativeDnsCache(
741
-				$c->get(ICacheFactory::class),
742
-			);
743
-		});
744
-		$this->registerDeprecatedAlias('HttpClientService', IClientService::class);
745
-		$this->registerService(IEventLogger::class, function (ContainerInterface $c) {
746
-			return new EventLogger($c->get(SystemConfig::class), $c->get(LoggerInterface::class), $c->get(Log::class));
747
-		});
748
-
749
-		$this->registerService(IQueryLogger::class, function (ContainerInterface $c) {
750
-			$queryLogger = new QueryLogger();
751
-			if ($c->get(SystemConfig::class)->getValue('debug', false)) {
752
-				// In debug mode, module is being activated by default
753
-				$queryLogger->activate();
754
-			}
755
-			return $queryLogger;
756
-		});
757
-
758
-		$this->registerAlias(ITempManager::class, TempManager::class);
759
-		$this->registerAlias(IDateTimeZone::class, DateTimeZone::class);
760
-
761
-		$this->registerService(IDateTimeFormatter::class, function (Server $c) {
762
-			$language = $c->get(\OCP\IConfig::class)->getUserValue($c->get(ISession::class)->get('user_id'), 'core', 'lang', null);
763
-
764
-			return new DateTimeFormatter(
765
-				$c->get(IDateTimeZone::class)->getTimeZone(),
766
-				$c->getL10N('lib', $language)
767
-			);
768
-		});
769
-
770
-		$this->registerService(IUserMountCache::class, function (ContainerInterface $c) {
771
-			$mountCache = $c->get(UserMountCache::class);
772
-			$listener = new UserMountCacheListener($mountCache);
773
-			$listener->listen($c->get(IUserManager::class));
774
-			return $mountCache;
775
-		});
776
-
777
-		$this->registerService(IMountProviderCollection::class, function (ContainerInterface $c) {
778
-			$loader = $c->get(IStorageFactory::class);
779
-			$mountCache = $c->get(IUserMountCache::class);
780
-			$eventLogger = $c->get(IEventLogger::class);
781
-			$manager = new MountProviderCollection($loader, $mountCache, $eventLogger);
782
-
783
-			// builtin providers
784
-
785
-			$config = $c->get(\OCP\IConfig::class);
786
-			$logger = $c->get(LoggerInterface::class);
787
-			$objectStoreConfig = $c->get(PrimaryObjectStoreConfig::class);
788
-			$manager->registerProvider(new CacheMountProvider($config));
789
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
790
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($objectStoreConfig));
791
-			$manager->registerRootProvider(new RootMountProvider($objectStoreConfig, $config));
792
-
793
-			return $manager;
794
-		});
795
-
796
-		$this->registerService(IBus::class, function (ContainerInterface $c) {
797
-			$busClass = $c->get(\OCP\IConfig::class)->getSystemValueString('commandbus');
798
-			if ($busClass) {
799
-				[$app, $class] = explode('::', $busClass, 2);
800
-				if ($c->get(IAppManager::class)->isEnabledForUser($app)) {
801
-					$c->get(IAppManager::class)->loadApp($app);
802
-					return $c->get($class);
803
-				} else {
804
-					throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
805
-				}
806
-			} else {
807
-				$jobList = $c->get(IJobList::class);
808
-				return new CronBus($jobList);
809
-			}
810
-		});
811
-		$this->registerDeprecatedAlias('AsyncCommandBus', IBus::class);
812
-		$this->registerAlias(ITrustedDomainHelper::class, TrustedDomainHelper::class);
813
-		$this->registerAlias(IThrottler::class, Throttler::class);
814
-
815
-		$this->registerService(\OC\Security\Bruteforce\Backend\IBackend::class, function ($c) {
816
-			$config = $c->get(\OCP\IConfig::class);
817
-			if (!$config->getSystemValueBool('auth.bruteforce.protection.force.database', false)
818
-				&& ltrim($config->getSystemValueString('memcache.distributed', ''), '\\') === \OC\Memcache\Redis::class) {
819
-				$backend = $c->get(\OC\Security\Bruteforce\Backend\MemoryCacheBackend::class);
820
-			} else {
821
-				$backend = $c->get(\OC\Security\Bruteforce\Backend\DatabaseBackend::class);
822
-			}
823
-
824
-			return $backend;
825
-		});
826
-
827
-		$this->registerDeprecatedAlias('IntegrityCodeChecker', Checker::class);
828
-		$this->registerService(Checker::class, function (ContainerInterface $c) {
829
-			// IConfig requires a working database. This code
830
-			// might however be called when Nextcloud is not yet setup.
831
-			if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
832
-				$config = $c->get(\OCP\IConfig::class);
833
-				$appConfig = $c->get(\OCP\IAppConfig::class);
834
-			} else {
835
-				$config = null;
836
-				$appConfig = null;
837
-			}
838
-
839
-			return new Checker(
840
-				$c->get(ServerVersion::class),
841
-				$c->get(EnvironmentHelper::class),
842
-				new FileAccessHelper(),
843
-				$config,
844
-				$appConfig,
845
-				$c->get(ICacheFactory::class),
846
-				$c->get(IAppManager::class),
847
-				$c->get(IMimeTypeDetector::class)
848
-			);
849
-		});
850
-		$this->registerService(Request::class, function (ContainerInterface $c) {
851
-			if (isset($this['urlParams'])) {
852
-				$urlParams = $this['urlParams'];
853
-			} else {
854
-				$urlParams = [];
855
-			}
856
-
857
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
858
-				&& in_array('fakeinput', stream_get_wrappers())
859
-			) {
860
-				$stream = 'fakeinput://data';
861
-			} else {
862
-				$stream = 'php://input';
863
-			}
864
-
865
-			return new Request(
866
-				[
867
-					'get' => $_GET,
868
-					'post' => $_POST,
869
-					'files' => $_FILES,
870
-					'server' => $_SERVER,
871
-					'env' => $_ENV,
872
-					'cookies' => $_COOKIE,
873
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
874
-						? $_SERVER['REQUEST_METHOD']
875
-						: '',
876
-					'urlParams' => $urlParams,
877
-				],
878
-				$this->get(IRequestId::class),
879
-				$this->get(\OCP\IConfig::class),
880
-				$this->get(CsrfTokenManager::class),
881
-				$stream
882
-			);
883
-		});
884
-		$this->registerAlias(\OCP\IRequest::class, Request::class);
885
-
886
-		$this->registerService(IRequestId::class, function (ContainerInterface $c): IRequestId {
887
-			return new RequestId(
888
-				$_SERVER['UNIQUE_ID'] ?? '',
889
-				$this->get(ISecureRandom::class)
890
-			);
891
-		});
892
-
893
-		/** @since 32.0.0 */
894
-		$this->registerAlias(IEmailValidator::class, EmailValidator::class);
895
-
896
-		$this->registerService(IMailer::class, function (Server $c) {
897
-			return new Mailer(
898
-				$c->get(\OCP\IConfig::class),
899
-				$c->get(LoggerInterface::class),
900
-				$c->get(Defaults::class),
901
-				$c->get(IURLGenerator::class),
902
-				$c->getL10N('lib'),
903
-				$c->get(IEventDispatcher::class),
904
-				$c->get(IFactory::class),
905
-				$c->get(IEmailValidator::class),
906
-			);
907
-		});
908
-
909
-		/** @since 30.0.0 */
910
-		$this->registerAlias(\OCP\Mail\Provider\IManager::class, \OC\Mail\Provider\Manager::class);
911
-
912
-		$this->registerService(ILDAPProviderFactory::class, function (ContainerInterface $c) {
913
-			$config = $c->get(\OCP\IConfig::class);
914
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
915
-			if (is_null($factoryClass) || !class_exists($factoryClass)) {
916
-				return new NullLDAPProviderFactory($this);
917
-			}
918
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
919
-			return new $factoryClass($this);
920
-		});
921
-		$this->registerService(ILDAPProvider::class, function (ContainerInterface $c) {
922
-			$factory = $c->get(ILDAPProviderFactory::class);
923
-			return $factory->getLDAPProvider();
924
-		});
925
-		$this->registerService(ILockingProvider::class, function (ContainerInterface $c) {
926
-			$ini = $c->get(IniGetWrapper::class);
927
-			$config = $c->get(\OCP\IConfig::class);
928
-			$ttl = $config->getSystemValueInt('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
929
-			if ($config->getSystemValueBool('filelocking.enabled', true) || (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
930
-				/** @var \OC\Memcache\Factory $memcacheFactory */
931
-				$memcacheFactory = $c->get(ICacheFactory::class);
932
-				$memcache = $memcacheFactory->createLocking('lock');
933
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
934
-					$timeFactory = $c->get(ITimeFactory::class);
935
-					return new MemcacheLockingProvider($memcache, $timeFactory, $ttl);
936
-				}
937
-				return new DBLockingProvider(
938
-					$c->get(IDBConnection::class),
939
-					new TimeFactory(),
940
-					$ttl,
941
-					!\OC::$CLI
942
-				);
943
-			}
944
-			return new NoopLockingProvider();
945
-		});
946
-
947
-		$this->registerService(ILockManager::class, function (Server $c): LockManager {
948
-			return new LockManager();
949
-		});
950
-
951
-		$this->registerAlias(ILockdownManager::class, 'LockdownManager');
952
-		$this->registerService(SetupManager::class, function ($c) {
953
-			// create the setupmanager through the mount manager to resolve the cyclic dependency
954
-			return $c->get(\OC\Files\Mount\Manager::class)->getSetupManager();
955
-		});
956
-		$this->registerAlias(IMountManager::class, \OC\Files\Mount\Manager::class);
957
-
958
-		$this->registerService(IMimeTypeDetector::class, function (ContainerInterface $c) {
959
-			return new \OC\Files\Type\Detection(
960
-				$c->get(IURLGenerator::class),
961
-				$c->get(LoggerInterface::class),
962
-				\OC::$configDir,
963
-				\OC::$SERVERROOT . '/resources/config/'
964
-			);
965
-		});
966
-
967
-		$this->registerAlias(IMimeTypeLoader::class, Loader::class);
968
-		$this->registerService(BundleFetcher::class, function () {
969
-			return new BundleFetcher($this->getL10N('lib'));
970
-		});
971
-		$this->registerAlias(\OCP\Notification\IManager::class, Manager::class);
972
-
973
-		$this->registerService(CapabilitiesManager::class, function (ContainerInterface $c) {
974
-			$manager = new CapabilitiesManager($c->get(LoggerInterface::class));
975
-			$manager->registerCapability(function () use ($c) {
976
-				return new \OC\OCS\CoreCapabilities($c->get(\OCP\IConfig::class));
977
-			});
978
-			$manager->registerCapability(function () use ($c) {
979
-				return $c->get(\OC\Security\Bruteforce\Capabilities::class);
980
-			});
981
-			return $manager;
982
-		});
983
-
984
-		$this->registerService(ICommentsManager::class, function (Server $c) {
985
-			$config = $c->get(\OCP\IConfig::class);
986
-			$factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
987
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
988
-			$factory = new $factoryClass($this);
989
-			$manager = $factory->getManager();
990
-
991
-			$manager->registerDisplayNameResolver('user', function ($id) use ($c) {
992
-				$manager = $c->get(IUserManager::class);
993
-				$userDisplayName = $manager->getDisplayName($id);
994
-				if ($userDisplayName === null) {
995
-					$l = $c->get(IFactory::class)->get('core');
996
-					return $l->t('Unknown account');
997
-				}
998
-				return $userDisplayName;
999
-			});
1000
-
1001
-			return $manager;
1002
-		});
1003
-
1004
-		$this->registerAlias(\OC_Defaults::class, 'ThemingDefaults');
1005
-		$this->registerService('ThemingDefaults', function (Server $c) {
1006
-			try {
1007
-				$classExists = class_exists('OCA\Theming\ThemingDefaults');
1008
-			} catch (\OCP\AutoloadNotAllowedException $e) {
1009
-				// App disabled or in maintenance mode
1010
-				$classExists = false;
1011
-			}
1012
-
1013
-			if ($classExists && $c->get(\OCP\IConfig::class)->getSystemValueBool('installed', false) && $c->get(IAppManager::class)->isEnabledForAnyone('theming') && $c->get(TrustedDomainHelper::class)->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
1014
-				$backgroundService = new BackgroundService(
1015
-					$c->get(IRootFolder::class),
1016
-					$c->getAppDataDir('theming'),
1017
-					$c->get(IAppConfig::class),
1018
-					$c->get(\OCP\IConfig::class),
1019
-					$c->get(ISession::class)->get('user_id'),
1020
-				);
1021
-				$imageManager = new ImageManager(
1022
-					$c->get(\OCP\IConfig::class),
1023
-					$c->getAppDataDir('theming'),
1024
-					$c->get(IURLGenerator::class),
1025
-					$c->get(ICacheFactory::class),
1026
-					$c->get(LoggerInterface::class),
1027
-					$c->get(ITempManager::class),
1028
-					$backgroundService,
1029
-				);
1030
-				return new ThemingDefaults(
1031
-					$c->get(\OCP\IConfig::class),
1032
-					$c->get(\OCP\IAppConfig::class),
1033
-					$c->getL10N('theming'),
1034
-					$c->get(IUserSession::class),
1035
-					$c->get(IURLGenerator::class),
1036
-					$c->get(ICacheFactory::class),
1037
-					new Util($c->get(ServerVersion::class), $c->get(\OCP\IConfig::class), $this->get(IAppManager::class), $c->getAppDataDir('theming'), $imageManager),
1038
-					$imageManager,
1039
-					$c->get(IAppManager::class),
1040
-					$c->get(INavigationManager::class),
1041
-					$backgroundService,
1042
-				);
1043
-			}
1044
-			return new \OC_Defaults();
1045
-		});
1046
-		$this->registerService(JSCombiner::class, function (Server $c) {
1047
-			return new JSCombiner(
1048
-				$c->getAppDataDir('js'),
1049
-				$c->get(IURLGenerator::class),
1050
-				$this->get(ICacheFactory::class),
1051
-				$c->get(\OCP\IConfig::class),
1052
-				$c->get(LoggerInterface::class)
1053
-			);
1054
-		});
1055
-		$this->registerAlias(\OCP\EventDispatcher\IEventDispatcher::class, \OC\EventDispatcher\EventDispatcher::class);
1056
-
1057
-		$this->registerService('CryptoWrapper', function (ContainerInterface $c) {
1058
-			// FIXME: Instantiated here due to cyclic dependency
1059
-			$request = new Request(
1060
-				[
1061
-					'get' => $_GET,
1062
-					'post' => $_POST,
1063
-					'files' => $_FILES,
1064
-					'server' => $_SERVER,
1065
-					'env' => $_ENV,
1066
-					'cookies' => $_COOKIE,
1067
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
1068
-						? $_SERVER['REQUEST_METHOD']
1069
-						: null,
1070
-				],
1071
-				$c->get(IRequestId::class),
1072
-				$c->get(\OCP\IConfig::class)
1073
-			);
1074
-
1075
-			return new CryptoWrapper(
1076
-				$c->get(ICrypto::class),
1077
-				$c->get(ISecureRandom::class),
1078
-				$request
1079
-			);
1080
-		});
1081
-		$this->registerService(SessionStorage::class, function (ContainerInterface $c) {
1082
-			return new SessionStorage($c->get(ISession::class));
1083
-		});
1084
-		$this->registerAlias(\OCP\Security\IContentSecurityPolicyManager::class, ContentSecurityPolicyManager::class);
1085
-
1086
-		$this->registerService(IProviderFactory::class, function (ContainerInterface $c) {
1087
-			$config = $c->get(\OCP\IConfig::class);
1088
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1089
-			/** @var \OCP\Share\IProviderFactory $factory */
1090
-			return $c->get($factoryClass);
1091
-		});
1092
-
1093
-		$this->registerAlias(\OCP\Share\IManager::class, \OC\Share20\Manager::class);
1094
-
1095
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function (Server $c) {
1096
-			$instance = new Collaboration\Collaborators\Search($c);
1097
-
1098
-			// register default plugins
1099
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1100
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1101
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1102
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1103
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE_GROUP', 'class' => RemoteGroupPlugin::class]);
1104
-
1105
-			return $instance;
1106
-		});
1107
-		$this->registerAlias(\OCP\Collaboration\Collaborators\ISearchResult::class, \OC\Collaboration\Collaborators\SearchResult::class);
1108
-
1109
-		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1110
-
1111
-		$this->registerAlias(\OCP\Collaboration\Resources\IProviderManager::class, \OC\Collaboration\Resources\ProviderManager::class);
1112
-		$this->registerAlias(\OCP\Collaboration\Resources\IManager::class, \OC\Collaboration\Resources\Manager::class);
1113
-
1114
-		$this->registerAlias(IReferenceManager::class, ReferenceManager::class);
1115
-		$this->registerAlias(ITeamManager::class, TeamManager::class);
1116
-
1117
-		$this->registerDeprecatedAlias('SettingsManager', \OC\Settings\Manager::class);
1118
-		$this->registerAlias(\OCP\Settings\IManager::class, \OC\Settings\Manager::class);
1119
-		$this->registerService(\OC\Files\AppData\Factory::class, function (ContainerInterface $c) {
1120
-			return new \OC\Files\AppData\Factory(
1121
-				$c->get(IRootFolder::class),
1122
-				$c->get(SystemConfig::class)
1123
-			);
1124
-		});
1125
-
1126
-		$this->registerService('LockdownManager', function (ContainerInterface $c) {
1127
-			return new LockdownManager(function () use ($c) {
1128
-				return $c->get(ISession::class);
1129
-			});
1130
-		});
1131
-
1132
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (ContainerInterface $c) {
1133
-			return new DiscoveryService(
1134
-				$c->get(ICacheFactory::class),
1135
-				$c->get(IClientService::class)
1136
-			);
1137
-		});
1138
-		$this->registerAlias(IOCMDiscoveryService::class, OCMDiscoveryService::class);
1139
-
1140
-		$this->registerService(ICloudIdManager::class, function (ContainerInterface $c) {
1141
-			return new CloudIdManager(
1142
-				$c->get(ICacheFactory::class),
1143
-				$c->get(IEventDispatcher::class),
1144
-				$c->get(\OCP\Contacts\IManager::class),
1145
-				$c->get(IURLGenerator::class),
1146
-				$c->get(IUserManager::class),
1147
-			);
1148
-		});
256
+    /** @var string */
257
+    private $webRoot;
258
+
259
+    /**
260
+     * @param string $webRoot
261
+     * @param \OC\Config $config
262
+     */
263
+    public function __construct($webRoot, \OC\Config $config) {
264
+        parent::__construct();
265
+        $this->webRoot = $webRoot;
266
+
267
+        // To find out if we are running from CLI or not
268
+        $this->registerParameter('isCLI', \OC::$CLI);
269
+        $this->registerParameter('serverRoot', \OC::$SERVERROOT);
270
+
271
+        $this->registerService(ContainerInterface::class, function (ContainerInterface $c) {
272
+            return $c;
273
+        });
274
+        $this->registerDeprecatedAlias(\OCP\IServerContainer::class, ContainerInterface::class);
275
+
276
+        $this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
277
+
278
+        $this->registerAlias(\OCP\Calendar\Resource\IManager::class, \OC\Calendar\Resource\Manager::class);
279
+
280
+        $this->registerAlias(\OCP\Calendar\Room\IManager::class, \OC\Calendar\Room\Manager::class);
281
+
282
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
283
+
284
+        $this->registerAlias(\OCP\ContextChat\IContentManager::class, \OC\ContextChat\ContentManager::class);
285
+
286
+        $this->registerAlias(\OCP\DirectEditing\IManager::class, \OC\DirectEditing\Manager::class);
287
+        $this->registerAlias(ITemplateManager::class, TemplateManager::class);
288
+        $this->registerAlias(\OCP\Template\ITemplateManager::class, \OC\Template\TemplateManager::class);
289
+
290
+        $this->registerAlias(IActionFactory::class, ActionFactory::class);
291
+
292
+        $this->registerService(View::class, function (Server $c) {
293
+            return new View();
294
+        }, false);
295
+
296
+        $this->registerService(IPreview::class, function (ContainerInterface $c) {
297
+            return new PreviewManager(
298
+                $c->get(\OCP\IConfig::class),
299
+                $c->get(IRootFolder::class),
300
+                $c->get(IEventDispatcher::class),
301
+                $c->get(GeneratorHelper::class),
302
+                $c->get(ISession::class)->get('user_id'),
303
+                $c->get(Coordinator::class),
304
+                $c->get(IServerContainer::class),
305
+                $c->get(IBinaryFinder::class),
306
+                $c->get(IMagickSupport::class)
307
+            );
308
+        });
309
+        $this->registerAlias(IMimeIconProvider::class, MimeIconProvider::class);
310
+
311
+        $this->registerService(Watcher::class, function (ContainerInterface $c): Watcher {
312
+            return new Watcher(
313
+                $c->get(\OC\Preview\Storage\StorageFactory::class),
314
+                $c->get(PreviewMapper::class),
315
+                $c->get(IDBConnection::class),
316
+            );
317
+        });
318
+
319
+        $this->registerService(IProfiler::class, function (Server $c) {
320
+            return new Profiler($c->get(SystemConfig::class));
321
+        });
322
+
323
+        $this->registerService(Encryption\Manager::class, function (Server $c): Encryption\Manager {
324
+            $view = new View();
325
+            $util = new Encryption\Util(
326
+                $view,
327
+                $c->get(IUserManager::class),
328
+                $c->get(IGroupManager::class),
329
+                $c->get(\OCP\IConfig::class)
330
+            );
331
+            return new Encryption\Manager(
332
+                $c->get(\OCP\IConfig::class),
333
+                $c->get(LoggerInterface::class),
334
+                $c->getL10N('core'),
335
+                new View(),
336
+                $util,
337
+                new ArrayCache()
338
+            );
339
+        });
340
+        $this->registerAlias(\OCP\Encryption\IManager::class, Encryption\Manager::class);
341
+
342
+        $this->registerService(IFile::class, function (ContainerInterface $c) {
343
+            $util = new Encryption\Util(
344
+                new View(),
345
+                $c->get(IUserManager::class),
346
+                $c->get(IGroupManager::class),
347
+                $c->get(\OCP\IConfig::class)
348
+            );
349
+            return new Encryption\File(
350
+                $util,
351
+                $c->get(IRootFolder::class),
352
+                $c->get(\OCP\Share\IManager::class)
353
+            );
354
+        });
355
+
356
+        $this->registerService(IStorage::class, function (ContainerInterface $c) {
357
+            $view = new View();
358
+            $util = new Encryption\Util(
359
+                $view,
360
+                $c->get(IUserManager::class),
361
+                $c->get(IGroupManager::class),
362
+                $c->get(\OCP\IConfig::class)
363
+            );
364
+
365
+            return new Encryption\Keys\Storage(
366
+                $view,
367
+                $util,
368
+                $c->get(ICrypto::class),
369
+                $c->get(\OCP\IConfig::class)
370
+            );
371
+        });
372
+
373
+        $this->registerAlias(\OCP\ITagManager::class, TagManager::class);
374
+
375
+        $this->registerService('SystemTagManagerFactory', function (ContainerInterface $c) {
376
+            /** @var \OCP\IConfig $config */
377
+            $config = $c->get(\OCP\IConfig::class);
378
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
379
+            return new $factoryClass($this);
380
+        });
381
+        $this->registerService(ISystemTagManager::class, function (ContainerInterface $c) {
382
+            return $c->get('SystemTagManagerFactory')->getManager();
383
+        });
384
+        /** @deprecated 19.0.0 */
385
+        $this->registerDeprecatedAlias('SystemTagManager', ISystemTagManager::class);
386
+
387
+        $this->registerService(ISystemTagObjectMapper::class, function (ContainerInterface $c) {
388
+            return $c->get('SystemTagManagerFactory')->getObjectMapper();
389
+        });
390
+        $this->registerAlias(IFileAccess::class, FileAccess::class);
391
+        $this->registerService('RootFolder', function (ContainerInterface $c) {
392
+            $manager = \OC\Files\Filesystem::getMountManager();
393
+            $view = new View();
394
+            /** @var IUserSession $userSession */
395
+            $userSession = $c->get(IUserSession::class);
396
+            $root = new Root(
397
+                $manager,
398
+                $view,
399
+                $userSession->getUser(),
400
+                $c->get(IUserMountCache::class),
401
+                $this->get(LoggerInterface::class),
402
+                $this->get(IUserManager::class),
403
+                $this->get(IEventDispatcher::class),
404
+                $this->get(ICacheFactory::class),
405
+                $this->get(IAppConfig::class),
406
+            );
407
+
408
+            $previewConnector = new \OC\Preview\WatcherConnector(
409
+                $root,
410
+                $c->get(SystemConfig::class),
411
+                $this->get(IEventDispatcher::class)
412
+            );
413
+            $previewConnector->connectWatcher();
414
+
415
+            return $root;
416
+        });
417
+        $this->registerService(HookConnector::class, function (ContainerInterface $c) {
418
+            return new HookConnector(
419
+                $c->get(IRootFolder::class),
420
+                new View(),
421
+                $c->get(IEventDispatcher::class),
422
+                $c->get(LoggerInterface::class)
423
+            );
424
+        });
425
+
426
+        $this->registerService(IRootFolder::class, function (ContainerInterface $c) {
427
+            return new LazyRoot(function () use ($c) {
428
+                return $c->get('RootFolder');
429
+            });
430
+        });
431
+
432
+        $this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
433
+
434
+        $this->registerService(DisplayNameCache::class, function (ContainerInterface $c) {
435
+            return $c->get(\OC\User\Manager::class)->getDisplayNameCache();
436
+        });
437
+
438
+        $this->registerService(\OCP\IGroupManager::class, function (ContainerInterface $c) {
439
+            $groupManager = new \OC\Group\Manager(
440
+                $this->get(IUserManager::class),
441
+                $this->get(IEventDispatcher::class),
442
+                $this->get(LoggerInterface::class),
443
+                $this->get(ICacheFactory::class),
444
+                $this->get(IRemoteAddress::class),
445
+            );
446
+            return $groupManager;
447
+        });
448
+
449
+        $this->registerService(Store::class, function (ContainerInterface $c) {
450
+            $session = $c->get(ISession::class);
451
+            if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
452
+                $tokenProvider = $c->get(IProvider::class);
453
+            } else {
454
+                $tokenProvider = null;
455
+            }
456
+            $logger = $c->get(LoggerInterface::class);
457
+            $crypto = $c->get(ICrypto::class);
458
+            return new Store($session, $logger, $crypto, $tokenProvider);
459
+        });
460
+        $this->registerAlias(IStore::class, Store::class);
461
+        $this->registerAlias(IProvider::class, Authentication\Token\Manager::class);
462
+        $this->registerAlias(OCPIProvider::class, Authentication\Token\Manager::class);
463
+
464
+        $this->registerService(\OC\User\Session::class, function (Server $c) {
465
+            $manager = $c->get(IUserManager::class);
466
+            $session = new \OC\Session\Memory();
467
+            $timeFactory = new TimeFactory();
468
+            // Token providers might require a working database. This code
469
+            // might however be called when Nextcloud is not yet setup.
470
+            if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
471
+                $provider = $c->get(IProvider::class);
472
+            } else {
473
+                $provider = null;
474
+            }
475
+
476
+            $userSession = new \OC\User\Session(
477
+                $manager,
478
+                $session,
479
+                $timeFactory,
480
+                $provider,
481
+                $c->get(\OCP\IConfig::class),
482
+                $c->get(ISecureRandom::class),
483
+                $c->get('LockdownManager'),
484
+                $c->get(LoggerInterface::class),
485
+                $c->get(IEventDispatcher::class),
486
+            );
487
+            /** @deprecated 21.0.0 use BeforeUserCreatedEvent event with the IEventDispatcher instead */
488
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
489
+                \OC_Hook::emit('OC_User', 'pre_createUser', ['run' => true, 'uid' => $uid, 'password' => $password]);
490
+            });
491
+            /** @deprecated 21.0.0 use UserCreatedEvent event with the IEventDispatcher instead */
492
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
493
+                /** @var \OC\User\User $user */
494
+                \OC_Hook::emit('OC_User', 'post_createUser', ['uid' => $user->getUID(), 'password' => $password]);
495
+            });
496
+            /** @deprecated 21.0.0 use BeforeUserDeletedEvent event with the IEventDispatcher instead */
497
+            $userSession->listen('\OC\User', 'preDelete', function ($user) {
498
+                /** @var \OC\User\User $user */
499
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', ['run' => true, 'uid' => $user->getUID()]);
500
+            });
501
+            /** @deprecated 21.0.0 use UserDeletedEvent event with the IEventDispatcher instead */
502
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
503
+                /** @var \OC\User\User $user */
504
+                \OC_Hook::emit('OC_User', 'post_deleteUser', ['uid' => $user->getUID()]);
505
+            });
506
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
507
+                /** @var \OC\User\User $user */
508
+                \OC_Hook::emit('OC_User', 'pre_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
509
+            });
510
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
511
+                /** @var \OC\User\User $user */
512
+                \OC_Hook::emit('OC_User', 'post_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
513
+            });
514
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
515
+                \OC_Hook::emit('OC_User', 'pre_login', ['run' => true, 'uid' => $uid, 'password' => $password]);
516
+
517
+                /** @var IEventDispatcher $dispatcher */
518
+                $dispatcher = $this->get(IEventDispatcher::class);
519
+                $dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password));
520
+            });
521
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $loginName, $password, $isTokenLogin) {
522
+                /** @var \OC\User\User $user */
523
+                \OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'loginName' => $loginName, 'password' => $password, 'isTokenLogin' => $isTokenLogin]);
524
+
525
+                /** @var IEventDispatcher $dispatcher */
526
+                $dispatcher = $this->get(IEventDispatcher::class);
527
+                $dispatcher->dispatchTyped(new UserLoggedInEvent($user, $loginName, $password, $isTokenLogin));
528
+            });
529
+            $userSession->listen('\OC\User', 'preRememberedLogin', function ($uid) {
530
+                /** @var IEventDispatcher $dispatcher */
531
+                $dispatcher = $this->get(IEventDispatcher::class);
532
+                $dispatcher->dispatchTyped(new BeforeUserLoggedInWithCookieEvent($uid));
533
+            });
534
+            $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
535
+                /** @var \OC\User\User $user */
536
+                \OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password]);
537
+
538
+                /** @var IEventDispatcher $dispatcher */
539
+                $dispatcher = $this->get(IEventDispatcher::class);
540
+                $dispatcher->dispatchTyped(new UserLoggedInWithCookieEvent($user, $password));
541
+            });
542
+            $userSession->listen('\OC\User', 'logout', function ($user) {
543
+                \OC_Hook::emit('OC_User', 'logout', []);
544
+
545
+                /** @var IEventDispatcher $dispatcher */
546
+                $dispatcher = $this->get(IEventDispatcher::class);
547
+                $dispatcher->dispatchTyped(new BeforeUserLoggedOutEvent($user));
548
+            });
549
+            $userSession->listen('\OC\User', 'postLogout', function ($user) {
550
+                /** @var IEventDispatcher $dispatcher */
551
+                $dispatcher = $this->get(IEventDispatcher::class);
552
+                $dispatcher->dispatchTyped(new UserLoggedOutEvent($user));
553
+            });
554
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
555
+                /** @var \OC\User\User $user */
556
+                \OC_Hook::emit('OC_User', 'changeUser', ['run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue]);
557
+            });
558
+            return $userSession;
559
+        });
560
+        $this->registerAlias(\OCP\IUserSession::class, \OC\User\Session::class);
561
+
562
+        $this->registerAlias(\OCP\Authentication\TwoFactorAuth\IRegistry::class, \OC\Authentication\TwoFactorAuth\Registry::class);
563
+
564
+        $this->registerAlias(INavigationManager::class, \OC\NavigationManager::class);
565
+
566
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
567
+
568
+        $this->registerService(\OC\SystemConfig::class, function ($c) use ($config) {
569
+            return new \OC\SystemConfig($config);
570
+        });
571
+
572
+        $this->registerAlias(IAppConfig::class, \OC\AppConfig::class);
573
+        $this->registerAlias(IUserConfig::class, \OC\Config\UserConfig::class);
574
+        $this->registerAlias(IAppManager::class, AppManager::class);
575
+
576
+        $this->registerService(IFactory::class, function (Server $c) {
577
+            return new \OC\L10N\Factory(
578
+                $c->get(\OCP\IConfig::class),
579
+                $c->getRequest(),
580
+                $c->get(IUserSession::class),
581
+                $c->get(ICacheFactory::class),
582
+                \OC::$SERVERROOT,
583
+                $c->get(IAppManager::class),
584
+            );
585
+        });
586
+
587
+        $this->registerAlias(IURLGenerator::class, URLGenerator::class);
588
+
589
+        $this->registerAlias(ICache::class, Cache\File::class);
590
+        $this->registerService(Factory::class, function (Server $c) {
591
+            $profiler = $c->get(IProfiler::class);
592
+            $logger = $c->get(LoggerInterface::class);
593
+            $serverVersion = $c->get(ServerVersion::class);
594
+            /** @var SystemConfig $config */
595
+            $config = $c->get(SystemConfig::class);
596
+            if (!$config->getValue('installed', false) || (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
597
+                return new \OC\Memcache\Factory(
598
+                    $logger,
599
+                    $profiler,
600
+                    $serverVersion,
601
+                    ArrayCache::class,
602
+                    ArrayCache::class,
603
+                    ArrayCache::class
604
+                );
605
+            }
606
+
607
+            return new \OC\Memcache\Factory(
608
+                $logger,
609
+                $profiler,
610
+                $serverVersion,
611
+                /** @psalm-taint-escape callable */
612
+                $config->getValue('memcache.local', null),
613
+                /** @psalm-taint-escape callable */
614
+                $config->getValue('memcache.distributed', null),
615
+                /** @psalm-taint-escape callable */
616
+                $config->getValue('memcache.locking', null),
617
+                /** @psalm-taint-escape callable */
618
+                $config->getValue('redis_log_file')
619
+            );
620
+        });
621
+        $this->registerAlias(ICacheFactory::class, Factory::class);
622
+
623
+        $this->registerService('RedisFactory', function (Server $c) {
624
+            $systemConfig = $c->get(SystemConfig::class);
625
+            return new RedisFactory($systemConfig, $c->get(IEventLogger::class));
626
+        });
627
+
628
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
629
+            $l10n = $this->get(IFactory::class)->get('lib');
630
+            return new \OC\Activity\Manager(
631
+                $c->getRequest(),
632
+                $c->get(IUserSession::class),
633
+                $c->get(\OCP\IConfig::class),
634
+                $c->get(IValidator::class),
635
+                $c->get(IRichTextFormatter::class),
636
+                $l10n,
637
+                $c->get(ITimeFactory::class),
638
+            );
639
+        });
640
+
641
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
642
+            return new \OC\Activity\EventMerger(
643
+                $c->getL10N('lib')
644
+            );
645
+        });
646
+        $this->registerAlias(IValidator::class, Validator::class);
647
+
648
+        $this->registerService(AvatarManager::class, function (Server $c) {
649
+            return new AvatarManager(
650
+                $c->get(IUserSession::class),
651
+                $c->get(\OC\User\Manager::class),
652
+                $c->getAppDataDir('avatar'),
653
+                $c->getL10N('lib'),
654
+                $c->get(LoggerInterface::class),
655
+                $c->get(\OCP\IConfig::class),
656
+                $c->get(IAccountManager::class),
657
+                $c->get(KnownUserService::class)
658
+            );
659
+        });
660
+
661
+        $this->registerAlias(IAvatarManager::class, AvatarManager::class);
662
+
663
+        $this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
664
+        $this->registerAlias(\OCP\Support\Subscription\IRegistry::class, \OC\Support\Subscription\Registry::class);
665
+        $this->registerAlias(\OCP\Support\Subscription\IAssertion::class, \OC\Support\Subscription\Assertion::class);
666
+
667
+        /** Only used by the PsrLoggerAdapter should not be used by apps */
668
+        $this->registerService(\OC\Log::class, function (Server $c) {
669
+            $logType = $c->get(AllConfig::class)->getSystemValue('log_type', 'file');
670
+            $factory = new LogFactory($c, $this->get(SystemConfig::class));
671
+            $logger = $factory->get($logType);
672
+            $registry = $c->get(\OCP\Support\CrashReport\IRegistry::class);
673
+
674
+            return new Log($logger, $this->get(SystemConfig::class), crashReporters: $registry);
675
+        });
676
+        // PSR-3 logger
677
+        $this->registerAlias(LoggerInterface::class, PsrLoggerAdapter::class);
678
+
679
+        $this->registerService(ILogFactory::class, function (Server $c) {
680
+            return new LogFactory($c, $this->get(SystemConfig::class));
681
+        });
682
+
683
+        $this->registerAlias(IJobList::class, \OC\BackgroundJob\JobList::class);
684
+
685
+        $this->registerService(Router::class, function (Server $c) {
686
+            $cacheFactory = $c->get(ICacheFactory::class);
687
+            if ($cacheFactory->isLocalCacheAvailable()) {
688
+                $router = $c->resolve(CachingRouter::class);
689
+            } else {
690
+                $router = $c->resolve(Router::class);
691
+            }
692
+            return $router;
693
+        });
694
+        $this->registerAlias(IRouter::class, Router::class);
695
+
696
+        $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
697
+            $config = $c->get(\OCP\IConfig::class);
698
+            if (ltrim($config->getSystemValueString('memcache.distributed', ''), '\\') === \OC\Memcache\Redis::class) {
699
+                $backend = new \OC\Security\RateLimiting\Backend\MemoryCacheBackend(
700
+                    $c->get(AllConfig::class),
701
+                    $this->get(ICacheFactory::class),
702
+                    new \OC\AppFramework\Utility\TimeFactory()
703
+                );
704
+            } else {
705
+                $backend = new \OC\Security\RateLimiting\Backend\DatabaseBackend(
706
+                    $c->get(AllConfig::class),
707
+                    $c->get(IDBConnection::class),
708
+                    new \OC\AppFramework\Utility\TimeFactory()
709
+                );
710
+            }
711
+
712
+            return $backend;
713
+        });
714
+
715
+        $this->registerAlias(\OCP\Security\ISecureRandom::class, SecureRandom::class);
716
+        $this->registerAlias(\OCP\Security\IRemoteHostValidator::class, \OC\Security\RemoteHostValidator::class);
717
+        $this->registerAlias(IVerificationToken::class, VerificationToken::class);
718
+
719
+        $this->registerAlias(ICrypto::class, Crypto::class);
720
+
721
+        $this->registerAlias(IHasher::class, Hasher::class);
722
+
723
+        $this->registerAlias(ICredentialsManager::class, CredentialsManager::class);
724
+
725
+        $this->registerAlias(IDBConnection::class, ConnectionAdapter::class);
726
+        $this->registerService(Connection::class, function (Server $c) {
727
+            $systemConfig = $c->get(SystemConfig::class);
728
+            $factory = new \OC\DB\ConnectionFactory($systemConfig, $c->get(ICacheFactory::class));
729
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
730
+            if (!$factory->isValidType($type)) {
731
+                throw new \OC\DatabaseException('Invalid database type');
732
+            }
733
+            $connection = $factory->getConnection($type, []);
734
+            return $connection;
735
+        });
736
+
737
+        $this->registerAlias(ICertificateManager::class, CertificateManager::class);
738
+        $this->registerAlias(IClientService::class, ClientService::class);
739
+        $this->registerService(NegativeDnsCache::class, function (ContainerInterface $c) {
740
+            return new NegativeDnsCache(
741
+                $c->get(ICacheFactory::class),
742
+            );
743
+        });
744
+        $this->registerDeprecatedAlias('HttpClientService', IClientService::class);
745
+        $this->registerService(IEventLogger::class, function (ContainerInterface $c) {
746
+            return new EventLogger($c->get(SystemConfig::class), $c->get(LoggerInterface::class), $c->get(Log::class));
747
+        });
748
+
749
+        $this->registerService(IQueryLogger::class, function (ContainerInterface $c) {
750
+            $queryLogger = new QueryLogger();
751
+            if ($c->get(SystemConfig::class)->getValue('debug', false)) {
752
+                // In debug mode, module is being activated by default
753
+                $queryLogger->activate();
754
+            }
755
+            return $queryLogger;
756
+        });
757
+
758
+        $this->registerAlias(ITempManager::class, TempManager::class);
759
+        $this->registerAlias(IDateTimeZone::class, DateTimeZone::class);
760
+
761
+        $this->registerService(IDateTimeFormatter::class, function (Server $c) {
762
+            $language = $c->get(\OCP\IConfig::class)->getUserValue($c->get(ISession::class)->get('user_id'), 'core', 'lang', null);
763
+
764
+            return new DateTimeFormatter(
765
+                $c->get(IDateTimeZone::class)->getTimeZone(),
766
+                $c->getL10N('lib', $language)
767
+            );
768
+        });
769
+
770
+        $this->registerService(IUserMountCache::class, function (ContainerInterface $c) {
771
+            $mountCache = $c->get(UserMountCache::class);
772
+            $listener = new UserMountCacheListener($mountCache);
773
+            $listener->listen($c->get(IUserManager::class));
774
+            return $mountCache;
775
+        });
776
+
777
+        $this->registerService(IMountProviderCollection::class, function (ContainerInterface $c) {
778
+            $loader = $c->get(IStorageFactory::class);
779
+            $mountCache = $c->get(IUserMountCache::class);
780
+            $eventLogger = $c->get(IEventLogger::class);
781
+            $manager = new MountProviderCollection($loader, $mountCache, $eventLogger);
782
+
783
+            // builtin providers
784
+
785
+            $config = $c->get(\OCP\IConfig::class);
786
+            $logger = $c->get(LoggerInterface::class);
787
+            $objectStoreConfig = $c->get(PrimaryObjectStoreConfig::class);
788
+            $manager->registerProvider(new CacheMountProvider($config));
789
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
790
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($objectStoreConfig));
791
+            $manager->registerRootProvider(new RootMountProvider($objectStoreConfig, $config));
792
+
793
+            return $manager;
794
+        });
795
+
796
+        $this->registerService(IBus::class, function (ContainerInterface $c) {
797
+            $busClass = $c->get(\OCP\IConfig::class)->getSystemValueString('commandbus');
798
+            if ($busClass) {
799
+                [$app, $class] = explode('::', $busClass, 2);
800
+                if ($c->get(IAppManager::class)->isEnabledForUser($app)) {
801
+                    $c->get(IAppManager::class)->loadApp($app);
802
+                    return $c->get($class);
803
+                } else {
804
+                    throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
805
+                }
806
+            } else {
807
+                $jobList = $c->get(IJobList::class);
808
+                return new CronBus($jobList);
809
+            }
810
+        });
811
+        $this->registerDeprecatedAlias('AsyncCommandBus', IBus::class);
812
+        $this->registerAlias(ITrustedDomainHelper::class, TrustedDomainHelper::class);
813
+        $this->registerAlias(IThrottler::class, Throttler::class);
814
+
815
+        $this->registerService(\OC\Security\Bruteforce\Backend\IBackend::class, function ($c) {
816
+            $config = $c->get(\OCP\IConfig::class);
817
+            if (!$config->getSystemValueBool('auth.bruteforce.protection.force.database', false)
818
+                && ltrim($config->getSystemValueString('memcache.distributed', ''), '\\') === \OC\Memcache\Redis::class) {
819
+                $backend = $c->get(\OC\Security\Bruteforce\Backend\MemoryCacheBackend::class);
820
+            } else {
821
+                $backend = $c->get(\OC\Security\Bruteforce\Backend\DatabaseBackend::class);
822
+            }
823
+
824
+            return $backend;
825
+        });
826
+
827
+        $this->registerDeprecatedAlias('IntegrityCodeChecker', Checker::class);
828
+        $this->registerService(Checker::class, function (ContainerInterface $c) {
829
+            // IConfig requires a working database. This code
830
+            // might however be called when Nextcloud is not yet setup.
831
+            if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
832
+                $config = $c->get(\OCP\IConfig::class);
833
+                $appConfig = $c->get(\OCP\IAppConfig::class);
834
+            } else {
835
+                $config = null;
836
+                $appConfig = null;
837
+            }
838
+
839
+            return new Checker(
840
+                $c->get(ServerVersion::class),
841
+                $c->get(EnvironmentHelper::class),
842
+                new FileAccessHelper(),
843
+                $config,
844
+                $appConfig,
845
+                $c->get(ICacheFactory::class),
846
+                $c->get(IAppManager::class),
847
+                $c->get(IMimeTypeDetector::class)
848
+            );
849
+        });
850
+        $this->registerService(Request::class, function (ContainerInterface $c) {
851
+            if (isset($this['urlParams'])) {
852
+                $urlParams = $this['urlParams'];
853
+            } else {
854
+                $urlParams = [];
855
+            }
856
+
857
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
858
+                && in_array('fakeinput', stream_get_wrappers())
859
+            ) {
860
+                $stream = 'fakeinput://data';
861
+            } else {
862
+                $stream = 'php://input';
863
+            }
864
+
865
+            return new Request(
866
+                [
867
+                    'get' => $_GET,
868
+                    'post' => $_POST,
869
+                    'files' => $_FILES,
870
+                    'server' => $_SERVER,
871
+                    'env' => $_ENV,
872
+                    'cookies' => $_COOKIE,
873
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
874
+                        ? $_SERVER['REQUEST_METHOD']
875
+                        : '',
876
+                    'urlParams' => $urlParams,
877
+                ],
878
+                $this->get(IRequestId::class),
879
+                $this->get(\OCP\IConfig::class),
880
+                $this->get(CsrfTokenManager::class),
881
+                $stream
882
+            );
883
+        });
884
+        $this->registerAlias(\OCP\IRequest::class, Request::class);
885
+
886
+        $this->registerService(IRequestId::class, function (ContainerInterface $c): IRequestId {
887
+            return new RequestId(
888
+                $_SERVER['UNIQUE_ID'] ?? '',
889
+                $this->get(ISecureRandom::class)
890
+            );
891
+        });
892
+
893
+        /** @since 32.0.0 */
894
+        $this->registerAlias(IEmailValidator::class, EmailValidator::class);
895
+
896
+        $this->registerService(IMailer::class, function (Server $c) {
897
+            return new Mailer(
898
+                $c->get(\OCP\IConfig::class),
899
+                $c->get(LoggerInterface::class),
900
+                $c->get(Defaults::class),
901
+                $c->get(IURLGenerator::class),
902
+                $c->getL10N('lib'),
903
+                $c->get(IEventDispatcher::class),
904
+                $c->get(IFactory::class),
905
+                $c->get(IEmailValidator::class),
906
+            );
907
+        });
908
+
909
+        /** @since 30.0.0 */
910
+        $this->registerAlias(\OCP\Mail\Provider\IManager::class, \OC\Mail\Provider\Manager::class);
911
+
912
+        $this->registerService(ILDAPProviderFactory::class, function (ContainerInterface $c) {
913
+            $config = $c->get(\OCP\IConfig::class);
914
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
915
+            if (is_null($factoryClass) || !class_exists($factoryClass)) {
916
+                return new NullLDAPProviderFactory($this);
917
+            }
918
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
919
+            return new $factoryClass($this);
920
+        });
921
+        $this->registerService(ILDAPProvider::class, function (ContainerInterface $c) {
922
+            $factory = $c->get(ILDAPProviderFactory::class);
923
+            return $factory->getLDAPProvider();
924
+        });
925
+        $this->registerService(ILockingProvider::class, function (ContainerInterface $c) {
926
+            $ini = $c->get(IniGetWrapper::class);
927
+            $config = $c->get(\OCP\IConfig::class);
928
+            $ttl = $config->getSystemValueInt('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
929
+            if ($config->getSystemValueBool('filelocking.enabled', true) || (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
930
+                /** @var \OC\Memcache\Factory $memcacheFactory */
931
+                $memcacheFactory = $c->get(ICacheFactory::class);
932
+                $memcache = $memcacheFactory->createLocking('lock');
933
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
934
+                    $timeFactory = $c->get(ITimeFactory::class);
935
+                    return new MemcacheLockingProvider($memcache, $timeFactory, $ttl);
936
+                }
937
+                return new DBLockingProvider(
938
+                    $c->get(IDBConnection::class),
939
+                    new TimeFactory(),
940
+                    $ttl,
941
+                    !\OC::$CLI
942
+                );
943
+            }
944
+            return new NoopLockingProvider();
945
+        });
946
+
947
+        $this->registerService(ILockManager::class, function (Server $c): LockManager {
948
+            return new LockManager();
949
+        });
950
+
951
+        $this->registerAlias(ILockdownManager::class, 'LockdownManager');
952
+        $this->registerService(SetupManager::class, function ($c) {
953
+            // create the setupmanager through the mount manager to resolve the cyclic dependency
954
+            return $c->get(\OC\Files\Mount\Manager::class)->getSetupManager();
955
+        });
956
+        $this->registerAlias(IMountManager::class, \OC\Files\Mount\Manager::class);
957
+
958
+        $this->registerService(IMimeTypeDetector::class, function (ContainerInterface $c) {
959
+            return new \OC\Files\Type\Detection(
960
+                $c->get(IURLGenerator::class),
961
+                $c->get(LoggerInterface::class),
962
+                \OC::$configDir,
963
+                \OC::$SERVERROOT . '/resources/config/'
964
+            );
965
+        });
966
+
967
+        $this->registerAlias(IMimeTypeLoader::class, Loader::class);
968
+        $this->registerService(BundleFetcher::class, function () {
969
+            return new BundleFetcher($this->getL10N('lib'));
970
+        });
971
+        $this->registerAlias(\OCP\Notification\IManager::class, Manager::class);
972
+
973
+        $this->registerService(CapabilitiesManager::class, function (ContainerInterface $c) {
974
+            $manager = new CapabilitiesManager($c->get(LoggerInterface::class));
975
+            $manager->registerCapability(function () use ($c) {
976
+                return new \OC\OCS\CoreCapabilities($c->get(\OCP\IConfig::class));
977
+            });
978
+            $manager->registerCapability(function () use ($c) {
979
+                return $c->get(\OC\Security\Bruteforce\Capabilities::class);
980
+            });
981
+            return $manager;
982
+        });
983
+
984
+        $this->registerService(ICommentsManager::class, function (Server $c) {
985
+            $config = $c->get(\OCP\IConfig::class);
986
+            $factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
987
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
988
+            $factory = new $factoryClass($this);
989
+            $manager = $factory->getManager();
990
+
991
+            $manager->registerDisplayNameResolver('user', function ($id) use ($c) {
992
+                $manager = $c->get(IUserManager::class);
993
+                $userDisplayName = $manager->getDisplayName($id);
994
+                if ($userDisplayName === null) {
995
+                    $l = $c->get(IFactory::class)->get('core');
996
+                    return $l->t('Unknown account');
997
+                }
998
+                return $userDisplayName;
999
+            });
1000
+
1001
+            return $manager;
1002
+        });
1003
+
1004
+        $this->registerAlias(\OC_Defaults::class, 'ThemingDefaults');
1005
+        $this->registerService('ThemingDefaults', function (Server $c) {
1006
+            try {
1007
+                $classExists = class_exists('OCA\Theming\ThemingDefaults');
1008
+            } catch (\OCP\AutoloadNotAllowedException $e) {
1009
+                // App disabled or in maintenance mode
1010
+                $classExists = false;
1011
+            }
1012
+
1013
+            if ($classExists && $c->get(\OCP\IConfig::class)->getSystemValueBool('installed', false) && $c->get(IAppManager::class)->isEnabledForAnyone('theming') && $c->get(TrustedDomainHelper::class)->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
1014
+                $backgroundService = new BackgroundService(
1015
+                    $c->get(IRootFolder::class),
1016
+                    $c->getAppDataDir('theming'),
1017
+                    $c->get(IAppConfig::class),
1018
+                    $c->get(\OCP\IConfig::class),
1019
+                    $c->get(ISession::class)->get('user_id'),
1020
+                );
1021
+                $imageManager = new ImageManager(
1022
+                    $c->get(\OCP\IConfig::class),
1023
+                    $c->getAppDataDir('theming'),
1024
+                    $c->get(IURLGenerator::class),
1025
+                    $c->get(ICacheFactory::class),
1026
+                    $c->get(LoggerInterface::class),
1027
+                    $c->get(ITempManager::class),
1028
+                    $backgroundService,
1029
+                );
1030
+                return new ThemingDefaults(
1031
+                    $c->get(\OCP\IConfig::class),
1032
+                    $c->get(\OCP\IAppConfig::class),
1033
+                    $c->getL10N('theming'),
1034
+                    $c->get(IUserSession::class),
1035
+                    $c->get(IURLGenerator::class),
1036
+                    $c->get(ICacheFactory::class),
1037
+                    new Util($c->get(ServerVersion::class), $c->get(\OCP\IConfig::class), $this->get(IAppManager::class), $c->getAppDataDir('theming'), $imageManager),
1038
+                    $imageManager,
1039
+                    $c->get(IAppManager::class),
1040
+                    $c->get(INavigationManager::class),
1041
+                    $backgroundService,
1042
+                );
1043
+            }
1044
+            return new \OC_Defaults();
1045
+        });
1046
+        $this->registerService(JSCombiner::class, function (Server $c) {
1047
+            return new JSCombiner(
1048
+                $c->getAppDataDir('js'),
1049
+                $c->get(IURLGenerator::class),
1050
+                $this->get(ICacheFactory::class),
1051
+                $c->get(\OCP\IConfig::class),
1052
+                $c->get(LoggerInterface::class)
1053
+            );
1054
+        });
1055
+        $this->registerAlias(\OCP\EventDispatcher\IEventDispatcher::class, \OC\EventDispatcher\EventDispatcher::class);
1056
+
1057
+        $this->registerService('CryptoWrapper', function (ContainerInterface $c) {
1058
+            // FIXME: Instantiated here due to cyclic dependency
1059
+            $request = new Request(
1060
+                [
1061
+                    'get' => $_GET,
1062
+                    'post' => $_POST,
1063
+                    'files' => $_FILES,
1064
+                    'server' => $_SERVER,
1065
+                    'env' => $_ENV,
1066
+                    'cookies' => $_COOKIE,
1067
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
1068
+                        ? $_SERVER['REQUEST_METHOD']
1069
+                        : null,
1070
+                ],
1071
+                $c->get(IRequestId::class),
1072
+                $c->get(\OCP\IConfig::class)
1073
+            );
1074
+
1075
+            return new CryptoWrapper(
1076
+                $c->get(ICrypto::class),
1077
+                $c->get(ISecureRandom::class),
1078
+                $request
1079
+            );
1080
+        });
1081
+        $this->registerService(SessionStorage::class, function (ContainerInterface $c) {
1082
+            return new SessionStorage($c->get(ISession::class));
1083
+        });
1084
+        $this->registerAlias(\OCP\Security\IContentSecurityPolicyManager::class, ContentSecurityPolicyManager::class);
1085
+
1086
+        $this->registerService(IProviderFactory::class, function (ContainerInterface $c) {
1087
+            $config = $c->get(\OCP\IConfig::class);
1088
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1089
+            /** @var \OCP\Share\IProviderFactory $factory */
1090
+            return $c->get($factoryClass);
1091
+        });
1092
+
1093
+        $this->registerAlias(\OCP\Share\IManager::class, \OC\Share20\Manager::class);
1094
+
1095
+        $this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function (Server $c) {
1096
+            $instance = new Collaboration\Collaborators\Search($c);
1097
+
1098
+            // register default plugins
1099
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1100
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1101
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1102
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1103
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE_GROUP', 'class' => RemoteGroupPlugin::class]);
1104
+
1105
+            return $instance;
1106
+        });
1107
+        $this->registerAlias(\OCP\Collaboration\Collaborators\ISearchResult::class, \OC\Collaboration\Collaborators\SearchResult::class);
1108
+
1109
+        $this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1110
+
1111
+        $this->registerAlias(\OCP\Collaboration\Resources\IProviderManager::class, \OC\Collaboration\Resources\ProviderManager::class);
1112
+        $this->registerAlias(\OCP\Collaboration\Resources\IManager::class, \OC\Collaboration\Resources\Manager::class);
1113
+
1114
+        $this->registerAlias(IReferenceManager::class, ReferenceManager::class);
1115
+        $this->registerAlias(ITeamManager::class, TeamManager::class);
1116
+
1117
+        $this->registerDeprecatedAlias('SettingsManager', \OC\Settings\Manager::class);
1118
+        $this->registerAlias(\OCP\Settings\IManager::class, \OC\Settings\Manager::class);
1119
+        $this->registerService(\OC\Files\AppData\Factory::class, function (ContainerInterface $c) {
1120
+            return new \OC\Files\AppData\Factory(
1121
+                $c->get(IRootFolder::class),
1122
+                $c->get(SystemConfig::class)
1123
+            );
1124
+        });
1125
+
1126
+        $this->registerService('LockdownManager', function (ContainerInterface $c) {
1127
+            return new LockdownManager(function () use ($c) {
1128
+                return $c->get(ISession::class);
1129
+            });
1130
+        });
1131
+
1132
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (ContainerInterface $c) {
1133
+            return new DiscoveryService(
1134
+                $c->get(ICacheFactory::class),
1135
+                $c->get(IClientService::class)
1136
+            );
1137
+        });
1138
+        $this->registerAlias(IOCMDiscoveryService::class, OCMDiscoveryService::class);
1139
+
1140
+        $this->registerService(ICloudIdManager::class, function (ContainerInterface $c) {
1141
+            return new CloudIdManager(
1142
+                $c->get(ICacheFactory::class),
1143
+                $c->get(IEventDispatcher::class),
1144
+                $c->get(\OCP\Contacts\IManager::class),
1145
+                $c->get(IURLGenerator::class),
1146
+                $c->get(IUserManager::class),
1147
+            );
1148
+        });
1149 1149
 
1150
-		$this->registerAlias(\OCP\GlobalScale\IConfig::class, \OC\GlobalScale\Config::class);
1151
-		$this->registerAlias(ICloudFederationProviderManager::class, CloudFederationProviderManager::class);
1152
-		$this->registerService(ICloudFederationFactory::class, function (Server $c) {
1153
-			return new CloudFederationFactory();
1154
-		});
1150
+        $this->registerAlias(\OCP\GlobalScale\IConfig::class, \OC\GlobalScale\Config::class);
1151
+        $this->registerAlias(ICloudFederationProviderManager::class, CloudFederationProviderManager::class);
1152
+        $this->registerService(ICloudFederationFactory::class, function (Server $c) {
1153
+            return new CloudFederationFactory();
1154
+        });
1155 1155
 
1156
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1156
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1157 1157
 
1158
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1159
-		$this->registerAlias(\Psr\Clock\ClockInterface::class, \OCP\AppFramework\Utility\ITimeFactory::class);
1158
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1159
+        $this->registerAlias(\Psr\Clock\ClockInterface::class, \OCP\AppFramework\Utility\ITimeFactory::class);
1160 1160
 
1161
-		$this->registerService(Defaults::class, function (Server $c) {
1162
-			return new Defaults(
1163
-				$c->get('ThemingDefaults')
1164
-			);
1165
-		});
1161
+        $this->registerService(Defaults::class, function (Server $c) {
1162
+            return new Defaults(
1163
+                $c->get('ThemingDefaults')
1164
+            );
1165
+        });
1166 1166
 
1167
-		$this->registerService(\OCP\ISession::class, function (ContainerInterface $c) {
1168
-			return $c->get(\OCP\IUserSession::class)->getSession();
1169
-		}, false);
1167
+        $this->registerService(\OCP\ISession::class, function (ContainerInterface $c) {
1168
+            return $c->get(\OCP\IUserSession::class)->getSession();
1169
+        }, false);
1170 1170
 
1171
-		$this->registerService(IShareHelper::class, function (ContainerInterface $c) {
1172
-			return new ShareHelper(
1173
-				$c->get(\OCP\Share\IManager::class)
1174
-			);
1175
-		});
1171
+        $this->registerService(IShareHelper::class, function (ContainerInterface $c) {
1172
+            return new ShareHelper(
1173
+                $c->get(\OCP\Share\IManager::class)
1174
+            );
1175
+        });
1176 1176
 
1177
-		$this->registerService(IApiFactory::class, function (ContainerInterface $c) {
1178
-			return new ApiFactory($c->get(IClientService::class));
1179
-		});
1177
+        $this->registerService(IApiFactory::class, function (ContainerInterface $c) {
1178
+            return new ApiFactory($c->get(IClientService::class));
1179
+        });
1180 1180
 
1181
-		$this->registerService(IInstanceFactory::class, function (ContainerInterface $c) {
1182
-			$memcacheFactory = $c->get(ICacheFactory::class);
1183
-			return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->get(IClientService::class));
1184
-		});
1181
+        $this->registerService(IInstanceFactory::class, function (ContainerInterface $c) {
1182
+            $memcacheFactory = $c->get(ICacheFactory::class);
1183
+            return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->get(IClientService::class));
1184
+        });
1185 1185
 
1186
-		$this->registerAlias(IContactsStore::class, ContactsStore::class);
1187
-		$this->registerAlias(IAccountManager::class, AccountManager::class);
1186
+        $this->registerAlias(IContactsStore::class, ContactsStore::class);
1187
+        $this->registerAlias(IAccountManager::class, AccountManager::class);
1188 1188
 
1189
-		$this->registerAlias(IStorageFactory::class, StorageFactory::class);
1189
+        $this->registerAlias(IStorageFactory::class, StorageFactory::class);
1190 1190
 
1191
-		$this->registerAlias(\OCP\Dashboard\IManager::class, \OC\Dashboard\Manager::class);
1191
+        $this->registerAlias(\OCP\Dashboard\IManager::class, \OC\Dashboard\Manager::class);
1192 1192
 
1193
-		$this->registerAlias(IFullTextSearchManager::class, FullTextSearchManager::class);
1194
-		$this->registerAlias(IFilesMetadataManager::class, FilesMetadataManager::class);
1193
+        $this->registerAlias(IFullTextSearchManager::class, FullTextSearchManager::class);
1194
+        $this->registerAlias(IFilesMetadataManager::class, FilesMetadataManager::class);
1195 1195
 
1196
-		$this->registerAlias(ISubAdmin::class, SubAdmin::class);
1196
+        $this->registerAlias(ISubAdmin::class, SubAdmin::class);
1197 1197
 
1198
-		$this->registerAlias(IInitialStateService::class, InitialStateService::class);
1198
+        $this->registerAlias(IInitialStateService::class, InitialStateService::class);
1199 1199
 
1200
-		$this->registerAlias(\OCP\IEmojiHelper::class, \OC\EmojiHelper::class);
1200
+        $this->registerAlias(\OCP\IEmojiHelper::class, \OC\EmojiHelper::class);
1201 1201
 
1202
-		$this->registerAlias(\OCP\UserStatus\IManager::class, \OC\UserStatus\Manager::class);
1202
+        $this->registerAlias(\OCP\UserStatus\IManager::class, \OC\UserStatus\Manager::class);
1203 1203
 
1204
-		$this->registerAlias(IBroker::class, Broker::class);
1204
+        $this->registerAlias(IBroker::class, Broker::class);
1205 1205
 
1206
-		$this->registerAlias(\OCP\Files\AppData\IAppDataFactory::class, \OC\Files\AppData\Factory::class);
1206
+        $this->registerAlias(\OCP\Files\AppData\IAppDataFactory::class, \OC\Files\AppData\Factory::class);
1207 1207
 
1208
-		$this->registerAlias(\OCP\Files\IFilenameValidator::class, \OC\Files\FilenameValidator::class);
1208
+        $this->registerAlias(\OCP\Files\IFilenameValidator::class, \OC\Files\FilenameValidator::class);
1209 1209
 
1210
-		$this->registerAlias(IBinaryFinder::class, BinaryFinder::class);
1210
+        $this->registerAlias(IBinaryFinder::class, BinaryFinder::class);
1211 1211
 
1212
-		$this->registerAlias(\OCP\Share\IPublicShareTemplateFactory::class, \OC\Share20\PublicShareTemplateFactory::class);
1212
+        $this->registerAlias(\OCP\Share\IPublicShareTemplateFactory::class, \OC\Share20\PublicShareTemplateFactory::class);
1213 1213
 
1214
-		$this->registerAlias(ITranslationManager::class, TranslationManager::class);
1214
+        $this->registerAlias(ITranslationManager::class, TranslationManager::class);
1215 1215
 
1216
-		$this->registerAlias(IConversionManager::class, ConversionManager::class);
1216
+        $this->registerAlias(IConversionManager::class, ConversionManager::class);
1217 1217
 
1218
-		$this->registerAlias(ISpeechToTextManager::class, SpeechToTextManager::class);
1218
+        $this->registerAlias(ISpeechToTextManager::class, SpeechToTextManager::class);
1219 1219
 
1220
-		$this->registerAlias(IEventSourceFactory::class, EventSourceFactory::class);
1220
+        $this->registerAlias(IEventSourceFactory::class, EventSourceFactory::class);
1221 1221
 
1222
-		$this->registerAlias(\OCP\TextProcessing\IManager::class, \OC\TextProcessing\Manager::class);
1222
+        $this->registerAlias(\OCP\TextProcessing\IManager::class, \OC\TextProcessing\Manager::class);
1223 1223
 
1224
-		$this->registerAlias(\OCP\TextToImage\IManager::class, \OC\TextToImage\Manager::class);
1224
+        $this->registerAlias(\OCP\TextToImage\IManager::class, \OC\TextToImage\Manager::class);
1225 1225
 
1226
-		$this->registerAlias(ILimiter::class, Limiter::class);
1226
+        $this->registerAlias(ILimiter::class, Limiter::class);
1227 1227
 
1228
-		$this->registerAlias(IPhoneNumberUtil::class, PhoneNumberUtil::class);
1228
+        $this->registerAlias(IPhoneNumberUtil::class, PhoneNumberUtil::class);
1229 1229
 
1230
-		// there is no reason for having OCMProvider as a Service
1231
-		$this->registerDeprecatedAlias(ICapabilityAwareOCMProvider::class, OCMProvider::class);
1232
-		$this->registerDeprecatedAlias(IOCMProvider::class, OCMProvider::class);
1230
+        // there is no reason for having OCMProvider as a Service
1231
+        $this->registerDeprecatedAlias(ICapabilityAwareOCMProvider::class, OCMProvider::class);
1232
+        $this->registerDeprecatedAlias(IOCMProvider::class, OCMProvider::class);
1233 1233
 
1234
-		$this->registerAlias(ISetupCheckManager::class, SetupCheckManager::class);
1234
+        $this->registerAlias(ISetupCheckManager::class, SetupCheckManager::class);
1235 1235
 
1236
-		$this->registerAlias(IProfileManager::class, ProfileManager::class);
1236
+        $this->registerAlias(IProfileManager::class, ProfileManager::class);
1237 1237
 
1238
-		$this->registerAlias(IAvailabilityCoordinator::class, AvailabilityCoordinator::class);
1238
+        $this->registerAlias(IAvailabilityCoordinator::class, AvailabilityCoordinator::class);
1239 1239
 
1240
-		$this->registerAlias(IDeclarativeManager::class, DeclarativeManager::class);
1240
+        $this->registerAlias(IDeclarativeManager::class, DeclarativeManager::class);
1241 1241
 
1242
-		$this->registerAlias(\OCP\TaskProcessing\IManager::class, \OC\TaskProcessing\Manager::class);
1242
+        $this->registerAlias(\OCP\TaskProcessing\IManager::class, \OC\TaskProcessing\Manager::class);
1243 1243
 
1244
-		$this->registerAlias(IRemoteAddress::class, RemoteAddress::class);
1244
+        $this->registerAlias(IRemoteAddress::class, RemoteAddress::class);
1245 1245
 
1246
-		$this->registerAlias(\OCP\Security\Ip\IFactory::class, \OC\Security\Ip\Factory::class);
1246
+        $this->registerAlias(\OCP\Security\Ip\IFactory::class, \OC\Security\Ip\Factory::class);
1247 1247
 
1248
-		$this->registerAlias(IRichTextFormatter::class, \OC\RichObjectStrings\RichTextFormatter::class);
1248
+        $this->registerAlias(IRichTextFormatter::class, \OC\RichObjectStrings\RichTextFormatter::class);
1249 1249
 
1250
-		$this->registerAlias(ISignatureManager::class, SignatureManager::class);
1250
+        $this->registerAlias(ISignatureManager::class, SignatureManager::class);
1251 1251
 
1252
-		$this->registerAlias(IGenerator::class, Generator::class);
1253
-		$this->registerAlias(IDecoder::class, Decoder::class);
1252
+        $this->registerAlias(IGenerator::class, Generator::class);
1253
+        $this->registerAlias(IDecoder::class, Decoder::class);
1254 1254
 
1255
-		$this->connectDispatcher();
1256
-	}
1255
+        $this->connectDispatcher();
1256
+    }
1257 1257
 
1258
-	public function boot() {
1259
-		/** @var HookConnector $hookConnector */
1260
-		$hookConnector = $this->get(HookConnector::class);
1261
-		$hookConnector->viewToNode();
1262
-	}
1263
-
1264
-	private function connectDispatcher(): void {
1265
-		/** @var IEventDispatcher $eventDispatcher */
1266
-		$eventDispatcher = $this->get(IEventDispatcher::class);
1267
-		$eventDispatcher->addServiceListener(LoginFailed::class, LoginFailedListener::class);
1268
-		$eventDispatcher->addServiceListener(PostLoginEvent::class, UserLoggedInListener::class);
1269
-		$eventDispatcher->addServiceListener(UserChangedEvent::class, UserChangedListener::class);
1270
-		$eventDispatcher->addServiceListener(BeforeUserDeletedEvent::class, BeforeUserDeletedListener::class);
1271
-
1272
-		FilesMetadataManager::loadListeners($eventDispatcher);
1273
-		GenerateBlurhashMetadata::loadListeners($eventDispatcher);
1274
-	}
1275
-
1276
-	/**
1277
-	 * @return \OCP\Contacts\IManager
1278
-	 * @deprecated 20.0.0
1279
-	 */
1280
-	public function getContactsManager() {
1281
-		return $this->get(\OCP\Contacts\IManager::class);
1282
-	}
1283
-
1284
-	/**
1285
-	 * @return \OC\Encryption\Manager
1286
-	 * @deprecated 20.0.0
1287
-	 */
1288
-	public function getEncryptionManager() {
1289
-		return $this->get(\OCP\Encryption\IManager::class);
1290
-	}
1291
-
1292
-	/**
1293
-	 * @return \OC\Encryption\File
1294
-	 * @deprecated 20.0.0
1295
-	 */
1296
-	public function getEncryptionFilesHelper() {
1297
-		return $this->get(IFile::class);
1298
-	}
1299
-
1300
-	/**
1301
-	 * The current request object holding all information about the request
1302
-	 * currently being processed is returned from this method.
1303
-	 * In case the current execution was not initiated by a web request null is returned
1304
-	 *
1305
-	 * @return \OCP\IRequest
1306
-	 * @deprecated 20.0.0
1307
-	 */
1308
-	public function getRequest() {
1309
-		return $this->get(IRequest::class);
1310
-	}
1311
-
1312
-	/**
1313
-	 * Returns the root folder of ownCloud's data directory
1314
-	 *
1315
-	 * @return IRootFolder
1316
-	 * @deprecated 20.0.0
1317
-	 */
1318
-	public function getRootFolder() {
1319
-		return $this->get(IRootFolder::class);
1320
-	}
1321
-
1322
-	/**
1323
-	 * Returns the root folder of ownCloud's data directory
1324
-	 * This is the lazy variant so this gets only initialized once it
1325
-	 * is actually used.
1326
-	 *
1327
-	 * @return IRootFolder
1328
-	 * @deprecated 20.0.0
1329
-	 */
1330
-	public function getLazyRootFolder() {
1331
-		return $this->get(IRootFolder::class);
1332
-	}
1333
-
1334
-	/**
1335
-	 * Returns a view to ownCloud's files folder
1336
-	 *
1337
-	 * @param string $userId user ID
1338
-	 * @return \OCP\Files\Folder|null
1339
-	 * @deprecated 20.0.0
1340
-	 */
1341
-	public function getUserFolder($userId = null) {
1342
-		if ($userId === null) {
1343
-			$user = $this->get(IUserSession::class)->getUser();
1344
-			if (!$user) {
1345
-				return null;
1346
-			}
1347
-			$userId = $user->getUID();
1348
-		}
1349
-		$root = $this->get(IRootFolder::class);
1350
-		return $root->getUserFolder($userId);
1351
-	}
1352
-
1353
-	/**
1354
-	 * @return \OC\User\Manager
1355
-	 * @deprecated 20.0.0
1356
-	 */
1357
-	public function getUserManager() {
1358
-		return $this->get(IUserManager::class);
1359
-	}
1360
-
1361
-	/**
1362
-	 * @return \OC\Group\Manager
1363
-	 * @deprecated 20.0.0
1364
-	 */
1365
-	public function getGroupManager() {
1366
-		return $this->get(IGroupManager::class);
1367
-	}
1368
-
1369
-	/**
1370
-	 * @return \OC\User\Session
1371
-	 * @deprecated 20.0.0
1372
-	 */
1373
-	public function getUserSession() {
1374
-		return $this->get(IUserSession::class);
1375
-	}
1376
-
1377
-	/**
1378
-	 * @return \OCP\ISession
1379
-	 * @deprecated 20.0.0
1380
-	 */
1381
-	public function getSession() {
1382
-		return $this->get(Session::class)->getSession();
1383
-	}
1384
-
1385
-	/**
1386
-	 * @param \OCP\ISession $session
1387
-	 * @return void
1388
-	 */
1389
-	public function setSession(\OCP\ISession $session) {
1390
-		$this->get(SessionStorage::class)->setSession($session);
1391
-		$this->get(Session::class)->setSession($session);
1392
-		$this->get(Store::class)->setSession($session);
1393
-	}
1394
-
1395
-	/**
1396
-	 * @return \OCP\IConfig
1397
-	 * @deprecated 20.0.0
1398
-	 */
1399
-	public function getConfig() {
1400
-		return $this->get(AllConfig::class);
1401
-	}
1402
-
1403
-	/**
1404
-	 * @return \OC\SystemConfig
1405
-	 * @deprecated 20.0.0
1406
-	 */
1407
-	public function getSystemConfig() {
1408
-		return $this->get(SystemConfig::class);
1409
-	}
1410
-
1411
-	/**
1412
-	 * @return IFactory
1413
-	 * @deprecated 20.0.0
1414
-	 */
1415
-	public function getL10NFactory() {
1416
-		return $this->get(IFactory::class);
1417
-	}
1418
-
1419
-	/**
1420
-	 * get an L10N instance
1421
-	 *
1422
-	 * @param string $app appid
1423
-	 * @param string $lang
1424
-	 * @return IL10N
1425
-	 * @deprecated 20.0.0 use DI of {@see IL10N} or {@see IFactory} instead, or {@see \OCP\Util::getL10N()} as a last resort
1426
-	 */
1427
-	public function getL10N($app, $lang = null) {
1428
-		return $this->get(IFactory::class)->get($app, $lang);
1429
-	}
1430
-
1431
-	/**
1432
-	 * @return IURLGenerator
1433
-	 * @deprecated 20.0.0
1434
-	 */
1435
-	public function getURLGenerator() {
1436
-		return $this->get(IURLGenerator::class);
1437
-	}
1438
-
1439
-	/**
1440
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1441
-	 * getMemCacheFactory() instead.
1442
-	 *
1443
-	 * @return ICache
1444
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1445
-	 */
1446
-	public function getCache() {
1447
-		return $this->get(ICache::class);
1448
-	}
1449
-
1450
-	/**
1451
-	 * Returns an \OCP\CacheFactory instance
1452
-	 *
1453
-	 * @return \OCP\ICacheFactory
1454
-	 * @deprecated 20.0.0
1455
-	 */
1456
-	public function getMemCacheFactory() {
1457
-		return $this->get(ICacheFactory::class);
1458
-	}
1459
-
1460
-	/**
1461
-	 * Returns the current session
1462
-	 *
1463
-	 * @return \OCP\IDBConnection
1464
-	 * @deprecated 20.0.0
1465
-	 */
1466
-	public function getDatabaseConnection() {
1467
-		return $this->get(IDBConnection::class);
1468
-	}
1469
-
1470
-	/**
1471
-	 * Returns the activity manager
1472
-	 *
1473
-	 * @return \OCP\Activity\IManager
1474
-	 * @deprecated 20.0.0
1475
-	 */
1476
-	public function getActivityManager() {
1477
-		return $this->get(\OCP\Activity\IManager::class);
1478
-	}
1479
-
1480
-	/**
1481
-	 * Returns an job list for controlling background jobs
1482
-	 *
1483
-	 * @return IJobList
1484
-	 * @deprecated 20.0.0
1485
-	 */
1486
-	public function getJobList() {
1487
-		return $this->get(IJobList::class);
1488
-	}
1489
-
1490
-	/**
1491
-	 * Returns a SecureRandom instance
1492
-	 *
1493
-	 * @return \OCP\Security\ISecureRandom
1494
-	 * @deprecated 20.0.0
1495
-	 */
1496
-	public function getSecureRandom() {
1497
-		return $this->get(ISecureRandom::class);
1498
-	}
1499
-
1500
-	/**
1501
-	 * Returns a Crypto instance
1502
-	 *
1503
-	 * @return ICrypto
1504
-	 * @deprecated 20.0.0
1505
-	 */
1506
-	public function getCrypto() {
1507
-		return $this->get(ICrypto::class);
1508
-	}
1509
-
1510
-	/**
1511
-	 * Returns a Hasher instance
1512
-	 *
1513
-	 * @return IHasher
1514
-	 * @deprecated 20.0.0
1515
-	 */
1516
-	public function getHasher() {
1517
-		return $this->get(IHasher::class);
1518
-	}
1519
-
1520
-	/**
1521
-	 * Get the certificate manager
1522
-	 *
1523
-	 * @return \OCP\ICertificateManager
1524
-	 */
1525
-	public function getCertificateManager() {
1526
-		return $this->get(ICertificateManager::class);
1527
-	}
1528
-
1529
-	/**
1530
-	 * Get the manager for temporary files and folders
1531
-	 *
1532
-	 * @return \OCP\ITempManager
1533
-	 * @deprecated 20.0.0
1534
-	 */
1535
-	public function getTempManager() {
1536
-		return $this->get(ITempManager::class);
1537
-	}
1538
-
1539
-	/**
1540
-	 * Get the app manager
1541
-	 *
1542
-	 * @return \OCP\App\IAppManager
1543
-	 * @deprecated 20.0.0
1544
-	 */
1545
-	public function getAppManager() {
1546
-		return $this->get(IAppManager::class);
1547
-	}
1548
-
1549
-	/**
1550
-	 * Creates a new mailer
1551
-	 *
1552
-	 * @return IMailer
1553
-	 * @deprecated 20.0.0
1554
-	 */
1555
-	public function getMailer() {
1556
-		return $this->get(IMailer::class);
1557
-	}
1558
-
1559
-	/**
1560
-	 * Get the webroot
1561
-	 *
1562
-	 * @return string
1563
-	 * @deprecated 20.0.0
1564
-	 */
1565
-	public function getWebRoot() {
1566
-		return $this->webRoot;
1567
-	}
1568
-
1569
-	/**
1570
-	 * Get the locking provider
1571
-	 *
1572
-	 * @return ILockingProvider
1573
-	 * @since 8.1.0
1574
-	 * @deprecated 20.0.0
1575
-	 */
1576
-	public function getLockingProvider() {
1577
-		return $this->get(ILockingProvider::class);
1578
-	}
1579
-
1580
-	/**
1581
-	 * Get the MimeTypeDetector
1582
-	 *
1583
-	 * @return IMimeTypeDetector
1584
-	 * @deprecated 20.0.0
1585
-	 */
1586
-	public function getMimeTypeDetector() {
1587
-		return $this->get(IMimeTypeDetector::class);
1588
-	}
1589
-
1590
-	/**
1591
-	 * Get the MimeTypeLoader
1592
-	 *
1593
-	 * @return IMimeTypeLoader
1594
-	 * @deprecated 20.0.0
1595
-	 */
1596
-	public function getMimeTypeLoader() {
1597
-		return $this->get(IMimeTypeLoader::class);
1598
-	}
1599
-
1600
-	/**
1601
-	 * Get the Notification Manager
1602
-	 *
1603
-	 * @return \OCP\Notification\IManager
1604
-	 * @since 8.2.0
1605
-	 * @deprecated 20.0.0
1606
-	 */
1607
-	public function getNotificationManager() {
1608
-		return $this->get(\OCP\Notification\IManager::class);
1609
-	}
1610
-
1611
-	/**
1612
-	 * @return \OCA\Theming\ThemingDefaults
1613
-	 * @deprecated 20.0.0
1614
-	 */
1615
-	public function getThemingDefaults() {
1616
-		return $this->get('ThemingDefaults');
1617
-	}
1618
-
1619
-	/**
1620
-	 * @return \OC\IntegrityCheck\Checker
1621
-	 * @deprecated 20.0.0
1622
-	 */
1623
-	public function getIntegrityCodeChecker() {
1624
-		return $this->get('IntegrityCodeChecker');
1625
-	}
1626
-
1627
-	/**
1628
-	 * @return CsrfTokenManager
1629
-	 * @deprecated 20.0.0
1630
-	 */
1631
-	public function getCsrfTokenManager() {
1632
-		return $this->get(CsrfTokenManager::class);
1633
-	}
1634
-
1635
-	/**
1636
-	 * @return ContentSecurityPolicyNonceManager
1637
-	 * @deprecated 20.0.0
1638
-	 */
1639
-	public function getContentSecurityPolicyNonceManager() {
1640
-		return $this->get(ContentSecurityPolicyNonceManager::class);
1641
-	}
1642
-
1643
-	/**
1644
-	 * @return \OCP\Settings\IManager
1645
-	 * @deprecated 20.0.0
1646
-	 */
1647
-	public function getSettingsManager() {
1648
-		return $this->get(\OC\Settings\Manager::class);
1649
-	}
1650
-
1651
-	/**
1652
-	 * @return \OCP\Files\IAppData
1653
-	 * @deprecated 20.0.0 Use get(\OCP\Files\AppData\IAppDataFactory::class)->get($app) instead
1654
-	 */
1655
-	public function getAppDataDir($app) {
1656
-		$factory = $this->get(\OC\Files\AppData\Factory::class);
1657
-		return $factory->get($app);
1658
-	}
1659
-
1660
-	/**
1661
-	 * @return \OCP\Federation\ICloudIdManager
1662
-	 * @deprecated 20.0.0
1663
-	 */
1664
-	public function getCloudIdManager() {
1665
-		return $this->get(ICloudIdManager::class);
1666
-	}
1258
+    public function boot() {
1259
+        /** @var HookConnector $hookConnector */
1260
+        $hookConnector = $this->get(HookConnector::class);
1261
+        $hookConnector->viewToNode();
1262
+    }
1263
+
1264
+    private function connectDispatcher(): void {
1265
+        /** @var IEventDispatcher $eventDispatcher */
1266
+        $eventDispatcher = $this->get(IEventDispatcher::class);
1267
+        $eventDispatcher->addServiceListener(LoginFailed::class, LoginFailedListener::class);
1268
+        $eventDispatcher->addServiceListener(PostLoginEvent::class, UserLoggedInListener::class);
1269
+        $eventDispatcher->addServiceListener(UserChangedEvent::class, UserChangedListener::class);
1270
+        $eventDispatcher->addServiceListener(BeforeUserDeletedEvent::class, BeforeUserDeletedListener::class);
1271
+
1272
+        FilesMetadataManager::loadListeners($eventDispatcher);
1273
+        GenerateBlurhashMetadata::loadListeners($eventDispatcher);
1274
+    }
1275
+
1276
+    /**
1277
+     * @return \OCP\Contacts\IManager
1278
+     * @deprecated 20.0.0
1279
+     */
1280
+    public function getContactsManager() {
1281
+        return $this->get(\OCP\Contacts\IManager::class);
1282
+    }
1283
+
1284
+    /**
1285
+     * @return \OC\Encryption\Manager
1286
+     * @deprecated 20.0.0
1287
+     */
1288
+    public function getEncryptionManager() {
1289
+        return $this->get(\OCP\Encryption\IManager::class);
1290
+    }
1291
+
1292
+    /**
1293
+     * @return \OC\Encryption\File
1294
+     * @deprecated 20.0.0
1295
+     */
1296
+    public function getEncryptionFilesHelper() {
1297
+        return $this->get(IFile::class);
1298
+    }
1299
+
1300
+    /**
1301
+     * The current request object holding all information about the request
1302
+     * currently being processed is returned from this method.
1303
+     * In case the current execution was not initiated by a web request null is returned
1304
+     *
1305
+     * @return \OCP\IRequest
1306
+     * @deprecated 20.0.0
1307
+     */
1308
+    public function getRequest() {
1309
+        return $this->get(IRequest::class);
1310
+    }
1311
+
1312
+    /**
1313
+     * Returns the root folder of ownCloud's data directory
1314
+     *
1315
+     * @return IRootFolder
1316
+     * @deprecated 20.0.0
1317
+     */
1318
+    public function getRootFolder() {
1319
+        return $this->get(IRootFolder::class);
1320
+    }
1321
+
1322
+    /**
1323
+     * Returns the root folder of ownCloud's data directory
1324
+     * This is the lazy variant so this gets only initialized once it
1325
+     * is actually used.
1326
+     *
1327
+     * @return IRootFolder
1328
+     * @deprecated 20.0.0
1329
+     */
1330
+    public function getLazyRootFolder() {
1331
+        return $this->get(IRootFolder::class);
1332
+    }
1333
+
1334
+    /**
1335
+     * Returns a view to ownCloud's files folder
1336
+     *
1337
+     * @param string $userId user ID
1338
+     * @return \OCP\Files\Folder|null
1339
+     * @deprecated 20.0.0
1340
+     */
1341
+    public function getUserFolder($userId = null) {
1342
+        if ($userId === null) {
1343
+            $user = $this->get(IUserSession::class)->getUser();
1344
+            if (!$user) {
1345
+                return null;
1346
+            }
1347
+            $userId = $user->getUID();
1348
+        }
1349
+        $root = $this->get(IRootFolder::class);
1350
+        return $root->getUserFolder($userId);
1351
+    }
1352
+
1353
+    /**
1354
+     * @return \OC\User\Manager
1355
+     * @deprecated 20.0.0
1356
+     */
1357
+    public function getUserManager() {
1358
+        return $this->get(IUserManager::class);
1359
+    }
1360
+
1361
+    /**
1362
+     * @return \OC\Group\Manager
1363
+     * @deprecated 20.0.0
1364
+     */
1365
+    public function getGroupManager() {
1366
+        return $this->get(IGroupManager::class);
1367
+    }
1368
+
1369
+    /**
1370
+     * @return \OC\User\Session
1371
+     * @deprecated 20.0.0
1372
+     */
1373
+    public function getUserSession() {
1374
+        return $this->get(IUserSession::class);
1375
+    }
1376
+
1377
+    /**
1378
+     * @return \OCP\ISession
1379
+     * @deprecated 20.0.0
1380
+     */
1381
+    public function getSession() {
1382
+        return $this->get(Session::class)->getSession();
1383
+    }
1384
+
1385
+    /**
1386
+     * @param \OCP\ISession $session
1387
+     * @return void
1388
+     */
1389
+    public function setSession(\OCP\ISession $session) {
1390
+        $this->get(SessionStorage::class)->setSession($session);
1391
+        $this->get(Session::class)->setSession($session);
1392
+        $this->get(Store::class)->setSession($session);
1393
+    }
1394
+
1395
+    /**
1396
+     * @return \OCP\IConfig
1397
+     * @deprecated 20.0.0
1398
+     */
1399
+    public function getConfig() {
1400
+        return $this->get(AllConfig::class);
1401
+    }
1402
+
1403
+    /**
1404
+     * @return \OC\SystemConfig
1405
+     * @deprecated 20.0.0
1406
+     */
1407
+    public function getSystemConfig() {
1408
+        return $this->get(SystemConfig::class);
1409
+    }
1410
+
1411
+    /**
1412
+     * @return IFactory
1413
+     * @deprecated 20.0.0
1414
+     */
1415
+    public function getL10NFactory() {
1416
+        return $this->get(IFactory::class);
1417
+    }
1418
+
1419
+    /**
1420
+     * get an L10N instance
1421
+     *
1422
+     * @param string $app appid
1423
+     * @param string $lang
1424
+     * @return IL10N
1425
+     * @deprecated 20.0.0 use DI of {@see IL10N} or {@see IFactory} instead, or {@see \OCP\Util::getL10N()} as a last resort
1426
+     */
1427
+    public function getL10N($app, $lang = null) {
1428
+        return $this->get(IFactory::class)->get($app, $lang);
1429
+    }
1430
+
1431
+    /**
1432
+     * @return IURLGenerator
1433
+     * @deprecated 20.0.0
1434
+     */
1435
+    public function getURLGenerator() {
1436
+        return $this->get(IURLGenerator::class);
1437
+    }
1438
+
1439
+    /**
1440
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1441
+     * getMemCacheFactory() instead.
1442
+     *
1443
+     * @return ICache
1444
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1445
+     */
1446
+    public function getCache() {
1447
+        return $this->get(ICache::class);
1448
+    }
1449
+
1450
+    /**
1451
+     * Returns an \OCP\CacheFactory instance
1452
+     *
1453
+     * @return \OCP\ICacheFactory
1454
+     * @deprecated 20.0.0
1455
+     */
1456
+    public function getMemCacheFactory() {
1457
+        return $this->get(ICacheFactory::class);
1458
+    }
1459
+
1460
+    /**
1461
+     * Returns the current session
1462
+     *
1463
+     * @return \OCP\IDBConnection
1464
+     * @deprecated 20.0.0
1465
+     */
1466
+    public function getDatabaseConnection() {
1467
+        return $this->get(IDBConnection::class);
1468
+    }
1469
+
1470
+    /**
1471
+     * Returns the activity manager
1472
+     *
1473
+     * @return \OCP\Activity\IManager
1474
+     * @deprecated 20.0.0
1475
+     */
1476
+    public function getActivityManager() {
1477
+        return $this->get(\OCP\Activity\IManager::class);
1478
+    }
1479
+
1480
+    /**
1481
+     * Returns an job list for controlling background jobs
1482
+     *
1483
+     * @return IJobList
1484
+     * @deprecated 20.0.0
1485
+     */
1486
+    public function getJobList() {
1487
+        return $this->get(IJobList::class);
1488
+    }
1489
+
1490
+    /**
1491
+     * Returns a SecureRandom instance
1492
+     *
1493
+     * @return \OCP\Security\ISecureRandom
1494
+     * @deprecated 20.0.0
1495
+     */
1496
+    public function getSecureRandom() {
1497
+        return $this->get(ISecureRandom::class);
1498
+    }
1499
+
1500
+    /**
1501
+     * Returns a Crypto instance
1502
+     *
1503
+     * @return ICrypto
1504
+     * @deprecated 20.0.0
1505
+     */
1506
+    public function getCrypto() {
1507
+        return $this->get(ICrypto::class);
1508
+    }
1509
+
1510
+    /**
1511
+     * Returns a Hasher instance
1512
+     *
1513
+     * @return IHasher
1514
+     * @deprecated 20.0.0
1515
+     */
1516
+    public function getHasher() {
1517
+        return $this->get(IHasher::class);
1518
+    }
1519
+
1520
+    /**
1521
+     * Get the certificate manager
1522
+     *
1523
+     * @return \OCP\ICertificateManager
1524
+     */
1525
+    public function getCertificateManager() {
1526
+        return $this->get(ICertificateManager::class);
1527
+    }
1528
+
1529
+    /**
1530
+     * Get the manager for temporary files and folders
1531
+     *
1532
+     * @return \OCP\ITempManager
1533
+     * @deprecated 20.0.0
1534
+     */
1535
+    public function getTempManager() {
1536
+        return $this->get(ITempManager::class);
1537
+    }
1538
+
1539
+    /**
1540
+     * Get the app manager
1541
+     *
1542
+     * @return \OCP\App\IAppManager
1543
+     * @deprecated 20.0.0
1544
+     */
1545
+    public function getAppManager() {
1546
+        return $this->get(IAppManager::class);
1547
+    }
1548
+
1549
+    /**
1550
+     * Creates a new mailer
1551
+     *
1552
+     * @return IMailer
1553
+     * @deprecated 20.0.0
1554
+     */
1555
+    public function getMailer() {
1556
+        return $this->get(IMailer::class);
1557
+    }
1558
+
1559
+    /**
1560
+     * Get the webroot
1561
+     *
1562
+     * @return string
1563
+     * @deprecated 20.0.0
1564
+     */
1565
+    public function getWebRoot() {
1566
+        return $this->webRoot;
1567
+    }
1568
+
1569
+    /**
1570
+     * Get the locking provider
1571
+     *
1572
+     * @return ILockingProvider
1573
+     * @since 8.1.0
1574
+     * @deprecated 20.0.0
1575
+     */
1576
+    public function getLockingProvider() {
1577
+        return $this->get(ILockingProvider::class);
1578
+    }
1579
+
1580
+    /**
1581
+     * Get the MimeTypeDetector
1582
+     *
1583
+     * @return IMimeTypeDetector
1584
+     * @deprecated 20.0.0
1585
+     */
1586
+    public function getMimeTypeDetector() {
1587
+        return $this->get(IMimeTypeDetector::class);
1588
+    }
1589
+
1590
+    /**
1591
+     * Get the MimeTypeLoader
1592
+     *
1593
+     * @return IMimeTypeLoader
1594
+     * @deprecated 20.0.0
1595
+     */
1596
+    public function getMimeTypeLoader() {
1597
+        return $this->get(IMimeTypeLoader::class);
1598
+    }
1599
+
1600
+    /**
1601
+     * Get the Notification Manager
1602
+     *
1603
+     * @return \OCP\Notification\IManager
1604
+     * @since 8.2.0
1605
+     * @deprecated 20.0.0
1606
+     */
1607
+    public function getNotificationManager() {
1608
+        return $this->get(\OCP\Notification\IManager::class);
1609
+    }
1610
+
1611
+    /**
1612
+     * @return \OCA\Theming\ThemingDefaults
1613
+     * @deprecated 20.0.0
1614
+     */
1615
+    public function getThemingDefaults() {
1616
+        return $this->get('ThemingDefaults');
1617
+    }
1618
+
1619
+    /**
1620
+     * @return \OC\IntegrityCheck\Checker
1621
+     * @deprecated 20.0.0
1622
+     */
1623
+    public function getIntegrityCodeChecker() {
1624
+        return $this->get('IntegrityCodeChecker');
1625
+    }
1626
+
1627
+    /**
1628
+     * @return CsrfTokenManager
1629
+     * @deprecated 20.0.0
1630
+     */
1631
+    public function getCsrfTokenManager() {
1632
+        return $this->get(CsrfTokenManager::class);
1633
+    }
1634
+
1635
+    /**
1636
+     * @return ContentSecurityPolicyNonceManager
1637
+     * @deprecated 20.0.0
1638
+     */
1639
+    public function getContentSecurityPolicyNonceManager() {
1640
+        return $this->get(ContentSecurityPolicyNonceManager::class);
1641
+    }
1642
+
1643
+    /**
1644
+     * @return \OCP\Settings\IManager
1645
+     * @deprecated 20.0.0
1646
+     */
1647
+    public function getSettingsManager() {
1648
+        return $this->get(\OC\Settings\Manager::class);
1649
+    }
1650
+
1651
+    /**
1652
+     * @return \OCP\Files\IAppData
1653
+     * @deprecated 20.0.0 Use get(\OCP\Files\AppData\IAppDataFactory::class)->get($app) instead
1654
+     */
1655
+    public function getAppDataDir($app) {
1656
+        $factory = $this->get(\OC\Files\AppData\Factory::class);
1657
+        return $factory->get($app);
1658
+    }
1659
+
1660
+    /**
1661
+     * @return \OCP\Federation\ICloudIdManager
1662
+     * @deprecated 20.0.0
1663
+     */
1664
+    public function getCloudIdManager() {
1665
+        return $this->get(ICloudIdManager::class);
1666
+    }
1667 1667
 }
Please login to merge, or discard this patch.
lib/private/AppFramework/Http/Dispatcher.php 2 patches
Indentation   +224 added lines, -224 removed lines patch added patch discarded remove patch
@@ -26,228 +26,228 @@
 block discarded – undo
26 26
  * Class to dispatch the request to the middleware dispatcher
27 27
  */
28 28
 class Dispatcher {
29
-	/** @var MiddlewareDispatcher */
30
-	private $middlewareDispatcher;
31
-
32
-	/** @var Http */
33
-	private $protocol;
34
-
35
-	/** @var ControllerMethodReflector */
36
-	private $reflector;
37
-
38
-	/** @var IRequest */
39
-	private $request;
40
-
41
-	/** @var IConfig */
42
-	private $config;
43
-
44
-	/** @var ConnectionAdapter */
45
-	private $connection;
46
-
47
-	/** @var LoggerInterface */
48
-	private $logger;
49
-
50
-	/** @var IEventLogger */
51
-	private $eventLogger;
52
-
53
-	private ContainerInterface $appContainer;
54
-
55
-	/**
56
-	 * @param Http $protocol the http protocol with contains all status headers
57
-	 * @param MiddlewareDispatcher $middlewareDispatcher the dispatcher which
58
-	 *                                                   runs the middleware
59
-	 * @param ControllerMethodReflector $reflector the reflector that is used to inject
60
-	 *                                             the arguments for the controller
61
-	 * @param IRequest $request the incoming request
62
-	 * @param IConfig $config
63
-	 * @param ConnectionAdapter $connection
64
-	 * @param LoggerInterface $logger
65
-	 * @param IEventLogger $eventLogger
66
-	 */
67
-	public function __construct(
68
-		Http $protocol,
69
-		MiddlewareDispatcher $middlewareDispatcher,
70
-		ControllerMethodReflector $reflector,
71
-		IRequest $request,
72
-		IConfig $config,
73
-		ConnectionAdapter $connection,
74
-		LoggerInterface $logger,
75
-		IEventLogger $eventLogger,
76
-		ContainerInterface $appContainer,
77
-	) {
78
-		$this->protocol = $protocol;
79
-		$this->middlewareDispatcher = $middlewareDispatcher;
80
-		$this->reflector = $reflector;
81
-		$this->request = $request;
82
-		$this->config = $config;
83
-		$this->connection = $connection;
84
-		$this->logger = $logger;
85
-		$this->eventLogger = $eventLogger;
86
-		$this->appContainer = $appContainer;
87
-	}
88
-
89
-
90
-	/**
91
-	 * Handles a request and calls the dispatcher on the controller
92
-	 * @param Controller $controller the controller which will be called
93
-	 * @param string $methodName the method name which will be called on
94
-	 *                           the controller
95
-	 * @return array $array[0] contains the http status header as a string,
96
-	 *               $array[1] contains response headers as an array,
97
-	 *               $array[2] contains response cookies as an array,
98
-	 *               $array[3] contains the response output as a string,
99
-	 *               $array[4] contains the response object
100
-	 * @throws \Exception
101
-	 */
102
-	public function dispatch(Controller $controller, string $methodName): array {
103
-		$out = [null, [], null];
104
-
105
-		try {
106
-			// prefill reflector with everything that's needed for the
107
-			// middlewares
108
-			$this->reflector->reflect($controller, $methodName);
109
-
110
-			$this->middlewareDispatcher->beforeController($controller,
111
-				$methodName);
112
-
113
-			$databaseStatsBefore = [];
114
-			if ($this->config->getSystemValueBool('debug', false)) {
115
-				$databaseStatsBefore = $this->connection->getInner()->getStats();
116
-			}
117
-
118
-			$response = $this->executeController($controller, $methodName);
119
-
120
-			if (!empty($databaseStatsBefore)) {
121
-				$databaseStatsAfter = $this->connection->getInner()->getStats();
122
-				$numBuilt = $databaseStatsAfter['built'] - $databaseStatsBefore['built'];
123
-				$numExecuted = $databaseStatsAfter['executed'] - $databaseStatsBefore['executed'];
124
-
125
-				if ($numBuilt > 50) {
126
-					$this->logger->debug('Controller {class}::{method} created {count} QueryBuilder objects, please check if they are created inside a loop by accident.', [
127
-						'class' => get_class($controller),
128
-						'method' => $methodName,
129
-						'count' => $numBuilt,
130
-					]);
131
-				}
132
-
133
-				if ($numExecuted > 100) {
134
-					$this->logger->warning('Controller {class}::{method} executed {count} queries.', [
135
-						'class' => get_class($controller),
136
-						'method' => $methodName,
137
-						'count' => $numExecuted,
138
-					]);
139
-				}
140
-			}
141
-
142
-			// if an exception appears, the middleware checks if it can handle the
143
-			// exception and creates a response. If no response is created, it is
144
-			// assumed that there's no middleware who can handle it and the error is
145
-			// thrown again
146
-		} catch (\Exception $exception) {
147
-			$response = $this->middlewareDispatcher->afterException(
148
-				$controller, $methodName, $exception);
149
-		} catch (\Throwable $throwable) {
150
-			$exception = new \Exception($throwable->getMessage() . ' in file \'' . $throwable->getFile() . '\' line ' . $throwable->getLine(), $throwable->getCode(), $throwable);
151
-			$response = $this->middlewareDispatcher->afterException(
152
-				$controller, $methodName, $exception);
153
-		}
154
-
155
-		$response = $this->middlewareDispatcher->afterController(
156
-			$controller, $methodName, $response);
157
-
158
-		// depending on the cache object the headers need to be changed
159
-		$out[0] = $this->protocol->getStatusHeader($response->getStatus());
160
-		$out[1] = array_merge($response->getHeaders());
161
-		$out[2] = $response->getCookies();
162
-		$out[3] = $this->middlewareDispatcher->beforeOutput(
163
-			$controller, $methodName, $response->render()
164
-		);
165
-		$out[4] = $response;
166
-
167
-		return $out;
168
-	}
169
-
170
-
171
-	/**
172
-	 * Uses the reflected parameters, types and request parameters to execute
173
-	 * the controller
174
-	 * @param Controller $controller the controller to be executed
175
-	 * @param string $methodName the method on the controller that should be executed
176
-	 * @return Response
177
-	 */
178
-	private function executeController(Controller $controller, string $methodName): Response {
179
-		$arguments = [];
180
-
181
-		// valid types that will be cast
182
-		$types = ['int', 'integer', 'bool', 'boolean', 'float', 'double'];
183
-
184
-		foreach ($this->reflector->getParameters() as $param => $default) {
185
-			// try to get the parameter from the request object and cast
186
-			// it to the type annotated in the @param annotation
187
-			$value = $this->request->getParam($param, $default);
188
-			$type = $this->reflector->getType($param);
189
-
190
-			// Converted the string `'false'` to false when the controller wants a boolean
191
-			if ($value === 'false' && ($type === 'bool' || $type === 'boolean')) {
192
-				$value = false;
193
-			} elseif ($value !== null && \in_array($type, $types, true)) {
194
-				settype($value, $type);
195
-				$this->ensureParameterValueSatisfiesRange($param, $value);
196
-			} elseif ($value === null && $type !== null && $this->appContainer->has($type)) {
197
-				$value = $this->appContainer->get($type);
198
-			}
199
-
200
-			$arguments[] = $value;
201
-		}
202
-
203
-		$this->eventLogger->start('controller:' . get_class($controller) . '::' . $methodName, 'App framework controller execution');
204
-		try {
205
-			$response = \call_user_func_array([$controller, $methodName], $arguments);
206
-		} catch (\TypeError $e) {
207
-			// Only intercept TypeErrors occurring on the first line, meaning that the invocation of the controller method failed.
208
-			// Any other TypeError happens inside the controller method logic and should be logged as normal.
209
-			if ($e->getFile() === $this->reflector->getFile() && $e->getLine() === $this->reflector->getStartLine()) {
210
-				$this->logger->debug('Failed to call controller method: ' . $e->getMessage(), ['exception' => $e]);
211
-				return new Response(Http::STATUS_BAD_REQUEST);
212
-			}
213
-
214
-			throw $e;
215
-		}
216
-		$this->eventLogger->end('controller:' . get_class($controller) . '::' . $methodName);
217
-
218
-		if (!($response instanceof Response)) {
219
-			$this->logger->debug($controller::class . '::' . $methodName . ' returned raw data. Please wrap it in a Response or one of it\'s inheritors.');
220
-		}
221
-
222
-		// format response
223
-		if ($response instanceof DataResponse || !($response instanceof Response)) {
224
-			$format = $this->request->getFormat();
225
-
226
-			if ($format !== null) {
227
-				$response = $controller->buildResponse($response, $format);
228
-			} else {
229
-				$response = $controller->buildResponse($response);
230
-			}
231
-		}
232
-
233
-		return $response;
234
-	}
235
-
236
-	/**
237
-	 * @psalm-param mixed $value
238
-	 * @throws ParameterOutOfRangeException
239
-	 */
240
-	private function ensureParameterValueSatisfiesRange(string $param, $value): void {
241
-		$rangeInfo = $this->reflector->getRange($param);
242
-		if ($rangeInfo) {
243
-			if ($value < $rangeInfo['min'] || $value > $rangeInfo['max']) {
244
-				throw new ParameterOutOfRangeException(
245
-					$param,
246
-					$value,
247
-					$rangeInfo['min'],
248
-					$rangeInfo['max'],
249
-				);
250
-			}
251
-		}
252
-	}
29
+    /** @var MiddlewareDispatcher */
30
+    private $middlewareDispatcher;
31
+
32
+    /** @var Http */
33
+    private $protocol;
34
+
35
+    /** @var ControllerMethodReflector */
36
+    private $reflector;
37
+
38
+    /** @var IRequest */
39
+    private $request;
40
+
41
+    /** @var IConfig */
42
+    private $config;
43
+
44
+    /** @var ConnectionAdapter */
45
+    private $connection;
46
+
47
+    /** @var LoggerInterface */
48
+    private $logger;
49
+
50
+    /** @var IEventLogger */
51
+    private $eventLogger;
52
+
53
+    private ContainerInterface $appContainer;
54
+
55
+    /**
56
+     * @param Http $protocol the http protocol with contains all status headers
57
+     * @param MiddlewareDispatcher $middlewareDispatcher the dispatcher which
58
+     *                                                   runs the middleware
59
+     * @param ControllerMethodReflector $reflector the reflector that is used to inject
60
+     *                                             the arguments for the controller
61
+     * @param IRequest $request the incoming request
62
+     * @param IConfig $config
63
+     * @param ConnectionAdapter $connection
64
+     * @param LoggerInterface $logger
65
+     * @param IEventLogger $eventLogger
66
+     */
67
+    public function __construct(
68
+        Http $protocol,
69
+        MiddlewareDispatcher $middlewareDispatcher,
70
+        ControllerMethodReflector $reflector,
71
+        IRequest $request,
72
+        IConfig $config,
73
+        ConnectionAdapter $connection,
74
+        LoggerInterface $logger,
75
+        IEventLogger $eventLogger,
76
+        ContainerInterface $appContainer,
77
+    ) {
78
+        $this->protocol = $protocol;
79
+        $this->middlewareDispatcher = $middlewareDispatcher;
80
+        $this->reflector = $reflector;
81
+        $this->request = $request;
82
+        $this->config = $config;
83
+        $this->connection = $connection;
84
+        $this->logger = $logger;
85
+        $this->eventLogger = $eventLogger;
86
+        $this->appContainer = $appContainer;
87
+    }
88
+
89
+
90
+    /**
91
+     * Handles a request and calls the dispatcher on the controller
92
+     * @param Controller $controller the controller which will be called
93
+     * @param string $methodName the method name which will be called on
94
+     *                           the controller
95
+     * @return array $array[0] contains the http status header as a string,
96
+     *               $array[1] contains response headers as an array,
97
+     *               $array[2] contains response cookies as an array,
98
+     *               $array[3] contains the response output as a string,
99
+     *               $array[4] contains the response object
100
+     * @throws \Exception
101
+     */
102
+    public function dispatch(Controller $controller, string $methodName): array {
103
+        $out = [null, [], null];
104
+
105
+        try {
106
+            // prefill reflector with everything that's needed for the
107
+            // middlewares
108
+            $this->reflector->reflect($controller, $methodName);
109
+
110
+            $this->middlewareDispatcher->beforeController($controller,
111
+                $methodName);
112
+
113
+            $databaseStatsBefore = [];
114
+            if ($this->config->getSystemValueBool('debug', false)) {
115
+                $databaseStatsBefore = $this->connection->getInner()->getStats();
116
+            }
117
+
118
+            $response = $this->executeController($controller, $methodName);
119
+
120
+            if (!empty($databaseStatsBefore)) {
121
+                $databaseStatsAfter = $this->connection->getInner()->getStats();
122
+                $numBuilt = $databaseStatsAfter['built'] - $databaseStatsBefore['built'];
123
+                $numExecuted = $databaseStatsAfter['executed'] - $databaseStatsBefore['executed'];
124
+
125
+                if ($numBuilt > 50) {
126
+                    $this->logger->debug('Controller {class}::{method} created {count} QueryBuilder objects, please check if they are created inside a loop by accident.', [
127
+                        'class' => get_class($controller),
128
+                        'method' => $methodName,
129
+                        'count' => $numBuilt,
130
+                    ]);
131
+                }
132
+
133
+                if ($numExecuted > 100) {
134
+                    $this->logger->warning('Controller {class}::{method} executed {count} queries.', [
135
+                        'class' => get_class($controller),
136
+                        'method' => $methodName,
137
+                        'count' => $numExecuted,
138
+                    ]);
139
+                }
140
+            }
141
+
142
+            // if an exception appears, the middleware checks if it can handle the
143
+            // exception and creates a response. If no response is created, it is
144
+            // assumed that there's no middleware who can handle it and the error is
145
+            // thrown again
146
+        } catch (\Exception $exception) {
147
+            $response = $this->middlewareDispatcher->afterException(
148
+                $controller, $methodName, $exception);
149
+        } catch (\Throwable $throwable) {
150
+            $exception = new \Exception($throwable->getMessage() . ' in file \'' . $throwable->getFile() . '\' line ' . $throwable->getLine(), $throwable->getCode(), $throwable);
151
+            $response = $this->middlewareDispatcher->afterException(
152
+                $controller, $methodName, $exception);
153
+        }
154
+
155
+        $response = $this->middlewareDispatcher->afterController(
156
+            $controller, $methodName, $response);
157
+
158
+        // depending on the cache object the headers need to be changed
159
+        $out[0] = $this->protocol->getStatusHeader($response->getStatus());
160
+        $out[1] = array_merge($response->getHeaders());
161
+        $out[2] = $response->getCookies();
162
+        $out[3] = $this->middlewareDispatcher->beforeOutput(
163
+            $controller, $methodName, $response->render()
164
+        );
165
+        $out[4] = $response;
166
+
167
+        return $out;
168
+    }
169
+
170
+
171
+    /**
172
+     * Uses the reflected parameters, types and request parameters to execute
173
+     * the controller
174
+     * @param Controller $controller the controller to be executed
175
+     * @param string $methodName the method on the controller that should be executed
176
+     * @return Response
177
+     */
178
+    private function executeController(Controller $controller, string $methodName): Response {
179
+        $arguments = [];
180
+
181
+        // valid types that will be cast
182
+        $types = ['int', 'integer', 'bool', 'boolean', 'float', 'double'];
183
+
184
+        foreach ($this->reflector->getParameters() as $param => $default) {
185
+            // try to get the parameter from the request object and cast
186
+            // it to the type annotated in the @param annotation
187
+            $value = $this->request->getParam($param, $default);
188
+            $type = $this->reflector->getType($param);
189
+
190
+            // Converted the string `'false'` to false when the controller wants a boolean
191
+            if ($value === 'false' && ($type === 'bool' || $type === 'boolean')) {
192
+                $value = false;
193
+            } elseif ($value !== null && \in_array($type, $types, true)) {
194
+                settype($value, $type);
195
+                $this->ensureParameterValueSatisfiesRange($param, $value);
196
+            } elseif ($value === null && $type !== null && $this->appContainer->has($type)) {
197
+                $value = $this->appContainer->get($type);
198
+            }
199
+
200
+            $arguments[] = $value;
201
+        }
202
+
203
+        $this->eventLogger->start('controller:' . get_class($controller) . '::' . $methodName, 'App framework controller execution');
204
+        try {
205
+            $response = \call_user_func_array([$controller, $methodName], $arguments);
206
+        } catch (\TypeError $e) {
207
+            // Only intercept TypeErrors occurring on the first line, meaning that the invocation of the controller method failed.
208
+            // Any other TypeError happens inside the controller method logic and should be logged as normal.
209
+            if ($e->getFile() === $this->reflector->getFile() && $e->getLine() === $this->reflector->getStartLine()) {
210
+                $this->logger->debug('Failed to call controller method: ' . $e->getMessage(), ['exception' => $e]);
211
+                return new Response(Http::STATUS_BAD_REQUEST);
212
+            }
213
+
214
+            throw $e;
215
+        }
216
+        $this->eventLogger->end('controller:' . get_class($controller) . '::' . $methodName);
217
+
218
+        if (!($response instanceof Response)) {
219
+            $this->logger->debug($controller::class . '::' . $methodName . ' returned raw data. Please wrap it in a Response or one of it\'s inheritors.');
220
+        }
221
+
222
+        // format response
223
+        if ($response instanceof DataResponse || !($response instanceof Response)) {
224
+            $format = $this->request->getFormat();
225
+
226
+            if ($format !== null) {
227
+                $response = $controller->buildResponse($response, $format);
228
+            } else {
229
+                $response = $controller->buildResponse($response);
230
+            }
231
+        }
232
+
233
+        return $response;
234
+    }
235
+
236
+    /**
237
+     * @psalm-param mixed $value
238
+     * @throws ParameterOutOfRangeException
239
+     */
240
+    private function ensureParameterValueSatisfiesRange(string $param, $value): void {
241
+        $rangeInfo = $this->reflector->getRange($param);
242
+        if ($rangeInfo) {
243
+            if ($value < $rangeInfo['min'] || $value > $rangeInfo['max']) {
244
+                throw new ParameterOutOfRangeException(
245
+                    $param,
246
+                    $value,
247
+                    $rangeInfo['min'],
248
+                    $rangeInfo['max'],
249
+                );
250
+            }
251
+        }
252
+    }
253 253
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -147,7 +147,7 @@  discard block
 block discarded – undo
147 147
 			$response = $this->middlewareDispatcher->afterException(
148 148
 				$controller, $methodName, $exception);
149 149
 		} catch (\Throwable $throwable) {
150
-			$exception = new \Exception($throwable->getMessage() . ' in file \'' . $throwable->getFile() . '\' line ' . $throwable->getLine(), $throwable->getCode(), $throwable);
150
+			$exception = new \Exception($throwable->getMessage().' in file \''.$throwable->getFile().'\' line '.$throwable->getLine(), $throwable->getCode(), $throwable);
151 151
 			$response = $this->middlewareDispatcher->afterException(
152 152
 				$controller, $methodName, $exception);
153 153
 		}
@@ -200,23 +200,23 @@  discard block
 block discarded – undo
200 200
 			$arguments[] = $value;
201 201
 		}
202 202
 
203
-		$this->eventLogger->start('controller:' . get_class($controller) . '::' . $methodName, 'App framework controller execution');
203
+		$this->eventLogger->start('controller:'.get_class($controller).'::'.$methodName, 'App framework controller execution');
204 204
 		try {
205 205
 			$response = \call_user_func_array([$controller, $methodName], $arguments);
206 206
 		} catch (\TypeError $e) {
207 207
 			// Only intercept TypeErrors occurring on the first line, meaning that the invocation of the controller method failed.
208 208
 			// Any other TypeError happens inside the controller method logic and should be logged as normal.
209 209
 			if ($e->getFile() === $this->reflector->getFile() && $e->getLine() === $this->reflector->getStartLine()) {
210
-				$this->logger->debug('Failed to call controller method: ' . $e->getMessage(), ['exception' => $e]);
210
+				$this->logger->debug('Failed to call controller method: '.$e->getMessage(), ['exception' => $e]);
211 211
 				return new Response(Http::STATUS_BAD_REQUEST);
212 212
 			}
213 213
 
214 214
 			throw $e;
215 215
 		}
216
-		$this->eventLogger->end('controller:' . get_class($controller) . '::' . $methodName);
216
+		$this->eventLogger->end('controller:'.get_class($controller).'::'.$methodName);
217 217
 
218 218
 		if (!($response instanceof Response)) {
219
-			$this->logger->debug($controller::class . '::' . $methodName . ' returned raw data. Please wrap it in a Response or one of it\'s inheritors.');
219
+			$this->logger->debug($controller::class.'::'.$methodName.' returned raw data. Please wrap it in a Response or one of it\'s inheritors.');
220 220
 		}
221 221
 
222 222
 		// format response
Please login to merge, or discard this patch.
lib/private/Preview/Storage/LocalPreviewStorage.php 2 patches
Indentation   +212 added lines, -212 removed lines patch added patch discarded remove patch
@@ -29,216 +29,216 @@
 block discarded – undo
29 29
 use RecursiveIteratorIterator;
30 30
 
31 31
 class LocalPreviewStorage implements IPreviewStorage {
32
-	private readonly string $rootFolder;
33
-	private readonly string $instanceId;
34
-
35
-	public function __construct(
36
-		private readonly IConfig $config,
37
-		private readonly PreviewMapper $previewMapper,
38
-		private readonly IAppConfig $appConfig,
39
-		private readonly IDBConnection $connection,
40
-		private readonly IMimeTypeDetector $mimeTypeDetector,
41
-		private readonly LoggerInterface $logger,
42
-		private readonly IGenerator $generator,
43
-	) {
44
-		$this->instanceId = $this->config->getSystemValueString('instanceid');
45
-		$this->rootFolder = $this->config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data');
46
-	}
47
-
48
-	#[Override]
49
-	public function writePreview(Preview $preview, mixed $stream): int {
50
-		$previewPath = $this->constructPath($preview);
51
-		$this->createParentFiles($previewPath);
52
-		return file_put_contents($previewPath, $stream);
53
-	}
54
-
55
-	#[Override]
56
-	public function readPreview(Preview $preview): mixed {
57
-		$previewPath = $this->constructPath($preview);
58
-		$resource = @fopen($previewPath, 'r');
59
-		if ($resource === false) {
60
-			throw new NotFoundException('Unable to open preview stream at ' . $previewPath);
61
-		}
62
-		return $resource;
63
-	}
64
-
65
-	#[Override]
66
-	public function deletePreview(Preview $preview): void {
67
-		$previewPath = $this->constructPath($preview);
68
-		if (!@unlink($previewPath) && is_file($previewPath)) {
69
-			throw new NotPermittedException('Unable to delete preview at ' . $previewPath);
70
-		}
71
-	}
72
-
73
-	public function getPreviewRootFolder(): string {
74
-		return $this->rootFolder . '/appdata_' . $this->instanceId . '/preview/';
75
-	}
76
-
77
-	private function constructPath(Preview $preview): string {
78
-		return $this->getPreviewRootFolder() . implode('/', str_split(substr(md5((string)$preview->getFileId()), 0, 7))) . '/' . $preview->getFileId() . '/' . $preview->getName();
79
-	}
80
-
81
-	private function createParentFiles(string $path): void {
82
-		$dirname = dirname($path);
83
-		@mkdir($dirname, recursive: true);
84
-		if (!is_dir($dirname)) {
85
-			throw new NotPermittedException("Unable to create directory '$dirname'");
86
-		}
87
-	}
88
-
89
-	#[Override]
90
-	public function migratePreview(Preview $preview, SimpleFile $file): void {
91
-		// legacy flat directory
92
-		$sourcePath = $this->getPreviewRootFolder() . $preview->getFileId() . '/' . $preview->getName();
93
-		if (!file_exists($sourcePath)) {
94
-			return;
95
-		}
96
-
97
-		$destinationPath = $this->constructPath($preview);
98
-		if (file_exists($destinationPath)) {
99
-			@unlink($sourcePath); // We already have a new preview, just delete the old one
100
-			return;
101
-		}
102
-
103
-		$this->createParentFiles($destinationPath);
104
-		$ok = rename($sourcePath, $destinationPath);
105
-		if (!$ok) {
106
-			throw new LogicException('Failed to move ' . $sourcePath . ' to ' . $destinationPath);
107
-		}
108
-	}
109
-
110
-	#[Override]
111
-	public function scan(): int {
112
-		$checkForFileCache = !$this->appConfig->getValueBool('core', 'previewMovedDone');
113
-
114
-		$scanner = new RecursiveDirectoryIterator($this->getPreviewRootFolder());
115
-		$previewsFound = 0;
116
-		foreach (new RecursiveIteratorIterator($scanner) as $file) {
117
-			if ($file->isFile()) {
118
-				$preview = Preview::fromPath((string)$file, $this->mimeTypeDetector);
119
-				if ($preview === false) {
120
-					$this->logger->error('Unable to parse preview information for ' . $file->getRealPath());
121
-					continue;
122
-				}
123
-				$preview->setId($this->generator->nextId());
124
-				try {
125
-					$preview->setSize($file->getSize());
126
-					$preview->setMtime($file->getMtime());
127
-					$preview->setEncrypted(false);
128
-
129
-					$qb = $this->connection->getQueryBuilder();
130
-					$result = $qb->select('storage', 'etag', 'mimetype')
131
-						->from('filecache')
132
-						->where($qb->expr()->eq('fileid', $qb->createNamedParameter($preview->getFileId())))
133
-						->setMaxResults(1)
134
-						->runAcrossAllShards() // Unavoidable because we can't extract the storage_id from the preview name
135
-						->executeQuery()
136
-						->fetchAll();
137
-
138
-					if (empty($result)) {
139
-						// original file is deleted
140
-						@unlink($file->getRealPath());
141
-						continue;
142
-					}
143
-
144
-					if ($checkForFileCache) {
145
-						$relativePath = str_replace($this->rootFolder . '/', '', $file->getRealPath());
146
-						$rowAffected = $qb->delete('filecache')
147
-							->where($qb->expr()->eq('path_hash', $qb->createNamedParameter(md5($relativePath))))
148
-							->executeStatement();
149
-						if ($rowAffected > 0) {
150
-							$this->deleteParentsFromFileCache(dirname($relativePath));
151
-						}
152
-					}
153
-
154
-					$preview->setStorageId($result[0]['storage']);
155
-					$preview->setEtag($result[0]['etag']);
156
-					$preview->setSourceMimetype($result[0]['mimetype']);
157
-
158
-					// try to insert, if that fails the preview is already in the DB
159
-					$this->previewMapper->insert($preview);
160
-
161
-					// Move old flat preview to new format
162
-					$dirName = str_replace($this->getPreviewRootFolder(), '', $file->getPath());
163
-					if (preg_match('/[0-9a-e]\/[0-9a-e]\/[0-9a-e]\/[0-9a-e]\/[0-9a-e]\/[0-9a-e]\/[0-9a-e]\/[0-9]+/', $dirName) !== 1) {
164
-						$previewPath = $this->constructPath($preview);
165
-						$this->createParentFiles($previewPath);
166
-						$ok = rename($file->getRealPath(), $previewPath);
167
-						if (!$ok) {
168
-							throw new LogicException('Failed to move ' . $file->getRealPath() . ' to ' . $previewPath);
169
-						}
170
-					}
171
-				} catch (Exception $e) {
172
-					if ($e->getReason() !== Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) {
173
-						throw $e;
174
-					}
175
-				}
176
-				$previewsFound++;
177
-			}
178
-		}
179
-
180
-		return $previewsFound;
181
-	}
182
-
183
-	private function deleteParentsFromFileCache(string $dirname): void {
184
-		$qb = $this->connection->getQueryBuilder();
185
-
186
-		$result = $qb->select('fileid', 'path', 'storage', 'parent')
187
-			->from('filecache')
188
-			->where($qb->expr()->eq('path_hash', $qb->createNamedParameter(md5($dirname))))
189
-			->setMaxResults(1)
190
-			->runAcrossAllShards()
191
-			->executeQuery()
192
-			->fetchAll();
193
-
194
-		if (empty($result)) {
195
-			return;
196
-		}
197
-
198
-		$this->connection->beginTransaction();
199
-
200
-		$parentId = $result[0]['parent'];
201
-		$fileId = $result[0]['fileid'];
202
-		$storage = $result[0]['storage'];
203
-
204
-		try {
205
-			while (true) {
206
-				$qb = $this->connection->getQueryBuilder();
207
-				$childs = $qb->select('fileid', 'path', 'storage')
208
-					->from('filecache')
209
-					->where($qb->expr()->eq('parent', $qb->createNamedParameter($fileId)))
210
-					->hintShardKey('storage', $storage)
211
-					->executeQuery()
212
-					->fetchAll();
213
-
214
-				if (!empty($childs)) {
215
-					break;
216
-				}
217
-
218
-				$qb = $this->connection->getQueryBuilder();
219
-				$qb->delete('filecache')
220
-					->where($qb->expr()->eq('fileid', $qb->createNamedParameter($fileId)))
221
-					->hintShardKey('storage', $result[0]['storage'])
222
-					->executeStatement();
223
-
224
-				$qb = $this->connection->getQueryBuilder();
225
-				$result = $qb->select('fileid', 'path', 'storage', 'parent')
226
-					->from('filecache')
227
-					->where($qb->expr()->eq('fileid', $qb->createNamedParameter($parentId)))
228
-					->setMaxResults(1)
229
-					->hintShardKey('storage', $storage)
230
-					->executeQuery()
231
-					->fetchAll();
232
-
233
-				if (empty($result)) {
234
-					break;
235
-				}
236
-
237
-				$fileId = $parentId;
238
-				$parentId = $result[0]['parent'];
239
-			}
240
-		} finally {
241
-			$this->connection->commit();
242
-		}
243
-	}
32
+    private readonly string $rootFolder;
33
+    private readonly string $instanceId;
34
+
35
+    public function __construct(
36
+        private readonly IConfig $config,
37
+        private readonly PreviewMapper $previewMapper,
38
+        private readonly IAppConfig $appConfig,
39
+        private readonly IDBConnection $connection,
40
+        private readonly IMimeTypeDetector $mimeTypeDetector,
41
+        private readonly LoggerInterface $logger,
42
+        private readonly IGenerator $generator,
43
+    ) {
44
+        $this->instanceId = $this->config->getSystemValueString('instanceid');
45
+        $this->rootFolder = $this->config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data');
46
+    }
47
+
48
+    #[Override]
49
+    public function writePreview(Preview $preview, mixed $stream): int {
50
+        $previewPath = $this->constructPath($preview);
51
+        $this->createParentFiles($previewPath);
52
+        return file_put_contents($previewPath, $stream);
53
+    }
54
+
55
+    #[Override]
56
+    public function readPreview(Preview $preview): mixed {
57
+        $previewPath = $this->constructPath($preview);
58
+        $resource = @fopen($previewPath, 'r');
59
+        if ($resource === false) {
60
+            throw new NotFoundException('Unable to open preview stream at ' . $previewPath);
61
+        }
62
+        return $resource;
63
+    }
64
+
65
+    #[Override]
66
+    public function deletePreview(Preview $preview): void {
67
+        $previewPath = $this->constructPath($preview);
68
+        if (!@unlink($previewPath) && is_file($previewPath)) {
69
+            throw new NotPermittedException('Unable to delete preview at ' . $previewPath);
70
+        }
71
+    }
72
+
73
+    public function getPreviewRootFolder(): string {
74
+        return $this->rootFolder . '/appdata_' . $this->instanceId . '/preview/';
75
+    }
76
+
77
+    private function constructPath(Preview $preview): string {
78
+        return $this->getPreviewRootFolder() . implode('/', str_split(substr(md5((string)$preview->getFileId()), 0, 7))) . '/' . $preview->getFileId() . '/' . $preview->getName();
79
+    }
80
+
81
+    private function createParentFiles(string $path): void {
82
+        $dirname = dirname($path);
83
+        @mkdir($dirname, recursive: true);
84
+        if (!is_dir($dirname)) {
85
+            throw new NotPermittedException("Unable to create directory '$dirname'");
86
+        }
87
+    }
88
+
89
+    #[Override]
90
+    public function migratePreview(Preview $preview, SimpleFile $file): void {
91
+        // legacy flat directory
92
+        $sourcePath = $this->getPreviewRootFolder() . $preview->getFileId() . '/' . $preview->getName();
93
+        if (!file_exists($sourcePath)) {
94
+            return;
95
+        }
96
+
97
+        $destinationPath = $this->constructPath($preview);
98
+        if (file_exists($destinationPath)) {
99
+            @unlink($sourcePath); // We already have a new preview, just delete the old one
100
+            return;
101
+        }
102
+
103
+        $this->createParentFiles($destinationPath);
104
+        $ok = rename($sourcePath, $destinationPath);
105
+        if (!$ok) {
106
+            throw new LogicException('Failed to move ' . $sourcePath . ' to ' . $destinationPath);
107
+        }
108
+    }
109
+
110
+    #[Override]
111
+    public function scan(): int {
112
+        $checkForFileCache = !$this->appConfig->getValueBool('core', 'previewMovedDone');
113
+
114
+        $scanner = new RecursiveDirectoryIterator($this->getPreviewRootFolder());
115
+        $previewsFound = 0;
116
+        foreach (new RecursiveIteratorIterator($scanner) as $file) {
117
+            if ($file->isFile()) {
118
+                $preview = Preview::fromPath((string)$file, $this->mimeTypeDetector);
119
+                if ($preview === false) {
120
+                    $this->logger->error('Unable to parse preview information for ' . $file->getRealPath());
121
+                    continue;
122
+                }
123
+                $preview->setId($this->generator->nextId());
124
+                try {
125
+                    $preview->setSize($file->getSize());
126
+                    $preview->setMtime($file->getMtime());
127
+                    $preview->setEncrypted(false);
128
+
129
+                    $qb = $this->connection->getQueryBuilder();
130
+                    $result = $qb->select('storage', 'etag', 'mimetype')
131
+                        ->from('filecache')
132
+                        ->where($qb->expr()->eq('fileid', $qb->createNamedParameter($preview->getFileId())))
133
+                        ->setMaxResults(1)
134
+                        ->runAcrossAllShards() // Unavoidable because we can't extract the storage_id from the preview name
135
+                        ->executeQuery()
136
+                        ->fetchAll();
137
+
138
+                    if (empty($result)) {
139
+                        // original file is deleted
140
+                        @unlink($file->getRealPath());
141
+                        continue;
142
+                    }
143
+
144
+                    if ($checkForFileCache) {
145
+                        $relativePath = str_replace($this->rootFolder . '/', '', $file->getRealPath());
146
+                        $rowAffected = $qb->delete('filecache')
147
+                            ->where($qb->expr()->eq('path_hash', $qb->createNamedParameter(md5($relativePath))))
148
+                            ->executeStatement();
149
+                        if ($rowAffected > 0) {
150
+                            $this->deleteParentsFromFileCache(dirname($relativePath));
151
+                        }
152
+                    }
153
+
154
+                    $preview->setStorageId($result[0]['storage']);
155
+                    $preview->setEtag($result[0]['etag']);
156
+                    $preview->setSourceMimetype($result[0]['mimetype']);
157
+
158
+                    // try to insert, if that fails the preview is already in the DB
159
+                    $this->previewMapper->insert($preview);
160
+
161
+                    // Move old flat preview to new format
162
+                    $dirName = str_replace($this->getPreviewRootFolder(), '', $file->getPath());
163
+                    if (preg_match('/[0-9a-e]\/[0-9a-e]\/[0-9a-e]\/[0-9a-e]\/[0-9a-e]\/[0-9a-e]\/[0-9a-e]\/[0-9]+/', $dirName) !== 1) {
164
+                        $previewPath = $this->constructPath($preview);
165
+                        $this->createParentFiles($previewPath);
166
+                        $ok = rename($file->getRealPath(), $previewPath);
167
+                        if (!$ok) {
168
+                            throw new LogicException('Failed to move ' . $file->getRealPath() . ' to ' . $previewPath);
169
+                        }
170
+                    }
171
+                } catch (Exception $e) {
172
+                    if ($e->getReason() !== Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) {
173
+                        throw $e;
174
+                    }
175
+                }
176
+                $previewsFound++;
177
+            }
178
+        }
179
+
180
+        return $previewsFound;
181
+    }
182
+
183
+    private function deleteParentsFromFileCache(string $dirname): void {
184
+        $qb = $this->connection->getQueryBuilder();
185
+
186
+        $result = $qb->select('fileid', 'path', 'storage', 'parent')
187
+            ->from('filecache')
188
+            ->where($qb->expr()->eq('path_hash', $qb->createNamedParameter(md5($dirname))))
189
+            ->setMaxResults(1)
190
+            ->runAcrossAllShards()
191
+            ->executeQuery()
192
+            ->fetchAll();
193
+
194
+        if (empty($result)) {
195
+            return;
196
+        }
197
+
198
+        $this->connection->beginTransaction();
199
+
200
+        $parentId = $result[0]['parent'];
201
+        $fileId = $result[0]['fileid'];
202
+        $storage = $result[0]['storage'];
203
+
204
+        try {
205
+            while (true) {
206
+                $qb = $this->connection->getQueryBuilder();
207
+                $childs = $qb->select('fileid', 'path', 'storage')
208
+                    ->from('filecache')
209
+                    ->where($qb->expr()->eq('parent', $qb->createNamedParameter($fileId)))
210
+                    ->hintShardKey('storage', $storage)
211
+                    ->executeQuery()
212
+                    ->fetchAll();
213
+
214
+                if (!empty($childs)) {
215
+                    break;
216
+                }
217
+
218
+                $qb = $this->connection->getQueryBuilder();
219
+                $qb->delete('filecache')
220
+                    ->where($qb->expr()->eq('fileid', $qb->createNamedParameter($fileId)))
221
+                    ->hintShardKey('storage', $result[0]['storage'])
222
+                    ->executeStatement();
223
+
224
+                $qb = $this->connection->getQueryBuilder();
225
+                $result = $qb->select('fileid', 'path', 'storage', 'parent')
226
+                    ->from('filecache')
227
+                    ->where($qb->expr()->eq('fileid', $qb->createNamedParameter($parentId)))
228
+                    ->setMaxResults(1)
229
+                    ->hintShardKey('storage', $storage)
230
+                    ->executeQuery()
231
+                    ->fetchAll();
232
+
233
+                if (empty($result)) {
234
+                    break;
235
+                }
236
+
237
+                $fileId = $parentId;
238
+                $parentId = $result[0]['parent'];
239
+            }
240
+        } finally {
241
+            $this->connection->commit();
242
+        }
243
+    }
244 244
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -42,7 +42,7 @@  discard block
 block discarded – undo
42 42
 		private readonly IGenerator $generator,
43 43
 	) {
44 44
 		$this->instanceId = $this->config->getSystemValueString('instanceid');
45
-		$this->rootFolder = $this->config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data');
45
+		$this->rootFolder = $this->config->getSystemValue('datadirectory', OC::$SERVERROOT.'/data');
46 46
 	}
47 47
 
48 48
 	#[Override]
@@ -57,7 +57,7 @@  discard block
 block discarded – undo
57 57
 		$previewPath = $this->constructPath($preview);
58 58
 		$resource = @fopen($previewPath, 'r');
59 59
 		if ($resource === false) {
60
-			throw new NotFoundException('Unable to open preview stream at ' . $previewPath);
60
+			throw new NotFoundException('Unable to open preview stream at '.$previewPath);
61 61
 		}
62 62
 		return $resource;
63 63
 	}
@@ -66,16 +66,16 @@  discard block
 block discarded – undo
66 66
 	public function deletePreview(Preview $preview): void {
67 67
 		$previewPath = $this->constructPath($preview);
68 68
 		if (!@unlink($previewPath) && is_file($previewPath)) {
69
-			throw new NotPermittedException('Unable to delete preview at ' . $previewPath);
69
+			throw new NotPermittedException('Unable to delete preview at '.$previewPath);
70 70
 		}
71 71
 	}
72 72
 
73 73
 	public function getPreviewRootFolder(): string {
74
-		return $this->rootFolder . '/appdata_' . $this->instanceId . '/preview/';
74
+		return $this->rootFolder.'/appdata_'.$this->instanceId.'/preview/';
75 75
 	}
76 76
 
77 77
 	private function constructPath(Preview $preview): string {
78
-		return $this->getPreviewRootFolder() . implode('/', str_split(substr(md5((string)$preview->getFileId()), 0, 7))) . '/' . $preview->getFileId() . '/' . $preview->getName();
78
+		return $this->getPreviewRootFolder().implode('/', str_split(substr(md5((string) $preview->getFileId()), 0, 7))).'/'.$preview->getFileId().'/'.$preview->getName();
79 79
 	}
80 80
 
81 81
 	private function createParentFiles(string $path): void {
@@ -89,7 +89,7 @@  discard block
 block discarded – undo
89 89
 	#[Override]
90 90
 	public function migratePreview(Preview $preview, SimpleFile $file): void {
91 91
 		// legacy flat directory
92
-		$sourcePath = $this->getPreviewRootFolder() . $preview->getFileId() . '/' . $preview->getName();
92
+		$sourcePath = $this->getPreviewRootFolder().$preview->getFileId().'/'.$preview->getName();
93 93
 		if (!file_exists($sourcePath)) {
94 94
 			return;
95 95
 		}
@@ -103,7 +103,7 @@  discard block
 block discarded – undo
103 103
 		$this->createParentFiles($destinationPath);
104 104
 		$ok = rename($sourcePath, $destinationPath);
105 105
 		if (!$ok) {
106
-			throw new LogicException('Failed to move ' . $sourcePath . ' to ' . $destinationPath);
106
+			throw new LogicException('Failed to move '.$sourcePath.' to '.$destinationPath);
107 107
 		}
108 108
 	}
109 109
 
@@ -115,9 +115,9 @@  discard block
 block discarded – undo
115 115
 		$previewsFound = 0;
116 116
 		foreach (new RecursiveIteratorIterator($scanner) as $file) {
117 117
 			if ($file->isFile()) {
118
-				$preview = Preview::fromPath((string)$file, $this->mimeTypeDetector);
118
+				$preview = Preview::fromPath((string) $file, $this->mimeTypeDetector);
119 119
 				if ($preview === false) {
120
-					$this->logger->error('Unable to parse preview information for ' . $file->getRealPath());
120
+					$this->logger->error('Unable to parse preview information for '.$file->getRealPath());
121 121
 					continue;
122 122
 				}
123 123
 				$preview->setId($this->generator->nextId());
@@ -142,7 +142,7 @@  discard block
 block discarded – undo
142 142
 					}
143 143
 
144 144
 					if ($checkForFileCache) {
145
-						$relativePath = str_replace($this->rootFolder . '/', '', $file->getRealPath());
145
+						$relativePath = str_replace($this->rootFolder.'/', '', $file->getRealPath());
146 146
 						$rowAffected = $qb->delete('filecache')
147 147
 							->where($qb->expr()->eq('path_hash', $qb->createNamedParameter(md5($relativePath))))
148 148
 							->executeStatement();
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
 						$this->createParentFiles($previewPath);
166 166
 						$ok = rename($file->getRealPath(), $previewPath);
167 167
 						if (!$ok) {
168
-							throw new LogicException('Failed to move ' . $file->getRealPath() . ' to ' . $previewPath);
168
+							throw new LogicException('Failed to move '.$file->getRealPath().' to '.$previewPath);
169 169
 						}
170 170
 					}
171 171
 				} catch (Exception $e) {
Please login to merge, or discard this patch.
lib/private/Preview/Db/PreviewMapper.php 2 patches
Indentation   +205 added lines, -205 removed lines patch added patch discarded remove patch
@@ -23,209 +23,209 @@
 block discarded – undo
23 23
  */
24 24
 class PreviewMapper extends QBMapper {
25 25
 
26
-	private const TABLE_NAME = 'previews';
27
-	private const LOCATION_TABLE_NAME = 'preview_locations';
28
-	private const VERSION_TABLE_NAME = 'preview_versions';
29
-
30
-	public function __construct(
31
-		IDBConnection $db,
32
-		private readonly IMimeTypeLoader $mimeTypeLoader,
33
-		private readonly IGenerator $snowflake,
34
-	) {
35
-		parent::__construct($db, self::TABLE_NAME, Preview::class);
36
-	}
37
-
38
-	protected function mapRowToEntity(array $row): Entity {
39
-		$row['mimetype'] = $this->mimeTypeLoader->getMimetypeById((int)$row['mimetype_id']);
40
-		$row['source_mimetype'] = $this->mimeTypeLoader->getMimetypeById((int)$row['source_mimetype_id']);
41
-
42
-		return parent::mapRowToEntity($row);
43
-	}
44
-
45
-	#[Override]
46
-	public function insert(Entity $entity): Entity {
47
-		/** @var Preview $preview */
48
-		$preview = $entity;
49
-
50
-		$preview->setMimetypeId($this->mimeTypeLoader->getId($preview->getMimeType()));
51
-		$preview->setSourceMimetypeId($this->mimeTypeLoader->getId($preview->getSourceMimeType()));
52
-
53
-		if ($preview->getVersion() !== null && $preview->getVersion() !== '') {
54
-			$qb = $this->db->getQueryBuilder();
55
-			$id = $this->snowflake->nextId();
56
-			$qb->insert(self::VERSION_TABLE_NAME)
57
-				->values([
58
-					'id' => $id,
59
-					'version' => $preview->getVersion(),
60
-					'file_id' => $preview->getFileId(),
61
-				])
62
-				->executeStatement();
63
-			$entity->setVersionId($id);
64
-		}
65
-		return parent::insert($preview);
66
-	}
67
-
68
-	#[Override]
69
-	public function update(Entity $entity): Entity {
70
-		/** @var Preview $preview */
71
-		$preview = $entity;
72
-
73
-		$preview->setMimetypeId($this->mimeTypeLoader->getId($preview->getMimeType()));
74
-		$preview->setSourceMimetypeId($this->mimeTypeLoader->getId($preview->getSourceMimeType()));
75
-
76
-		return parent::update($preview);
77
-	}
78
-
79
-	#[Override]
80
-	public function delete(Entity $entity): Entity {
81
-		/** @var Preview $preview */
82
-		$preview = $entity;
83
-		if ($preview->getVersion() !== null && $preview->getVersion() !== '') {
84
-			$qb = $this->db->getQueryBuilder();
85
-			$qb->delete(self::VERSION_TABLE_NAME)
86
-				->where($qb->expr()->eq('file_id', $qb->createNamedParameter($preview->getFileId())))
87
-				->andWhere($qb->expr()->eq('version', $qb->createNamedParameter($preview->getVersion())))
88
-				->executeStatement();
89
-		}
90
-
91
-		return parent::delete($entity);
92
-	}
93
-
94
-	/**
95
-	 * @return \Generator<Preview>
96
-	 * @throws Exception
97
-	 */
98
-	public function getAvailablePreviewsForFile(int $fileId): \Generator {
99
-		$selectQb = $this->db->getQueryBuilder();
100
-		$this->joinLocation($selectQb)
101
-			->where($selectQb->expr()->eq('p.file_id', $selectQb->createNamedParameter($fileId, IQueryBuilder::PARAM_INT)));
102
-		yield from $this->yieldEntities($selectQb);
103
-	}
104
-
105
-	/**
106
-	 * @param int[] $fileIds
107
-	 * @return array<int, Preview[]>
108
-	 * @throws Exception
109
-	 */
110
-	public function getAvailablePreviews(array $fileIds): array {
111
-		$selectQb = $this->db->getQueryBuilder();
112
-		$this->joinLocation($selectQb)
113
-			->where(
114
-				$selectQb->expr()->in('p.file_id', $selectQb->createNamedParameter($fileIds, IQueryBuilder::PARAM_INT_ARRAY)),
115
-			);
116
-		$previews = array_fill_keys($fileIds, []);
117
-		foreach ($this->yieldEntities($selectQb) as $preview) {
118
-			$previews[$preview->getFileId()][] = $preview;
119
-		}
120
-		return $previews;
121
-	}
122
-
123
-	/**
124
-	 * @return \Generator<Preview>
125
-	 */
126
-	public function getByFileId(int $fileId): \Generator {
127
-		$selectQb = $this->db->getQueryBuilder();
128
-		$this->joinLocation($selectQb)
129
-			->where($selectQb->expr()->eq('file_id', $selectQb->createNamedParameter($fileId, IQueryBuilder::PARAM_INT)));
130
-		yield from $this->yieldEntities($selectQb);
131
-	}
132
-
133
-	/**
134
-	 * @param int[] $previewIds
135
-	 */
136
-	public function deleteByIds(array $previewIds): void {
137
-		$qb = $this->db->getQueryBuilder();
138
-		$qb->delete(self::TABLE_NAME)
139
-			->where($qb->expr()->andX(
140
-				$qb->expr()->in('id', $qb->createNamedParameter($previewIds, IQueryBuilder::PARAM_INT_ARRAY))
141
-			))->executeStatement();
142
-	}
143
-
144
-	protected function joinLocation(IQueryBuilder $qb): IQueryBuilder {
145
-		return $qb->select('p.*', 'l.bucket_name', 'l.object_store_name', 'v.version')
146
-			->from(self::TABLE_NAME, 'p')
147
-			->leftJoin('p', self::LOCATION_TABLE_NAME, 'l', $qb->expr()->eq(
148
-				'p.location_id', 'l.id'
149
-			))
150
-			->leftJoin('p', self::VERSION_TABLE_NAME, 'v', $qb->expr()->eq(
151
-				'p.version_id', 'v.id'
152
-			));
153
-	}
154
-
155
-	/**
156
-	 * Get the location id corresponding to the $bucket and $objectStore. Create one
157
-	 * if not existing yet.
158
-	 *
159
-	 * @throws Exception
160
-	 */
161
-	public function getLocationId(string $bucket, string $objectStore): string {
162
-		$qb = $this->db->getQueryBuilder();
163
-		$result = $qb->select('id')
164
-			->from(self::LOCATION_TABLE_NAME)
165
-			->where($qb->expr()->eq('bucket_name', $qb->createNamedParameter($bucket)))
166
-			->andWhere($qb->expr()->eq('object_store_name', $qb->createNamedParameter($objectStore)))
167
-			->executeQuery();
168
-		$data = $result->fetchOne();
169
-		if ($data) {
170
-			return (string)$data;
171
-		} else {
172
-			try {
173
-				$id = $this->snowflake->nextId();
174
-				$qb->insert(self::LOCATION_TABLE_NAME)
175
-					->values([
176
-						'id' => $qb->createNamedParameter($id),
177
-						'bucket_name' => $qb->createNamedParameter($bucket),
178
-						'object_store_name' => $qb->createNamedParameter($objectStore),
179
-					])->executeStatement();
180
-				return $id;
181
-			} catch (Exception $e) {
182
-				if ($e->getReason() === Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) {
183
-					// Fetch again as there seems to be another entry added meanwhile
184
-					$result = $qb->select('id')
185
-						->from(self::LOCATION_TABLE_NAME)
186
-						->where($qb->expr()->eq('bucket_name', $qb->createNamedParameter($bucket)))
187
-						->andWhere($qb->expr()->eq('object_store_name', $qb->createNamedParameter($objectStore)))
188
-						->executeQuery();
189
-					$data = $result->fetchOne();
190
-					if ($data) {
191
-						return (string)$data;
192
-					}
193
-				}
194
-
195
-				throw $e;
196
-			}
197
-		}
198
-	}
199
-
200
-	public function deleteAll(): void {
201
-		$delete = $this->db->getQueryBuilder();
202
-		$delete->delete($this->getTableName());
203
-	}
204
-
205
-	/**
206
-	 * @return \Generator<Preview>
207
-	 */
208
-	public function getPreviews(int $lastId, int $limit = 1000): \Generator {
209
-		$qb = $this->db->getQueryBuilder();
210
-		$this->joinLocation($qb)
211
-			->where($qb->expr()->gt('p.id', $qb->createNamedParameter($lastId, IQueryBuilder::PARAM_INT)))
212
-			->setMaxResults($limit);
213
-		return $this->yieldEntities($qb);
214
-
215
-	}
216
-
217
-	/**
218
-	 * @param string[] $mimeTypes
219
-	 * @return \Generator<Preview>
220
-	 */
221
-	public function getPreviewsForMimeTypes(array $mimeTypes): \Generator {
222
-		$qb = $this->db->getQueryBuilder();
223
-		$this->joinLocation($qb)
224
-			->where($qb->expr()->orX(
225
-				...array_map(function (string $mimeType) use ($qb): string {
226
-					return $qb->expr()->eq('source_mimetype_id', $qb->createNamedParameter($this->mimeTypeLoader->getId($mimeType), IQueryBuilder::PARAM_INT));
227
-				}, $mimeTypes)
228
-			));
229
-		return $this->yieldEntities($qb);
230
-	}
26
+    private const TABLE_NAME = 'previews';
27
+    private const LOCATION_TABLE_NAME = 'preview_locations';
28
+    private const VERSION_TABLE_NAME = 'preview_versions';
29
+
30
+    public function __construct(
31
+        IDBConnection $db,
32
+        private readonly IMimeTypeLoader $mimeTypeLoader,
33
+        private readonly IGenerator $snowflake,
34
+    ) {
35
+        parent::__construct($db, self::TABLE_NAME, Preview::class);
36
+    }
37
+
38
+    protected function mapRowToEntity(array $row): Entity {
39
+        $row['mimetype'] = $this->mimeTypeLoader->getMimetypeById((int)$row['mimetype_id']);
40
+        $row['source_mimetype'] = $this->mimeTypeLoader->getMimetypeById((int)$row['source_mimetype_id']);
41
+
42
+        return parent::mapRowToEntity($row);
43
+    }
44
+
45
+    #[Override]
46
+    public function insert(Entity $entity): Entity {
47
+        /** @var Preview $preview */
48
+        $preview = $entity;
49
+
50
+        $preview->setMimetypeId($this->mimeTypeLoader->getId($preview->getMimeType()));
51
+        $preview->setSourceMimetypeId($this->mimeTypeLoader->getId($preview->getSourceMimeType()));
52
+
53
+        if ($preview->getVersion() !== null && $preview->getVersion() !== '') {
54
+            $qb = $this->db->getQueryBuilder();
55
+            $id = $this->snowflake->nextId();
56
+            $qb->insert(self::VERSION_TABLE_NAME)
57
+                ->values([
58
+                    'id' => $id,
59
+                    'version' => $preview->getVersion(),
60
+                    'file_id' => $preview->getFileId(),
61
+                ])
62
+                ->executeStatement();
63
+            $entity->setVersionId($id);
64
+        }
65
+        return parent::insert($preview);
66
+    }
67
+
68
+    #[Override]
69
+    public function update(Entity $entity): Entity {
70
+        /** @var Preview $preview */
71
+        $preview = $entity;
72
+
73
+        $preview->setMimetypeId($this->mimeTypeLoader->getId($preview->getMimeType()));
74
+        $preview->setSourceMimetypeId($this->mimeTypeLoader->getId($preview->getSourceMimeType()));
75
+
76
+        return parent::update($preview);
77
+    }
78
+
79
+    #[Override]
80
+    public function delete(Entity $entity): Entity {
81
+        /** @var Preview $preview */
82
+        $preview = $entity;
83
+        if ($preview->getVersion() !== null && $preview->getVersion() !== '') {
84
+            $qb = $this->db->getQueryBuilder();
85
+            $qb->delete(self::VERSION_TABLE_NAME)
86
+                ->where($qb->expr()->eq('file_id', $qb->createNamedParameter($preview->getFileId())))
87
+                ->andWhere($qb->expr()->eq('version', $qb->createNamedParameter($preview->getVersion())))
88
+                ->executeStatement();
89
+        }
90
+
91
+        return parent::delete($entity);
92
+    }
93
+
94
+    /**
95
+     * @return \Generator<Preview>
96
+     * @throws Exception
97
+     */
98
+    public function getAvailablePreviewsForFile(int $fileId): \Generator {
99
+        $selectQb = $this->db->getQueryBuilder();
100
+        $this->joinLocation($selectQb)
101
+            ->where($selectQb->expr()->eq('p.file_id', $selectQb->createNamedParameter($fileId, IQueryBuilder::PARAM_INT)));
102
+        yield from $this->yieldEntities($selectQb);
103
+    }
104
+
105
+    /**
106
+     * @param int[] $fileIds
107
+     * @return array<int, Preview[]>
108
+     * @throws Exception
109
+     */
110
+    public function getAvailablePreviews(array $fileIds): array {
111
+        $selectQb = $this->db->getQueryBuilder();
112
+        $this->joinLocation($selectQb)
113
+            ->where(
114
+                $selectQb->expr()->in('p.file_id', $selectQb->createNamedParameter($fileIds, IQueryBuilder::PARAM_INT_ARRAY)),
115
+            );
116
+        $previews = array_fill_keys($fileIds, []);
117
+        foreach ($this->yieldEntities($selectQb) as $preview) {
118
+            $previews[$preview->getFileId()][] = $preview;
119
+        }
120
+        return $previews;
121
+    }
122
+
123
+    /**
124
+     * @return \Generator<Preview>
125
+     */
126
+    public function getByFileId(int $fileId): \Generator {
127
+        $selectQb = $this->db->getQueryBuilder();
128
+        $this->joinLocation($selectQb)
129
+            ->where($selectQb->expr()->eq('file_id', $selectQb->createNamedParameter($fileId, IQueryBuilder::PARAM_INT)));
130
+        yield from $this->yieldEntities($selectQb);
131
+    }
132
+
133
+    /**
134
+     * @param int[] $previewIds
135
+     */
136
+    public function deleteByIds(array $previewIds): void {
137
+        $qb = $this->db->getQueryBuilder();
138
+        $qb->delete(self::TABLE_NAME)
139
+            ->where($qb->expr()->andX(
140
+                $qb->expr()->in('id', $qb->createNamedParameter($previewIds, IQueryBuilder::PARAM_INT_ARRAY))
141
+            ))->executeStatement();
142
+    }
143
+
144
+    protected function joinLocation(IQueryBuilder $qb): IQueryBuilder {
145
+        return $qb->select('p.*', 'l.bucket_name', 'l.object_store_name', 'v.version')
146
+            ->from(self::TABLE_NAME, 'p')
147
+            ->leftJoin('p', self::LOCATION_TABLE_NAME, 'l', $qb->expr()->eq(
148
+                'p.location_id', 'l.id'
149
+            ))
150
+            ->leftJoin('p', self::VERSION_TABLE_NAME, 'v', $qb->expr()->eq(
151
+                'p.version_id', 'v.id'
152
+            ));
153
+    }
154
+
155
+    /**
156
+     * Get the location id corresponding to the $bucket and $objectStore. Create one
157
+     * if not existing yet.
158
+     *
159
+     * @throws Exception
160
+     */
161
+    public function getLocationId(string $bucket, string $objectStore): string {
162
+        $qb = $this->db->getQueryBuilder();
163
+        $result = $qb->select('id')
164
+            ->from(self::LOCATION_TABLE_NAME)
165
+            ->where($qb->expr()->eq('bucket_name', $qb->createNamedParameter($bucket)))
166
+            ->andWhere($qb->expr()->eq('object_store_name', $qb->createNamedParameter($objectStore)))
167
+            ->executeQuery();
168
+        $data = $result->fetchOne();
169
+        if ($data) {
170
+            return (string)$data;
171
+        } else {
172
+            try {
173
+                $id = $this->snowflake->nextId();
174
+                $qb->insert(self::LOCATION_TABLE_NAME)
175
+                    ->values([
176
+                        'id' => $qb->createNamedParameter($id),
177
+                        'bucket_name' => $qb->createNamedParameter($bucket),
178
+                        'object_store_name' => $qb->createNamedParameter($objectStore),
179
+                    ])->executeStatement();
180
+                return $id;
181
+            } catch (Exception $e) {
182
+                if ($e->getReason() === Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) {
183
+                    // Fetch again as there seems to be another entry added meanwhile
184
+                    $result = $qb->select('id')
185
+                        ->from(self::LOCATION_TABLE_NAME)
186
+                        ->where($qb->expr()->eq('bucket_name', $qb->createNamedParameter($bucket)))
187
+                        ->andWhere($qb->expr()->eq('object_store_name', $qb->createNamedParameter($objectStore)))
188
+                        ->executeQuery();
189
+                    $data = $result->fetchOne();
190
+                    if ($data) {
191
+                        return (string)$data;
192
+                    }
193
+                }
194
+
195
+                throw $e;
196
+            }
197
+        }
198
+    }
199
+
200
+    public function deleteAll(): void {
201
+        $delete = $this->db->getQueryBuilder();
202
+        $delete->delete($this->getTableName());
203
+    }
204
+
205
+    /**
206
+     * @return \Generator<Preview>
207
+     */
208
+    public function getPreviews(int $lastId, int $limit = 1000): \Generator {
209
+        $qb = $this->db->getQueryBuilder();
210
+        $this->joinLocation($qb)
211
+            ->where($qb->expr()->gt('p.id', $qb->createNamedParameter($lastId, IQueryBuilder::PARAM_INT)))
212
+            ->setMaxResults($limit);
213
+        return $this->yieldEntities($qb);
214
+
215
+    }
216
+
217
+    /**
218
+     * @param string[] $mimeTypes
219
+     * @return \Generator<Preview>
220
+     */
221
+    public function getPreviewsForMimeTypes(array $mimeTypes): \Generator {
222
+        $qb = $this->db->getQueryBuilder();
223
+        $this->joinLocation($qb)
224
+            ->where($qb->expr()->orX(
225
+                ...array_map(function (string $mimeType) use ($qb): string {
226
+                    return $qb->expr()->eq('source_mimetype_id', $qb->createNamedParameter($this->mimeTypeLoader->getId($mimeType), IQueryBuilder::PARAM_INT));
227
+                }, $mimeTypes)
228
+            ));
229
+        return $this->yieldEntities($qb);
230
+    }
231 231
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -36,8 +36,8 @@  discard block
 block discarded – undo
36 36
 	}
37 37
 
38 38
 	protected function mapRowToEntity(array $row): Entity {
39
-		$row['mimetype'] = $this->mimeTypeLoader->getMimetypeById((int)$row['mimetype_id']);
40
-		$row['source_mimetype'] = $this->mimeTypeLoader->getMimetypeById((int)$row['source_mimetype_id']);
39
+		$row['mimetype'] = $this->mimeTypeLoader->getMimetypeById((int) $row['mimetype_id']);
40
+		$row['source_mimetype'] = $this->mimeTypeLoader->getMimetypeById((int) $row['source_mimetype_id']);
41 41
 
42 42
 		return parent::mapRowToEntity($row);
43 43
 	}
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
 			->executeQuery();
168 168
 		$data = $result->fetchOne();
169 169
 		if ($data) {
170
-			return (string)$data;
170
+			return (string) $data;
171 171
 		} else {
172 172
 			try {
173 173
 				$id = $this->snowflake->nextId();
@@ -188,7 +188,7 @@  discard block
 block discarded – undo
188 188
 						->executeQuery();
189 189
 					$data = $result->fetchOne();
190 190
 					if ($data) {
191
-						return (string)$data;
191
+						return (string) $data;
192 192
 					}
193 193
 				}
194 194
 
@@ -222,7 +222,7 @@  discard block
 block discarded – undo
222 222
 		$qb = $this->db->getQueryBuilder();
223 223
 		$this->joinLocation($qb)
224 224
 			->where($qb->expr()->orX(
225
-				...array_map(function (string $mimeType) use ($qb): string {
225
+				...array_map(function(string $mimeType) use ($qb): string {
226 226
 					return $qb->expr()->eq('source_mimetype_id', $qb->createNamedParameter($this->mimeTypeLoader->getId($mimeType), IQueryBuilder::PARAM_INT));
227 227
 				}, $mimeTypes)
228 228
 			));
Please login to merge, or discard this patch.
lib/private/Preview/Db/Preview.php 1 patch
Indentation   +123 added lines, -123 removed lines patch added patch discarded remove patch
@@ -56,127 +56,127 @@
 block discarded – undo
56 56
  * @see PreviewMapper
57 57
  */
58 58
 class Preview extends Entity {
59
-	protected ?int $fileId = null;
60
-	protected ?int $oldFileId = null;
61
-	protected ?int $storageId = null;
62
-	protected ?string $locationId = null;
63
-	protected ?string $bucketName = null;
64
-	protected ?string $objectStoreName = null;
65
-	protected ?int $width = null;
66
-	protected ?int $height = null;
67
-	protected ?int $mimetypeId = null;
68
-	protected ?int $sourceMimetypeId = null;
69
-	protected string $mimetype = 'application/octet-stream';
70
-	protected string $sourceMimetype = 'application/octet-stream';
71
-	protected ?int $mtime = null;
72
-	protected ?int $size = null;
73
-	protected ?bool $max = null;
74
-	protected ?bool $cropped = null;
75
-	protected ?string $etag = null;
76
-	protected ?string $version = null;
77
-	protected ?string $versionId = null;
78
-	protected ?bool $encrypted = null;
79
-
80
-	public function __construct() {
81
-		$this->addType('id', Types::STRING);
82
-		$this->addType('fileId', Types::BIGINT);
83
-		$this->addType('storageId', Types::BIGINT);
84
-		$this->addType('oldFileId', Types::BIGINT);
85
-		$this->addType('locationId', Types::STRING);
86
-		$this->addType('width', Types::INTEGER);
87
-		$this->addType('height', Types::INTEGER);
88
-		$this->addType('mimetypeId', Types::INTEGER);
89
-		$this->addType('sourceMimetypeId', Types::INTEGER);
90
-		$this->addType('mtime', Types::INTEGER);
91
-		$this->addType('size', Types::INTEGER);
92
-		$this->addType('max', Types::BOOLEAN);
93
-		$this->addType('cropped', Types::BOOLEAN);
94
-		$this->addType('encrypted', Types::BOOLEAN);
95
-		$this->addType('etag', Types::STRING);
96
-		$this->addType('versionId', Types::STRING);
97
-	}
98
-
99
-	public static function fromPath(string $path, IMimeTypeDetector $mimeTypeDetector): Preview|false {
100
-		$preview = new self();
101
-		$preview->setFileId((int)basename(dirname($path)));
102
-
103
-		$fileName = pathinfo($path, PATHINFO_FILENAME) . '.' . pathinfo($path, PATHINFO_EXTENSION);
104
-		$ok = preg_match('/(([A-Za-z0-9\+\/]+)-)?([0-9]+)-([0-9]+)(-(max))?(-(crop))?\.([a-z]{3,4})/', $fileName, $matches);
105
-
106
-		if ($ok !== 1) {
107
-			return false;
108
-		}
109
-
110
-		[
111
-			2 => $version,
112
-			3 => $width,
113
-			4 => $height,
114
-			6 => $max,
115
-			8 => $crop,
116
-		] = $matches;
117
-
118
-		$preview->setMimeType($mimeTypeDetector->detectPath($fileName));
119
-
120
-		$preview->setWidth((int)$width);
121
-		$preview->setHeight((int)$height);
122
-		$preview->setCropped($crop === 'crop');
123
-		$preview->setMax($max === 'max');
124
-
125
-		if (!empty($version)) {
126
-			$preview->setVersion($version);
127
-		}
128
-		return $preview;
129
-	}
130
-
131
-	public function getName(): string {
132
-		$path = ($this->getVersion() > -1 ? $this->getVersion() . '-' : '') . $this->getWidth() . '-' . $this->getHeight();
133
-		if ($this->isCropped()) {
134
-			$path .= '-crop';
135
-		}
136
-		if ($this->isMax()) {
137
-			$path .= '-max';
138
-		}
139
-
140
-		$ext = $this->getExtension();
141
-		$path .= '.' . $ext;
142
-		return $path;
143
-	}
144
-
145
-	public function getExtension(): string {
146
-		return match ($this->getMimeType()) {
147
-			'image/png' => 'png',
148
-			'image/gif' => 'gif',
149
-			'image/jpeg' => 'jpg',
150
-			'image/webp' => 'webp',
151
-			default => 'png',
152
-		};
153
-	}
154
-
155
-	public function setBucketName(string $bucketName): void {
156
-		$this->bucketName = $bucketName;
157
-	}
158
-
159
-	public function setObjectStoreName(string $objectStoreName): void {
160
-		$this->objectStoreName = $objectStoreName;
161
-	}
162
-
163
-	public function setVersion(?string $version): void {
164
-		$this->version = $version;
165
-	}
166
-
167
-	public function getMimeType(): string {
168
-		return $this->mimetype;
169
-	}
170
-
171
-	public function setMimeType(string $mimeType): void {
172
-		$this->mimetype = $mimeType;
173
-	}
174
-
175
-	public function getSourceMimeType(): string {
176
-		return $this->sourceMimetype;
177
-	}
178
-
179
-	public function setSourceMimeType(string $mimeType): void {
180
-		$this->sourceMimetype = $mimeType;
181
-	}
59
+    protected ?int $fileId = null;
60
+    protected ?int $oldFileId = null;
61
+    protected ?int $storageId = null;
62
+    protected ?string $locationId = null;
63
+    protected ?string $bucketName = null;
64
+    protected ?string $objectStoreName = null;
65
+    protected ?int $width = null;
66
+    protected ?int $height = null;
67
+    protected ?int $mimetypeId = null;
68
+    protected ?int $sourceMimetypeId = null;
69
+    protected string $mimetype = 'application/octet-stream';
70
+    protected string $sourceMimetype = 'application/octet-stream';
71
+    protected ?int $mtime = null;
72
+    protected ?int $size = null;
73
+    protected ?bool $max = null;
74
+    protected ?bool $cropped = null;
75
+    protected ?string $etag = null;
76
+    protected ?string $version = null;
77
+    protected ?string $versionId = null;
78
+    protected ?bool $encrypted = null;
79
+
80
+    public function __construct() {
81
+        $this->addType('id', Types::STRING);
82
+        $this->addType('fileId', Types::BIGINT);
83
+        $this->addType('storageId', Types::BIGINT);
84
+        $this->addType('oldFileId', Types::BIGINT);
85
+        $this->addType('locationId', Types::STRING);
86
+        $this->addType('width', Types::INTEGER);
87
+        $this->addType('height', Types::INTEGER);
88
+        $this->addType('mimetypeId', Types::INTEGER);
89
+        $this->addType('sourceMimetypeId', Types::INTEGER);
90
+        $this->addType('mtime', Types::INTEGER);
91
+        $this->addType('size', Types::INTEGER);
92
+        $this->addType('max', Types::BOOLEAN);
93
+        $this->addType('cropped', Types::BOOLEAN);
94
+        $this->addType('encrypted', Types::BOOLEAN);
95
+        $this->addType('etag', Types::STRING);
96
+        $this->addType('versionId', Types::STRING);
97
+    }
98
+
99
+    public static function fromPath(string $path, IMimeTypeDetector $mimeTypeDetector): Preview|false {
100
+        $preview = new self();
101
+        $preview->setFileId((int)basename(dirname($path)));
102
+
103
+        $fileName = pathinfo($path, PATHINFO_FILENAME) . '.' . pathinfo($path, PATHINFO_EXTENSION);
104
+        $ok = preg_match('/(([A-Za-z0-9\+\/]+)-)?([0-9]+)-([0-9]+)(-(max))?(-(crop))?\.([a-z]{3,4})/', $fileName, $matches);
105
+
106
+        if ($ok !== 1) {
107
+            return false;
108
+        }
109
+
110
+        [
111
+            2 => $version,
112
+            3 => $width,
113
+            4 => $height,
114
+            6 => $max,
115
+            8 => $crop,
116
+        ] = $matches;
117
+
118
+        $preview->setMimeType($mimeTypeDetector->detectPath($fileName));
119
+
120
+        $preview->setWidth((int)$width);
121
+        $preview->setHeight((int)$height);
122
+        $preview->setCropped($crop === 'crop');
123
+        $preview->setMax($max === 'max');
124
+
125
+        if (!empty($version)) {
126
+            $preview->setVersion($version);
127
+        }
128
+        return $preview;
129
+    }
130
+
131
+    public function getName(): string {
132
+        $path = ($this->getVersion() > -1 ? $this->getVersion() . '-' : '') . $this->getWidth() . '-' . $this->getHeight();
133
+        if ($this->isCropped()) {
134
+            $path .= '-crop';
135
+        }
136
+        if ($this->isMax()) {
137
+            $path .= '-max';
138
+        }
139
+
140
+        $ext = $this->getExtension();
141
+        $path .= '.' . $ext;
142
+        return $path;
143
+    }
144
+
145
+    public function getExtension(): string {
146
+        return match ($this->getMimeType()) {
147
+            'image/png' => 'png',
148
+            'image/gif' => 'gif',
149
+            'image/jpeg' => 'jpg',
150
+            'image/webp' => 'webp',
151
+            default => 'png',
152
+        };
153
+    }
154
+
155
+    public function setBucketName(string $bucketName): void {
156
+        $this->bucketName = $bucketName;
157
+    }
158
+
159
+    public function setObjectStoreName(string $objectStoreName): void {
160
+        $this->objectStoreName = $objectStoreName;
161
+    }
162
+
163
+    public function setVersion(?string $version): void {
164
+        $this->version = $version;
165
+    }
166
+
167
+    public function getMimeType(): string {
168
+        return $this->mimetype;
169
+    }
170
+
171
+    public function setMimeType(string $mimeType): void {
172
+        $this->mimetype = $mimeType;
173
+    }
174
+
175
+    public function getSourceMimeType(): string {
176
+        return $this->sourceMimetype;
177
+    }
178
+
179
+    public function setSourceMimeType(string $mimeType): void {
180
+        $this->sourceMimetype = $mimeType;
181
+    }
182 182
 }
Please login to merge, or discard this patch.