Completed
Pull Request — master (#9009)
by Jan-Christoph
18:50
created
apps/dav/lib/SystemTag/SystemTagsObjectMappingCollection.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -89,6 +89,9 @@
 block discarded – undo
89 89
 		$this->user = $user;
90 90
 	}
91 91
 
92
+	/**
93
+	 * @param string $tagId
94
+	 */
92 95
 	function createFile($tagId, $data = null) {
93 96
 		try {
94 97
 			$tags = $this->tagManager->getTagsByIds([$tagId]);
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -95,15 +95,15 @@  discard block
 block discarded – undo
95 95
 			$tags = $this->tagManager->getTagsByIds([$tagId]);
96 96
 			$tag = current($tags);
97 97
 			if (!$this->tagManager->canUserSeeTag($tag, $this->user)) {
98
-				throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
98
+				throw new PreconditionFailed('Tag with id '.$tagId.' does not exist, cannot assign');
99 99
 			}
100 100
 			if (!$this->tagManager->canUserAssignTag($tag, $this->user)) {
101
-				throw new Forbidden('No permission to assign tag ' . $tagId);
101
+				throw new Forbidden('No permission to assign tag '.$tagId);
102 102
 			}
103 103
 
104 104
 			$this->tagMapper->assignTags($this->objectId, $this->objectType, $tagId);
105 105
 		} catch (TagNotFoundException $e) {
106
-			throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
106
+			throw new PreconditionFailed('Tag with id '.$tagId.' does not exist, cannot assign');
107 107
 		}
108 108
 	}
109 109
 
@@ -120,11 +120,11 @@  discard block
 block discarded – undo
120 120
 					return $this->makeNode($tag);
121 121
 				}
122 122
 			}
123
-			throw new NotFound('Tag with id ' . $tagId . ' not present for object ' . $this->objectId);
123
+			throw new NotFound('Tag with id '.$tagId.' not present for object '.$this->objectId);
124 124
 		} catch (\InvalidArgumentException $e) {
125 125
 			throw new BadRequest('Invalid tag id', 0, $e);
126 126
 		} catch (TagNotFoundException $e) {
127
-			throw new NotFound('Tag with id ' . $tagId . ' not found', 0, $e);
127
+			throw new NotFound('Tag with id '.$tagId.' not found', 0, $e);
128 128
 		}
129 129
 	}
130 130
 
Please login to merge, or discard this patch.
Indentation   +165 added lines, -165 removed lines patch added patch discarded remove patch
@@ -39,169 +39,169 @@
 block discarded – undo
39 39
  */
40 40
 class SystemTagsObjectMappingCollection implements ICollection {
41 41
 
42
-	/**
43
-	 * @var string
44
-	 */
45
-	private $objectId;
46
-
47
-	/**
48
-	 * @var string
49
-	 */
50
-	private $objectType;
51
-
52
-	/**
53
-	 * @var ISystemTagManager
54
-	 */
55
-	private $tagManager;
56
-
57
-	/**
58
-	 * @var ISystemTagObjectMapper
59
-	 */
60
-	private $tagMapper;
61
-
62
-	/**
63
-	 * User
64
-	 *
65
-	 * @var IUser
66
-	 */
67
-	private $user;
68
-
69
-
70
-	/**
71
-	 * Constructor
72
-	 *
73
-	 * @param string $objectId object id
74
-	 * @param string $objectType object type
75
-	 * @param IUser $user user
76
-	 * @param ISystemTagManager $tagManager tag manager
77
-	 * @param ISystemTagObjectMapper $tagMapper tag mapper
78
-	 */
79
-	public function __construct(
80
-		$objectId,
81
-		$objectType,
82
-		IUser $user,
83
-		ISystemTagManager $tagManager,
84
-		ISystemTagObjectMapper $tagMapper
85
-	) {
86
-		$this->tagManager = $tagManager;
87
-		$this->tagMapper = $tagMapper;
88
-		$this->objectId = $objectId;
89
-		$this->objectType = $objectType;
90
-		$this->user = $user;
91
-	}
92
-
93
-	function createFile($tagId, $data = null) {
94
-		try {
95
-			$tags = $this->tagManager->getTagsByIds([$tagId]);
96
-			$tag = current($tags);
97
-			if (!$this->tagManager->canUserSeeTag($tag, $this->user)) {
98
-				throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
99
-			}
100
-			if (!$this->tagManager->canUserAssignTag($tag, $this->user)) {
101
-				throw new Forbidden('No permission to assign tag ' . $tagId);
102
-			}
103
-
104
-			$this->tagMapper->assignTags($this->objectId, $this->objectType, $tagId);
105
-		} catch (TagNotFoundException $e) {
106
-			throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
107
-		}
108
-	}
109
-
110
-	function createDirectory($name) {
111
-		throw new Forbidden('Permission denied to create collections');
112
-	}
113
-
114
-	function getChild($tagId) {
115
-		try {
116
-			if ($this->tagMapper->haveTag([$this->objectId], $this->objectType, $tagId, true)) {
117
-				$tag = $this->tagManager->getTagsByIds([$tagId]);
118
-				$tag = current($tag);
119
-				if ($this->tagManager->canUserSeeTag($tag, $this->user)) {
120
-					return $this->makeNode($tag);
121
-				}
122
-			}
123
-			throw new NotFound('Tag with id ' . $tagId . ' not present for object ' . $this->objectId);
124
-		} catch (\InvalidArgumentException $e) {
125
-			throw new BadRequest('Invalid tag id', 0, $e);
126
-		} catch (TagNotFoundException $e) {
127
-			throw new NotFound('Tag with id ' . $tagId . ' not found', 0, $e);
128
-		}
129
-	}
130
-
131
-	function getChildren() {
132
-		$tagIds = current($this->tagMapper->getTagIdsForObjects([$this->objectId], $this->objectType));
133
-		if (empty($tagIds)) {
134
-			return [];
135
-		}
136
-		$tags = $this->tagManager->getTagsByIds($tagIds);
137
-
138
-		// filter out non-visible tags
139
-		$tags = array_filter($tags, function($tag) {
140
-			return $this->tagManager->canUserSeeTag($tag, $this->user);
141
-		});
142
-
143
-		return array_values(array_map(function($tag) {
144
-			return $this->makeNode($tag);
145
-		}, $tags));
146
-	}
147
-
148
-	function childExists($tagId) {
149
-		try {
150
-			$result = $this->tagMapper->haveTag([$this->objectId], $this->objectType, $tagId, true);
151
-
152
-			if ($result) {
153
-				$tags = $this->tagManager->getTagsByIds([$tagId]);
154
-				$tag = current($tags);
155
-				if (!$this->tagManager->canUserSeeTag($tag, $this->user)) {
156
-					return false;
157
-				}
158
-			}
159
-
160
-			return $result;
161
-		} catch (\InvalidArgumentException $e) {
162
-			throw new BadRequest('Invalid tag id', 0, $e);
163
-		} catch (TagNotFoundException $e) {
164
-			return false;
165
-		}
166
-	}
167
-
168
-	function delete() {
169
-		throw new Forbidden('Permission denied to delete this collection');
170
-	}
171
-
172
-	function getName() {
173
-		return $this->objectId;
174
-	}
175
-
176
-	function setName($name) {
177
-		throw new Forbidden('Permission denied to rename this collection');
178
-	}
179
-
180
-	/**
181
-	 * Returns the last modification time, as a unix timestamp
182
-	 *
183
-	 * @return int
184
-	 */
185
-	function getLastModified() {
186
-		return null;
187
-	}
188
-
189
-	/**
190
-	 * Create a sabre node for the mapping of the 
191
-	 * given system tag to the collection's object
192
-	 *
193
-	 * @param ISystemTag $tag
194
-	 *
195
-	 * @return SystemTagMappingNode
196
-	 */
197
-	private function makeNode(ISystemTag $tag) {
198
-		return new SystemTagMappingNode(
199
-			$tag,
200
-			$this->objectId,
201
-			$this->objectType,
202
-			$this->user,
203
-			$this->tagManager,
204
-			$this->tagMapper
205
-		);
206
-	}
42
+    /**
43
+     * @var string
44
+     */
45
+    private $objectId;
46
+
47
+    /**
48
+     * @var string
49
+     */
50
+    private $objectType;
51
+
52
+    /**
53
+     * @var ISystemTagManager
54
+     */
55
+    private $tagManager;
56
+
57
+    /**
58
+     * @var ISystemTagObjectMapper
59
+     */
60
+    private $tagMapper;
61
+
62
+    /**
63
+     * User
64
+     *
65
+     * @var IUser
66
+     */
67
+    private $user;
68
+
69
+
70
+    /**
71
+     * Constructor
72
+     *
73
+     * @param string $objectId object id
74
+     * @param string $objectType object type
75
+     * @param IUser $user user
76
+     * @param ISystemTagManager $tagManager tag manager
77
+     * @param ISystemTagObjectMapper $tagMapper tag mapper
78
+     */
79
+    public function __construct(
80
+        $objectId,
81
+        $objectType,
82
+        IUser $user,
83
+        ISystemTagManager $tagManager,
84
+        ISystemTagObjectMapper $tagMapper
85
+    ) {
86
+        $this->tagManager = $tagManager;
87
+        $this->tagMapper = $tagMapper;
88
+        $this->objectId = $objectId;
89
+        $this->objectType = $objectType;
90
+        $this->user = $user;
91
+    }
92
+
93
+    function createFile($tagId, $data = null) {
94
+        try {
95
+            $tags = $this->tagManager->getTagsByIds([$tagId]);
96
+            $tag = current($tags);
97
+            if (!$this->tagManager->canUserSeeTag($tag, $this->user)) {
98
+                throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
99
+            }
100
+            if (!$this->tagManager->canUserAssignTag($tag, $this->user)) {
101
+                throw new Forbidden('No permission to assign tag ' . $tagId);
102
+            }
103
+
104
+            $this->tagMapper->assignTags($this->objectId, $this->objectType, $tagId);
105
+        } catch (TagNotFoundException $e) {
106
+            throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
107
+        }
108
+    }
109
+
110
+    function createDirectory($name) {
111
+        throw new Forbidden('Permission denied to create collections');
112
+    }
113
+
114
+    function getChild($tagId) {
115
+        try {
116
+            if ($this->tagMapper->haveTag([$this->objectId], $this->objectType, $tagId, true)) {
117
+                $tag = $this->tagManager->getTagsByIds([$tagId]);
118
+                $tag = current($tag);
119
+                if ($this->tagManager->canUserSeeTag($tag, $this->user)) {
120
+                    return $this->makeNode($tag);
121
+                }
122
+            }
123
+            throw new NotFound('Tag with id ' . $tagId . ' not present for object ' . $this->objectId);
124
+        } catch (\InvalidArgumentException $e) {
125
+            throw new BadRequest('Invalid tag id', 0, $e);
126
+        } catch (TagNotFoundException $e) {
127
+            throw new NotFound('Tag with id ' . $tagId . ' not found', 0, $e);
128
+        }
129
+    }
130
+
131
+    function getChildren() {
132
+        $tagIds = current($this->tagMapper->getTagIdsForObjects([$this->objectId], $this->objectType));
133
+        if (empty($tagIds)) {
134
+            return [];
135
+        }
136
+        $tags = $this->tagManager->getTagsByIds($tagIds);
137
+
138
+        // filter out non-visible tags
139
+        $tags = array_filter($tags, function($tag) {
140
+            return $this->tagManager->canUserSeeTag($tag, $this->user);
141
+        });
142
+
143
+        return array_values(array_map(function($tag) {
144
+            return $this->makeNode($tag);
145
+        }, $tags));
146
+    }
147
+
148
+    function childExists($tagId) {
149
+        try {
150
+            $result = $this->tagMapper->haveTag([$this->objectId], $this->objectType, $tagId, true);
151
+
152
+            if ($result) {
153
+                $tags = $this->tagManager->getTagsByIds([$tagId]);
154
+                $tag = current($tags);
155
+                if (!$this->tagManager->canUserSeeTag($tag, $this->user)) {
156
+                    return false;
157
+                }
158
+            }
159
+
160
+            return $result;
161
+        } catch (\InvalidArgumentException $e) {
162
+            throw new BadRequest('Invalid tag id', 0, $e);
163
+        } catch (TagNotFoundException $e) {
164
+            return false;
165
+        }
166
+    }
167
+
168
+    function delete() {
169
+        throw new Forbidden('Permission denied to delete this collection');
170
+    }
171
+
172
+    function getName() {
173
+        return $this->objectId;
174
+    }
175
+
176
+    function setName($name) {
177
+        throw new Forbidden('Permission denied to rename this collection');
178
+    }
179
+
180
+    /**
181
+     * Returns the last modification time, as a unix timestamp
182
+     *
183
+     * @return int
184
+     */
185
+    function getLastModified() {
186
+        return null;
187
+    }
188
+
189
+    /**
190
+     * Create a sabre node for the mapping of the 
191
+     * given system tag to the collection's object
192
+     *
193
+     * @param ISystemTag $tag
194
+     *
195
+     * @return SystemTagMappingNode
196
+     */
197
+    private function makeNode(ISystemTag $tag) {
198
+        return new SystemTagMappingNode(
199
+            $tag,
200
+            $this->objectId,
201
+            $this->objectType,
202
+            $this->user,
203
+            $this->tagManager,
204
+            $this->tagMapper
205
+        );
206
+    }
207 207
 }
Please login to merge, or discard this patch.
lib/private/DB/Migrator.php 3 patches
Doc Comments   +8 added lines patch added patch discarded remove patch
@@ -273,6 +273,10 @@  discard block
 block discarded – undo
273 273
 		return '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
274 274
 	}
275 275
 
276
+	/**
277
+	 * @param integer $step
278
+	 * @param integer $max
279
+	 */
276 280
 	protected function emit($sql, $step, $max) {
277 281
 		if ($this->noEmit) {
278 282
 			return;
@@ -283,6 +287,10 @@  discard block
 block discarded – undo
283 287
 		$this->dispatcher->dispatch('\OC\DB\Migrator::executeSql', new GenericEvent($sql, [$step+1, $max]));
284 288
 	}
285 289
 
290
+	/**
291
+	 * @param integer $step
292
+	 * @param integer $max
293
+	 */
286 294
 	private function emitCheckStep($tableName, $step, $max) {
287 295
 		if(is_null($this->dispatcher)) {
288 296
 			return;
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -137,7 +137,7 @@  discard block
 block discarded – undo
137 137
 	 * @return string
138 138
 	 */
139 139
 	protected function generateTemporaryTableName($name) {
140
-		return $this->config->getSystemValue('dbtableprefix', 'oc_') . $name . '_' . $this->random->generate(13, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
140
+		return $this->config->getSystemValue('dbtableprefix', 'oc_').$name.'_'.$this->random->generate(13, ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_DIGITS);
141 141
 	}
142 142
 
143 143
 	/**
@@ -188,7 +188,7 @@  discard block
 block discarded – undo
188 188
 				$indexName = $index->getName();
189 189
 			} else {
190 190
 				// avoid conflicts in index names
191
-				$indexName = $this->config->getSystemValue('dbtableprefix', 'oc_') . $this->random->generate(13, ISecureRandom::CHAR_LOWER);
191
+				$indexName = $this->config->getSystemValue('dbtableprefix', 'oc_').$this->random->generate(13, ISecureRandom::CHAR_LOWER);
192 192
 			}
193 193
 			$newIndexes[] = new Index($indexName, $index->getColumns(), $index->isUnique(), $index->isPrimary());
194 194
 		}
@@ -268,15 +268,15 @@  discard block
 block discarded – undo
268 268
 		$quotedSource = $this->connection->quoteIdentifier($sourceName);
269 269
 		$quotedTarget = $this->connection->quoteIdentifier($targetName);
270 270
 
271
-		$this->connection->exec('CREATE TABLE ' . $quotedTarget . ' (LIKE ' . $quotedSource . ')');
272
-		$this->connection->exec('INSERT INTO ' . $quotedTarget . ' SELECT * FROM ' . $quotedSource);
271
+		$this->connection->exec('CREATE TABLE '.$quotedTarget.' (LIKE '.$quotedSource.')');
272
+		$this->connection->exec('INSERT INTO '.$quotedTarget.' SELECT * FROM '.$quotedSource);
273 273
 	}
274 274
 
275 275
 	/**
276 276
 	 * @param string $name
277 277
 	 */
278 278
 	protected function dropTable($name) {
279
-		$this->connection->exec('DROP TABLE ' . $this->connection->quoteIdentifier($name));
279
+		$this->connection->exec('DROP TABLE '.$this->connection->quoteIdentifier($name));
280 280
 	}
281 281
 
282 282
 	/**
@@ -284,30 +284,30 @@  discard block
 block discarded – undo
284 284
 	 * @return string
285 285
 	 */
286 286
 	protected function convertStatementToScript($statement) {
287
-		$script = $statement . ';';
287
+		$script = $statement.';';
288 288
 		$script .= PHP_EOL;
289 289
 		$script .= PHP_EOL;
290 290
 		return $script;
291 291
 	}
292 292
 
293 293
 	protected function getFilterExpression() {
294
-		return '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
294
+		return '/^'.preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')).'/';
295 295
 	}
296 296
 
297 297
 	protected function emit($sql, $step, $max) {
298 298
 		if ($this->noEmit) {
299 299
 			return;
300 300
 		}
301
-		if(is_null($this->dispatcher)) {
301
+		if (is_null($this->dispatcher)) {
302 302
 			return;
303 303
 		}
304
-		$this->dispatcher->dispatch('\OC\DB\Migrator::executeSql', new GenericEvent($sql, [$step+1, $max]));
304
+		$this->dispatcher->dispatch('\OC\DB\Migrator::executeSql', new GenericEvent($sql, [$step + 1, $max]));
305 305
 	}
306 306
 
307 307
 	private function emitCheckStep($tableName, $step, $max) {
308
-		if(is_null($this->dispatcher)) {
308
+		if (is_null($this->dispatcher)) {
309 309
 			return;
310 310
 		}
311
-		$this->dispatcher->dispatch('\OC\DB\Migrator::checkTable', new GenericEvent($tableName, [$step+1, $max]));
311
+		$this->dispatcher->dispatch('\OC\DB\Migrator::checkTable', new GenericEvent($tableName, [$step + 1, $max]));
312 312
 	}
313 313
 }
Please login to merge, or discard this patch.
Indentation   +268 added lines, -268 removed lines patch added patch discarded remove patch
@@ -43,272 +43,272 @@
 block discarded – undo
43 43
 
44 44
 class Migrator {
45 45
 
46
-	/** @var \Doctrine\DBAL\Connection */
47
-	protected $connection;
48
-
49
-	/** @var ISecureRandom */
50
-	private $random;
51
-
52
-	/** @var IConfig */
53
-	protected $config;
54
-
55
-	/** @var EventDispatcher  */
56
-	private $dispatcher;
57
-
58
-	/** @var bool */
59
-	private $noEmit = false;
60
-
61
-	/**
62
-	 * @param \Doctrine\DBAL\Connection|Connection $connection
63
-	 * @param ISecureRandom $random
64
-	 * @param IConfig $config
65
-	 * @param EventDispatcher $dispatcher
66
-	 */
67
-	public function __construct(\Doctrine\DBAL\Connection $connection,
68
-								ISecureRandom $random,
69
-								IConfig $config,
70
-								EventDispatcher $dispatcher = null) {
71
-		$this->connection = $connection;
72
-		$this->random = $random;
73
-		$this->config = $config;
74
-		$this->dispatcher = $dispatcher;
75
-	}
76
-
77
-	/**
78
-	 * @param \Doctrine\DBAL\Schema\Schema $targetSchema
79
-	 */
80
-	public function migrate(Schema $targetSchema) {
81
-		$this->noEmit = true;
82
-		$this->applySchema($targetSchema);
83
-	}
84
-
85
-	/**
86
-	 * @param \Doctrine\DBAL\Schema\Schema $targetSchema
87
-	 * @return string
88
-	 */
89
-	public function generateChangeScript(Schema $targetSchema) {
90
-		$schemaDiff = $this->getDiff($targetSchema, $this->connection);
91
-
92
-		$script = '';
93
-		$sqls = $schemaDiff->toSql($this->connection->getDatabasePlatform());
94
-		foreach ($sqls as $sql) {
95
-			$script .= $this->convertStatementToScript($sql);
96
-		}
97
-
98
-		return $script;
99
-	}
100
-
101
-	/**
102
-	 * @param Schema $targetSchema
103
-	 * @throws \OC\DB\MigrationException
104
-	 */
105
-	public function checkMigrate(Schema $targetSchema) {
106
-		$this->noEmit = true;
107
-		/**@var \Doctrine\DBAL\Schema\Table[] $tables */
108
-		$tables = $targetSchema->getTables();
109
-		$filterExpression = $this->getFilterExpression();
110
-		$this->connection->getConfiguration()->
111
-			setFilterSchemaAssetsExpression($filterExpression);
112
-		$existingTables = $this->connection->getSchemaManager()->listTableNames();
113
-
114
-		$step = 0;
115
-		foreach ($tables as $table) {
116
-			if (strpos($table->getName(), '.')) {
117
-				list(, $tableName) = explode('.', $table->getName());
118
-			} else {
119
-				$tableName = $table->getName();
120
-			}
121
-			$this->emitCheckStep($tableName, $step++, count($tables));
122
-			// don't need to check for new tables
123
-			if (array_search($tableName, $existingTables) !== false) {
124
-				$this->checkTableMigrate($table);
125
-			}
126
-		}
127
-	}
128
-
129
-	/**
130
-	 * Create a unique name for the temporary table
131
-	 *
132
-	 * @param string $name
133
-	 * @return string
134
-	 */
135
-	protected function generateTemporaryTableName($name) {
136
-		return $this->config->getSystemValue('dbtableprefix', 'oc_') . $name . '_' . $this->random->generate(13, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
137
-	}
138
-
139
-	/**
140
-	 * Check the migration of a table on a copy so we can detect errors before messing with the real table
141
-	 *
142
-	 * @param \Doctrine\DBAL\Schema\Table $table
143
-	 * @throws \OC\DB\MigrationException
144
-	 */
145
-	protected function checkTableMigrate(Table $table) {
146
-		$name = $table->getName();
147
-		$tmpName = $this->generateTemporaryTableName($name);
148
-
149
-		$this->copyTable($name, $tmpName);
150
-
151
-		//create the migration schema for the temporary table
152
-		$tmpTable = $this->renameTableSchema($table, $tmpName);
153
-		$schemaConfig = new SchemaConfig();
154
-		$schemaConfig->setName($this->connection->getDatabase());
155
-		$schema = new Schema(array($tmpTable), array(), $schemaConfig);
156
-
157
-		try {
158
-			$this->applySchema($schema);
159
-			$this->dropTable($tmpName);
160
-		} catch (DBALException $e) {
161
-			// pgsql needs to commit it's failed transaction before doing anything else
162
-			if ($this->connection->isTransactionActive()) {
163
-				$this->connection->commit();
164
-			}
165
-			$this->dropTable($tmpName);
166
-			throw new MigrationException($table->getName(), $e->getMessage());
167
-		}
168
-	}
169
-
170
-	/**
171
-	 * @param \Doctrine\DBAL\Schema\Table $table
172
-	 * @param string $newName
173
-	 * @return \Doctrine\DBAL\Schema\Table
174
-	 */
175
-	protected function renameTableSchema(Table $table, $newName) {
176
-		/**
177
-		 * @var \Doctrine\DBAL\Schema\Index[] $indexes
178
-		 */
179
-		$indexes = $table->getIndexes();
180
-		$newIndexes = array();
181
-		foreach ($indexes as $index) {
182
-			if ($index->isPrimary()) {
183
-				// do not rename primary key
184
-				$indexName = $index->getName();
185
-			} else {
186
-				// avoid conflicts in index names
187
-				$indexName = $this->config->getSystemValue('dbtableprefix', 'oc_') . $this->random->generate(13, ISecureRandom::CHAR_LOWER);
188
-			}
189
-			$newIndexes[] = new Index($indexName, $index->getColumns(), $index->isUnique(), $index->isPrimary());
190
-		}
191
-
192
-		// foreign keys are not supported so we just set it to an empty array
193
-		return new Table($newName, $table->getColumns(), $newIndexes, array(), 0, $table->getOptions());
194
-	}
195
-
196
-	public function createSchema() {
197
-		$filterExpression = $this->getFilterExpression();
198
-		$this->connection->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression);
199
-		return $this->connection->getSchemaManager()->createSchema();
200
-	}
201
-
202
-	/**
203
-	 * @param Schema $targetSchema
204
-	 * @param \Doctrine\DBAL\Connection $connection
205
-	 * @return \Doctrine\DBAL\Schema\SchemaDiff
206
-	 * @throws DBALException
207
-	 */
208
-	protected function getDiff(Schema $targetSchema, \Doctrine\DBAL\Connection $connection) {
209
-		// adjust varchar columns with a length higher then getVarcharMaxLength to clob
210
-		foreach ($targetSchema->getTables() as $table) {
211
-			foreach ($table->getColumns() as $column) {
212
-				if ($column->getType() instanceof StringType) {
213
-					if ($column->getLength() > $connection->getDatabasePlatform()->getVarcharMaxLength()) {
214
-						$column->setType(Type::getType('text'));
215
-						$column->setLength(null);
216
-					}
217
-				}
218
-			}
219
-		}
220
-
221
-		$filterExpression = $this->getFilterExpression();
222
-		$this->connection->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression);
223
-		$sourceSchema = $connection->getSchemaManager()->createSchema();
224
-
225
-		// remove tables we don't know about
226
-		/** @var $table \Doctrine\DBAL\Schema\Table */
227
-		foreach ($sourceSchema->getTables() as $table) {
228
-			if (!$targetSchema->hasTable($table->getName())) {
229
-				$sourceSchema->dropTable($table->getName());
230
-			}
231
-		}
232
-		// remove sequences we don't know about
233
-		foreach ($sourceSchema->getSequences() as $table) {
234
-			if (!$targetSchema->hasSequence($table->getName())) {
235
-				$sourceSchema->dropSequence($table->getName());
236
-			}
237
-		}
238
-
239
-		$comparator = new Comparator();
240
-		return $comparator->compare($sourceSchema, $targetSchema);
241
-	}
242
-
243
-	/**
244
-	 * @param \Doctrine\DBAL\Schema\Schema $targetSchema
245
-	 * @param \Doctrine\DBAL\Connection $connection
246
-	 */
247
-	protected function applySchema(Schema $targetSchema, \Doctrine\DBAL\Connection $connection = null) {
248
-		if (is_null($connection)) {
249
-			$connection = $this->connection;
250
-		}
251
-
252
-		$schemaDiff = $this->getDiff($targetSchema, $connection);
253
-
254
-		$connection->beginTransaction();
255
-		$sqls = $schemaDiff->toSql($connection->getDatabasePlatform());
256
-		$step = 0;
257
-		foreach ($sqls as $sql) {
258
-			$this->emit($sql, $step++, count($sqls));
259
-			$connection->query($sql);
260
-		}
261
-		$connection->commit();
262
-	}
263
-
264
-	/**
265
-	 * @param string $sourceName
266
-	 * @param string $targetName
267
-	 */
268
-	protected function copyTable($sourceName, $targetName) {
269
-		$quotedSource = $this->connection->quoteIdentifier($sourceName);
270
-		$quotedTarget = $this->connection->quoteIdentifier($targetName);
271
-
272
-		$this->connection->exec('CREATE TABLE ' . $quotedTarget . ' (LIKE ' . $quotedSource . ')');
273
-		$this->connection->exec('INSERT INTO ' . $quotedTarget . ' SELECT * FROM ' . $quotedSource);
274
-	}
275
-
276
-	/**
277
-	 * @param string $name
278
-	 */
279
-	protected function dropTable($name) {
280
-		$this->connection->exec('DROP TABLE ' . $this->connection->quoteIdentifier($name));
281
-	}
282
-
283
-	/**
284
-	 * @param $statement
285
-	 * @return string
286
-	 */
287
-	protected function convertStatementToScript($statement) {
288
-		$script = $statement . ';';
289
-		$script .= PHP_EOL;
290
-		$script .= PHP_EOL;
291
-		return $script;
292
-	}
293
-
294
-	protected function getFilterExpression() {
295
-		return '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
296
-	}
297
-
298
-	protected function emit($sql, $step, $max) {
299
-		if ($this->noEmit) {
300
-			return;
301
-		}
302
-		if(is_null($this->dispatcher)) {
303
-			return;
304
-		}
305
-		$this->dispatcher->dispatch('\OC\DB\Migrator::executeSql', new GenericEvent($sql, [$step+1, $max]));
306
-	}
307
-
308
-	private function emitCheckStep($tableName, $step, $max) {
309
-		if(is_null($this->dispatcher)) {
310
-			return;
311
-		}
312
-		$this->dispatcher->dispatch('\OC\DB\Migrator::checkTable', new GenericEvent($tableName, [$step+1, $max]));
313
-	}
46
+    /** @var \Doctrine\DBAL\Connection */
47
+    protected $connection;
48
+
49
+    /** @var ISecureRandom */
50
+    private $random;
51
+
52
+    /** @var IConfig */
53
+    protected $config;
54
+
55
+    /** @var EventDispatcher  */
56
+    private $dispatcher;
57
+
58
+    /** @var bool */
59
+    private $noEmit = false;
60
+
61
+    /**
62
+     * @param \Doctrine\DBAL\Connection|Connection $connection
63
+     * @param ISecureRandom $random
64
+     * @param IConfig $config
65
+     * @param EventDispatcher $dispatcher
66
+     */
67
+    public function __construct(\Doctrine\DBAL\Connection $connection,
68
+                                ISecureRandom $random,
69
+                                IConfig $config,
70
+                                EventDispatcher $dispatcher = null) {
71
+        $this->connection = $connection;
72
+        $this->random = $random;
73
+        $this->config = $config;
74
+        $this->dispatcher = $dispatcher;
75
+    }
76
+
77
+    /**
78
+     * @param \Doctrine\DBAL\Schema\Schema $targetSchema
79
+     */
80
+    public function migrate(Schema $targetSchema) {
81
+        $this->noEmit = true;
82
+        $this->applySchema($targetSchema);
83
+    }
84
+
85
+    /**
86
+     * @param \Doctrine\DBAL\Schema\Schema $targetSchema
87
+     * @return string
88
+     */
89
+    public function generateChangeScript(Schema $targetSchema) {
90
+        $schemaDiff = $this->getDiff($targetSchema, $this->connection);
91
+
92
+        $script = '';
93
+        $sqls = $schemaDiff->toSql($this->connection->getDatabasePlatform());
94
+        foreach ($sqls as $sql) {
95
+            $script .= $this->convertStatementToScript($sql);
96
+        }
97
+
98
+        return $script;
99
+    }
100
+
101
+    /**
102
+     * @param Schema $targetSchema
103
+     * @throws \OC\DB\MigrationException
104
+     */
105
+    public function checkMigrate(Schema $targetSchema) {
106
+        $this->noEmit = true;
107
+        /**@var \Doctrine\DBAL\Schema\Table[] $tables */
108
+        $tables = $targetSchema->getTables();
109
+        $filterExpression = $this->getFilterExpression();
110
+        $this->connection->getConfiguration()->
111
+            setFilterSchemaAssetsExpression($filterExpression);
112
+        $existingTables = $this->connection->getSchemaManager()->listTableNames();
113
+
114
+        $step = 0;
115
+        foreach ($tables as $table) {
116
+            if (strpos($table->getName(), '.')) {
117
+                list(, $tableName) = explode('.', $table->getName());
118
+            } else {
119
+                $tableName = $table->getName();
120
+            }
121
+            $this->emitCheckStep($tableName, $step++, count($tables));
122
+            // don't need to check for new tables
123
+            if (array_search($tableName, $existingTables) !== false) {
124
+                $this->checkTableMigrate($table);
125
+            }
126
+        }
127
+    }
128
+
129
+    /**
130
+     * Create a unique name for the temporary table
131
+     *
132
+     * @param string $name
133
+     * @return string
134
+     */
135
+    protected function generateTemporaryTableName($name) {
136
+        return $this->config->getSystemValue('dbtableprefix', 'oc_') . $name . '_' . $this->random->generate(13, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
137
+    }
138
+
139
+    /**
140
+     * Check the migration of a table on a copy so we can detect errors before messing with the real table
141
+     *
142
+     * @param \Doctrine\DBAL\Schema\Table $table
143
+     * @throws \OC\DB\MigrationException
144
+     */
145
+    protected function checkTableMigrate(Table $table) {
146
+        $name = $table->getName();
147
+        $tmpName = $this->generateTemporaryTableName($name);
148
+
149
+        $this->copyTable($name, $tmpName);
150
+
151
+        //create the migration schema for the temporary table
152
+        $tmpTable = $this->renameTableSchema($table, $tmpName);
153
+        $schemaConfig = new SchemaConfig();
154
+        $schemaConfig->setName($this->connection->getDatabase());
155
+        $schema = new Schema(array($tmpTable), array(), $schemaConfig);
156
+
157
+        try {
158
+            $this->applySchema($schema);
159
+            $this->dropTable($tmpName);
160
+        } catch (DBALException $e) {
161
+            // pgsql needs to commit it's failed transaction before doing anything else
162
+            if ($this->connection->isTransactionActive()) {
163
+                $this->connection->commit();
164
+            }
165
+            $this->dropTable($tmpName);
166
+            throw new MigrationException($table->getName(), $e->getMessage());
167
+        }
168
+    }
169
+
170
+    /**
171
+     * @param \Doctrine\DBAL\Schema\Table $table
172
+     * @param string $newName
173
+     * @return \Doctrine\DBAL\Schema\Table
174
+     */
175
+    protected function renameTableSchema(Table $table, $newName) {
176
+        /**
177
+         * @var \Doctrine\DBAL\Schema\Index[] $indexes
178
+         */
179
+        $indexes = $table->getIndexes();
180
+        $newIndexes = array();
181
+        foreach ($indexes as $index) {
182
+            if ($index->isPrimary()) {
183
+                // do not rename primary key
184
+                $indexName = $index->getName();
185
+            } else {
186
+                // avoid conflicts in index names
187
+                $indexName = $this->config->getSystemValue('dbtableprefix', 'oc_') . $this->random->generate(13, ISecureRandom::CHAR_LOWER);
188
+            }
189
+            $newIndexes[] = new Index($indexName, $index->getColumns(), $index->isUnique(), $index->isPrimary());
190
+        }
191
+
192
+        // foreign keys are not supported so we just set it to an empty array
193
+        return new Table($newName, $table->getColumns(), $newIndexes, array(), 0, $table->getOptions());
194
+    }
195
+
196
+    public function createSchema() {
197
+        $filterExpression = $this->getFilterExpression();
198
+        $this->connection->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression);
199
+        return $this->connection->getSchemaManager()->createSchema();
200
+    }
201
+
202
+    /**
203
+     * @param Schema $targetSchema
204
+     * @param \Doctrine\DBAL\Connection $connection
205
+     * @return \Doctrine\DBAL\Schema\SchemaDiff
206
+     * @throws DBALException
207
+     */
208
+    protected function getDiff(Schema $targetSchema, \Doctrine\DBAL\Connection $connection) {
209
+        // adjust varchar columns with a length higher then getVarcharMaxLength to clob
210
+        foreach ($targetSchema->getTables() as $table) {
211
+            foreach ($table->getColumns() as $column) {
212
+                if ($column->getType() instanceof StringType) {
213
+                    if ($column->getLength() > $connection->getDatabasePlatform()->getVarcharMaxLength()) {
214
+                        $column->setType(Type::getType('text'));
215
+                        $column->setLength(null);
216
+                    }
217
+                }
218
+            }
219
+        }
220
+
221
+        $filterExpression = $this->getFilterExpression();
222
+        $this->connection->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression);
223
+        $sourceSchema = $connection->getSchemaManager()->createSchema();
224
+
225
+        // remove tables we don't know about
226
+        /** @var $table \Doctrine\DBAL\Schema\Table */
227
+        foreach ($sourceSchema->getTables() as $table) {
228
+            if (!$targetSchema->hasTable($table->getName())) {
229
+                $sourceSchema->dropTable($table->getName());
230
+            }
231
+        }
232
+        // remove sequences we don't know about
233
+        foreach ($sourceSchema->getSequences() as $table) {
234
+            if (!$targetSchema->hasSequence($table->getName())) {
235
+                $sourceSchema->dropSequence($table->getName());
236
+            }
237
+        }
238
+
239
+        $comparator = new Comparator();
240
+        return $comparator->compare($sourceSchema, $targetSchema);
241
+    }
242
+
243
+    /**
244
+     * @param \Doctrine\DBAL\Schema\Schema $targetSchema
245
+     * @param \Doctrine\DBAL\Connection $connection
246
+     */
247
+    protected function applySchema(Schema $targetSchema, \Doctrine\DBAL\Connection $connection = null) {
248
+        if (is_null($connection)) {
249
+            $connection = $this->connection;
250
+        }
251
+
252
+        $schemaDiff = $this->getDiff($targetSchema, $connection);
253
+
254
+        $connection->beginTransaction();
255
+        $sqls = $schemaDiff->toSql($connection->getDatabasePlatform());
256
+        $step = 0;
257
+        foreach ($sqls as $sql) {
258
+            $this->emit($sql, $step++, count($sqls));
259
+            $connection->query($sql);
260
+        }
261
+        $connection->commit();
262
+    }
263
+
264
+    /**
265
+     * @param string $sourceName
266
+     * @param string $targetName
267
+     */
268
+    protected function copyTable($sourceName, $targetName) {
269
+        $quotedSource = $this->connection->quoteIdentifier($sourceName);
270
+        $quotedTarget = $this->connection->quoteIdentifier($targetName);
271
+
272
+        $this->connection->exec('CREATE TABLE ' . $quotedTarget . ' (LIKE ' . $quotedSource . ')');
273
+        $this->connection->exec('INSERT INTO ' . $quotedTarget . ' SELECT * FROM ' . $quotedSource);
274
+    }
275
+
276
+    /**
277
+     * @param string $name
278
+     */
279
+    protected function dropTable($name) {
280
+        $this->connection->exec('DROP TABLE ' . $this->connection->quoteIdentifier($name));
281
+    }
282
+
283
+    /**
284
+     * @param $statement
285
+     * @return string
286
+     */
287
+    protected function convertStatementToScript($statement) {
288
+        $script = $statement . ';';
289
+        $script .= PHP_EOL;
290
+        $script .= PHP_EOL;
291
+        return $script;
292
+    }
293
+
294
+    protected function getFilterExpression() {
295
+        return '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
296
+    }
297
+
298
+    protected function emit($sql, $step, $max) {
299
+        if ($this->noEmit) {
300
+            return;
301
+        }
302
+        if(is_null($this->dispatcher)) {
303
+            return;
304
+        }
305
+        $this->dispatcher->dispatch('\OC\DB\Migrator::executeSql', new GenericEvent($sql, [$step+1, $max]));
306
+    }
307
+
308
+    private function emitCheckStep($tableName, $step, $max) {
309
+        if(is_null($this->dispatcher)) {
310
+            return;
311
+        }
312
+        $this->dispatcher->dispatch('\OC\DB\Migrator::checkTable', new GenericEvent($tableName, [$step+1, $max]));
313
+    }
314 314
 }
Please login to merge, or discard this patch.
settings/Controller/CheckSetupController.php 3 patches
Doc Comments   +2 added lines, -1 removed lines patch added patch discarded remove patch
@@ -103,6 +103,7 @@  discard block
 block discarded – undo
103 103
 
104 104
 	/**
105 105
 	* Chceks if the ownCloud server can connect to a specific URL using both HTTPS and HTTP
106
+	* @param string $sitename
106 107
 	* @return bool
107 108
 	*/
108 109
 	private function isSiteReachable($sitename) {
@@ -285,7 +286,7 @@  discard block
 block discarded – undo
285 286
 
286 287
 	/**
287 288
 	 * @NoCSRFRequired
288
-	 * @return DataResponse
289
+	 * @return DataDisplayResponse
289 290
 	 */
290 291
 	public function getFailedIntegrityCheckFiles() {
291 292
 		if(!$this->checker->isCodeCheckEnforced()) {
Please login to merge, or discard this patch.
Spacing   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 						'www.google.com',
105 105
 						'www.github.com'];
106 106
 
107
-		foreach($siteArray as $site) {
107
+		foreach ($siteArray as $site) {
108 108
 			if ($this->isSiteReachable($site)) {
109 109
 				return true;
110 110
 			}
@@ -117,8 +117,8 @@  discard block
 block discarded – undo
117 117
 	* @return bool
118 118
 	*/
119 119
 	private function isSiteReachable($sitename) {
120
-		$httpSiteName = 'http://' . $sitename . '/';
121
-		$httpsSiteName = 'https://' . $sitename . '/';
120
+		$httpSiteName = 'http://'.$sitename.'/';
121
+		$httpsSiteName = 'https://'.$sitename.'/';
122 122
 
123 123
 		try {
124 124
 			$client = $this->clientService->newClient();
@@ -145,9 +145,9 @@  discard block
 block discarded – undo
145 145
 	 * @return bool
146 146
 	 */
147 147
 	private function isUrandomAvailable() {
148
-		if(@file_exists('/dev/urandom')) {
148
+		if (@file_exists('/dev/urandom')) {
149 149
 			$file = fopen('/dev/urandom', 'rb');
150
-			if($file) {
150
+			if ($file) {
151 151
 				fclose($file);
152 152
 				return true;
153 153
 			}
@@ -178,40 +178,40 @@  discard block
 block discarded – undo
178 178
 		// Don't run check when:
179 179
 		// 1. Server has `has_internet_connection` set to false
180 180
 		// 2. AppStore AND S2S is disabled
181
-		if(!$this->config->getSystemValue('has_internet_connection', true)) {
181
+		if (!$this->config->getSystemValue('has_internet_connection', true)) {
182 182
 			return '';
183 183
 		}
184
-		if(!$this->config->getSystemValue('appstoreenabled', true)
184
+		if (!$this->config->getSystemValue('appstoreenabled', true)
185 185
 			&& $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'no'
186 186
 			&& $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes') === 'no') {
187 187
 			return '';
188 188
 		}
189 189
 
190 190
 		$versionString = $this->getCurlVersion();
191
-		if(isset($versionString['ssl_version'])) {
191
+		if (isset($versionString['ssl_version'])) {
192 192
 			$versionString = $versionString['ssl_version'];
193 193
 		} else {
194 194
 			return '';
195 195
 		}
196 196
 
197
-		$features = (string)$this->l10n->t('installing and updating apps via the app store or Federated Cloud Sharing');
198
-		if(!$this->config->getSystemValue('appstoreenabled', true)) {
199
-			$features = (string)$this->l10n->t('Federated Cloud Sharing');
197
+		$features = (string) $this->l10n->t('installing and updating apps via the app store or Federated Cloud Sharing');
198
+		if (!$this->config->getSystemValue('appstoreenabled', true)) {
199
+			$features = (string) $this->l10n->t('Federated Cloud Sharing');
200 200
 		}
201 201
 
202 202
 		// Check if at least OpenSSL after 1.01d or 1.0.2b
203
-		if(strpos($versionString, 'OpenSSL/') === 0) {
203
+		if (strpos($versionString, 'OpenSSL/') === 0) {
204 204
 			$majorVersion = substr($versionString, 8, 5);
205 205
 			$patchRelease = substr($versionString, 13, 6);
206 206
 
207
-			if(($majorVersion === '1.0.1' && ord($patchRelease) < ord('d')) ||
207
+			if (($majorVersion === '1.0.1' && ord($patchRelease) < ord('d')) ||
208 208
 				($majorVersion === '1.0.2' && ord($patchRelease) < ord('b'))) {
209 209
 				return (string) $this->l10n->t('cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably.', ['OpenSSL', $versionString, $features]);
210 210
 			}
211 211
 		}
212 212
 
213 213
 		// Check if NSS and perform heuristic check
214
-		if(strpos($versionString, 'NSS/') === 0) {
214
+		if (strpos($versionString, 'NSS/') === 0) {
215 215
 			try {
216 216
 				$firstClient = $this->clientService->newClient();
217 217
 				$firstClient->get('https://nextcloud.com/');
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
 				$secondClient = $this->clientService->newClient();
220 220
 				$secondClient->get('https://nextcloud.com/');
221 221
 			} catch (ClientException $e) {
222
-				if($e->getResponse()->getStatusCode() === 400) {
222
+				if ($e->getResponse()->getStatusCode() === 400) {
223 223
 					return (string) $this->l10n->t('cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably.', ['NSS', $versionString, $features]);
224 224
 				}
225 225
 			}
@@ -314,13 +314,13 @@  discard block
 block discarded – undo
314 314
 	 * @return DataResponse
315 315
 	 */
316 316
 	public function getFailedIntegrityCheckFiles() {
317
-		if(!$this->checker->isCodeCheckEnforced()) {
317
+		if (!$this->checker->isCodeCheckEnforced()) {
318 318
 			return new DataDisplayResponse('Integrity checker has been disabled. Integrity cannot be verified.');
319 319
 		}
320 320
 
321 321
 		$completeResults = $this->checker->getResults();
322 322
 
323
-		if(!empty($completeResults)) {
323
+		if (!empty($completeResults)) {
324 324
 			$formattedTextResponse = 'Technical information
325 325
 =====================
326 326
 The following list covers which files have failed the integrity check. Please read
@@ -330,12 +330,12 @@  discard block
 block discarded – undo
330 330
 Results
331 331
 =======
332 332
 ';
333
-			foreach($completeResults as $context => $contextResult) {
333
+			foreach ($completeResults as $context => $contextResult) {
334 334
 				$formattedTextResponse .= "- $context\n";
335 335
 
336
-				foreach($contextResult as $category => $result) {
336
+				foreach ($contextResult as $category => $result) {
337 337
 					$formattedTextResponse .= "\t- $category\n";
338
-					if($category !== 'EXCEPTION') {
338
+					if ($category !== 'EXCEPTION') {
339 339
 						foreach ($result as $key => $results) {
340 340
 							$formattedTextResponse .= "\t\t- $key\n";
341 341
 						}
@@ -378,27 +378,27 @@  discard block
 block discarded – undo
378 378
 
379 379
 		$isOpcacheProperlySetUp = true;
380 380
 
381
-		if(!$iniWrapper->getBool('opcache.enable')) {
381
+		if (!$iniWrapper->getBool('opcache.enable')) {
382 382
 			$isOpcacheProperlySetUp = false;
383 383
 		}
384 384
 
385
-		if(!$iniWrapper->getBool('opcache.save_comments')) {
385
+		if (!$iniWrapper->getBool('opcache.save_comments')) {
386 386
 			$isOpcacheProperlySetUp = false;
387 387
 		}
388 388
 
389
-		if(!$iniWrapper->getBool('opcache.enable_cli')) {
389
+		if (!$iniWrapper->getBool('opcache.enable_cli')) {
390 390
 			$isOpcacheProperlySetUp = false;
391 391
 		}
392 392
 
393
-		if($iniWrapper->getNumeric('opcache.max_accelerated_files') < 10000) {
393
+		if ($iniWrapper->getNumeric('opcache.max_accelerated_files') < 10000) {
394 394
 			$isOpcacheProperlySetUp = false;
395 395
 		}
396 396
 
397
-		if($iniWrapper->getNumeric('opcache.memory_consumption') < 128) {
397
+		if ($iniWrapper->getNumeric('opcache.memory_consumption') < 128) {
398 398
 			$isOpcacheProperlySetUp = false;
399 399
 		}
400 400
 
401
-		if($iniWrapper->getNumeric('opcache.interned_strings_buffer') < 8) {
401
+		if ($iniWrapper->getNumeric('opcache.interned_strings_buffer') < 8) {
402 402
 			$isOpcacheProperlySetUp = false;
403 403
 		}
404 404
 
Please login to merge, or discard this patch.
Indentation   +381 added lines, -381 removed lines patch added patch discarded remove patch
@@ -49,282 +49,282 @@  discard block
 block discarded – undo
49 49
  * @package OC\Settings\Controller
50 50
  */
51 51
 class CheckSetupController extends Controller {
52
-	/** @var IConfig */
53
-	private $config;
54
-	/** @var IClientService */
55
-	private $clientService;
56
-	/** @var \OC_Util */
57
-	private $util;
58
-	/** @var IURLGenerator */
59
-	private $urlGenerator;
60
-	/** @var IL10N */
61
-	private $l10n;
62
-	/** @var Checker */
63
-	private $checker;
64
-	/** @var ILogger */
65
-	private $logger;
66
-
67
-	/**
68
-	 * @param string $AppName
69
-	 * @param IRequest $request
70
-	 * @param IConfig $config
71
-	 * @param IClientService $clientService
72
-	 * @param IURLGenerator $urlGenerator
73
-	 * @param \OC_Util $util
74
-	 * @param IL10N $l10n
75
-	 * @param Checker $checker
76
-	 * @param ILogger $logger
77
-	 */
78
-	public function __construct($AppName,
79
-								IRequest $request,
80
-								IConfig $config,
81
-								IClientService $clientService,
82
-								IURLGenerator $urlGenerator,
83
-								\OC_Util $util,
84
-								IL10N $l10n,
85
-								Checker $checker,
86
-								ILogger $logger) {
87
-		parent::__construct($AppName, $request);
88
-		$this->config = $config;
89
-		$this->clientService = $clientService;
90
-		$this->util = $util;
91
-		$this->urlGenerator = $urlGenerator;
92
-		$this->l10n = $l10n;
93
-		$this->checker = $checker;
94
-		$this->logger = $logger;
95
-	}
96
-
97
-	/**
98
-	 * Checks if the server can connect to the internet using HTTPS and HTTP
99
-	 * @return bool
100
-	 */
101
-	private function isInternetConnectionWorking() {
102
-		if ($this->config->getSystemValue('has_internet_connection', true) === false) {
103
-			return false;
104
-		}
105
-
106
-		$siteArray = ['www.nextcloud.com',
107
-						'www.google.com',
108
-						'www.github.com'];
109
-
110
-		foreach($siteArray as $site) {
111
-			if ($this->isSiteReachable($site)) {
112
-				return true;
113
-			}
114
-		}
115
-		return false;
116
-	}
117
-
118
-	/**
119
-	* Chceks if the ownCloud server can connect to a specific URL using both HTTPS and HTTP
120
-	* @return bool
121
-	*/
122
-	private function isSiteReachable($sitename) {
123
-		$httpSiteName = 'http://' . $sitename . '/';
124
-		$httpsSiteName = 'https://' . $sitename . '/';
125
-
126
-		try {
127
-			$client = $this->clientService->newClient();
128
-			$client->get($httpSiteName);
129
-			$client->get($httpsSiteName);
130
-		} catch (\Exception $e) {
131
-			$this->logger->logException($e, ['app' => 'internet_connection_check']);
132
-			return false;
133
-		}
134
-		return true;
135
-	}
136
-
137
-	/**
138
-	 * Checks whether a local memcache is installed or not
139
-	 * @return bool
140
-	 */
141
-	private function isMemcacheConfigured() {
142
-		return $this->config->getSystemValue('memcache.local', null) !== null;
143
-	}
144
-
145
-	/**
146
-	 * Whether /dev/urandom is available to the PHP controller
147
-	 *
148
-	 * @return bool
149
-	 */
150
-	private function isUrandomAvailable() {
151
-		if(@file_exists('/dev/urandom')) {
152
-			$file = fopen('/dev/urandom', 'rb');
153
-			if($file) {
154
-				fclose($file);
155
-				return true;
156
-			}
157
-		}
158
-
159
-		return false;
160
-	}
161
-
162
-	/**
163
-	 * Public for the sake of unit-testing
164
-	 *
165
-	 * @return array
166
-	 */
167
-	protected function getCurlVersion() {
168
-		return curl_version();
169
-	}
170
-
171
-	/**
172
-	 * Check if the used  SSL lib is outdated. Older OpenSSL and NSS versions do
173
-	 * have multiple bugs which likely lead to problems in combination with
174
-	 * functionality required by ownCloud such as SNI.
175
-	 *
176
-	 * @link https://github.com/owncloud/core/issues/17446#issuecomment-122877546
177
-	 * @link https://bugzilla.redhat.com/show_bug.cgi?id=1241172
178
-	 * @return string
179
-	 */
180
-	private function isUsedTlsLibOutdated() {
181
-		// Don't run check when:
182
-		// 1. Server has `has_internet_connection` set to false
183
-		// 2. AppStore AND S2S is disabled
184
-		if(!$this->config->getSystemValue('has_internet_connection', true)) {
185
-			return '';
186
-		}
187
-		if(!$this->config->getSystemValue('appstoreenabled', true)
188
-			&& $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'no'
189
-			&& $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes') === 'no') {
190
-			return '';
191
-		}
192
-
193
-		$versionString = $this->getCurlVersion();
194
-		if(isset($versionString['ssl_version'])) {
195
-			$versionString = $versionString['ssl_version'];
196
-		} else {
197
-			return '';
198
-		}
199
-
200
-		$features = (string)$this->l10n->t('installing and updating apps via the app store or Federated Cloud Sharing');
201
-		if(!$this->config->getSystemValue('appstoreenabled', true)) {
202
-			$features = (string)$this->l10n->t('Federated Cloud Sharing');
203
-		}
204
-
205
-		// Check if at least OpenSSL after 1.01d or 1.0.2b
206
-		if(strpos($versionString, 'OpenSSL/') === 0) {
207
-			$majorVersion = substr($versionString, 8, 5);
208
-			$patchRelease = substr($versionString, 13, 6);
209
-
210
-			if(($majorVersion === '1.0.1' && ord($patchRelease) < ord('d')) ||
211
-				($majorVersion === '1.0.2' && ord($patchRelease) < ord('b'))) {
212
-				return (string) $this->l10n->t('cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably.', ['OpenSSL', $versionString, $features]);
213
-			}
214
-		}
215
-
216
-		// Check if NSS and perform heuristic check
217
-		if(strpos($versionString, 'NSS/') === 0) {
218
-			try {
219
-				$firstClient = $this->clientService->newClient();
220
-				$firstClient->get('https://nextcloud.com/');
221
-
222
-				$secondClient = $this->clientService->newClient();
223
-				$secondClient->get('https://nextcloud.com/');
224
-			} catch (ClientException $e) {
225
-				if($e->getResponse()->getStatusCode() === 400) {
226
-					return (string) $this->l10n->t('cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably.', ['NSS', $versionString, $features]);
227
-				}
228
-			}
229
-		}
230
-
231
-		return '';
232
-	}
233
-
234
-	/**
235
-	 * Whether the version is outdated
236
-	 *
237
-	 * @return bool
238
-	 */
239
-	protected function isPhpOutdated() {
240
-		if (version_compare(PHP_VERSION, '7.0.0', '<')) {
241
-			return true;
242
-		}
243
-
244
-		return false;
245
-	}
246
-
247
-	/**
248
-	 * Whether the php version is still supported (at time of release)
249
-	 * according to: https://secure.php.net/supported-versions.php
250
-	 *
251
-	 * @return array
252
-	 */
253
-	private function isPhpSupported() {
254
-		return ['eol' => $this->isPhpOutdated(), 'version' => PHP_VERSION];
255
-	}
256
-
257
-	/**
258
-	 * Check if the reverse proxy configuration is working as expected
259
-	 *
260
-	 * @return bool
261
-	 */
262
-	private function forwardedForHeadersWorking() {
263
-		$trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
264
-		$remoteAddress = $this->request->getRemoteAddress();
265
-
266
-		if (is_array($trustedProxies) && in_array($remoteAddress, $trustedProxies)) {
267
-			return false;
268
-		}
269
-
270
-		// either not enabled or working correctly
271
-		return true;
272
-	}
273
-
274
-	/**
275
-	 * Checks if the correct memcache module for PHP is installed. Only
276
-	 * fails if memcached is configured and the working module is not installed.
277
-	 *
278
-	 * @return bool
279
-	 */
280
-	private function isCorrectMemcachedPHPModuleInstalled() {
281
-		if ($this->config->getSystemValue('memcache.distributed', null) !== '\OC\Memcache\Memcached') {
282
-			return true;
283
-		}
284
-
285
-		// there are two different memcached modules for PHP
286
-		// we only support memcached and not memcache
287
-		// https://code.google.com/p/memcached/wiki/PHPClientComparison
288
-		return !(!extension_loaded('memcached') && extension_loaded('memcache'));
289
-	}
290
-
291
-	/**
292
-	 * Checks if set_time_limit is not disabled.
293
-	 *
294
-	 * @return bool
295
-	 */
296
-	private function isSettimelimitAvailable() {
297
-		if (function_exists('set_time_limit')
298
-			&& strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
299
-			return true;
300
-		}
301
-
302
-		return false;
303
-	}
304
-
305
-	/**
306
-	 * @return RedirectResponse
307
-	 */
308
-	public function rescanFailedIntegrityCheck() {
309
-		$this->checker->runInstanceVerification();
310
-		return new RedirectResponse(
311
-			$this->urlGenerator->linkToRoute('settings.AdminSettings.index')
312
-		);
313
-	}
314
-
315
-	/**
316
-	 * @NoCSRFRequired
317
-	 * @return DataResponse
318
-	 */
319
-	public function getFailedIntegrityCheckFiles() {
320
-		if(!$this->checker->isCodeCheckEnforced()) {
321
-			return new DataDisplayResponse('Integrity checker has been disabled. Integrity cannot be verified.');
322
-		}
323
-
324
-		$completeResults = $this->checker->getResults();
325
-
326
-		if(!empty($completeResults)) {
327
-			$formattedTextResponse = 'Technical information
52
+    /** @var IConfig */
53
+    private $config;
54
+    /** @var IClientService */
55
+    private $clientService;
56
+    /** @var \OC_Util */
57
+    private $util;
58
+    /** @var IURLGenerator */
59
+    private $urlGenerator;
60
+    /** @var IL10N */
61
+    private $l10n;
62
+    /** @var Checker */
63
+    private $checker;
64
+    /** @var ILogger */
65
+    private $logger;
66
+
67
+    /**
68
+     * @param string $AppName
69
+     * @param IRequest $request
70
+     * @param IConfig $config
71
+     * @param IClientService $clientService
72
+     * @param IURLGenerator $urlGenerator
73
+     * @param \OC_Util $util
74
+     * @param IL10N $l10n
75
+     * @param Checker $checker
76
+     * @param ILogger $logger
77
+     */
78
+    public function __construct($AppName,
79
+                                IRequest $request,
80
+                                IConfig $config,
81
+                                IClientService $clientService,
82
+                                IURLGenerator $urlGenerator,
83
+                                \OC_Util $util,
84
+                                IL10N $l10n,
85
+                                Checker $checker,
86
+                                ILogger $logger) {
87
+        parent::__construct($AppName, $request);
88
+        $this->config = $config;
89
+        $this->clientService = $clientService;
90
+        $this->util = $util;
91
+        $this->urlGenerator = $urlGenerator;
92
+        $this->l10n = $l10n;
93
+        $this->checker = $checker;
94
+        $this->logger = $logger;
95
+    }
96
+
97
+    /**
98
+     * Checks if the server can connect to the internet using HTTPS and HTTP
99
+     * @return bool
100
+     */
101
+    private function isInternetConnectionWorking() {
102
+        if ($this->config->getSystemValue('has_internet_connection', true) === false) {
103
+            return false;
104
+        }
105
+
106
+        $siteArray = ['www.nextcloud.com',
107
+                        'www.google.com',
108
+                        'www.github.com'];
109
+
110
+        foreach($siteArray as $site) {
111
+            if ($this->isSiteReachable($site)) {
112
+                return true;
113
+            }
114
+        }
115
+        return false;
116
+    }
117
+
118
+    /**
119
+     * Chceks if the ownCloud server can connect to a specific URL using both HTTPS and HTTP
120
+     * @return bool
121
+     */
122
+    private function isSiteReachable($sitename) {
123
+        $httpSiteName = 'http://' . $sitename . '/';
124
+        $httpsSiteName = 'https://' . $sitename . '/';
125
+
126
+        try {
127
+            $client = $this->clientService->newClient();
128
+            $client->get($httpSiteName);
129
+            $client->get($httpsSiteName);
130
+        } catch (\Exception $e) {
131
+            $this->logger->logException($e, ['app' => 'internet_connection_check']);
132
+            return false;
133
+        }
134
+        return true;
135
+    }
136
+
137
+    /**
138
+     * Checks whether a local memcache is installed or not
139
+     * @return bool
140
+     */
141
+    private function isMemcacheConfigured() {
142
+        return $this->config->getSystemValue('memcache.local', null) !== null;
143
+    }
144
+
145
+    /**
146
+     * Whether /dev/urandom is available to the PHP controller
147
+     *
148
+     * @return bool
149
+     */
150
+    private function isUrandomAvailable() {
151
+        if(@file_exists('/dev/urandom')) {
152
+            $file = fopen('/dev/urandom', 'rb');
153
+            if($file) {
154
+                fclose($file);
155
+                return true;
156
+            }
157
+        }
158
+
159
+        return false;
160
+    }
161
+
162
+    /**
163
+     * Public for the sake of unit-testing
164
+     *
165
+     * @return array
166
+     */
167
+    protected function getCurlVersion() {
168
+        return curl_version();
169
+    }
170
+
171
+    /**
172
+     * Check if the used  SSL lib is outdated. Older OpenSSL and NSS versions do
173
+     * have multiple bugs which likely lead to problems in combination with
174
+     * functionality required by ownCloud such as SNI.
175
+     *
176
+     * @link https://github.com/owncloud/core/issues/17446#issuecomment-122877546
177
+     * @link https://bugzilla.redhat.com/show_bug.cgi?id=1241172
178
+     * @return string
179
+     */
180
+    private function isUsedTlsLibOutdated() {
181
+        // Don't run check when:
182
+        // 1. Server has `has_internet_connection` set to false
183
+        // 2. AppStore AND S2S is disabled
184
+        if(!$this->config->getSystemValue('has_internet_connection', true)) {
185
+            return '';
186
+        }
187
+        if(!$this->config->getSystemValue('appstoreenabled', true)
188
+            && $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'no'
189
+            && $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes') === 'no') {
190
+            return '';
191
+        }
192
+
193
+        $versionString = $this->getCurlVersion();
194
+        if(isset($versionString['ssl_version'])) {
195
+            $versionString = $versionString['ssl_version'];
196
+        } else {
197
+            return '';
198
+        }
199
+
200
+        $features = (string)$this->l10n->t('installing and updating apps via the app store or Federated Cloud Sharing');
201
+        if(!$this->config->getSystemValue('appstoreenabled', true)) {
202
+            $features = (string)$this->l10n->t('Federated Cloud Sharing');
203
+        }
204
+
205
+        // Check if at least OpenSSL after 1.01d or 1.0.2b
206
+        if(strpos($versionString, 'OpenSSL/') === 0) {
207
+            $majorVersion = substr($versionString, 8, 5);
208
+            $patchRelease = substr($versionString, 13, 6);
209
+
210
+            if(($majorVersion === '1.0.1' && ord($patchRelease) < ord('d')) ||
211
+                ($majorVersion === '1.0.2' && ord($patchRelease) < ord('b'))) {
212
+                return (string) $this->l10n->t('cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably.', ['OpenSSL', $versionString, $features]);
213
+            }
214
+        }
215
+
216
+        // Check if NSS and perform heuristic check
217
+        if(strpos($versionString, 'NSS/') === 0) {
218
+            try {
219
+                $firstClient = $this->clientService->newClient();
220
+                $firstClient->get('https://nextcloud.com/');
221
+
222
+                $secondClient = $this->clientService->newClient();
223
+                $secondClient->get('https://nextcloud.com/');
224
+            } catch (ClientException $e) {
225
+                if($e->getResponse()->getStatusCode() === 400) {
226
+                    return (string) $this->l10n->t('cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably.', ['NSS', $versionString, $features]);
227
+                }
228
+            }
229
+        }
230
+
231
+        return '';
232
+    }
233
+
234
+    /**
235
+     * Whether the version is outdated
236
+     *
237
+     * @return bool
238
+     */
239
+    protected function isPhpOutdated() {
240
+        if (version_compare(PHP_VERSION, '7.0.0', '<')) {
241
+            return true;
242
+        }
243
+
244
+        return false;
245
+    }
246
+
247
+    /**
248
+     * Whether the php version is still supported (at time of release)
249
+     * according to: https://secure.php.net/supported-versions.php
250
+     *
251
+     * @return array
252
+     */
253
+    private function isPhpSupported() {
254
+        return ['eol' => $this->isPhpOutdated(), 'version' => PHP_VERSION];
255
+    }
256
+
257
+    /**
258
+     * Check if the reverse proxy configuration is working as expected
259
+     *
260
+     * @return bool
261
+     */
262
+    private function forwardedForHeadersWorking() {
263
+        $trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
264
+        $remoteAddress = $this->request->getRemoteAddress();
265
+
266
+        if (is_array($trustedProxies) && in_array($remoteAddress, $trustedProxies)) {
267
+            return false;
268
+        }
269
+
270
+        // either not enabled or working correctly
271
+        return true;
272
+    }
273
+
274
+    /**
275
+     * Checks if the correct memcache module for PHP is installed. Only
276
+     * fails if memcached is configured and the working module is not installed.
277
+     *
278
+     * @return bool
279
+     */
280
+    private function isCorrectMemcachedPHPModuleInstalled() {
281
+        if ($this->config->getSystemValue('memcache.distributed', null) !== '\OC\Memcache\Memcached') {
282
+            return true;
283
+        }
284
+
285
+        // there are two different memcached modules for PHP
286
+        // we only support memcached and not memcache
287
+        // https://code.google.com/p/memcached/wiki/PHPClientComparison
288
+        return !(!extension_loaded('memcached') && extension_loaded('memcache'));
289
+    }
290
+
291
+    /**
292
+     * Checks if set_time_limit is not disabled.
293
+     *
294
+     * @return bool
295
+     */
296
+    private function isSettimelimitAvailable() {
297
+        if (function_exists('set_time_limit')
298
+            && strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
299
+            return true;
300
+        }
301
+
302
+        return false;
303
+    }
304
+
305
+    /**
306
+     * @return RedirectResponse
307
+     */
308
+    public function rescanFailedIntegrityCheck() {
309
+        $this->checker->runInstanceVerification();
310
+        return new RedirectResponse(
311
+            $this->urlGenerator->linkToRoute('settings.AdminSettings.index')
312
+        );
313
+    }
314
+
315
+    /**
316
+     * @NoCSRFRequired
317
+     * @return DataResponse
318
+     */
319
+    public function getFailedIntegrityCheckFiles() {
320
+        if(!$this->checker->isCodeCheckEnforced()) {
321
+            return new DataDisplayResponse('Integrity checker has been disabled. Integrity cannot be verified.');
322
+        }
323
+
324
+        $completeResults = $this->checker->getResults();
325
+
326
+        if(!empty($completeResults)) {
327
+            $formattedTextResponse = 'Technical information
328 328
 =====================
329 329
 The following list covers which files have failed the integrity check. Please read
330 330
 the previous linked documentation to learn more about the errors and how to fix
@@ -333,112 +333,112 @@  discard block
 block discarded – undo
333 333
 Results
334 334
 =======
335 335
 ';
336
-			foreach($completeResults as $context => $contextResult) {
337
-				$formattedTextResponse .= "- $context\n";
338
-
339
-				foreach($contextResult as $category => $result) {
340
-					$formattedTextResponse .= "\t- $category\n";
341
-					if($category !== 'EXCEPTION') {
342
-						foreach ($result as $key => $results) {
343
-							$formattedTextResponse .= "\t\t- $key\n";
344
-						}
345
-					} else {
346
-						foreach ($result as $key => $results) {
347
-							$formattedTextResponse .= "\t\t- $results\n";
348
-						}
349
-					}
350
-
351
-				}
352
-			}
353
-
354
-			$formattedTextResponse .= '
336
+            foreach($completeResults as $context => $contextResult) {
337
+                $formattedTextResponse .= "- $context\n";
338
+
339
+                foreach($contextResult as $category => $result) {
340
+                    $formattedTextResponse .= "\t- $category\n";
341
+                    if($category !== 'EXCEPTION') {
342
+                        foreach ($result as $key => $results) {
343
+                            $formattedTextResponse .= "\t\t- $key\n";
344
+                        }
345
+                    } else {
346
+                        foreach ($result as $key => $results) {
347
+                            $formattedTextResponse .= "\t\t- $results\n";
348
+                        }
349
+                    }
350
+
351
+                }
352
+            }
353
+
354
+            $formattedTextResponse .= '
355 355
 Raw output
356 356
 ==========
357 357
 ';
358
-			$formattedTextResponse .= print_r($completeResults, true);
359
-		} else {
360
-			$formattedTextResponse = 'No errors have been found.';
361
-		}
362
-
363
-
364
-		$response = new DataDisplayResponse(
365
-			$formattedTextResponse,
366
-			Http::STATUS_OK,
367
-			[
368
-				'Content-Type' => 'text/plain',
369
-			]
370
-		);
371
-
372
-		return $response;
373
-	}
374
-
375
-	/**
376
-	 * Checks whether a PHP opcache is properly set up
377
-	 * @return bool
378
-	 */
379
-	protected function isOpcacheProperlySetup() {
380
-		$iniWrapper = new IniGetWrapper();
381
-
382
-		$isOpcacheProperlySetUp = true;
383
-
384
-		if(!$iniWrapper->getBool('opcache.enable')) {
385
-			$isOpcacheProperlySetUp = false;
386
-		}
387
-
388
-		if(!$iniWrapper->getBool('opcache.save_comments')) {
389
-			$isOpcacheProperlySetUp = false;
390
-		}
391
-
392
-		if(!$iniWrapper->getBool('opcache.enable_cli')) {
393
-			$isOpcacheProperlySetUp = false;
394
-		}
395
-
396
-		if($iniWrapper->getNumeric('opcache.max_accelerated_files') < 10000) {
397
-			$isOpcacheProperlySetUp = false;
398
-		}
399
-
400
-		if($iniWrapper->getNumeric('opcache.memory_consumption') < 128) {
401
-			$isOpcacheProperlySetUp = false;
402
-		}
403
-
404
-		if($iniWrapper->getNumeric('opcache.interned_strings_buffer') < 8) {
405
-			$isOpcacheProperlySetUp = false;
406
-		}
407
-
408
-		return $isOpcacheProperlySetUp;
409
-	}
410
-
411
-	/**
412
-	 * Check if the required FreeType functions are present
413
-	 * @return bool
414
-	 */
415
-	protected function hasFreeTypeSupport() {
416
-		return function_exists('imagettfbbox') && function_exists('imagettftext');
417
-	}
418
-
419
-	/**
420
-	 * @return DataResponse
421
-	 */
422
-	public function check() {
423
-		return new DataResponse(
424
-			[
425
-				'serverHasInternetConnection' => $this->isInternetConnectionWorking(),
426
-				'isMemcacheConfigured' => $this->isMemcacheConfigured(),
427
-				'memcacheDocs' => $this->urlGenerator->linkToDocs('admin-performance'),
428
-				'isUrandomAvailable' => $this->isUrandomAvailable(),
429
-				'securityDocs' => $this->urlGenerator->linkToDocs('admin-security'),
430
-				'isUsedTlsLibOutdated' => $this->isUsedTlsLibOutdated(),
431
-				'phpSupported' => $this->isPhpSupported(),
432
-				'forwardedForHeadersWorking' => $this->forwardedForHeadersWorking(),
433
-				'reverseProxyDocs' => $this->urlGenerator->linkToDocs('admin-reverse-proxy'),
434
-				'isCorrectMemcachedPHPModuleInstalled' => $this->isCorrectMemcachedPHPModuleInstalled(),
435
-				'hasPassedCodeIntegrityCheck' => $this->checker->hasPassedCheck(),
436
-				'codeIntegrityCheckerDocumentation' => $this->urlGenerator->linkToDocs('admin-code-integrity'),
437
-				'isOpcacheProperlySetup' => $this->isOpcacheProperlySetup(),
438
-				'phpOpcacheDocumentation' => $this->urlGenerator->linkToDocs('admin-php-opcache'),
439
-				'isSettimelimitAvailable' => $this->isSettimelimitAvailable(),
440
-				'hasFreeTypeSupport' => $this->hasFreeTypeSupport(),
441
-			]
442
-		);
443
-	}
358
+            $formattedTextResponse .= print_r($completeResults, true);
359
+        } else {
360
+            $formattedTextResponse = 'No errors have been found.';
361
+        }
362
+
363
+
364
+        $response = new DataDisplayResponse(
365
+            $formattedTextResponse,
366
+            Http::STATUS_OK,
367
+            [
368
+                'Content-Type' => 'text/plain',
369
+            ]
370
+        );
371
+
372
+        return $response;
373
+    }
374
+
375
+    /**
376
+     * Checks whether a PHP opcache is properly set up
377
+     * @return bool
378
+     */
379
+    protected function isOpcacheProperlySetup() {
380
+        $iniWrapper = new IniGetWrapper();
381
+
382
+        $isOpcacheProperlySetUp = true;
383
+
384
+        if(!$iniWrapper->getBool('opcache.enable')) {
385
+            $isOpcacheProperlySetUp = false;
386
+        }
387
+
388
+        if(!$iniWrapper->getBool('opcache.save_comments')) {
389
+            $isOpcacheProperlySetUp = false;
390
+        }
391
+
392
+        if(!$iniWrapper->getBool('opcache.enable_cli')) {
393
+            $isOpcacheProperlySetUp = false;
394
+        }
395
+
396
+        if($iniWrapper->getNumeric('opcache.max_accelerated_files') < 10000) {
397
+            $isOpcacheProperlySetUp = false;
398
+        }
399
+
400
+        if($iniWrapper->getNumeric('opcache.memory_consumption') < 128) {
401
+            $isOpcacheProperlySetUp = false;
402
+        }
403
+
404
+        if($iniWrapper->getNumeric('opcache.interned_strings_buffer') < 8) {
405
+            $isOpcacheProperlySetUp = false;
406
+        }
407
+
408
+        return $isOpcacheProperlySetUp;
409
+    }
410
+
411
+    /**
412
+     * Check if the required FreeType functions are present
413
+     * @return bool
414
+     */
415
+    protected function hasFreeTypeSupport() {
416
+        return function_exists('imagettfbbox') && function_exists('imagettftext');
417
+    }
418
+
419
+    /**
420
+     * @return DataResponse
421
+     */
422
+    public function check() {
423
+        return new DataResponse(
424
+            [
425
+                'serverHasInternetConnection' => $this->isInternetConnectionWorking(),
426
+                'isMemcacheConfigured' => $this->isMemcacheConfigured(),
427
+                'memcacheDocs' => $this->urlGenerator->linkToDocs('admin-performance'),
428
+                'isUrandomAvailable' => $this->isUrandomAvailable(),
429
+                'securityDocs' => $this->urlGenerator->linkToDocs('admin-security'),
430
+                'isUsedTlsLibOutdated' => $this->isUsedTlsLibOutdated(),
431
+                'phpSupported' => $this->isPhpSupported(),
432
+                'forwardedForHeadersWorking' => $this->forwardedForHeadersWorking(),
433
+                'reverseProxyDocs' => $this->urlGenerator->linkToDocs('admin-reverse-proxy'),
434
+                'isCorrectMemcachedPHPModuleInstalled' => $this->isCorrectMemcachedPHPModuleInstalled(),
435
+                'hasPassedCodeIntegrityCheck' => $this->checker->hasPassedCheck(),
436
+                'codeIntegrityCheckerDocumentation' => $this->urlGenerator->linkToDocs('admin-code-integrity'),
437
+                'isOpcacheProperlySetup' => $this->isOpcacheProperlySetup(),
438
+                'phpOpcacheDocumentation' => $this->urlGenerator->linkToDocs('admin-php-opcache'),
439
+                'isSettimelimitAvailable' => $this->isSettimelimitAvailable(),
440
+                'hasFreeTypeSupport' => $this->hasFreeTypeSupport(),
441
+            ]
442
+        );
443
+    }
444 444
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Wizard.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1104,7 +1104,7 @@
 block discarded – undo
1104 1104
 	}
1105 1105
 
1106 1106
 	/**
1107
-	 * @param array $reqs
1107
+	 * @param string[] $reqs
1108 1108
 	 * @return bool
1109 1109
 	 */
1110 1110
 	private function checkRequirements($reqs) {
Please login to merge, or discard this patch.
Spacing   +154 added lines, -154 removed lines patch added patch discarded remove patch
@@ -71,7 +71,7 @@  discard block
 block discarded – undo
71 71
 	public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) {
72 72
 		parent::__construct($ldap);
73 73
 		$this->configuration = $configuration;
74
-		if(is_null(Wizard::$l)) {
74
+		if (is_null(Wizard::$l)) {
75 75
 			Wizard::$l = \OC::$server->getL10N('user_ldap');
76 76
 		}
77 77
 		$this->access = $access;
@@ -79,7 +79,7 @@  discard block
 block discarded – undo
79 79
 	}
80 80
 
81 81
 	public function  __destruct() {
82
-		if($this->result->hasChanges()) {
82
+		if ($this->result->hasChanges()) {
83 83
 			$this->configuration->saveConfiguration();
84 84
 		}
85 85
 	}
@@ -94,18 +94,18 @@  discard block
 block discarded – undo
94 94
 	 */
95 95
 	public function countEntries($filter, $type) {
96 96
 		$reqs = array('ldapHost', 'ldapPort', 'ldapBase');
97
-		if($type === 'users') {
97
+		if ($type === 'users') {
98 98
 			$reqs[] = 'ldapUserFilter';
99 99
 		}
100
-		if(!$this->checkRequirements($reqs)) {
100
+		if (!$this->checkRequirements($reqs)) {
101 101
 			throw new \Exception('Requirements not met', 400);
102 102
 		}
103 103
 
104 104
 		$attr = array('dn'); // default
105 105
 		$limit = 1001;
106
-		if($type === 'groups') {
107
-			$result =  $this->access->countGroups($filter, $attr, $limit);
108
-		} else if($type === 'users') {
106
+		if ($type === 'groups') {
107
+			$result = $this->access->countGroups($filter, $attr, $limit);
108
+		} else if ($type === 'users') {
109 109
 			$result = $this->access->countUsers($filter, $attr, $limit);
110 110
 		} else if ($type === 'objects') {
111 111
 			$result = $this->access->countObjects($limit);
@@ -125,7 +125,7 @@  discard block
 block discarded – undo
125 125
 	 */
126 126
 	private function formatCountResult($count) {
127 127
 		$formatted = ($count !== false) ? $count : 0;
128
-		if($formatted > 1000) {
128
+		if ($formatted > 1000) {
129 129
 			$formatted = '> 1000';
130 130
 		}
131 131
 		return $formatted;
@@ -134,7 +134,7 @@  discard block
 block discarded – undo
134 134
 	public function countGroups() {
135 135
 		$filter = $this->configuration->ldapGroupFilter;
136 136
 
137
-		if(empty($filter)) {
137
+		if (empty($filter)) {
138 138
 			$output = self::$l->n('%s group found', '%s groups found', 0, array(0));
139 139
 			$this->result->addChange('ldap_group_count', $output);
140 140
 			return $this->result;
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
 			$groupsTotal = $this->formatCountResult($this->countEntries($filter, 'groups'));
145 145
 		} catch (\Exception $e) {
146 146
 			//400 can be ignored, 500 is forwarded
147
-			if($e->getCode() === 500) {
147
+			if ($e->getCode() === 500) {
148 148
 				throw $e;
149 149
 			}
150 150
 			return false;
@@ -176,7 +176,7 @@  discard block
 block discarded – undo
176 176
 	public function countInBaseDN() {
177 177
 		// we don't need to provide a filter in this case
178 178
 		$total = $this->countEntries(null, 'objects');
179
-		if($total === false) {
179
+		if ($total === false) {
180 180
 			throw new \Exception('invalid results received');
181 181
 		}
182 182
 		$this->result->addChange('ldap_test_base', $total);
@@ -190,7 +190,7 @@  discard block
 block discarded – undo
190 190
 	 * @return int|bool
191 191
 	 */
192 192
 	public function countUsersWithAttribute($attr, $existsCheck = false) {
193
-		if(!$this->checkRequirements(array('ldapHost',
193
+		if (!$this->checkRequirements(array('ldapHost',
194 194
 										   'ldapPort',
195 195
 										   'ldapBase',
196 196
 										   'ldapUserFilter',
@@ -200,7 +200,7 @@  discard block
 block discarded – undo
200 200
 
201 201
 		$filter = $this->access->combineFilterWithAnd(array(
202 202
 			$this->configuration->ldapUserFilter,
203
-			$attr . '=*'
203
+			$attr.'=*'
204 204
 		));
205 205
 
206 206
 		$limit = ($existsCheck === false) ? null : 1;
@@ -215,7 +215,7 @@  discard block
 block discarded – undo
215 215
 	 * @throws \Exception
216 216
 	 */
217 217
 	public function detectUserDisplayNameAttribute() {
218
-		if(!$this->checkRequirements(array('ldapHost',
218
+		if (!$this->checkRequirements(array('ldapHost',
219 219
 										'ldapPort',
220 220
 										'ldapBase',
221 221
 										'ldapUserFilter',
@@ -227,8 +227,8 @@  discard block
 block discarded – undo
227 227
 		if ($attr !== '' && $attr !== 'displayName') {
228 228
 			// most likely not the default value with upper case N,
229 229
 			// verify it still produces a result
230
-			$count = (int)$this->countUsersWithAttribute($attr, true);
231
-			if($count > 0) {
230
+			$count = (int) $this->countUsersWithAttribute($attr, true);
231
+			if ($count > 0) {
232 232
 				//no change, but we sent it back to make sure the user interface
233 233
 				//is still correct, even if the ajax call was cancelled meanwhile
234 234
 				$this->result->addChange('ldap_display_name', $attr);
@@ -239,9 +239,9 @@  discard block
 block discarded – undo
239 239
 		// first attribute that has at least one result wins
240 240
 		$displayNameAttrs = array('displayname', 'cn');
241 241
 		foreach ($displayNameAttrs as $attr) {
242
-			$count = (int)$this->countUsersWithAttribute($attr, true);
242
+			$count = (int) $this->countUsersWithAttribute($attr, true);
243 243
 
244
-			if($count > 0) {
244
+			if ($count > 0) {
245 245
 				$this->applyFind('ldap_display_name', $attr);
246 246
 				return $this->result;
247 247
 			}
@@ -257,7 +257,7 @@  discard block
 block discarded – undo
257 257
 	 * @return WizardResult|bool
258 258
 	 */
259 259
 	public function detectEmailAttribute() {
260
-		if(!$this->checkRequirements(array('ldapHost',
260
+		if (!$this->checkRequirements(array('ldapHost',
261 261
 										   'ldapPort',
262 262
 										   'ldapBase',
263 263
 										   'ldapUserFilter',
@@ -267,8 +267,8 @@  discard block
 block discarded – undo
267 267
 
268 268
 		$attr = $this->configuration->ldapEmailAttribute;
269 269
 		if ($attr !== '') {
270
-			$count = (int)$this->countUsersWithAttribute($attr, true);
271
-			if($count > 0) {
270
+			$count = (int) $this->countUsersWithAttribute($attr, true);
271
+			if ($count > 0) {
272 272
 				return false;
273 273
 			}
274 274
 			$writeLog = true;
@@ -279,19 +279,19 @@  discard block
 block discarded – undo
279 279
 		$emailAttributes = array('mail', 'mailPrimaryAddress');
280 280
 		$winner = '';
281 281
 		$maxUsers = 0;
282
-		foreach($emailAttributes as $attr) {
282
+		foreach ($emailAttributes as $attr) {
283 283
 			$count = $this->countUsersWithAttribute($attr);
284
-			if($count > $maxUsers) {
284
+			if ($count > $maxUsers) {
285 285
 				$maxUsers = $count;
286 286
 				$winner = $attr;
287 287
 			}
288 288
 		}
289 289
 
290
-		if($winner !== '') {
290
+		if ($winner !== '') {
291 291
 			$this->applyFind('ldap_email_attr', $winner);
292
-			if($writeLog) {
293
-				\OCP\Util::writeLog('user_ldap', 'The mail attribute has ' .
294
-					'automatically been reset, because the original value ' .
292
+			if ($writeLog) {
293
+				\OCP\Util::writeLog('user_ldap', 'The mail attribute has '.
294
+					'automatically been reset, because the original value '.
295 295
 					'did not return any results.', \OCP\Util::INFO);
296 296
 			}
297 297
 		}
@@ -304,7 +304,7 @@  discard block
 block discarded – undo
304 304
 	 * @throws \Exception
305 305
 	 */
306 306
 	public function determineAttributes() {
307
-		if(!$this->checkRequirements(array('ldapHost',
307
+		if (!$this->checkRequirements(array('ldapHost',
308 308
 										   'ldapPort',
309 309
 										   'ldapBase',
310 310
 										   'ldapUserFilter',
@@ -320,7 +320,7 @@  discard block
 block discarded – undo
320 320
 		$this->result->addOptions('ldap_loginfilter_attributes', $attributes);
321 321
 
322 322
 		$selected = $this->configuration->ldapLoginFilterAttributes;
323
-		if(is_array($selected) && !empty($selected)) {
323
+		if (is_array($selected) && !empty($selected)) {
324 324
 			$this->result->addChange('ldap_loginfilter_attributes', $selected);
325 325
 		}
326 326
 
@@ -333,7 +333,7 @@  discard block
 block discarded – undo
333 333
 	 * @throws \Exception
334 334
 	 */
335 335
 	private function getUserAttributes() {
336
-		if(!$this->checkRequirements(array('ldapHost',
336
+		if (!$this->checkRequirements(array('ldapHost',
337 337
 										   'ldapPort',
338 338
 										   'ldapBase',
339 339
 										   'ldapUserFilter',
@@ -341,20 +341,20 @@  discard block
 block discarded – undo
341 341
 			return  false;
342 342
 		}
343 343
 		$cr = $this->getConnection();
344
-		if(!$cr) {
344
+		if (!$cr) {
345 345
 			throw new \Exception('Could not connect to LDAP');
346 346
 		}
347 347
 
348 348
 		$base = $this->configuration->ldapBase[0];
349 349
 		$filter = $this->configuration->ldapUserFilter;
350 350
 		$rr = $this->ldap->search($cr, $base, $filter, array(), 1, 1);
351
-		if(!$this->ldap->isResource($rr)) {
351
+		if (!$this->ldap->isResource($rr)) {
352 352
 			return false;
353 353
 		}
354 354
 		$er = $this->ldap->firstEntry($cr, $rr);
355 355
 		$attributes = $this->ldap->getAttributes($cr, $er);
356 356
 		$pureAttributes = array();
357
-		for($i = 0; $i < $attributes['count']; $i++) {
357
+		for ($i = 0; $i < $attributes['count']; $i++) {
358 358
 			$pureAttributes[] = $attributes[$i];
359 359
 		}
360 360
 
@@ -389,23 +389,23 @@  discard block
 block discarded – undo
389 389
 	 * @throws \Exception
390 390
 	 */
391 391
 	private function determineGroups($dbKey, $confKey, $testMemberOf = true) {
392
-		if(!$this->checkRequirements(array('ldapHost',
392
+		if (!$this->checkRequirements(array('ldapHost',
393 393
 										   'ldapPort',
394 394
 										   'ldapBase',
395 395
 										   ))) {
396 396
 			return  false;
397 397
 		}
398 398
 		$cr = $this->getConnection();
399
-		if(!$cr) {
399
+		if (!$cr) {
400 400
 			throw new \Exception('Could not connect to LDAP');
401 401
 		}
402 402
 
403 403
 		$this->fetchGroups($dbKey, $confKey);
404 404
 
405
-		if($testMemberOf) {
405
+		if ($testMemberOf) {
406 406
 			$this->configuration->hasMemberOfFilterSupport = $this->testMemberOf();
407 407
 			$this->result->markChange();
408
-			if(!$this->configuration->hasMemberOfFilterSupport) {
408
+			if (!$this->configuration->hasMemberOfFilterSupport) {
409 409
 				throw new \Exception('memberOf is not supported by the server');
410 410
 			}
411 411
 		}
@@ -425,7 +425,7 @@  discard block
 block discarded – undo
425 425
 		$obclasses = array('posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames', 'groupOfUniqueNames');
426 426
 
427 427
 		$filterParts = array();
428
-		foreach($obclasses as $obclass) {
428
+		foreach ($obclasses as $obclass) {
429 429
 			$filterParts[] = 'objectclass='.$obclass;
430 430
 		}
431 431
 		//we filter for everything
@@ -442,8 +442,8 @@  discard block
 block discarded – undo
442 442
 			// we need to request dn additionally here, otherwise memberOf
443 443
 			// detection will fail later
444 444
 			$result = $this->access->searchGroups($filter, array('cn', 'dn'), $limit, $offset);
445
-			foreach($result as $item) {
446
-				if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
445
+			foreach ($result as $item) {
446
+				if (!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
447 447
 					// just in case - no issue known
448 448
 					continue;
449 449
 				}
@@ -453,7 +453,7 @@  discard block
 block discarded – undo
453 453
 			$offset += $limit;
454 454
 		} while ($this->access->hasMoreResults());
455 455
 
456
-		if(count($groupNames) > 0) {
456
+		if (count($groupNames) > 0) {
457 457
 			natsort($groupNames);
458 458
 			$this->result->addOptions($dbKey, array_values($groupNames));
459 459
 		} else {
@@ -461,7 +461,7 @@  discard block
 block discarded – undo
461 461
 		}
462 462
 
463 463
 		$setFeatures = $this->configuration->$confKey;
464
-		if(is_array($setFeatures) && !empty($setFeatures)) {
464
+		if (is_array($setFeatures) && !empty($setFeatures)) {
465 465
 			//something is already configured? pre-select it.
466 466
 			$this->result->addChange($dbKey, $setFeatures);
467 467
 		}
@@ -469,14 +469,14 @@  discard block
 block discarded – undo
469 469
 	}
470 470
 
471 471
 	public function determineGroupMemberAssoc() {
472
-		if(!$this->checkRequirements(array('ldapHost',
472
+		if (!$this->checkRequirements(array('ldapHost',
473 473
 										   'ldapPort',
474 474
 										   'ldapGroupFilter',
475 475
 										   ))) {
476 476
 			return  false;
477 477
 		}
478 478
 		$attribute = $this->detectGroupMemberAssoc();
479
-		if($attribute === false) {
479
+		if ($attribute === false) {
480 480
 			return false;
481 481
 		}
482 482
 		$this->configuration->setConfiguration(array('ldapGroupMemberAssocAttr' => $attribute));
@@ -491,14 +491,14 @@  discard block
 block discarded – undo
491 491
 	 * @throws \Exception
492 492
 	 */
493 493
 	public function determineGroupObjectClasses() {
494
-		if(!$this->checkRequirements(array('ldapHost',
494
+		if (!$this->checkRequirements(array('ldapHost',
495 495
 										   'ldapPort',
496 496
 										   'ldapBase',
497 497
 										   ))) {
498 498
 			return  false;
499 499
 		}
500 500
 		$cr = $this->getConnection();
501
-		if(!$cr) {
501
+		if (!$cr) {
502 502
 			throw new \Exception('Could not connect to LDAP');
503 503
 		}
504 504
 
@@ -518,14 +518,14 @@  discard block
 block discarded – undo
518 518
 	 * @throws \Exception
519 519
 	 */
520 520
 	public function determineUserObjectClasses() {
521
-		if(!$this->checkRequirements(array('ldapHost',
521
+		if (!$this->checkRequirements(array('ldapHost',
522 522
 										   'ldapPort',
523 523
 										   'ldapBase',
524 524
 										   ))) {
525 525
 			return  false;
526 526
 		}
527 527
 		$cr = $this->getConnection();
528
-		if(!$cr) {
528
+		if (!$cr) {
529 529
 			throw new \Exception('Could not connect to LDAP');
530 530
 		}
531 531
 
@@ -548,7 +548,7 @@  discard block
 block discarded – undo
548 548
 	 * @throws \Exception
549 549
 	 */
550 550
 	public function getGroupFilter() {
551
-		if(!$this->checkRequirements(array('ldapHost',
551
+		if (!$this->checkRequirements(array('ldapHost',
552 552
 										   'ldapPort',
553 553
 										   'ldapBase',
554 554
 										   ))) {
@@ -572,7 +572,7 @@  discard block
 block discarded – undo
572 572
 	 * @throws \Exception
573 573
 	 */
574 574
 	public function getUserListFilter() {
575
-		if(!$this->checkRequirements(array('ldapHost',
575
+		if (!$this->checkRequirements(array('ldapHost',
576 576
 										   'ldapPort',
577 577
 										   'ldapBase',
578 578
 										   ))) {
@@ -585,7 +585,7 @@  discard block
 block discarded – undo
585 585
 			$this->applyFind('ldap_display_name', $d['ldap_display_name']);
586 586
 		}
587 587
 		$filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
588
-		if(!$filter) {
588
+		if (!$filter) {
589 589
 			throw new \Exception('Cannot create filter');
590 590
 		}
591 591
 
@@ -598,7 +598,7 @@  discard block
 block discarded – undo
598 598
 	 * @throws \Exception
599 599
 	 */
600 600
 	public function getUserLoginFilter() {
601
-		if(!$this->checkRequirements(array('ldapHost',
601
+		if (!$this->checkRequirements(array('ldapHost',
602 602
 										   'ldapPort',
603 603
 										   'ldapBase',
604 604
 										   'ldapUserFilter',
@@ -607,7 +607,7 @@  discard block
 block discarded – undo
607 607
 		}
608 608
 
609 609
 		$filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
610
-		if(!$filter) {
610
+		if (!$filter) {
611 611
 			throw new \Exception('Cannot create filter');
612 612
 		}
613 613
 
@@ -621,7 +621,7 @@  discard block
 block discarded – undo
621 621
 	 * @throws \Exception
622 622
 	 */
623 623
 	public function testLoginName($loginName) {
624
-		if(!$this->checkRequirements(array('ldapHost',
624
+		if (!$this->checkRequirements(array('ldapHost',
625 625
 			'ldapPort',
626 626
 			'ldapBase',
627 627
 			'ldapLoginFilter',
@@ -630,17 +630,17 @@  discard block
 block discarded – undo
630 630
 		}
631 631
 
632 632
 		$cr = $this->access->connection->getConnectionResource();
633
-		if(!$this->ldap->isResource($cr)) {
633
+		if (!$this->ldap->isResource($cr)) {
634 634
 			throw new \Exception('connection error');
635 635
 		}
636 636
 
637
-		if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
637
+		if (mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
638 638
 			=== false) {
639 639
 			throw new \Exception('missing placeholder');
640 640
 		}
641 641
 
642 642
 		$users = $this->access->countUsersByLoginName($loginName);
643
-		if($this->ldap->errno($cr) !== 0) {
643
+		if ($this->ldap->errno($cr) !== 0) {
644 644
 			throw new \Exception($this->ldap->error($cr));
645 645
 		}
646 646
 		$filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
@@ -655,22 +655,22 @@  discard block
 block discarded – undo
655 655
 	 * @throws \Exception
656 656
 	 */
657 657
 	public function guessPortAndTLS() {
658
-		if(!$this->checkRequirements(array('ldapHost',
658
+		if (!$this->checkRequirements(array('ldapHost',
659 659
 										   ))) {
660 660
 			return false;
661 661
 		}
662 662
 		$this->checkHost();
663 663
 		$portSettings = $this->getPortSettingsToTry();
664 664
 
665
-		if(!is_array($portSettings)) {
665
+		if (!is_array($portSettings)) {
666 666
 			throw new \Exception(print_r($portSettings, true));
667 667
 		}
668 668
 
669 669
 		//proceed from the best configuration and return on first success
670
-		foreach($portSettings as $setting) {
670
+		foreach ($portSettings as $setting) {
671 671
 			$p = $setting['port'];
672 672
 			$t = $setting['tls'];
673
-			\OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, \OCP\Util::DEBUG);
673
+			\OCP\Util::writeLog('user_ldap', 'Wiz: trying port '.$p.', TLS '.$t, \OCP\Util::DEBUG);
674 674
 			//connectAndBind may throw Exception, it needs to be catched by the
675 675
 			//callee of this method
676 676
 
@@ -680,7 +680,7 @@  discard block
 block discarded – undo
680 680
 				// any reply other than -1 (= cannot connect) is already okay,
681 681
 				// because then we found the server
682 682
 				// unavailable startTLS returns -11
683
-				if($e->getCode() > 0) {
683
+				if ($e->getCode() > 0) {
684 684
 					$settingsFound = true;
685 685
 				} else {
686 686
 					throw $e;
@@ -690,10 +690,10 @@  discard block
 block discarded – undo
690 690
 			if ($settingsFound === true) {
691 691
 				$config = array(
692 692
 					'ldapPort' => $p,
693
-					'ldapTLS' => (int)$t
693
+					'ldapTLS' => (int) $t
694 694
 				);
695 695
 				$this->configuration->setConfiguration($config);
696
-				\OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, \OCP\Util::DEBUG);
696
+				\OCP\Util::writeLog('user_ldap', 'Wiz: detected Port '.$p, \OCP\Util::DEBUG);
697 697
 				$this->result->addChange('ldap_port', $p);
698 698
 				return $this->result;
699 699
 			}
@@ -708,7 +708,7 @@  discard block
 block discarded – undo
708 708
 	 * @return WizardResult|false WizardResult on success, false otherwise
709 709
 	 */
710 710
 	public function guessBaseDN() {
711
-		if(!$this->checkRequirements(array('ldapHost',
711
+		if (!$this->checkRequirements(array('ldapHost',
712 712
 										   'ldapPort',
713 713
 										   ))) {
714 714
 			return false;
@@ -717,9 +717,9 @@  discard block
 block discarded – undo
717 717
 		//check whether a DN is given in the agent name (99.9% of all cases)
718 718
 		$base = null;
719 719
 		$i = stripos($this->configuration->ldapAgentName, 'dc=');
720
-		if($i !== false) {
720
+		if ($i !== false) {
721 721
 			$base = substr($this->configuration->ldapAgentName, $i);
722
-			if($this->testBaseDN($base)) {
722
+			if ($this->testBaseDN($base)) {
723 723
 				$this->applyFind('ldap_base', $base);
724 724
 				return $this->result;
725 725
 			}
@@ -730,13 +730,13 @@  discard block
 block discarded – undo
730 730
 		//a base DN
731 731
 		$helper = new Helper(\OC::$server->getConfig());
732 732
 		$domain = $helper->getDomainFromURL($this->configuration->ldapHost);
733
-		if(!$domain) {
733
+		if (!$domain) {
734 734
 			return false;
735 735
 		}
736 736
 
737 737
 		$dparts = explode('.', $domain);
738
-		while(count($dparts) > 0) {
739
-			$base2 = 'dc=' . implode(',dc=', $dparts);
738
+		while (count($dparts) > 0) {
739
+			$base2 = 'dc='.implode(',dc=', $dparts);
740 740
 			if ($base !== $base2 && $this->testBaseDN($base2)) {
741 741
 				$this->applyFind('ldap_base', $base2);
742 742
 				return $this->result;
@@ -769,7 +769,7 @@  discard block
 block discarded – undo
769 769
 		$hostInfo = parse_url($host);
770 770
 
771 771
 		//removes Port from Host
772
-		if(is_array($hostInfo) && isset($hostInfo['port'])) {
772
+		if (is_array($hostInfo) && isset($hostInfo['port'])) {
773 773
 			$port = $hostInfo['port'];
774 774
 			$host = str_replace(':'.$port, '', $host);
775 775
 			$this->applyFind('ldap_host', $host);
@@ -786,30 +786,30 @@  discard block
 block discarded – undo
786 786
 	private function detectGroupMemberAssoc() {
787 787
 		$possibleAttrs = array('uniqueMember', 'memberUid', 'member', 'gidNumber');
788 788
 		$filter = $this->configuration->ldapGroupFilter;
789
-		if(empty($filter)) {
789
+		if (empty($filter)) {
790 790
 			return false;
791 791
 		}
792 792
 		$cr = $this->getConnection();
793
-		if(!$cr) {
793
+		if (!$cr) {
794 794
 			throw new \Exception('Could not connect to LDAP');
795 795
 		}
796 796
 		$base = $this->configuration->ldapBase[0];
797 797
 		$rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
798
-		if(!$this->ldap->isResource($rr)) {
798
+		if (!$this->ldap->isResource($rr)) {
799 799
 			return false;
800 800
 		}
801 801
 		$er = $this->ldap->firstEntry($cr, $rr);
802
-		while(is_resource($er)) {
802
+		while (is_resource($er)) {
803 803
 			$this->ldap->getDN($cr, $er);
804 804
 			$attrs = $this->ldap->getAttributes($cr, $er);
805 805
 			$result = array();
806 806
 			$possibleAttrsCount = count($possibleAttrs);
807
-			for($i = 0; $i < $possibleAttrsCount; $i++) {
808
-				if(isset($attrs[$possibleAttrs[$i]])) {
807
+			for ($i = 0; $i < $possibleAttrsCount; $i++) {
808
+				if (isset($attrs[$possibleAttrs[$i]])) {
809 809
 					$result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
810 810
 				}
811 811
 			}
812
-			if(!empty($result)) {
812
+			if (!empty($result)) {
813 813
 				natsort($result);
814 814
 				return key($result);
815 815
 			}
@@ -828,14 +828,14 @@  discard block
 block discarded – undo
828 828
 	 */
829 829
 	private function testBaseDN($base) {
830 830
 		$cr = $this->getConnection();
831
-		if(!$cr) {
831
+		if (!$cr) {
832 832
 			throw new \Exception('Could not connect to LDAP');
833 833
 		}
834 834
 
835 835
 		//base is there, let's validate it. If we search for anything, we should
836 836
 		//get a result set > 0 on a proper base
837 837
 		$rr = $this->ldap->search($cr, $base, 'objectClass=*', array('dn'), 0, 1);
838
-		if(!$this->ldap->isResource($rr)) {
838
+		if (!$this->ldap->isResource($rr)) {
839 839
 			$errorNo  = $this->ldap->errno($cr);
840 840
 			$errorMsg = $this->ldap->error($cr);
841 841
 			\OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base.
@@ -857,11 +857,11 @@  discard block
 block discarded – undo
857 857
 	 */
858 858
 	private function testMemberOf() {
859 859
 		$cr = $this->getConnection();
860
-		if(!$cr) {
860
+		if (!$cr) {
861 861
 			throw new \Exception('Could not connect to LDAP');
862 862
 		}
863 863
 		$result = $this->access->countUsers('memberOf=*', array('memberOf'), 1);
864
-		if(is_int($result) &&  $result > 0) {
864
+		if (is_int($result) && $result > 0) {
865 865
 			return true;
866 866
 		}
867 867
 		return false;
@@ -882,27 +882,27 @@  discard block
 block discarded – undo
882 882
 			case self::LFILTER_USER_LIST:
883 883
 				$objcs = $this->configuration->ldapUserFilterObjectclass;
884 884
 				//glue objectclasses
885
-				if(is_array($objcs) && count($objcs) > 0) {
885
+				if (is_array($objcs) && count($objcs) > 0) {
886 886
 					$filter .= '(|';
887
-					foreach($objcs as $objc) {
888
-						$filter .= '(objectclass=' . $objc . ')';
887
+					foreach ($objcs as $objc) {
888
+						$filter .= '(objectclass='.$objc.')';
889 889
 					}
890 890
 					$filter .= ')';
891 891
 					$parts++;
892 892
 				}
893 893
 				//glue group memberships
894
-				if($this->configuration->hasMemberOfFilterSupport) {
894
+				if ($this->configuration->hasMemberOfFilterSupport) {
895 895
 					$cns = $this->configuration->ldapUserFilterGroups;
896
-					if(is_array($cns) && count($cns) > 0) {
896
+					if (is_array($cns) && count($cns) > 0) {
897 897
 						$filter .= '(|';
898 898
 						$cr = $this->getConnection();
899
-						if(!$cr) {
899
+						if (!$cr) {
900 900
 							throw new \Exception('Could not connect to LDAP');
901 901
 						}
902 902
 						$base = $this->configuration->ldapBase[0];
903
-						foreach($cns as $cn) {
904
-							$rr = $this->ldap->search($cr, $base, 'cn=' . $cn, array('dn', 'primaryGroupToken'));
905
-							if(!$this->ldap->isResource($rr)) {
903
+						foreach ($cns as $cn) {
904
+							$rr = $this->ldap->search($cr, $base, 'cn='.$cn, array('dn', 'primaryGroupToken'));
905
+							if (!$this->ldap->isResource($rr)) {
906 906
 								continue;
907 907
 							}
908 908
 							$er = $this->ldap->firstEntry($cr, $rr);
@@ -911,11 +911,11 @@  discard block
 block discarded – undo
911 911
 							if ($dn === false || $dn === '') {
912 912
 								continue;
913 913
 							}
914
-							$filterPart = '(memberof=' . $dn . ')';
915
-							if(isset($attrs['primaryGroupToken'])) {
914
+							$filterPart = '(memberof='.$dn.')';
915
+							if (isset($attrs['primaryGroupToken'])) {
916 916
 								$pgt = $attrs['primaryGroupToken'][0];
917
-								$primaryFilterPart = '(primaryGroupID=' . $pgt .')';
918
-								$filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
917
+								$primaryFilterPart = '(primaryGroupID='.$pgt.')';
918
+								$filterPart = '(|'.$filterPart.$primaryFilterPart.')';
919 919
 							}
920 920
 							$filter .= $filterPart;
921 921
 						}
@@ -924,8 +924,8 @@  discard block
 block discarded – undo
924 924
 					$parts++;
925 925
 				}
926 926
 				//wrap parts in AND condition
927
-				if($parts > 1) {
928
-					$filter = '(&' . $filter . ')';
927
+				if ($parts > 1) {
928
+					$filter = '(&'.$filter.')';
929 929
 				}
930 930
 				if ($filter === '') {
931 931
 					$filter = '(objectclass=*)';
@@ -935,27 +935,27 @@  discard block
 block discarded – undo
935 935
 			case self::LFILTER_GROUP_LIST:
936 936
 				$objcs = $this->configuration->ldapGroupFilterObjectclass;
937 937
 				//glue objectclasses
938
-				if(is_array($objcs) && count($objcs) > 0) {
938
+				if (is_array($objcs) && count($objcs) > 0) {
939 939
 					$filter .= '(|';
940
-					foreach($objcs as $objc) {
941
-						$filter .= '(objectclass=' . $objc . ')';
940
+					foreach ($objcs as $objc) {
941
+						$filter .= '(objectclass='.$objc.')';
942 942
 					}
943 943
 					$filter .= ')';
944 944
 					$parts++;
945 945
 				}
946 946
 				//glue group memberships
947 947
 				$cns = $this->configuration->ldapGroupFilterGroups;
948
-				if(is_array($cns) && count($cns) > 0) {
948
+				if (is_array($cns) && count($cns) > 0) {
949 949
 					$filter .= '(|';
950
-					foreach($cns as $cn) {
951
-						$filter .= '(cn=' . $cn . ')';
950
+					foreach ($cns as $cn) {
951
+						$filter .= '(cn='.$cn.')';
952 952
 					}
953 953
 					$filter .= ')';
954 954
 				}
955 955
 				$parts++;
956 956
 				//wrap parts in AND condition
957
-				if($parts > 1) {
958
-					$filter = '(&' . $filter . ')';
957
+				if ($parts > 1) {
958
+					$filter = '(&'.$filter.')';
959 959
 				}
960 960
 				break;
961 961
 
@@ -967,47 +967,47 @@  discard block
 block discarded – undo
967 967
 				$userAttributes = array_change_key_case(array_flip($userAttributes));
968 968
 				$parts = 0;
969 969
 
970
-				if($this->configuration->ldapLoginFilterUsername === '1') {
970
+				if ($this->configuration->ldapLoginFilterUsername === '1') {
971 971
 					$attr = '';
972
-					if(isset($userAttributes['uid'])) {
972
+					if (isset($userAttributes['uid'])) {
973 973
 						$attr = 'uid';
974
-					} else if(isset($userAttributes['samaccountname'])) {
974
+					} else if (isset($userAttributes['samaccountname'])) {
975 975
 						$attr = 'samaccountname';
976
-					} else if(isset($userAttributes['cn'])) {
976
+					} else if (isset($userAttributes['cn'])) {
977 977
 						//fallback
978 978
 						$attr = 'cn';
979 979
 					}
980 980
 					if ($attr !== '') {
981
-						$filterUsername = '(' . $attr . $loginpart . ')';
981
+						$filterUsername = '('.$attr.$loginpart.')';
982 982
 						$parts++;
983 983
 					}
984 984
 				}
985 985
 
986 986
 				$filterEmail = '';
987
-				if($this->configuration->ldapLoginFilterEmail === '1') {
987
+				if ($this->configuration->ldapLoginFilterEmail === '1') {
988 988
 					$filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
989 989
 					$parts++;
990 990
 				}
991 991
 
992 992
 				$filterAttributes = '';
993 993
 				$attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
994
-				if(is_array($attrsToFilter) && count($attrsToFilter) > 0) {
994
+				if (is_array($attrsToFilter) && count($attrsToFilter) > 0) {
995 995
 					$filterAttributes = '(|';
996
-					foreach($attrsToFilter as $attribute) {
997
-						$filterAttributes .= '(' . $attribute . $loginpart . ')';
996
+					foreach ($attrsToFilter as $attribute) {
997
+						$filterAttributes .= '('.$attribute.$loginpart.')';
998 998
 					}
999 999
 					$filterAttributes .= ')';
1000 1000
 					$parts++;
1001 1001
 				}
1002 1002
 
1003 1003
 				$filterLogin = '';
1004
-				if($parts > 1) {
1004
+				if ($parts > 1) {
1005 1005
 					$filterLogin = '(|';
1006 1006
 				}
1007 1007
 				$filterLogin .= $filterUsername;
1008 1008
 				$filterLogin .= $filterEmail;
1009 1009
 				$filterLogin .= $filterAttributes;
1010
-				if($parts > 1) {
1010
+				if ($parts > 1) {
1011 1011
 					$filterLogin .= ')';
1012 1012
 				}
1013 1013
 
@@ -1032,12 +1032,12 @@  discard block
 block discarded – undo
1032 1032
 		//connect, does not really trigger any server communication
1033 1033
 		$host = $this->configuration->ldapHost;
1034 1034
 		$hostInfo = parse_url($host);
1035
-		if(!$hostInfo) {
1035
+		if (!$hostInfo) {
1036 1036
 			throw new \Exception(self::$l->t('Invalid Host'));
1037 1037
 		}
1038 1038
 		\OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', \OCP\Util::DEBUG);
1039 1039
 		$cr = $this->ldap->connect($host, $port);
1040
-		if(!is_resource($cr)) {
1040
+		if (!is_resource($cr)) {
1041 1041
 			throw new \Exception(self::$l->t('Invalid Host'));
1042 1042
 		}
1043 1043
 
@@ -1047,9 +1047,9 @@  discard block
 block discarded – undo
1047 1047
 		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1048 1048
 
1049 1049
 		try {
1050
-			if($tls) {
1050
+			if ($tls) {
1051 1051
 				$isTlsWorking = @$this->ldap->startTls($cr);
1052
-				if(!$isTlsWorking) {
1052
+				if (!$isTlsWorking) {
1053 1053
 					return false;
1054 1054
 				}
1055 1055
 			}
@@ -1063,17 +1063,17 @@  discard block
 block discarded – undo
1063 1063
 			$errNo = $this->ldap->errno($cr);
1064 1064
 			$error = ldap_error($cr);
1065 1065
 			$this->ldap->unbind($cr);
1066
-		} catch(ServerNotAvailableException $e) {
1066
+		} catch (ServerNotAvailableException $e) {
1067 1067
 			return false;
1068 1068
 		}
1069 1069
 
1070
-		if($login === true) {
1070
+		if ($login === true) {
1071 1071
 			$this->ldap->unbind($cr);
1072
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . (int)$tls, \OCP\Util::DEBUG);
1072
+			\OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '.$port.' TLS '.(int) $tls, \OCP\Util::DEBUG);
1073 1073
 			return true;
1074 1074
 		}
1075 1075
 
1076
-		if($errNo === -1) {
1076
+		if ($errNo === -1) {
1077 1077
 			//host, port or TLS wrong
1078 1078
 			return false;
1079 1079
 		}
@@ -1101,9 +1101,9 @@  discard block
 block discarded – undo
1101 1101
 	 */
1102 1102
 	private function checkRequirements($reqs) {
1103 1103
 		$this->checkAgentRequirements();
1104
-		foreach($reqs as $option) {
1104
+		foreach ($reqs as $option) {
1105 1105
 			$value = $this->configuration->$option;
1106
-			if(empty($value)) {
1106
+			if (empty($value)) {
1107 1107
 				return false;
1108 1108
 			}
1109 1109
 		}
@@ -1125,33 +1125,33 @@  discard block
 block discarded – undo
1125 1125
 		$dnRead = array();
1126 1126
 		$foundItems = array();
1127 1127
 		$maxEntries = 0;
1128
-		if(!is_array($this->configuration->ldapBase)
1128
+		if (!is_array($this->configuration->ldapBase)
1129 1129
 		   || !isset($this->configuration->ldapBase[0])) {
1130 1130
 			return false;
1131 1131
 		}
1132 1132
 		$base = $this->configuration->ldapBase[0];
1133 1133
 		$cr = $this->getConnection();
1134
-		if(!$this->ldap->isResource($cr)) {
1134
+		if (!$this->ldap->isResource($cr)) {
1135 1135
 			return false;
1136 1136
 		}
1137 1137
 		$lastFilter = null;
1138
-		if(isset($filters[count($filters)-1])) {
1139
-			$lastFilter = $filters[count($filters)-1];
1138
+		if (isset($filters[count($filters) - 1])) {
1139
+			$lastFilter = $filters[count($filters) - 1];
1140 1140
 		}
1141
-		foreach($filters as $filter) {
1142
-			if($lastFilter === $filter && count($foundItems) > 0) {
1141
+		foreach ($filters as $filter) {
1142
+			if ($lastFilter === $filter && count($foundItems) > 0) {
1143 1143
 				//skip when the filter is a wildcard and results were found
1144 1144
 				continue;
1145 1145
 			}
1146 1146
 			// 20k limit for performance and reason
1147 1147
 			$rr = $this->ldap->search($cr, $base, $filter, array($attr), 0, 20000);
1148
-			if(!$this->ldap->isResource($rr)) {
1148
+			if (!$this->ldap->isResource($rr)) {
1149 1149
 				continue;
1150 1150
 			}
1151 1151
 			$entries = $this->ldap->countEntries($cr, $rr);
1152 1152
 			$getEntryFunc = 'firstEntry';
1153
-			if(($entries !== false) && ($entries > 0)) {
1154
-				if(!is_null($maxF) && $entries > $maxEntries) {
1153
+			if (($entries !== false) && ($entries > 0)) {
1154
+				if (!is_null($maxF) && $entries > $maxEntries) {
1155 1155
 					$maxEntries = $entries;
1156 1156
 					$maxF = $filter;
1157 1157
 				}
@@ -1159,13 +1159,13 @@  discard block
 block discarded – undo
1159 1159
 				do {
1160 1160
 					$entry = $this->ldap->$getEntryFunc($cr, $rr);
1161 1161
 					$getEntryFunc = 'nextEntry';
1162
-					if(!$this->ldap->isResource($entry)) {
1162
+					if (!$this->ldap->isResource($entry)) {
1163 1163
 						continue 2;
1164 1164
 					}
1165 1165
 					$rr = $entry; //will be expected by nextEntry next round
1166 1166
 					$attributes = $this->ldap->getAttributes($cr, $entry);
1167 1167
 					$dn = $this->ldap->getDN($cr, $entry);
1168
-					if($dn === false || in_array($dn, $dnRead)) {
1168
+					if ($dn === false || in_array($dn, $dnRead)) {
1169 1169
 						continue;
1170 1170
 					}
1171 1171
 					$newItems = array();
@@ -1176,7 +1176,7 @@  discard block
 block discarded – undo
1176 1176
 					$foundItems = array_merge($foundItems, $newItems);
1177 1177
 					$this->resultCache[$dn][$attr] = $newItems;
1178 1178
 					$dnRead[] = $dn;
1179
-				} while(($state === self::LRESULT_PROCESSED_SKIP
1179
+				} while (($state === self::LRESULT_PROCESSED_SKIP
1180 1180
 						|| $this->ldap->isResource($entry))
1181 1181
 						&& ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit));
1182 1182
 			}
@@ -1199,11 +1199,11 @@  discard block
 block discarded – undo
1199 1199
 	 */
1200 1200
 	private function determineFeature($objectclasses, $attr, $dbkey, $confkey, $po = false) {
1201 1201
 		$cr = $this->getConnection();
1202
-		if(!$cr) {
1202
+		if (!$cr) {
1203 1203
 			throw new \Exception('Could not connect to LDAP');
1204 1204
 		}
1205 1205
 		$p = 'objectclass=';
1206
-		foreach($objectclasses as $key => $value) {
1206
+		foreach ($objectclasses as $key => $value) {
1207 1207
 			$objectclasses[$key] = $p.$value;
1208 1208
 		}
1209 1209
 		$maxEntryObjC = '';
@@ -1215,7 +1215,7 @@  discard block
 block discarded – undo
1215 1215
 		$availableFeatures =
1216 1216
 			$this->cumulativeSearchOnAttribute($objectclasses, $attr,
1217 1217
 											   $dig, $maxEntryObjC);
1218
-		if(is_array($availableFeatures)
1218
+		if (is_array($availableFeatures)
1219 1219
 		   && count($availableFeatures) > 0) {
1220 1220
 			natcasesort($availableFeatures);
1221 1221
 			//natcasesort keeps indices, but we must get rid of them for proper
@@ -1226,7 +1226,7 @@  discard block
 block discarded – undo
1226 1226
 		}
1227 1227
 
1228 1228
 		$setFeatures = $this->configuration->$confkey;
1229
-		if(is_array($setFeatures) && !empty($setFeatures)) {
1229
+		if (is_array($setFeatures) && !empty($setFeatures)) {
1230 1230
 			//something is already configured? pre-select it.
1231 1231
 			$this->result->addChange($dbkey, $setFeatures);
1232 1232
 		} else if ($po && $maxEntryObjC !== '') {
@@ -1248,7 +1248,7 @@  discard block
 block discarded – undo
1248 1248
 	 * LRESULT_PROCESSED_INVALID or LRESULT_PROCESSED_SKIP
1249 1249
 	 */
1250 1250
 	private function getAttributeValuesFromEntry($result, $attribute, &$known) {
1251
-		if(!is_array($result)
1251
+		if (!is_array($result)
1252 1252
 		   || !isset($result['count'])
1253 1253
 		   || !$result['count'] > 0) {
1254 1254
 			return self::LRESULT_PROCESSED_INVALID;
@@ -1257,12 +1257,12 @@  discard block
 block discarded – undo
1257 1257
 		// strtolower on all keys for proper comparison
1258 1258
 		$result = \OCP\Util::mb_array_change_key_case($result);
1259 1259
 		$attribute = strtolower($attribute);
1260
-		if(isset($result[$attribute])) {
1261
-			foreach($result[$attribute] as $key => $val) {
1262
-				if($key === 'count') {
1260
+		if (isset($result[$attribute])) {
1261
+			foreach ($result[$attribute] as $key => $val) {
1262
+				if ($key === 'count') {
1263 1263
 					continue;
1264 1264
 				}
1265
-				if(!in_array($val, $known)) {
1265
+				if (!in_array($val, $known)) {
1266 1266
 					$known[] = $val;
1267 1267
 				}
1268 1268
 			}
@@ -1276,7 +1276,7 @@  discard block
 block discarded – undo
1276 1276
 	 * @return bool|mixed
1277 1277
 	 */
1278 1278
 	private function getConnection() {
1279
-		if(!is_null($this->cr)) {
1279
+		if (!is_null($this->cr)) {
1280 1280
 			return $this->cr;
1281 1281
 		}
1282 1282
 
@@ -1288,14 +1288,14 @@  discard block
 block discarded – undo
1288 1288
 		$this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1289 1289
 		$this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1290 1290
 		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1291
-		if($this->configuration->ldapTLS === 1) {
1291
+		if ($this->configuration->ldapTLS === 1) {
1292 1292
 			$this->ldap->startTls($cr);
1293 1293
 		}
1294 1294
 
1295 1295
 		$lo = @$this->ldap->bind($cr,
1296 1296
 								 $this->configuration->ldapAgentName,
1297 1297
 								 $this->configuration->ldapAgentPassword);
1298
-		if($lo === true) {
1298
+		if ($lo === true) {
1299 1299
 			$this->$cr = $cr;
1300 1300
 			return $cr;
1301 1301
 		}
@@ -1326,18 +1326,18 @@  discard block
 block discarded – undo
1326 1326
 		//636 ← LDAPS / SSL
1327 1327
 		//7xxx ← UCS. need to be checked first, because both ports may be open
1328 1328
 		$host = $this->configuration->ldapHost;
1329
-		$port = (int)$this->configuration->ldapPort;
1329
+		$port = (int) $this->configuration->ldapPort;
1330 1330
 		$portSettings = array();
1331 1331
 
1332 1332
 		//In case the port is already provided, we will check this first
1333
-		if($port > 0) {
1333
+		if ($port > 0) {
1334 1334
 			$hostInfo = parse_url($host);
1335
-			if(!(is_array($hostInfo)
1335
+			if (!(is_array($hostInfo)
1336 1336
 				&& isset($hostInfo['scheme'])
1337 1337
 				&& stripos($hostInfo['scheme'], 'ldaps') !== false)) {
1338 1338
 				$portSettings[] = array('port' => $port, 'tls' => true);
1339 1339
 			}
1340
-			$portSettings[] =array('port' => $port, 'tls' => false);
1340
+			$portSettings[] = array('port' => $port, 'tls' => false);
1341 1341
 		}
1342 1342
 
1343 1343
 		//default ports
Please login to merge, or discard this patch.
Indentation   +1305 added lines, -1305 removed lines patch added patch discarded remove patch
@@ -41,1311 +41,1311 @@
 block discarded – undo
41 41
 use OC\ServerNotAvailableException;
42 42
 
43 43
 class Wizard extends LDAPUtility {
44
-	/** @var \OCP\IL10N */
45
-	static protected $l;
46
-	protected $access;
47
-	protected $cr;
48
-	protected $configuration;
49
-	protected $result;
50
-	protected $resultCache = array();
51
-
52
-	const LRESULT_PROCESSED_OK = 2;
53
-	const LRESULT_PROCESSED_INVALID = 3;
54
-	const LRESULT_PROCESSED_SKIP = 4;
55
-
56
-	const LFILTER_LOGIN      = 2;
57
-	const LFILTER_USER_LIST  = 3;
58
-	const LFILTER_GROUP_LIST = 4;
59
-
60
-	const LFILTER_MODE_ASSISTED = 2;
61
-	const LFILTER_MODE_RAW = 1;
62
-
63
-	const LDAP_NW_TIMEOUT = 4;
64
-
65
-	/**
66
-	 * Constructor
67
-	 * @param Configuration $configuration an instance of Configuration
68
-	 * @param ILDAPWrapper $ldap an instance of ILDAPWrapper
69
-	 * @param Access $access
70
-	 */
71
-	public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) {
72
-		parent::__construct($ldap);
73
-		$this->configuration = $configuration;
74
-		if(is_null(Wizard::$l)) {
75
-			Wizard::$l = \OC::$server->getL10N('user_ldap');
76
-		}
77
-		$this->access = $access;
78
-		$this->result = new WizardResult();
79
-	}
80
-
81
-	public function  __destruct() {
82
-		if($this->result->hasChanges()) {
83
-			$this->configuration->saveConfiguration();
84
-		}
85
-	}
86
-
87
-	/**
88
-	 * counts entries in the LDAP directory
89
-	 *
90
-	 * @param string $filter the LDAP search filter
91
-	 * @param string $type a string being either 'users' or 'groups';
92
-	 * @return bool|int
93
-	 * @throws \Exception
94
-	 */
95
-	public function countEntries($filter, $type) {
96
-		$reqs = array('ldapHost', 'ldapPort', 'ldapBase');
97
-		if($type === 'users') {
98
-			$reqs[] = 'ldapUserFilter';
99
-		}
100
-		if(!$this->checkRequirements($reqs)) {
101
-			throw new \Exception('Requirements not met', 400);
102
-		}
103
-
104
-		$attr = array('dn'); // default
105
-		$limit = 1001;
106
-		if($type === 'groups') {
107
-			$result =  $this->access->countGroups($filter, $attr, $limit);
108
-		} else if($type === 'users') {
109
-			$result = $this->access->countUsers($filter, $attr, $limit);
110
-		} else if ($type === 'objects') {
111
-			$result = $this->access->countObjects($limit);
112
-		} else {
113
-			throw new \Exception('Internal error: Invalid object type', 500);
114
-		}
115
-
116
-		return $result;
117
-	}
118
-
119
-	/**
120
-	 * formats the return value of a count operation to the string to be
121
-	 * inserted.
122
-	 *
123
-	 * @param bool|int $count
124
-	 * @return int|string
125
-	 */
126
-	private function formatCountResult($count) {
127
-		$formatted = ($count !== false) ? $count : 0;
128
-		if($formatted > 1000) {
129
-			$formatted = '> 1000';
130
-		}
131
-		return $formatted;
132
-	}
133
-
134
-	public function countGroups() {
135
-		$filter = $this->configuration->ldapGroupFilter;
136
-
137
-		if(empty($filter)) {
138
-			$output = self::$l->n('%s group found', '%s groups found', 0, array(0));
139
-			$this->result->addChange('ldap_group_count', $output);
140
-			return $this->result;
141
-		}
142
-
143
-		try {
144
-			$groupsTotal = $this->formatCountResult($this->countEntries($filter, 'groups'));
145
-		} catch (\Exception $e) {
146
-			//400 can be ignored, 500 is forwarded
147
-			if($e->getCode() === 500) {
148
-				throw $e;
149
-			}
150
-			return false;
151
-		}
152
-		$output = self::$l->n('%s group found', '%s groups found', $groupsTotal, array($groupsTotal));
153
-		$this->result->addChange('ldap_group_count', $output);
154
-		return $this->result;
155
-	}
156
-
157
-	/**
158
-	 * @return WizardResult
159
-	 * @throws \Exception
160
-	 */
161
-	public function countUsers() {
162
-		$filter = $this->access->getFilterForUserCount();
163
-
164
-		$usersTotal = $this->formatCountResult($this->countEntries($filter, 'users'));
165
-		$output = self::$l->n('%s user found', '%s users found', $usersTotal, array($usersTotal));
166
-		$this->result->addChange('ldap_user_count', $output);
167
-		return $this->result;
168
-	}
169
-
170
-	/**
171
-	 * counts any objects in the currently set base dn
172
-	 *
173
-	 * @return WizardResult
174
-	 * @throws \Exception
175
-	 */
176
-	public function countInBaseDN() {
177
-		// we don't need to provide a filter in this case
178
-		$total = $this->countEntries(null, 'objects');
179
-		if($total === false) {
180
-			throw new \Exception('invalid results received');
181
-		}
182
-		$this->result->addChange('ldap_test_base', $total);
183
-		return $this->result;
184
-	}
185
-
186
-	/**
187
-	 * counts users with a specified attribute
188
-	 * @param string $attr
189
-	 * @param bool $existsCheck
190
-	 * @return int|bool
191
-	 */
192
-	public function countUsersWithAttribute($attr, $existsCheck = false) {
193
-		if(!$this->checkRequirements(array('ldapHost',
194
-										   'ldapPort',
195
-										   'ldapBase',
196
-										   'ldapUserFilter',
197
-										   ))) {
198
-			return  false;
199
-		}
200
-
201
-		$filter = $this->access->combineFilterWithAnd(array(
202
-			$this->configuration->ldapUserFilter,
203
-			$attr . '=*'
204
-		));
205
-
206
-		$limit = ($existsCheck === false) ? null : 1;
207
-
208
-		return $this->access->countUsers($filter, array('dn'), $limit);
209
-	}
210
-
211
-	/**
212
-	 * detects the display name attribute. If a setting is already present that
213
-	 * returns at least one hit, the detection will be canceled.
214
-	 * @return WizardResult|bool
215
-	 * @throws \Exception
216
-	 */
217
-	public function detectUserDisplayNameAttribute() {
218
-		if(!$this->checkRequirements(array('ldapHost',
219
-										'ldapPort',
220
-										'ldapBase',
221
-										'ldapUserFilter',
222
-										))) {
223
-			return  false;
224
-		}
225
-
226
-		$attr = $this->configuration->ldapUserDisplayName;
227
-		if ($attr !== '' && $attr !== 'displayName') {
228
-			// most likely not the default value with upper case N,
229
-			// verify it still produces a result
230
-			$count = (int)$this->countUsersWithAttribute($attr, true);
231
-			if($count > 0) {
232
-				//no change, but we sent it back to make sure the user interface
233
-				//is still correct, even if the ajax call was cancelled meanwhile
234
-				$this->result->addChange('ldap_display_name', $attr);
235
-				return $this->result;
236
-			}
237
-		}
238
-
239
-		// first attribute that has at least one result wins
240
-		$displayNameAttrs = array('displayname', 'cn');
241
-		foreach ($displayNameAttrs as $attr) {
242
-			$count = (int)$this->countUsersWithAttribute($attr, true);
243
-
244
-			if($count > 0) {
245
-				$this->applyFind('ldap_display_name', $attr);
246
-				return $this->result;
247
-			}
248
-		}
249
-
250
-		throw new \Exception(self::$l->t('Could not detect user display name attribute. Please specify it yourself in advanced LDAP settings.'));
251
-	}
252
-
253
-	/**
254
-	 * detects the most often used email attribute for users applying to the
255
-	 * user list filter. If a setting is already present that returns at least
256
-	 * one hit, the detection will be canceled.
257
-	 * @return WizardResult|bool
258
-	 */
259
-	public function detectEmailAttribute() {
260
-		if(!$this->checkRequirements(array('ldapHost',
261
-										   'ldapPort',
262
-										   'ldapBase',
263
-										   'ldapUserFilter',
264
-										   ))) {
265
-			return  false;
266
-		}
267
-
268
-		$attr = $this->configuration->ldapEmailAttribute;
269
-		if ($attr !== '') {
270
-			$count = (int)$this->countUsersWithAttribute($attr, true);
271
-			if($count > 0) {
272
-				return false;
273
-			}
274
-			$writeLog = true;
275
-		} else {
276
-			$writeLog = false;
277
-		}
278
-
279
-		$emailAttributes = array('mail', 'mailPrimaryAddress');
280
-		$winner = '';
281
-		$maxUsers = 0;
282
-		foreach($emailAttributes as $attr) {
283
-			$count = $this->countUsersWithAttribute($attr);
284
-			if($count > $maxUsers) {
285
-				$maxUsers = $count;
286
-				$winner = $attr;
287
-			}
288
-		}
289
-
290
-		if($winner !== '') {
291
-			$this->applyFind('ldap_email_attr', $winner);
292
-			if($writeLog) {
293
-				\OCP\Util::writeLog('user_ldap', 'The mail attribute has ' .
294
-					'automatically been reset, because the original value ' .
295
-					'did not return any results.', \OCP\Util::INFO);
296
-			}
297
-		}
298
-
299
-		return $this->result;
300
-	}
301
-
302
-	/**
303
-	 * @return WizardResult
304
-	 * @throws \Exception
305
-	 */
306
-	public function determineAttributes() {
307
-		if(!$this->checkRequirements(array('ldapHost',
308
-										   'ldapPort',
309
-										   'ldapBase',
310
-										   'ldapUserFilter',
311
-										   ))) {
312
-			return  false;
313
-		}
314
-
315
-		$attributes = $this->getUserAttributes();
316
-
317
-		natcasesort($attributes);
318
-		$attributes = array_values($attributes);
319
-
320
-		$this->result->addOptions('ldap_loginfilter_attributes', $attributes);
321
-
322
-		$selected = $this->configuration->ldapLoginFilterAttributes;
323
-		if(is_array($selected) && !empty($selected)) {
324
-			$this->result->addChange('ldap_loginfilter_attributes', $selected);
325
-		}
326
-
327
-		return $this->result;
328
-	}
329
-
330
-	/**
331
-	 * detects the available LDAP attributes
332
-	 * @return array|false The instance's WizardResult instance
333
-	 * @throws \Exception
334
-	 */
335
-	private function getUserAttributes() {
336
-		if(!$this->checkRequirements(array('ldapHost',
337
-										   'ldapPort',
338
-										   'ldapBase',
339
-										   'ldapUserFilter',
340
-										   ))) {
341
-			return  false;
342
-		}
343
-		$cr = $this->getConnection();
344
-		if(!$cr) {
345
-			throw new \Exception('Could not connect to LDAP');
346
-		}
347
-
348
-		$base = $this->configuration->ldapBase[0];
349
-		$filter = $this->configuration->ldapUserFilter;
350
-		$rr = $this->ldap->search($cr, $base, $filter, array(), 1, 1);
351
-		if(!$this->ldap->isResource($rr)) {
352
-			return false;
353
-		}
354
-		$er = $this->ldap->firstEntry($cr, $rr);
355
-		$attributes = $this->ldap->getAttributes($cr, $er);
356
-		$pureAttributes = array();
357
-		for($i = 0; $i < $attributes['count']; $i++) {
358
-			$pureAttributes[] = $attributes[$i];
359
-		}
360
-
361
-		return $pureAttributes;
362
-	}
363
-
364
-	/**
365
-	 * detects the available LDAP groups
366
-	 * @return WizardResult|false the instance's WizardResult instance
367
-	 */
368
-	public function determineGroupsForGroups() {
369
-		return $this->determineGroups('ldap_groupfilter_groups',
370
-									  'ldapGroupFilterGroups',
371
-									  false);
372
-	}
373
-
374
-	/**
375
-	 * detects the available LDAP groups
376
-	 * @return WizardResult|false the instance's WizardResult instance
377
-	 */
378
-	public function determineGroupsForUsers() {
379
-		return $this->determineGroups('ldap_userfilter_groups',
380
-									  'ldapUserFilterGroups');
381
-	}
382
-
383
-	/**
384
-	 * detects the available LDAP groups
385
-	 * @param string $dbKey
386
-	 * @param string $confKey
387
-	 * @param bool $testMemberOf
388
-	 * @return WizardResult|false the instance's WizardResult instance
389
-	 * @throws \Exception
390
-	 */
391
-	private function determineGroups($dbKey, $confKey, $testMemberOf = true) {
392
-		if(!$this->checkRequirements(array('ldapHost',
393
-										   'ldapPort',
394
-										   'ldapBase',
395
-										   ))) {
396
-			return  false;
397
-		}
398
-		$cr = $this->getConnection();
399
-		if(!$cr) {
400
-			throw new \Exception('Could not connect to LDAP');
401
-		}
402
-
403
-		$this->fetchGroups($dbKey, $confKey);
404
-
405
-		if($testMemberOf) {
406
-			$this->configuration->hasMemberOfFilterSupport = $this->testMemberOf();
407
-			$this->result->markChange();
408
-			if(!$this->configuration->hasMemberOfFilterSupport) {
409
-				throw new \Exception('memberOf is not supported by the server');
410
-			}
411
-		}
412
-
413
-		return $this->result;
414
-	}
415
-
416
-	/**
417
-	 * fetches all groups from LDAP and adds them to the result object
418
-	 *
419
-	 * @param string $dbKey
420
-	 * @param string $confKey
421
-	 * @return array $groupEntries
422
-	 * @throws \Exception
423
-	 */
424
-	public function fetchGroups($dbKey, $confKey) {
425
-		$obclasses = array('posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames', 'groupOfUniqueNames');
426
-
427
-		$filterParts = array();
428
-		foreach($obclasses as $obclass) {
429
-			$filterParts[] = 'objectclass='.$obclass;
430
-		}
431
-		//we filter for everything
432
-		//- that looks like a group and
433
-		//- has the group display name set
434
-		$filter = $this->access->combineFilterWithOr($filterParts);
435
-		$filter = $this->access->combineFilterWithAnd(array($filter, 'cn=*'));
436
-
437
-		$groupNames = array();
438
-		$groupEntries = array();
439
-		$limit = 400;
440
-		$offset = 0;
441
-		do {
442
-			// we need to request dn additionally here, otherwise memberOf
443
-			// detection will fail later
444
-			$result = $this->access->searchGroups($filter, array('cn', 'dn'), $limit, $offset);
445
-			foreach($result as $item) {
446
-				if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
447
-					// just in case - no issue known
448
-					continue;
449
-				}
450
-				$groupNames[] = $item['cn'][0];
451
-				$groupEntries[] = $item;
452
-			}
453
-			$offset += $limit;
454
-		} while ($this->access->hasMoreResults());
455
-
456
-		if(count($groupNames) > 0) {
457
-			natsort($groupNames);
458
-			$this->result->addOptions($dbKey, array_values($groupNames));
459
-		} else {
460
-			throw new \Exception(self::$l->t('Could not find the desired feature'));
461
-		}
462
-
463
-		$setFeatures = $this->configuration->$confKey;
464
-		if(is_array($setFeatures) && !empty($setFeatures)) {
465
-			//something is already configured? pre-select it.
466
-			$this->result->addChange($dbKey, $setFeatures);
467
-		}
468
-		return $groupEntries;
469
-	}
470
-
471
-	public function determineGroupMemberAssoc() {
472
-		if(!$this->checkRequirements(array('ldapHost',
473
-										   'ldapPort',
474
-										   'ldapGroupFilter',
475
-										   ))) {
476
-			return  false;
477
-		}
478
-		$attribute = $this->detectGroupMemberAssoc();
479
-		if($attribute === false) {
480
-			return false;
481
-		}
482
-		$this->configuration->setConfiguration(array('ldapGroupMemberAssocAttr' => $attribute));
483
-		$this->result->addChange('ldap_group_member_assoc_attribute', $attribute);
484
-
485
-		return $this->result;
486
-	}
487
-
488
-	/**
489
-	 * Detects the available object classes
490
-	 * @return WizardResult|false the instance's WizardResult instance
491
-	 * @throws \Exception
492
-	 */
493
-	public function determineGroupObjectClasses() {
494
-		if(!$this->checkRequirements(array('ldapHost',
495
-										   'ldapPort',
496
-										   'ldapBase',
497
-										   ))) {
498
-			return  false;
499
-		}
500
-		$cr = $this->getConnection();
501
-		if(!$cr) {
502
-			throw new \Exception('Could not connect to LDAP');
503
-		}
504
-
505
-		$obclasses = array('groupOfNames', 'groupOfUniqueNames', 'group', 'posixGroup', '*');
506
-		$this->determineFeature($obclasses,
507
-								'objectclass',
508
-								'ldap_groupfilter_objectclass',
509
-								'ldapGroupFilterObjectclass',
510
-								false);
511
-
512
-		return $this->result;
513
-	}
514
-
515
-	/**
516
-	 * detects the available object classes
517
-	 * @return WizardResult
518
-	 * @throws \Exception
519
-	 */
520
-	public function determineUserObjectClasses() {
521
-		if(!$this->checkRequirements(array('ldapHost',
522
-										   'ldapPort',
523
-										   'ldapBase',
524
-										   ))) {
525
-			return  false;
526
-		}
527
-		$cr = $this->getConnection();
528
-		if(!$cr) {
529
-			throw new \Exception('Could not connect to LDAP');
530
-		}
531
-
532
-		$obclasses = array('inetOrgPerson', 'person', 'organizationalPerson',
533
-						   'user', 'posixAccount', '*');
534
-		$filter = $this->configuration->ldapUserFilter;
535
-		//if filter is empty, it is probably the first time the wizard is called
536
-		//then, apply suggestions.
537
-		$this->determineFeature($obclasses,
538
-								'objectclass',
539
-								'ldap_userfilter_objectclass',
540
-								'ldapUserFilterObjectclass',
541
-								empty($filter));
542
-
543
-		return $this->result;
544
-	}
545
-
546
-	/**
547
-	 * @return WizardResult|false
548
-	 * @throws \Exception
549
-	 */
550
-	public function getGroupFilter() {
551
-		if(!$this->checkRequirements(array('ldapHost',
552
-										   'ldapPort',
553
-										   'ldapBase',
554
-										   ))) {
555
-			return false;
556
-		}
557
-		//make sure the use display name is set
558
-		$displayName = $this->configuration->ldapGroupDisplayName;
559
-		if ($displayName === '') {
560
-			$d = $this->configuration->getDefaults();
561
-			$this->applyFind('ldap_group_display_name',
562
-							 $d['ldap_group_display_name']);
563
-		}
564
-		$filter = $this->composeLdapFilter(self::LFILTER_GROUP_LIST);
565
-
566
-		$this->applyFind('ldap_group_filter', $filter);
567
-		return $this->result;
568
-	}
569
-
570
-	/**
571
-	 * @return WizardResult|false
572
-	 * @throws \Exception
573
-	 */
574
-	public function getUserListFilter() {
575
-		if(!$this->checkRequirements(array('ldapHost',
576
-										   'ldapPort',
577
-										   'ldapBase',
578
-										   ))) {
579
-			return false;
580
-		}
581
-		//make sure the use display name is set
582
-		$displayName = $this->configuration->ldapUserDisplayName;
583
-		if ($displayName === '') {
584
-			$d = $this->configuration->getDefaults();
585
-			$this->applyFind('ldap_display_name', $d['ldap_display_name']);
586
-		}
587
-		$filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
588
-		if(!$filter) {
589
-			throw new \Exception('Cannot create filter');
590
-		}
591
-
592
-		$this->applyFind('ldap_userlist_filter', $filter);
593
-		return $this->result;
594
-	}
595
-
596
-	/**
597
-	 * @return bool|WizardResult
598
-	 * @throws \Exception
599
-	 */
600
-	public function getUserLoginFilter() {
601
-		if(!$this->checkRequirements(array('ldapHost',
602
-										   'ldapPort',
603
-										   'ldapBase',
604
-										   'ldapUserFilter',
605
-										   ))) {
606
-			return false;
607
-		}
608
-
609
-		$filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
610
-		if(!$filter) {
611
-			throw new \Exception('Cannot create filter');
612
-		}
613
-
614
-		$this->applyFind('ldap_login_filter', $filter);
615
-		return $this->result;
616
-	}
617
-
618
-	/**
619
-	 * @return bool|WizardResult
620
-	 * @param string $loginName
621
-	 * @throws \Exception
622
-	 */
623
-	public function testLoginName($loginName) {
624
-		if(!$this->checkRequirements(array('ldapHost',
625
-			'ldapPort',
626
-			'ldapBase',
627
-			'ldapLoginFilter',
628
-		))) {
629
-			return false;
630
-		}
631
-
632
-		$cr = $this->access->connection->getConnectionResource();
633
-		if(!$this->ldap->isResource($cr)) {
634
-			throw new \Exception('connection error');
635
-		}
636
-
637
-		if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
638
-			=== false) {
639
-			throw new \Exception('missing placeholder');
640
-		}
641
-
642
-		$users = $this->access->countUsersByLoginName($loginName);
643
-		if($this->ldap->errno($cr) !== 0) {
644
-			throw new \Exception($this->ldap->error($cr));
645
-		}
646
-		$filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
647
-		$this->result->addChange('ldap_test_loginname', $users);
648
-		$this->result->addChange('ldap_test_effective_filter', $filter);
649
-		return $this->result;
650
-	}
651
-
652
-	/**
653
-	 * Tries to determine the port, requires given Host, User DN and Password
654
-	 * @return WizardResult|false WizardResult on success, false otherwise
655
-	 * @throws \Exception
656
-	 */
657
-	public function guessPortAndTLS() {
658
-		if(!$this->checkRequirements(array('ldapHost',
659
-										   ))) {
660
-			return false;
661
-		}
662
-		$this->checkHost();
663
-		$portSettings = $this->getPortSettingsToTry();
664
-
665
-		if(!is_array($portSettings)) {
666
-			throw new \Exception(print_r($portSettings, true));
667
-		}
668
-
669
-		//proceed from the best configuration and return on first success
670
-		foreach($portSettings as $setting) {
671
-			$p = $setting['port'];
672
-			$t = $setting['tls'];
673
-			\OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, \OCP\Util::DEBUG);
674
-			//connectAndBind may throw Exception, it needs to be catched by the
675
-			//callee of this method
676
-
677
-			try {
678
-				$settingsFound = $this->connectAndBind($p, $t);
679
-			} catch (\Exception $e) {
680
-				// any reply other than -1 (= cannot connect) is already okay,
681
-				// because then we found the server
682
-				// unavailable startTLS returns -11
683
-				if($e->getCode() > 0) {
684
-					$settingsFound = true;
685
-				} else {
686
-					throw $e;
687
-				}
688
-			}
689
-
690
-			if ($settingsFound === true) {
691
-				$config = array(
692
-					'ldapPort' => $p,
693
-					'ldapTLS' => (int)$t
694
-				);
695
-				$this->configuration->setConfiguration($config);
696
-				\OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, \OCP\Util::DEBUG);
697
-				$this->result->addChange('ldap_port', $p);
698
-				return $this->result;
699
-			}
700
-		}
701
-
702
-		//custom port, undetected (we do not brute force)
703
-		return false;
704
-	}
705
-
706
-	/**
707
-	 * tries to determine a base dn from User DN or LDAP Host
708
-	 * @return WizardResult|false WizardResult on success, false otherwise
709
-	 */
710
-	public function guessBaseDN() {
711
-		if(!$this->checkRequirements(array('ldapHost',
712
-										   'ldapPort',
713
-										   ))) {
714
-			return false;
715
-		}
716
-
717
-		//check whether a DN is given in the agent name (99.9% of all cases)
718
-		$base = null;
719
-		$i = stripos($this->configuration->ldapAgentName, 'dc=');
720
-		if($i !== false) {
721
-			$base = substr($this->configuration->ldapAgentName, $i);
722
-			if($this->testBaseDN($base)) {
723
-				$this->applyFind('ldap_base', $base);
724
-				return $this->result;
725
-			}
726
-		}
727
-
728
-		//this did not help :(
729
-		//Let's see whether we can parse the Host URL and convert the domain to
730
-		//a base DN
731
-		$helper = new Helper(\OC::$server->getConfig());
732
-		$domain = $helper->getDomainFromURL($this->configuration->ldapHost);
733
-		if(!$domain) {
734
-			return false;
735
-		}
736
-
737
-		$dparts = explode('.', $domain);
738
-		while(count($dparts) > 0) {
739
-			$base2 = 'dc=' . implode(',dc=', $dparts);
740
-			if ($base !== $base2 && $this->testBaseDN($base2)) {
741
-				$this->applyFind('ldap_base', $base2);
742
-				return $this->result;
743
-			}
744
-			array_shift($dparts);
745
-		}
746
-
747
-		return false;
748
-	}
749
-
750
-	/**
751
-	 * sets the found value for the configuration key in the WizardResult
752
-	 * as well as in the Configuration instance
753
-	 * @param string $key the configuration key
754
-	 * @param string $value the (detected) value
755
-	 *
756
-	 */
757
-	private function applyFind($key, $value) {
758
-		$this->result->addChange($key, $value);
759
-		$this->configuration->setConfiguration(array($key => $value));
760
-	}
761
-
762
-	/**
763
-	 * Checks, whether a port was entered in the Host configuration
764
-	 * field. In this case the port will be stripped off, but also stored as
765
-	 * setting.
766
-	 */
767
-	private function checkHost() {
768
-		$host = $this->configuration->ldapHost;
769
-		$hostInfo = parse_url($host);
770
-
771
-		//removes Port from Host
772
-		if(is_array($hostInfo) && isset($hostInfo['port'])) {
773
-			$port = $hostInfo['port'];
774
-			$host = str_replace(':'.$port, '', $host);
775
-			$this->applyFind('ldap_host', $host);
776
-			$this->applyFind('ldap_port', $port);
777
-		}
778
-	}
779
-
780
-	/**
781
-	 * tries to detect the group member association attribute which is
782
-	 * one of 'uniqueMember', 'memberUid', 'member', 'gidNumber'
783
-	 * @return string|false, string with the attribute name, false on error
784
-	 * @throws \Exception
785
-	 */
786
-	private function detectGroupMemberAssoc() {
787
-		$possibleAttrs = array('uniqueMember', 'memberUid', 'member', 'gidNumber');
788
-		$filter = $this->configuration->ldapGroupFilter;
789
-		if(empty($filter)) {
790
-			return false;
791
-		}
792
-		$cr = $this->getConnection();
793
-		if(!$cr) {
794
-			throw new \Exception('Could not connect to LDAP');
795
-		}
796
-		$base = $this->configuration->ldapBase[0];
797
-		$rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
798
-		if(!$this->ldap->isResource($rr)) {
799
-			return false;
800
-		}
801
-		$er = $this->ldap->firstEntry($cr, $rr);
802
-		while(is_resource($er)) {
803
-			$this->ldap->getDN($cr, $er);
804
-			$attrs = $this->ldap->getAttributes($cr, $er);
805
-			$result = array();
806
-			$possibleAttrsCount = count($possibleAttrs);
807
-			for($i = 0; $i < $possibleAttrsCount; $i++) {
808
-				if(isset($attrs[$possibleAttrs[$i]])) {
809
-					$result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
810
-				}
811
-			}
812
-			if(!empty($result)) {
813
-				natsort($result);
814
-				return key($result);
815
-			}
816
-
817
-			$er = $this->ldap->nextEntry($cr, $er);
818
-		}
819
-
820
-		return false;
821
-	}
822
-
823
-	/**
824
-	 * Checks whether for a given BaseDN results will be returned
825
-	 * @param string $base the BaseDN to test
826
-	 * @return bool true on success, false otherwise
827
-	 * @throws \Exception
828
-	 */
829
-	private function testBaseDN($base) {
830
-		$cr = $this->getConnection();
831
-		if(!$cr) {
832
-			throw new \Exception('Could not connect to LDAP');
833
-		}
834
-
835
-		//base is there, let's validate it. If we search for anything, we should
836
-		//get a result set > 0 on a proper base
837
-		$rr = $this->ldap->search($cr, $base, 'objectClass=*', array('dn'), 0, 1);
838
-		if(!$this->ldap->isResource($rr)) {
839
-			$errorNo  = $this->ldap->errno($cr);
840
-			$errorMsg = $this->ldap->error($cr);
841
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base.
842
-							' Error '.$errorNo.': '.$errorMsg, \OCP\Util::INFO);
843
-			return false;
844
-		}
845
-		$entries = $this->ldap->countEntries($cr, $rr);
846
-		return ($entries !== false) && ($entries > 0);
847
-	}
848
-
849
-	/**
850
-	 * Checks whether the server supports memberOf in LDAP Filter.
851
-	 * Note: at least in OpenLDAP, availability of memberOf is dependent on
852
-	 * a configured objectClass. I.e. not necessarily for all available groups
853
-	 * memberOf does work.
854
-	 *
855
-	 * @return bool true if it does, false otherwise
856
-	 * @throws \Exception
857
-	 */
858
-	private function testMemberOf() {
859
-		$cr = $this->getConnection();
860
-		if(!$cr) {
861
-			throw new \Exception('Could not connect to LDAP');
862
-		}
863
-		$result = $this->access->countUsers('memberOf=*', array('memberOf'), 1);
864
-		if(is_int($result) &&  $result > 0) {
865
-			return true;
866
-		}
867
-		return false;
868
-	}
869
-
870
-	/**
871
-	 * creates an LDAP Filter from given configuration
872
-	 * @param integer $filterType int, for which use case the filter shall be created
873
-	 * can be any of self::LFILTER_USER_LIST, self::LFILTER_LOGIN or
874
-	 * self::LFILTER_GROUP_LIST
875
-	 * @return string|false string with the filter on success, false otherwise
876
-	 * @throws \Exception
877
-	 */
878
-	private function composeLdapFilter($filterType) {
879
-		$filter = '';
880
-		$parts = 0;
881
-		switch ($filterType) {
882
-			case self::LFILTER_USER_LIST:
883
-				$objcs = $this->configuration->ldapUserFilterObjectclass;
884
-				//glue objectclasses
885
-				if(is_array($objcs) && count($objcs) > 0) {
886
-					$filter .= '(|';
887
-					foreach($objcs as $objc) {
888
-						$filter .= '(objectclass=' . $objc . ')';
889
-					}
890
-					$filter .= ')';
891
-					$parts++;
892
-				}
893
-				//glue group memberships
894
-				if($this->configuration->hasMemberOfFilterSupport) {
895
-					$cns = $this->configuration->ldapUserFilterGroups;
896
-					if(is_array($cns) && count($cns) > 0) {
897
-						$filter .= '(|';
898
-						$cr = $this->getConnection();
899
-						if(!$cr) {
900
-							throw new \Exception('Could not connect to LDAP');
901
-						}
902
-						$base = $this->configuration->ldapBase[0];
903
-						foreach($cns as $cn) {
904
-							$rr = $this->ldap->search($cr, $base, 'cn=' . $cn, array('dn', 'primaryGroupToken'));
905
-							if(!$this->ldap->isResource($rr)) {
906
-								continue;
907
-							}
908
-							$er = $this->ldap->firstEntry($cr, $rr);
909
-							$attrs = $this->ldap->getAttributes($cr, $er);
910
-							$dn = $this->ldap->getDN($cr, $er);
911
-							if ($dn === false || $dn === '') {
912
-								continue;
913
-							}
914
-							$filterPart = '(memberof=' . $dn . ')';
915
-							if(isset($attrs['primaryGroupToken'])) {
916
-								$pgt = $attrs['primaryGroupToken'][0];
917
-								$primaryFilterPart = '(primaryGroupID=' . $pgt .')';
918
-								$filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
919
-							}
920
-							$filter .= $filterPart;
921
-						}
922
-						$filter .= ')';
923
-					}
924
-					$parts++;
925
-				}
926
-				//wrap parts in AND condition
927
-				if($parts > 1) {
928
-					$filter = '(&' . $filter . ')';
929
-				}
930
-				if ($filter === '') {
931
-					$filter = '(objectclass=*)';
932
-				}
933
-				break;
934
-
935
-			case self::LFILTER_GROUP_LIST:
936
-				$objcs = $this->configuration->ldapGroupFilterObjectclass;
937
-				//glue objectclasses
938
-				if(is_array($objcs) && count($objcs) > 0) {
939
-					$filter .= '(|';
940
-					foreach($objcs as $objc) {
941
-						$filter .= '(objectclass=' . $objc . ')';
942
-					}
943
-					$filter .= ')';
944
-					$parts++;
945
-				}
946
-				//glue group memberships
947
-				$cns = $this->configuration->ldapGroupFilterGroups;
948
-				if(is_array($cns) && count($cns) > 0) {
949
-					$filter .= '(|';
950
-					foreach($cns as $cn) {
951
-						$filter .= '(cn=' . $cn . ')';
952
-					}
953
-					$filter .= ')';
954
-				}
955
-				$parts++;
956
-				//wrap parts in AND condition
957
-				if($parts > 1) {
958
-					$filter = '(&' . $filter . ')';
959
-				}
960
-				break;
961
-
962
-			case self::LFILTER_LOGIN:
963
-				$ulf = $this->configuration->ldapUserFilter;
964
-				$loginpart = '=%uid';
965
-				$filterUsername = '';
966
-				$userAttributes = $this->getUserAttributes();
967
-				$userAttributes = array_change_key_case(array_flip($userAttributes));
968
-				$parts = 0;
969
-
970
-				if($this->configuration->ldapLoginFilterUsername === '1') {
971
-					$attr = '';
972
-					if(isset($userAttributes['uid'])) {
973
-						$attr = 'uid';
974
-					} else if(isset($userAttributes['samaccountname'])) {
975
-						$attr = 'samaccountname';
976
-					} else if(isset($userAttributes['cn'])) {
977
-						//fallback
978
-						$attr = 'cn';
979
-					}
980
-					if ($attr !== '') {
981
-						$filterUsername = '(' . $attr . $loginpart . ')';
982
-						$parts++;
983
-					}
984
-				}
985
-
986
-				$filterEmail = '';
987
-				if($this->configuration->ldapLoginFilterEmail === '1') {
988
-					$filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
989
-					$parts++;
990
-				}
991
-
992
-				$filterAttributes = '';
993
-				$attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
994
-				if(is_array($attrsToFilter) && count($attrsToFilter) > 0) {
995
-					$filterAttributes = '(|';
996
-					foreach($attrsToFilter as $attribute) {
997
-						$filterAttributes .= '(' . $attribute . $loginpart . ')';
998
-					}
999
-					$filterAttributes .= ')';
1000
-					$parts++;
1001
-				}
1002
-
1003
-				$filterLogin = '';
1004
-				if($parts > 1) {
1005
-					$filterLogin = '(|';
1006
-				}
1007
-				$filterLogin .= $filterUsername;
1008
-				$filterLogin .= $filterEmail;
1009
-				$filterLogin .= $filterAttributes;
1010
-				if($parts > 1) {
1011
-					$filterLogin .= ')';
1012
-				}
1013
-
1014
-				$filter = '(&'.$ulf.$filterLogin.')';
1015
-				break;
1016
-		}
1017
-
1018
-		\OCP\Util::writeLog('user_ldap', 'Wiz: Final filter '.$filter, \OCP\Util::DEBUG);
1019
-
1020
-		return $filter;
1021
-	}
1022
-
1023
-	/**
1024
-	 * Connects and Binds to an LDAP Server
1025
-	 *
1026
-	 * @param int $port the port to connect with
1027
-	 * @param bool $tls whether startTLS is to be used
1028
-	 * @return bool
1029
-	 * @throws \Exception
1030
-	 */
1031
-	private function connectAndBind($port, $tls) {
1032
-		//connect, does not really trigger any server communication
1033
-		$host = $this->configuration->ldapHost;
1034
-		$hostInfo = parse_url($host);
1035
-		if(!$hostInfo) {
1036
-			throw new \Exception(self::$l->t('Invalid Host'));
1037
-		}
1038
-		\OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', \OCP\Util::DEBUG);
1039
-		$cr = $this->ldap->connect($host, $port);
1040
-		if(!is_resource($cr)) {
1041
-			throw new \Exception(self::$l->t('Invalid Host'));
1042
-		}
1043
-
1044
-		//set LDAP options
1045
-		$this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1046
-		$this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1047
-		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1048
-
1049
-		try {
1050
-			if($tls) {
1051
-				$isTlsWorking = @$this->ldap->startTls($cr);
1052
-				if(!$isTlsWorking) {
1053
-					return false;
1054
-				}
1055
-			}
1056
-
1057
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Attemping to Bind ', \OCP\Util::DEBUG);
1058
-			//interesting part: do the bind!
1059
-			$login = $this->ldap->bind($cr,
1060
-				$this->configuration->ldapAgentName,
1061
-				$this->configuration->ldapAgentPassword
1062
-			);
1063
-			$errNo = $this->ldap->errno($cr);
1064
-			$error = ldap_error($cr);
1065
-			$this->ldap->unbind($cr);
1066
-		} catch(ServerNotAvailableException $e) {
1067
-			return false;
1068
-		}
1069
-
1070
-		if($login === true) {
1071
-			$this->ldap->unbind($cr);
1072
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . (int)$tls, \OCP\Util::DEBUG);
1073
-			return true;
1074
-		}
1075
-
1076
-		if($errNo === -1) {
1077
-			//host, port or TLS wrong
1078
-			return false;
1079
-		}
1080
-		throw new \Exception($error, $errNo);
1081
-	}
1082
-
1083
-	/**
1084
-	 * checks whether a valid combination of agent and password has been
1085
-	 * provided (either two values or nothing for anonymous connect)
1086
-	 * @return bool, true if everything is fine, false otherwise
1087
-	 */
1088
-	private function checkAgentRequirements() {
1089
-		$agent = $this->configuration->ldapAgentName;
1090
-		$pwd = $this->configuration->ldapAgentPassword;
1091
-
1092
-		return
1093
-			($agent !== '' && $pwd !== '')
1094
-			||  ($agent === '' && $pwd === '')
1095
-		;
1096
-	}
1097
-
1098
-	/**
1099
-	 * @param array $reqs
1100
-	 * @return bool
1101
-	 */
1102
-	private function checkRequirements($reqs) {
1103
-		$this->checkAgentRequirements();
1104
-		foreach($reqs as $option) {
1105
-			$value = $this->configuration->$option;
1106
-			if(empty($value)) {
1107
-				return false;
1108
-			}
1109
-		}
1110
-		return true;
1111
-	}
1112
-
1113
-	/**
1114
-	 * does a cumulativeSearch on LDAP to get different values of a
1115
-	 * specified attribute
1116
-	 * @param string[] $filters array, the filters that shall be used in the search
1117
-	 * @param string $attr the attribute of which a list of values shall be returned
1118
-	 * @param int $dnReadLimit the amount of how many DNs should be analyzed.
1119
-	 * The lower, the faster
1120
-	 * @param string $maxF string. if not null, this variable will have the filter that
1121
-	 * yields most result entries
1122
-	 * @return array|false an array with the values on success, false otherwise
1123
-	 */
1124
-	public function cumulativeSearchOnAttribute($filters, $attr, $dnReadLimit = 3, &$maxF = null) {
1125
-		$dnRead = array();
1126
-		$foundItems = array();
1127
-		$maxEntries = 0;
1128
-		if(!is_array($this->configuration->ldapBase)
1129
-		   || !isset($this->configuration->ldapBase[0])) {
1130
-			return false;
1131
-		}
1132
-		$base = $this->configuration->ldapBase[0];
1133
-		$cr = $this->getConnection();
1134
-		if(!$this->ldap->isResource($cr)) {
1135
-			return false;
1136
-		}
1137
-		$lastFilter = null;
1138
-		if(isset($filters[count($filters)-1])) {
1139
-			$lastFilter = $filters[count($filters)-1];
1140
-		}
1141
-		foreach($filters as $filter) {
1142
-			if($lastFilter === $filter && count($foundItems) > 0) {
1143
-				//skip when the filter is a wildcard and results were found
1144
-				continue;
1145
-			}
1146
-			// 20k limit for performance and reason
1147
-			$rr = $this->ldap->search($cr, $base, $filter, array($attr), 0, 20000);
1148
-			if(!$this->ldap->isResource($rr)) {
1149
-				continue;
1150
-			}
1151
-			$entries = $this->ldap->countEntries($cr, $rr);
1152
-			$getEntryFunc = 'firstEntry';
1153
-			if(($entries !== false) && ($entries > 0)) {
1154
-				if(!is_null($maxF) && $entries > $maxEntries) {
1155
-					$maxEntries = $entries;
1156
-					$maxF = $filter;
1157
-				}
1158
-				$dnReadCount = 0;
1159
-				do {
1160
-					$entry = $this->ldap->$getEntryFunc($cr, $rr);
1161
-					$getEntryFunc = 'nextEntry';
1162
-					if(!$this->ldap->isResource($entry)) {
1163
-						continue 2;
1164
-					}
1165
-					$rr = $entry; //will be expected by nextEntry next round
1166
-					$attributes = $this->ldap->getAttributes($cr, $entry);
1167
-					$dn = $this->ldap->getDN($cr, $entry);
1168
-					if($dn === false || in_array($dn, $dnRead)) {
1169
-						continue;
1170
-					}
1171
-					$newItems = array();
1172
-					$state = $this->getAttributeValuesFromEntry($attributes,
1173
-																$attr,
1174
-																$newItems);
1175
-					$dnReadCount++;
1176
-					$foundItems = array_merge($foundItems, $newItems);
1177
-					$this->resultCache[$dn][$attr] = $newItems;
1178
-					$dnRead[] = $dn;
1179
-				} while(($state === self::LRESULT_PROCESSED_SKIP
1180
-						|| $this->ldap->isResource($entry))
1181
-						&& ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit));
1182
-			}
1183
-		}
1184
-
1185
-		return array_unique($foundItems);
1186
-	}
1187
-
1188
-	/**
1189
-	 * determines if and which $attr are available on the LDAP server
1190
-	 * @param string[] $objectclasses the objectclasses to use as search filter
1191
-	 * @param string $attr the attribute to look for
1192
-	 * @param string $dbkey the dbkey of the setting the feature is connected to
1193
-	 * @param string $confkey the confkey counterpart for the $dbkey as used in the
1194
-	 * Configuration class
1195
-	 * @param bool $po whether the objectClass with most result entries
1196
-	 * shall be pre-selected via the result
1197
-	 * @return array|false list of found items.
1198
-	 * @throws \Exception
1199
-	 */
1200
-	private function determineFeature($objectclasses, $attr, $dbkey, $confkey, $po = false) {
1201
-		$cr = $this->getConnection();
1202
-		if(!$cr) {
1203
-			throw new \Exception('Could not connect to LDAP');
1204
-		}
1205
-		$p = 'objectclass=';
1206
-		foreach($objectclasses as $key => $value) {
1207
-			$objectclasses[$key] = $p.$value;
1208
-		}
1209
-		$maxEntryObjC = '';
1210
-
1211
-		//how deep to dig?
1212
-		//When looking for objectclasses, testing few entries is sufficient,
1213
-		$dig = 3;
1214
-
1215
-		$availableFeatures =
1216
-			$this->cumulativeSearchOnAttribute($objectclasses, $attr,
1217
-											   $dig, $maxEntryObjC);
1218
-		if(is_array($availableFeatures)
1219
-		   && count($availableFeatures) > 0) {
1220
-			natcasesort($availableFeatures);
1221
-			//natcasesort keeps indices, but we must get rid of them for proper
1222
-			//sorting in the web UI. Therefore: array_values
1223
-			$this->result->addOptions($dbkey, array_values($availableFeatures));
1224
-		} else {
1225
-			throw new \Exception(self::$l->t('Could not find the desired feature'));
1226
-		}
1227
-
1228
-		$setFeatures = $this->configuration->$confkey;
1229
-		if(is_array($setFeatures) && !empty($setFeatures)) {
1230
-			//something is already configured? pre-select it.
1231
-			$this->result->addChange($dbkey, $setFeatures);
1232
-		} else if ($po && $maxEntryObjC !== '') {
1233
-			//pre-select objectclass with most result entries
1234
-			$maxEntryObjC = str_replace($p, '', $maxEntryObjC);
1235
-			$this->applyFind($dbkey, $maxEntryObjC);
1236
-			$this->result->addChange($dbkey, $maxEntryObjC);
1237
-		}
1238
-
1239
-		return $availableFeatures;
1240
-	}
1241
-
1242
-	/**
1243
-	 * appends a list of values fr
1244
-	 * @param resource $result the return value from ldap_get_attributes
1245
-	 * @param string $attribute the attribute values to look for
1246
-	 * @param array &$known new values will be appended here
1247
-	 * @return int, state on of the class constants LRESULT_PROCESSED_OK,
1248
-	 * LRESULT_PROCESSED_INVALID or LRESULT_PROCESSED_SKIP
1249
-	 */
1250
-	private function getAttributeValuesFromEntry($result, $attribute, &$known) {
1251
-		if(!is_array($result)
1252
-		   || !isset($result['count'])
1253
-		   || !$result['count'] > 0) {
1254
-			return self::LRESULT_PROCESSED_INVALID;
1255
-		}
1256
-
1257
-		// strtolower on all keys for proper comparison
1258
-		$result = \OCP\Util::mb_array_change_key_case($result);
1259
-		$attribute = strtolower($attribute);
1260
-		if(isset($result[$attribute])) {
1261
-			foreach($result[$attribute] as $key => $val) {
1262
-				if($key === 'count') {
1263
-					continue;
1264
-				}
1265
-				if(!in_array($val, $known)) {
1266
-					$known[] = $val;
1267
-				}
1268
-			}
1269
-			return self::LRESULT_PROCESSED_OK;
1270
-		} else {
1271
-			return self::LRESULT_PROCESSED_SKIP;
1272
-		}
1273
-	}
1274
-
1275
-	/**
1276
-	 * @return bool|mixed
1277
-	 */
1278
-	private function getConnection() {
1279
-		if(!is_null($this->cr)) {
1280
-			return $this->cr;
1281
-		}
1282
-
1283
-		$cr = $this->ldap->connect(
1284
-			$this->configuration->ldapHost,
1285
-			$this->configuration->ldapPort
1286
-		);
1287
-
1288
-		$this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1289
-		$this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1290
-		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1291
-		if($this->configuration->ldapTLS === 1) {
1292
-			$this->ldap->startTls($cr);
1293
-		}
1294
-
1295
-		$lo = @$this->ldap->bind($cr,
1296
-								 $this->configuration->ldapAgentName,
1297
-								 $this->configuration->ldapAgentPassword);
1298
-		if($lo === true) {
1299
-			$this->$cr = $cr;
1300
-			return $cr;
1301
-		}
1302
-
1303
-		return false;
1304
-	}
1305
-
1306
-	/**
1307
-	 * @return array
1308
-	 */
1309
-	private function getDefaultLdapPortSettings() {
1310
-		static $settings = array(
1311
-								array('port' => 7636, 'tls' => false),
1312
-								array('port' =>  636, 'tls' => false),
1313
-								array('port' => 7389, 'tls' => true),
1314
-								array('port' =>  389, 'tls' => true),
1315
-								array('port' => 7389, 'tls' => false),
1316
-								array('port' =>  389, 'tls' => false),
1317
-						  );
1318
-		return $settings;
1319
-	}
1320
-
1321
-	/**
1322
-	 * @return array
1323
-	 */
1324
-	private function getPortSettingsToTry() {
1325
-		//389 ← LDAP / Unencrypted or StartTLS
1326
-		//636 ← LDAPS / SSL
1327
-		//7xxx ← UCS. need to be checked first, because both ports may be open
1328
-		$host = $this->configuration->ldapHost;
1329
-		$port = (int)$this->configuration->ldapPort;
1330
-		$portSettings = array();
1331
-
1332
-		//In case the port is already provided, we will check this first
1333
-		if($port > 0) {
1334
-			$hostInfo = parse_url($host);
1335
-			if(!(is_array($hostInfo)
1336
-				&& isset($hostInfo['scheme'])
1337
-				&& stripos($hostInfo['scheme'], 'ldaps') !== false)) {
1338
-				$portSettings[] = array('port' => $port, 'tls' => true);
1339
-			}
1340
-			$portSettings[] =array('port' => $port, 'tls' => false);
1341
-		}
1342
-
1343
-		//default ports
1344
-		$portSettings = array_merge($portSettings,
1345
-		                            $this->getDefaultLdapPortSettings());
1346
-
1347
-		return $portSettings;
1348
-	}
44
+    /** @var \OCP\IL10N */
45
+    static protected $l;
46
+    protected $access;
47
+    protected $cr;
48
+    protected $configuration;
49
+    protected $result;
50
+    protected $resultCache = array();
51
+
52
+    const LRESULT_PROCESSED_OK = 2;
53
+    const LRESULT_PROCESSED_INVALID = 3;
54
+    const LRESULT_PROCESSED_SKIP = 4;
55
+
56
+    const LFILTER_LOGIN      = 2;
57
+    const LFILTER_USER_LIST  = 3;
58
+    const LFILTER_GROUP_LIST = 4;
59
+
60
+    const LFILTER_MODE_ASSISTED = 2;
61
+    const LFILTER_MODE_RAW = 1;
62
+
63
+    const LDAP_NW_TIMEOUT = 4;
64
+
65
+    /**
66
+     * Constructor
67
+     * @param Configuration $configuration an instance of Configuration
68
+     * @param ILDAPWrapper $ldap an instance of ILDAPWrapper
69
+     * @param Access $access
70
+     */
71
+    public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) {
72
+        parent::__construct($ldap);
73
+        $this->configuration = $configuration;
74
+        if(is_null(Wizard::$l)) {
75
+            Wizard::$l = \OC::$server->getL10N('user_ldap');
76
+        }
77
+        $this->access = $access;
78
+        $this->result = new WizardResult();
79
+    }
80
+
81
+    public function  __destruct() {
82
+        if($this->result->hasChanges()) {
83
+            $this->configuration->saveConfiguration();
84
+        }
85
+    }
86
+
87
+    /**
88
+     * counts entries in the LDAP directory
89
+     *
90
+     * @param string $filter the LDAP search filter
91
+     * @param string $type a string being either 'users' or 'groups';
92
+     * @return bool|int
93
+     * @throws \Exception
94
+     */
95
+    public function countEntries($filter, $type) {
96
+        $reqs = array('ldapHost', 'ldapPort', 'ldapBase');
97
+        if($type === 'users') {
98
+            $reqs[] = 'ldapUserFilter';
99
+        }
100
+        if(!$this->checkRequirements($reqs)) {
101
+            throw new \Exception('Requirements not met', 400);
102
+        }
103
+
104
+        $attr = array('dn'); // default
105
+        $limit = 1001;
106
+        if($type === 'groups') {
107
+            $result =  $this->access->countGroups($filter, $attr, $limit);
108
+        } else if($type === 'users') {
109
+            $result = $this->access->countUsers($filter, $attr, $limit);
110
+        } else if ($type === 'objects') {
111
+            $result = $this->access->countObjects($limit);
112
+        } else {
113
+            throw new \Exception('Internal error: Invalid object type', 500);
114
+        }
115
+
116
+        return $result;
117
+    }
118
+
119
+    /**
120
+     * formats the return value of a count operation to the string to be
121
+     * inserted.
122
+     *
123
+     * @param bool|int $count
124
+     * @return int|string
125
+     */
126
+    private function formatCountResult($count) {
127
+        $formatted = ($count !== false) ? $count : 0;
128
+        if($formatted > 1000) {
129
+            $formatted = '> 1000';
130
+        }
131
+        return $formatted;
132
+    }
133
+
134
+    public function countGroups() {
135
+        $filter = $this->configuration->ldapGroupFilter;
136
+
137
+        if(empty($filter)) {
138
+            $output = self::$l->n('%s group found', '%s groups found', 0, array(0));
139
+            $this->result->addChange('ldap_group_count', $output);
140
+            return $this->result;
141
+        }
142
+
143
+        try {
144
+            $groupsTotal = $this->formatCountResult($this->countEntries($filter, 'groups'));
145
+        } catch (\Exception $e) {
146
+            //400 can be ignored, 500 is forwarded
147
+            if($e->getCode() === 500) {
148
+                throw $e;
149
+            }
150
+            return false;
151
+        }
152
+        $output = self::$l->n('%s group found', '%s groups found', $groupsTotal, array($groupsTotal));
153
+        $this->result->addChange('ldap_group_count', $output);
154
+        return $this->result;
155
+    }
156
+
157
+    /**
158
+     * @return WizardResult
159
+     * @throws \Exception
160
+     */
161
+    public function countUsers() {
162
+        $filter = $this->access->getFilterForUserCount();
163
+
164
+        $usersTotal = $this->formatCountResult($this->countEntries($filter, 'users'));
165
+        $output = self::$l->n('%s user found', '%s users found', $usersTotal, array($usersTotal));
166
+        $this->result->addChange('ldap_user_count', $output);
167
+        return $this->result;
168
+    }
169
+
170
+    /**
171
+     * counts any objects in the currently set base dn
172
+     *
173
+     * @return WizardResult
174
+     * @throws \Exception
175
+     */
176
+    public function countInBaseDN() {
177
+        // we don't need to provide a filter in this case
178
+        $total = $this->countEntries(null, 'objects');
179
+        if($total === false) {
180
+            throw new \Exception('invalid results received');
181
+        }
182
+        $this->result->addChange('ldap_test_base', $total);
183
+        return $this->result;
184
+    }
185
+
186
+    /**
187
+     * counts users with a specified attribute
188
+     * @param string $attr
189
+     * @param bool $existsCheck
190
+     * @return int|bool
191
+     */
192
+    public function countUsersWithAttribute($attr, $existsCheck = false) {
193
+        if(!$this->checkRequirements(array('ldapHost',
194
+                                            'ldapPort',
195
+                                            'ldapBase',
196
+                                            'ldapUserFilter',
197
+                                            ))) {
198
+            return  false;
199
+        }
200
+
201
+        $filter = $this->access->combineFilterWithAnd(array(
202
+            $this->configuration->ldapUserFilter,
203
+            $attr . '=*'
204
+        ));
205
+
206
+        $limit = ($existsCheck === false) ? null : 1;
207
+
208
+        return $this->access->countUsers($filter, array('dn'), $limit);
209
+    }
210
+
211
+    /**
212
+     * detects the display name attribute. If a setting is already present that
213
+     * returns at least one hit, the detection will be canceled.
214
+     * @return WizardResult|bool
215
+     * @throws \Exception
216
+     */
217
+    public function detectUserDisplayNameAttribute() {
218
+        if(!$this->checkRequirements(array('ldapHost',
219
+                                        'ldapPort',
220
+                                        'ldapBase',
221
+                                        'ldapUserFilter',
222
+                                        ))) {
223
+            return  false;
224
+        }
225
+
226
+        $attr = $this->configuration->ldapUserDisplayName;
227
+        if ($attr !== '' && $attr !== 'displayName') {
228
+            // most likely not the default value with upper case N,
229
+            // verify it still produces a result
230
+            $count = (int)$this->countUsersWithAttribute($attr, true);
231
+            if($count > 0) {
232
+                //no change, but we sent it back to make sure the user interface
233
+                //is still correct, even if the ajax call was cancelled meanwhile
234
+                $this->result->addChange('ldap_display_name', $attr);
235
+                return $this->result;
236
+            }
237
+        }
238
+
239
+        // first attribute that has at least one result wins
240
+        $displayNameAttrs = array('displayname', 'cn');
241
+        foreach ($displayNameAttrs as $attr) {
242
+            $count = (int)$this->countUsersWithAttribute($attr, true);
243
+
244
+            if($count > 0) {
245
+                $this->applyFind('ldap_display_name', $attr);
246
+                return $this->result;
247
+            }
248
+        }
249
+
250
+        throw new \Exception(self::$l->t('Could not detect user display name attribute. Please specify it yourself in advanced LDAP settings.'));
251
+    }
252
+
253
+    /**
254
+     * detects the most often used email attribute for users applying to the
255
+     * user list filter. If a setting is already present that returns at least
256
+     * one hit, the detection will be canceled.
257
+     * @return WizardResult|bool
258
+     */
259
+    public function detectEmailAttribute() {
260
+        if(!$this->checkRequirements(array('ldapHost',
261
+                                            'ldapPort',
262
+                                            'ldapBase',
263
+                                            'ldapUserFilter',
264
+                                            ))) {
265
+            return  false;
266
+        }
267
+
268
+        $attr = $this->configuration->ldapEmailAttribute;
269
+        if ($attr !== '') {
270
+            $count = (int)$this->countUsersWithAttribute($attr, true);
271
+            if($count > 0) {
272
+                return false;
273
+            }
274
+            $writeLog = true;
275
+        } else {
276
+            $writeLog = false;
277
+        }
278
+
279
+        $emailAttributes = array('mail', 'mailPrimaryAddress');
280
+        $winner = '';
281
+        $maxUsers = 0;
282
+        foreach($emailAttributes as $attr) {
283
+            $count = $this->countUsersWithAttribute($attr);
284
+            if($count > $maxUsers) {
285
+                $maxUsers = $count;
286
+                $winner = $attr;
287
+            }
288
+        }
289
+
290
+        if($winner !== '') {
291
+            $this->applyFind('ldap_email_attr', $winner);
292
+            if($writeLog) {
293
+                \OCP\Util::writeLog('user_ldap', 'The mail attribute has ' .
294
+                    'automatically been reset, because the original value ' .
295
+                    'did not return any results.', \OCP\Util::INFO);
296
+            }
297
+        }
298
+
299
+        return $this->result;
300
+    }
301
+
302
+    /**
303
+     * @return WizardResult
304
+     * @throws \Exception
305
+     */
306
+    public function determineAttributes() {
307
+        if(!$this->checkRequirements(array('ldapHost',
308
+                                            'ldapPort',
309
+                                            'ldapBase',
310
+                                            'ldapUserFilter',
311
+                                            ))) {
312
+            return  false;
313
+        }
314
+
315
+        $attributes = $this->getUserAttributes();
316
+
317
+        natcasesort($attributes);
318
+        $attributes = array_values($attributes);
319
+
320
+        $this->result->addOptions('ldap_loginfilter_attributes', $attributes);
321
+
322
+        $selected = $this->configuration->ldapLoginFilterAttributes;
323
+        if(is_array($selected) && !empty($selected)) {
324
+            $this->result->addChange('ldap_loginfilter_attributes', $selected);
325
+        }
326
+
327
+        return $this->result;
328
+    }
329
+
330
+    /**
331
+     * detects the available LDAP attributes
332
+     * @return array|false The instance's WizardResult instance
333
+     * @throws \Exception
334
+     */
335
+    private function getUserAttributes() {
336
+        if(!$this->checkRequirements(array('ldapHost',
337
+                                            'ldapPort',
338
+                                            'ldapBase',
339
+                                            'ldapUserFilter',
340
+                                            ))) {
341
+            return  false;
342
+        }
343
+        $cr = $this->getConnection();
344
+        if(!$cr) {
345
+            throw new \Exception('Could not connect to LDAP');
346
+        }
347
+
348
+        $base = $this->configuration->ldapBase[0];
349
+        $filter = $this->configuration->ldapUserFilter;
350
+        $rr = $this->ldap->search($cr, $base, $filter, array(), 1, 1);
351
+        if(!$this->ldap->isResource($rr)) {
352
+            return false;
353
+        }
354
+        $er = $this->ldap->firstEntry($cr, $rr);
355
+        $attributes = $this->ldap->getAttributes($cr, $er);
356
+        $pureAttributes = array();
357
+        for($i = 0; $i < $attributes['count']; $i++) {
358
+            $pureAttributes[] = $attributes[$i];
359
+        }
360
+
361
+        return $pureAttributes;
362
+    }
363
+
364
+    /**
365
+     * detects the available LDAP groups
366
+     * @return WizardResult|false the instance's WizardResult instance
367
+     */
368
+    public function determineGroupsForGroups() {
369
+        return $this->determineGroups('ldap_groupfilter_groups',
370
+                                        'ldapGroupFilterGroups',
371
+                                        false);
372
+    }
373
+
374
+    /**
375
+     * detects the available LDAP groups
376
+     * @return WizardResult|false the instance's WizardResult instance
377
+     */
378
+    public function determineGroupsForUsers() {
379
+        return $this->determineGroups('ldap_userfilter_groups',
380
+                                        'ldapUserFilterGroups');
381
+    }
382
+
383
+    /**
384
+     * detects the available LDAP groups
385
+     * @param string $dbKey
386
+     * @param string $confKey
387
+     * @param bool $testMemberOf
388
+     * @return WizardResult|false the instance's WizardResult instance
389
+     * @throws \Exception
390
+     */
391
+    private function determineGroups($dbKey, $confKey, $testMemberOf = true) {
392
+        if(!$this->checkRequirements(array('ldapHost',
393
+                                            'ldapPort',
394
+                                            'ldapBase',
395
+                                            ))) {
396
+            return  false;
397
+        }
398
+        $cr = $this->getConnection();
399
+        if(!$cr) {
400
+            throw new \Exception('Could not connect to LDAP');
401
+        }
402
+
403
+        $this->fetchGroups($dbKey, $confKey);
404
+
405
+        if($testMemberOf) {
406
+            $this->configuration->hasMemberOfFilterSupport = $this->testMemberOf();
407
+            $this->result->markChange();
408
+            if(!$this->configuration->hasMemberOfFilterSupport) {
409
+                throw new \Exception('memberOf is not supported by the server');
410
+            }
411
+        }
412
+
413
+        return $this->result;
414
+    }
415
+
416
+    /**
417
+     * fetches all groups from LDAP and adds them to the result object
418
+     *
419
+     * @param string $dbKey
420
+     * @param string $confKey
421
+     * @return array $groupEntries
422
+     * @throws \Exception
423
+     */
424
+    public function fetchGroups($dbKey, $confKey) {
425
+        $obclasses = array('posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames', 'groupOfUniqueNames');
426
+
427
+        $filterParts = array();
428
+        foreach($obclasses as $obclass) {
429
+            $filterParts[] = 'objectclass='.$obclass;
430
+        }
431
+        //we filter for everything
432
+        //- that looks like a group and
433
+        //- has the group display name set
434
+        $filter = $this->access->combineFilterWithOr($filterParts);
435
+        $filter = $this->access->combineFilterWithAnd(array($filter, 'cn=*'));
436
+
437
+        $groupNames = array();
438
+        $groupEntries = array();
439
+        $limit = 400;
440
+        $offset = 0;
441
+        do {
442
+            // we need to request dn additionally here, otherwise memberOf
443
+            // detection will fail later
444
+            $result = $this->access->searchGroups($filter, array('cn', 'dn'), $limit, $offset);
445
+            foreach($result as $item) {
446
+                if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
447
+                    // just in case - no issue known
448
+                    continue;
449
+                }
450
+                $groupNames[] = $item['cn'][0];
451
+                $groupEntries[] = $item;
452
+            }
453
+            $offset += $limit;
454
+        } while ($this->access->hasMoreResults());
455
+
456
+        if(count($groupNames) > 0) {
457
+            natsort($groupNames);
458
+            $this->result->addOptions($dbKey, array_values($groupNames));
459
+        } else {
460
+            throw new \Exception(self::$l->t('Could not find the desired feature'));
461
+        }
462
+
463
+        $setFeatures = $this->configuration->$confKey;
464
+        if(is_array($setFeatures) && !empty($setFeatures)) {
465
+            //something is already configured? pre-select it.
466
+            $this->result->addChange($dbKey, $setFeatures);
467
+        }
468
+        return $groupEntries;
469
+    }
470
+
471
+    public function determineGroupMemberAssoc() {
472
+        if(!$this->checkRequirements(array('ldapHost',
473
+                                            'ldapPort',
474
+                                            'ldapGroupFilter',
475
+                                            ))) {
476
+            return  false;
477
+        }
478
+        $attribute = $this->detectGroupMemberAssoc();
479
+        if($attribute === false) {
480
+            return false;
481
+        }
482
+        $this->configuration->setConfiguration(array('ldapGroupMemberAssocAttr' => $attribute));
483
+        $this->result->addChange('ldap_group_member_assoc_attribute', $attribute);
484
+
485
+        return $this->result;
486
+    }
487
+
488
+    /**
489
+     * Detects the available object classes
490
+     * @return WizardResult|false the instance's WizardResult instance
491
+     * @throws \Exception
492
+     */
493
+    public function determineGroupObjectClasses() {
494
+        if(!$this->checkRequirements(array('ldapHost',
495
+                                            'ldapPort',
496
+                                            'ldapBase',
497
+                                            ))) {
498
+            return  false;
499
+        }
500
+        $cr = $this->getConnection();
501
+        if(!$cr) {
502
+            throw new \Exception('Could not connect to LDAP');
503
+        }
504
+
505
+        $obclasses = array('groupOfNames', 'groupOfUniqueNames', 'group', 'posixGroup', '*');
506
+        $this->determineFeature($obclasses,
507
+                                'objectclass',
508
+                                'ldap_groupfilter_objectclass',
509
+                                'ldapGroupFilterObjectclass',
510
+                                false);
511
+
512
+        return $this->result;
513
+    }
514
+
515
+    /**
516
+     * detects the available object classes
517
+     * @return WizardResult
518
+     * @throws \Exception
519
+     */
520
+    public function determineUserObjectClasses() {
521
+        if(!$this->checkRequirements(array('ldapHost',
522
+                                            'ldapPort',
523
+                                            'ldapBase',
524
+                                            ))) {
525
+            return  false;
526
+        }
527
+        $cr = $this->getConnection();
528
+        if(!$cr) {
529
+            throw new \Exception('Could not connect to LDAP');
530
+        }
531
+
532
+        $obclasses = array('inetOrgPerson', 'person', 'organizationalPerson',
533
+                            'user', 'posixAccount', '*');
534
+        $filter = $this->configuration->ldapUserFilter;
535
+        //if filter is empty, it is probably the first time the wizard is called
536
+        //then, apply suggestions.
537
+        $this->determineFeature($obclasses,
538
+                                'objectclass',
539
+                                'ldap_userfilter_objectclass',
540
+                                'ldapUserFilterObjectclass',
541
+                                empty($filter));
542
+
543
+        return $this->result;
544
+    }
545
+
546
+    /**
547
+     * @return WizardResult|false
548
+     * @throws \Exception
549
+     */
550
+    public function getGroupFilter() {
551
+        if(!$this->checkRequirements(array('ldapHost',
552
+                                            'ldapPort',
553
+                                            'ldapBase',
554
+                                            ))) {
555
+            return false;
556
+        }
557
+        //make sure the use display name is set
558
+        $displayName = $this->configuration->ldapGroupDisplayName;
559
+        if ($displayName === '') {
560
+            $d = $this->configuration->getDefaults();
561
+            $this->applyFind('ldap_group_display_name',
562
+                                $d['ldap_group_display_name']);
563
+        }
564
+        $filter = $this->composeLdapFilter(self::LFILTER_GROUP_LIST);
565
+
566
+        $this->applyFind('ldap_group_filter', $filter);
567
+        return $this->result;
568
+    }
569
+
570
+    /**
571
+     * @return WizardResult|false
572
+     * @throws \Exception
573
+     */
574
+    public function getUserListFilter() {
575
+        if(!$this->checkRequirements(array('ldapHost',
576
+                                            'ldapPort',
577
+                                            'ldapBase',
578
+                                            ))) {
579
+            return false;
580
+        }
581
+        //make sure the use display name is set
582
+        $displayName = $this->configuration->ldapUserDisplayName;
583
+        if ($displayName === '') {
584
+            $d = $this->configuration->getDefaults();
585
+            $this->applyFind('ldap_display_name', $d['ldap_display_name']);
586
+        }
587
+        $filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
588
+        if(!$filter) {
589
+            throw new \Exception('Cannot create filter');
590
+        }
591
+
592
+        $this->applyFind('ldap_userlist_filter', $filter);
593
+        return $this->result;
594
+    }
595
+
596
+    /**
597
+     * @return bool|WizardResult
598
+     * @throws \Exception
599
+     */
600
+    public function getUserLoginFilter() {
601
+        if(!$this->checkRequirements(array('ldapHost',
602
+                                            'ldapPort',
603
+                                            'ldapBase',
604
+                                            'ldapUserFilter',
605
+                                            ))) {
606
+            return false;
607
+        }
608
+
609
+        $filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
610
+        if(!$filter) {
611
+            throw new \Exception('Cannot create filter');
612
+        }
613
+
614
+        $this->applyFind('ldap_login_filter', $filter);
615
+        return $this->result;
616
+    }
617
+
618
+    /**
619
+     * @return bool|WizardResult
620
+     * @param string $loginName
621
+     * @throws \Exception
622
+     */
623
+    public function testLoginName($loginName) {
624
+        if(!$this->checkRequirements(array('ldapHost',
625
+            'ldapPort',
626
+            'ldapBase',
627
+            'ldapLoginFilter',
628
+        ))) {
629
+            return false;
630
+        }
631
+
632
+        $cr = $this->access->connection->getConnectionResource();
633
+        if(!$this->ldap->isResource($cr)) {
634
+            throw new \Exception('connection error');
635
+        }
636
+
637
+        if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
638
+            === false) {
639
+            throw new \Exception('missing placeholder');
640
+        }
641
+
642
+        $users = $this->access->countUsersByLoginName($loginName);
643
+        if($this->ldap->errno($cr) !== 0) {
644
+            throw new \Exception($this->ldap->error($cr));
645
+        }
646
+        $filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
647
+        $this->result->addChange('ldap_test_loginname', $users);
648
+        $this->result->addChange('ldap_test_effective_filter', $filter);
649
+        return $this->result;
650
+    }
651
+
652
+    /**
653
+     * Tries to determine the port, requires given Host, User DN and Password
654
+     * @return WizardResult|false WizardResult on success, false otherwise
655
+     * @throws \Exception
656
+     */
657
+    public function guessPortAndTLS() {
658
+        if(!$this->checkRequirements(array('ldapHost',
659
+                                            ))) {
660
+            return false;
661
+        }
662
+        $this->checkHost();
663
+        $portSettings = $this->getPortSettingsToTry();
664
+
665
+        if(!is_array($portSettings)) {
666
+            throw new \Exception(print_r($portSettings, true));
667
+        }
668
+
669
+        //proceed from the best configuration and return on first success
670
+        foreach($portSettings as $setting) {
671
+            $p = $setting['port'];
672
+            $t = $setting['tls'];
673
+            \OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, \OCP\Util::DEBUG);
674
+            //connectAndBind may throw Exception, it needs to be catched by the
675
+            //callee of this method
676
+
677
+            try {
678
+                $settingsFound = $this->connectAndBind($p, $t);
679
+            } catch (\Exception $e) {
680
+                // any reply other than -1 (= cannot connect) is already okay,
681
+                // because then we found the server
682
+                // unavailable startTLS returns -11
683
+                if($e->getCode() > 0) {
684
+                    $settingsFound = true;
685
+                } else {
686
+                    throw $e;
687
+                }
688
+            }
689
+
690
+            if ($settingsFound === true) {
691
+                $config = array(
692
+                    'ldapPort' => $p,
693
+                    'ldapTLS' => (int)$t
694
+                );
695
+                $this->configuration->setConfiguration($config);
696
+                \OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, \OCP\Util::DEBUG);
697
+                $this->result->addChange('ldap_port', $p);
698
+                return $this->result;
699
+            }
700
+        }
701
+
702
+        //custom port, undetected (we do not brute force)
703
+        return false;
704
+    }
705
+
706
+    /**
707
+     * tries to determine a base dn from User DN or LDAP Host
708
+     * @return WizardResult|false WizardResult on success, false otherwise
709
+     */
710
+    public function guessBaseDN() {
711
+        if(!$this->checkRequirements(array('ldapHost',
712
+                                            'ldapPort',
713
+                                            ))) {
714
+            return false;
715
+        }
716
+
717
+        //check whether a DN is given in the agent name (99.9% of all cases)
718
+        $base = null;
719
+        $i = stripos($this->configuration->ldapAgentName, 'dc=');
720
+        if($i !== false) {
721
+            $base = substr($this->configuration->ldapAgentName, $i);
722
+            if($this->testBaseDN($base)) {
723
+                $this->applyFind('ldap_base', $base);
724
+                return $this->result;
725
+            }
726
+        }
727
+
728
+        //this did not help :(
729
+        //Let's see whether we can parse the Host URL and convert the domain to
730
+        //a base DN
731
+        $helper = new Helper(\OC::$server->getConfig());
732
+        $domain = $helper->getDomainFromURL($this->configuration->ldapHost);
733
+        if(!$domain) {
734
+            return false;
735
+        }
736
+
737
+        $dparts = explode('.', $domain);
738
+        while(count($dparts) > 0) {
739
+            $base2 = 'dc=' . implode(',dc=', $dparts);
740
+            if ($base !== $base2 && $this->testBaseDN($base2)) {
741
+                $this->applyFind('ldap_base', $base2);
742
+                return $this->result;
743
+            }
744
+            array_shift($dparts);
745
+        }
746
+
747
+        return false;
748
+    }
749
+
750
+    /**
751
+     * sets the found value for the configuration key in the WizardResult
752
+     * as well as in the Configuration instance
753
+     * @param string $key the configuration key
754
+     * @param string $value the (detected) value
755
+     *
756
+     */
757
+    private function applyFind($key, $value) {
758
+        $this->result->addChange($key, $value);
759
+        $this->configuration->setConfiguration(array($key => $value));
760
+    }
761
+
762
+    /**
763
+     * Checks, whether a port was entered in the Host configuration
764
+     * field. In this case the port will be stripped off, but also stored as
765
+     * setting.
766
+     */
767
+    private function checkHost() {
768
+        $host = $this->configuration->ldapHost;
769
+        $hostInfo = parse_url($host);
770
+
771
+        //removes Port from Host
772
+        if(is_array($hostInfo) && isset($hostInfo['port'])) {
773
+            $port = $hostInfo['port'];
774
+            $host = str_replace(':'.$port, '', $host);
775
+            $this->applyFind('ldap_host', $host);
776
+            $this->applyFind('ldap_port', $port);
777
+        }
778
+    }
779
+
780
+    /**
781
+     * tries to detect the group member association attribute which is
782
+     * one of 'uniqueMember', 'memberUid', 'member', 'gidNumber'
783
+     * @return string|false, string with the attribute name, false on error
784
+     * @throws \Exception
785
+     */
786
+    private function detectGroupMemberAssoc() {
787
+        $possibleAttrs = array('uniqueMember', 'memberUid', 'member', 'gidNumber');
788
+        $filter = $this->configuration->ldapGroupFilter;
789
+        if(empty($filter)) {
790
+            return false;
791
+        }
792
+        $cr = $this->getConnection();
793
+        if(!$cr) {
794
+            throw new \Exception('Could not connect to LDAP');
795
+        }
796
+        $base = $this->configuration->ldapBase[0];
797
+        $rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
798
+        if(!$this->ldap->isResource($rr)) {
799
+            return false;
800
+        }
801
+        $er = $this->ldap->firstEntry($cr, $rr);
802
+        while(is_resource($er)) {
803
+            $this->ldap->getDN($cr, $er);
804
+            $attrs = $this->ldap->getAttributes($cr, $er);
805
+            $result = array();
806
+            $possibleAttrsCount = count($possibleAttrs);
807
+            for($i = 0; $i < $possibleAttrsCount; $i++) {
808
+                if(isset($attrs[$possibleAttrs[$i]])) {
809
+                    $result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
810
+                }
811
+            }
812
+            if(!empty($result)) {
813
+                natsort($result);
814
+                return key($result);
815
+            }
816
+
817
+            $er = $this->ldap->nextEntry($cr, $er);
818
+        }
819
+
820
+        return false;
821
+    }
822
+
823
+    /**
824
+     * Checks whether for a given BaseDN results will be returned
825
+     * @param string $base the BaseDN to test
826
+     * @return bool true on success, false otherwise
827
+     * @throws \Exception
828
+     */
829
+    private function testBaseDN($base) {
830
+        $cr = $this->getConnection();
831
+        if(!$cr) {
832
+            throw new \Exception('Could not connect to LDAP');
833
+        }
834
+
835
+        //base is there, let's validate it. If we search for anything, we should
836
+        //get a result set > 0 on a proper base
837
+        $rr = $this->ldap->search($cr, $base, 'objectClass=*', array('dn'), 0, 1);
838
+        if(!$this->ldap->isResource($rr)) {
839
+            $errorNo  = $this->ldap->errno($cr);
840
+            $errorMsg = $this->ldap->error($cr);
841
+            \OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base.
842
+                            ' Error '.$errorNo.': '.$errorMsg, \OCP\Util::INFO);
843
+            return false;
844
+        }
845
+        $entries = $this->ldap->countEntries($cr, $rr);
846
+        return ($entries !== false) && ($entries > 0);
847
+    }
848
+
849
+    /**
850
+     * Checks whether the server supports memberOf in LDAP Filter.
851
+     * Note: at least in OpenLDAP, availability of memberOf is dependent on
852
+     * a configured objectClass. I.e. not necessarily for all available groups
853
+     * memberOf does work.
854
+     *
855
+     * @return bool true if it does, false otherwise
856
+     * @throws \Exception
857
+     */
858
+    private function testMemberOf() {
859
+        $cr = $this->getConnection();
860
+        if(!$cr) {
861
+            throw new \Exception('Could not connect to LDAP');
862
+        }
863
+        $result = $this->access->countUsers('memberOf=*', array('memberOf'), 1);
864
+        if(is_int($result) &&  $result > 0) {
865
+            return true;
866
+        }
867
+        return false;
868
+    }
869
+
870
+    /**
871
+     * creates an LDAP Filter from given configuration
872
+     * @param integer $filterType int, for which use case the filter shall be created
873
+     * can be any of self::LFILTER_USER_LIST, self::LFILTER_LOGIN or
874
+     * self::LFILTER_GROUP_LIST
875
+     * @return string|false string with the filter on success, false otherwise
876
+     * @throws \Exception
877
+     */
878
+    private function composeLdapFilter($filterType) {
879
+        $filter = '';
880
+        $parts = 0;
881
+        switch ($filterType) {
882
+            case self::LFILTER_USER_LIST:
883
+                $objcs = $this->configuration->ldapUserFilterObjectclass;
884
+                //glue objectclasses
885
+                if(is_array($objcs) && count($objcs) > 0) {
886
+                    $filter .= '(|';
887
+                    foreach($objcs as $objc) {
888
+                        $filter .= '(objectclass=' . $objc . ')';
889
+                    }
890
+                    $filter .= ')';
891
+                    $parts++;
892
+                }
893
+                //glue group memberships
894
+                if($this->configuration->hasMemberOfFilterSupport) {
895
+                    $cns = $this->configuration->ldapUserFilterGroups;
896
+                    if(is_array($cns) && count($cns) > 0) {
897
+                        $filter .= '(|';
898
+                        $cr = $this->getConnection();
899
+                        if(!$cr) {
900
+                            throw new \Exception('Could not connect to LDAP');
901
+                        }
902
+                        $base = $this->configuration->ldapBase[0];
903
+                        foreach($cns as $cn) {
904
+                            $rr = $this->ldap->search($cr, $base, 'cn=' . $cn, array('dn', 'primaryGroupToken'));
905
+                            if(!$this->ldap->isResource($rr)) {
906
+                                continue;
907
+                            }
908
+                            $er = $this->ldap->firstEntry($cr, $rr);
909
+                            $attrs = $this->ldap->getAttributes($cr, $er);
910
+                            $dn = $this->ldap->getDN($cr, $er);
911
+                            if ($dn === false || $dn === '') {
912
+                                continue;
913
+                            }
914
+                            $filterPart = '(memberof=' . $dn . ')';
915
+                            if(isset($attrs['primaryGroupToken'])) {
916
+                                $pgt = $attrs['primaryGroupToken'][0];
917
+                                $primaryFilterPart = '(primaryGroupID=' . $pgt .')';
918
+                                $filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
919
+                            }
920
+                            $filter .= $filterPart;
921
+                        }
922
+                        $filter .= ')';
923
+                    }
924
+                    $parts++;
925
+                }
926
+                //wrap parts in AND condition
927
+                if($parts > 1) {
928
+                    $filter = '(&' . $filter . ')';
929
+                }
930
+                if ($filter === '') {
931
+                    $filter = '(objectclass=*)';
932
+                }
933
+                break;
934
+
935
+            case self::LFILTER_GROUP_LIST:
936
+                $objcs = $this->configuration->ldapGroupFilterObjectclass;
937
+                //glue objectclasses
938
+                if(is_array($objcs) && count($objcs) > 0) {
939
+                    $filter .= '(|';
940
+                    foreach($objcs as $objc) {
941
+                        $filter .= '(objectclass=' . $objc . ')';
942
+                    }
943
+                    $filter .= ')';
944
+                    $parts++;
945
+                }
946
+                //glue group memberships
947
+                $cns = $this->configuration->ldapGroupFilterGroups;
948
+                if(is_array($cns) && count($cns) > 0) {
949
+                    $filter .= '(|';
950
+                    foreach($cns as $cn) {
951
+                        $filter .= '(cn=' . $cn . ')';
952
+                    }
953
+                    $filter .= ')';
954
+                }
955
+                $parts++;
956
+                //wrap parts in AND condition
957
+                if($parts > 1) {
958
+                    $filter = '(&' . $filter . ')';
959
+                }
960
+                break;
961
+
962
+            case self::LFILTER_LOGIN:
963
+                $ulf = $this->configuration->ldapUserFilter;
964
+                $loginpart = '=%uid';
965
+                $filterUsername = '';
966
+                $userAttributes = $this->getUserAttributes();
967
+                $userAttributes = array_change_key_case(array_flip($userAttributes));
968
+                $parts = 0;
969
+
970
+                if($this->configuration->ldapLoginFilterUsername === '1') {
971
+                    $attr = '';
972
+                    if(isset($userAttributes['uid'])) {
973
+                        $attr = 'uid';
974
+                    } else if(isset($userAttributes['samaccountname'])) {
975
+                        $attr = 'samaccountname';
976
+                    } else if(isset($userAttributes['cn'])) {
977
+                        //fallback
978
+                        $attr = 'cn';
979
+                    }
980
+                    if ($attr !== '') {
981
+                        $filterUsername = '(' . $attr . $loginpart . ')';
982
+                        $parts++;
983
+                    }
984
+                }
985
+
986
+                $filterEmail = '';
987
+                if($this->configuration->ldapLoginFilterEmail === '1') {
988
+                    $filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
989
+                    $parts++;
990
+                }
991
+
992
+                $filterAttributes = '';
993
+                $attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
994
+                if(is_array($attrsToFilter) && count($attrsToFilter) > 0) {
995
+                    $filterAttributes = '(|';
996
+                    foreach($attrsToFilter as $attribute) {
997
+                        $filterAttributes .= '(' . $attribute . $loginpart . ')';
998
+                    }
999
+                    $filterAttributes .= ')';
1000
+                    $parts++;
1001
+                }
1002
+
1003
+                $filterLogin = '';
1004
+                if($parts > 1) {
1005
+                    $filterLogin = '(|';
1006
+                }
1007
+                $filterLogin .= $filterUsername;
1008
+                $filterLogin .= $filterEmail;
1009
+                $filterLogin .= $filterAttributes;
1010
+                if($parts > 1) {
1011
+                    $filterLogin .= ')';
1012
+                }
1013
+
1014
+                $filter = '(&'.$ulf.$filterLogin.')';
1015
+                break;
1016
+        }
1017
+
1018
+        \OCP\Util::writeLog('user_ldap', 'Wiz: Final filter '.$filter, \OCP\Util::DEBUG);
1019
+
1020
+        return $filter;
1021
+    }
1022
+
1023
+    /**
1024
+     * Connects and Binds to an LDAP Server
1025
+     *
1026
+     * @param int $port the port to connect with
1027
+     * @param bool $tls whether startTLS is to be used
1028
+     * @return bool
1029
+     * @throws \Exception
1030
+     */
1031
+    private function connectAndBind($port, $tls) {
1032
+        //connect, does not really trigger any server communication
1033
+        $host = $this->configuration->ldapHost;
1034
+        $hostInfo = parse_url($host);
1035
+        if(!$hostInfo) {
1036
+            throw new \Exception(self::$l->t('Invalid Host'));
1037
+        }
1038
+        \OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', \OCP\Util::DEBUG);
1039
+        $cr = $this->ldap->connect($host, $port);
1040
+        if(!is_resource($cr)) {
1041
+            throw new \Exception(self::$l->t('Invalid Host'));
1042
+        }
1043
+
1044
+        //set LDAP options
1045
+        $this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1046
+        $this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1047
+        $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1048
+
1049
+        try {
1050
+            if($tls) {
1051
+                $isTlsWorking = @$this->ldap->startTls($cr);
1052
+                if(!$isTlsWorking) {
1053
+                    return false;
1054
+                }
1055
+            }
1056
+
1057
+            \OCP\Util::writeLog('user_ldap', 'Wiz: Attemping to Bind ', \OCP\Util::DEBUG);
1058
+            //interesting part: do the bind!
1059
+            $login = $this->ldap->bind($cr,
1060
+                $this->configuration->ldapAgentName,
1061
+                $this->configuration->ldapAgentPassword
1062
+            );
1063
+            $errNo = $this->ldap->errno($cr);
1064
+            $error = ldap_error($cr);
1065
+            $this->ldap->unbind($cr);
1066
+        } catch(ServerNotAvailableException $e) {
1067
+            return false;
1068
+        }
1069
+
1070
+        if($login === true) {
1071
+            $this->ldap->unbind($cr);
1072
+            \OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . (int)$tls, \OCP\Util::DEBUG);
1073
+            return true;
1074
+        }
1075
+
1076
+        if($errNo === -1) {
1077
+            //host, port or TLS wrong
1078
+            return false;
1079
+        }
1080
+        throw new \Exception($error, $errNo);
1081
+    }
1082
+
1083
+    /**
1084
+     * checks whether a valid combination of agent and password has been
1085
+     * provided (either two values or nothing for anonymous connect)
1086
+     * @return bool, true if everything is fine, false otherwise
1087
+     */
1088
+    private function checkAgentRequirements() {
1089
+        $agent = $this->configuration->ldapAgentName;
1090
+        $pwd = $this->configuration->ldapAgentPassword;
1091
+
1092
+        return
1093
+            ($agent !== '' && $pwd !== '')
1094
+            ||  ($agent === '' && $pwd === '')
1095
+        ;
1096
+    }
1097
+
1098
+    /**
1099
+     * @param array $reqs
1100
+     * @return bool
1101
+     */
1102
+    private function checkRequirements($reqs) {
1103
+        $this->checkAgentRequirements();
1104
+        foreach($reqs as $option) {
1105
+            $value = $this->configuration->$option;
1106
+            if(empty($value)) {
1107
+                return false;
1108
+            }
1109
+        }
1110
+        return true;
1111
+    }
1112
+
1113
+    /**
1114
+     * does a cumulativeSearch on LDAP to get different values of a
1115
+     * specified attribute
1116
+     * @param string[] $filters array, the filters that shall be used in the search
1117
+     * @param string $attr the attribute of which a list of values shall be returned
1118
+     * @param int $dnReadLimit the amount of how many DNs should be analyzed.
1119
+     * The lower, the faster
1120
+     * @param string $maxF string. if not null, this variable will have the filter that
1121
+     * yields most result entries
1122
+     * @return array|false an array with the values on success, false otherwise
1123
+     */
1124
+    public function cumulativeSearchOnAttribute($filters, $attr, $dnReadLimit = 3, &$maxF = null) {
1125
+        $dnRead = array();
1126
+        $foundItems = array();
1127
+        $maxEntries = 0;
1128
+        if(!is_array($this->configuration->ldapBase)
1129
+           || !isset($this->configuration->ldapBase[0])) {
1130
+            return false;
1131
+        }
1132
+        $base = $this->configuration->ldapBase[0];
1133
+        $cr = $this->getConnection();
1134
+        if(!$this->ldap->isResource($cr)) {
1135
+            return false;
1136
+        }
1137
+        $lastFilter = null;
1138
+        if(isset($filters[count($filters)-1])) {
1139
+            $lastFilter = $filters[count($filters)-1];
1140
+        }
1141
+        foreach($filters as $filter) {
1142
+            if($lastFilter === $filter && count($foundItems) > 0) {
1143
+                //skip when the filter is a wildcard and results were found
1144
+                continue;
1145
+            }
1146
+            // 20k limit for performance and reason
1147
+            $rr = $this->ldap->search($cr, $base, $filter, array($attr), 0, 20000);
1148
+            if(!$this->ldap->isResource($rr)) {
1149
+                continue;
1150
+            }
1151
+            $entries = $this->ldap->countEntries($cr, $rr);
1152
+            $getEntryFunc = 'firstEntry';
1153
+            if(($entries !== false) && ($entries > 0)) {
1154
+                if(!is_null($maxF) && $entries > $maxEntries) {
1155
+                    $maxEntries = $entries;
1156
+                    $maxF = $filter;
1157
+                }
1158
+                $dnReadCount = 0;
1159
+                do {
1160
+                    $entry = $this->ldap->$getEntryFunc($cr, $rr);
1161
+                    $getEntryFunc = 'nextEntry';
1162
+                    if(!$this->ldap->isResource($entry)) {
1163
+                        continue 2;
1164
+                    }
1165
+                    $rr = $entry; //will be expected by nextEntry next round
1166
+                    $attributes = $this->ldap->getAttributes($cr, $entry);
1167
+                    $dn = $this->ldap->getDN($cr, $entry);
1168
+                    if($dn === false || in_array($dn, $dnRead)) {
1169
+                        continue;
1170
+                    }
1171
+                    $newItems = array();
1172
+                    $state = $this->getAttributeValuesFromEntry($attributes,
1173
+                                                                $attr,
1174
+                                                                $newItems);
1175
+                    $dnReadCount++;
1176
+                    $foundItems = array_merge($foundItems, $newItems);
1177
+                    $this->resultCache[$dn][$attr] = $newItems;
1178
+                    $dnRead[] = $dn;
1179
+                } while(($state === self::LRESULT_PROCESSED_SKIP
1180
+                        || $this->ldap->isResource($entry))
1181
+                        && ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit));
1182
+            }
1183
+        }
1184
+
1185
+        return array_unique($foundItems);
1186
+    }
1187
+
1188
+    /**
1189
+     * determines if and which $attr are available on the LDAP server
1190
+     * @param string[] $objectclasses the objectclasses to use as search filter
1191
+     * @param string $attr the attribute to look for
1192
+     * @param string $dbkey the dbkey of the setting the feature is connected to
1193
+     * @param string $confkey the confkey counterpart for the $dbkey as used in the
1194
+     * Configuration class
1195
+     * @param bool $po whether the objectClass with most result entries
1196
+     * shall be pre-selected via the result
1197
+     * @return array|false list of found items.
1198
+     * @throws \Exception
1199
+     */
1200
+    private function determineFeature($objectclasses, $attr, $dbkey, $confkey, $po = false) {
1201
+        $cr = $this->getConnection();
1202
+        if(!$cr) {
1203
+            throw new \Exception('Could not connect to LDAP');
1204
+        }
1205
+        $p = 'objectclass=';
1206
+        foreach($objectclasses as $key => $value) {
1207
+            $objectclasses[$key] = $p.$value;
1208
+        }
1209
+        $maxEntryObjC = '';
1210
+
1211
+        //how deep to dig?
1212
+        //When looking for objectclasses, testing few entries is sufficient,
1213
+        $dig = 3;
1214
+
1215
+        $availableFeatures =
1216
+            $this->cumulativeSearchOnAttribute($objectclasses, $attr,
1217
+                                                $dig, $maxEntryObjC);
1218
+        if(is_array($availableFeatures)
1219
+           && count($availableFeatures) > 0) {
1220
+            natcasesort($availableFeatures);
1221
+            //natcasesort keeps indices, but we must get rid of them for proper
1222
+            //sorting in the web UI. Therefore: array_values
1223
+            $this->result->addOptions($dbkey, array_values($availableFeatures));
1224
+        } else {
1225
+            throw new \Exception(self::$l->t('Could not find the desired feature'));
1226
+        }
1227
+
1228
+        $setFeatures = $this->configuration->$confkey;
1229
+        if(is_array($setFeatures) && !empty($setFeatures)) {
1230
+            //something is already configured? pre-select it.
1231
+            $this->result->addChange($dbkey, $setFeatures);
1232
+        } else if ($po && $maxEntryObjC !== '') {
1233
+            //pre-select objectclass with most result entries
1234
+            $maxEntryObjC = str_replace($p, '', $maxEntryObjC);
1235
+            $this->applyFind($dbkey, $maxEntryObjC);
1236
+            $this->result->addChange($dbkey, $maxEntryObjC);
1237
+        }
1238
+
1239
+        return $availableFeatures;
1240
+    }
1241
+
1242
+    /**
1243
+     * appends a list of values fr
1244
+     * @param resource $result the return value from ldap_get_attributes
1245
+     * @param string $attribute the attribute values to look for
1246
+     * @param array &$known new values will be appended here
1247
+     * @return int, state on of the class constants LRESULT_PROCESSED_OK,
1248
+     * LRESULT_PROCESSED_INVALID or LRESULT_PROCESSED_SKIP
1249
+     */
1250
+    private function getAttributeValuesFromEntry($result, $attribute, &$known) {
1251
+        if(!is_array($result)
1252
+           || !isset($result['count'])
1253
+           || !$result['count'] > 0) {
1254
+            return self::LRESULT_PROCESSED_INVALID;
1255
+        }
1256
+
1257
+        // strtolower on all keys for proper comparison
1258
+        $result = \OCP\Util::mb_array_change_key_case($result);
1259
+        $attribute = strtolower($attribute);
1260
+        if(isset($result[$attribute])) {
1261
+            foreach($result[$attribute] as $key => $val) {
1262
+                if($key === 'count') {
1263
+                    continue;
1264
+                }
1265
+                if(!in_array($val, $known)) {
1266
+                    $known[] = $val;
1267
+                }
1268
+            }
1269
+            return self::LRESULT_PROCESSED_OK;
1270
+        } else {
1271
+            return self::LRESULT_PROCESSED_SKIP;
1272
+        }
1273
+    }
1274
+
1275
+    /**
1276
+     * @return bool|mixed
1277
+     */
1278
+    private function getConnection() {
1279
+        if(!is_null($this->cr)) {
1280
+            return $this->cr;
1281
+        }
1282
+
1283
+        $cr = $this->ldap->connect(
1284
+            $this->configuration->ldapHost,
1285
+            $this->configuration->ldapPort
1286
+        );
1287
+
1288
+        $this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1289
+        $this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1290
+        $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1291
+        if($this->configuration->ldapTLS === 1) {
1292
+            $this->ldap->startTls($cr);
1293
+        }
1294
+
1295
+        $lo = @$this->ldap->bind($cr,
1296
+                                    $this->configuration->ldapAgentName,
1297
+                                    $this->configuration->ldapAgentPassword);
1298
+        if($lo === true) {
1299
+            $this->$cr = $cr;
1300
+            return $cr;
1301
+        }
1302
+
1303
+        return false;
1304
+    }
1305
+
1306
+    /**
1307
+     * @return array
1308
+     */
1309
+    private function getDefaultLdapPortSettings() {
1310
+        static $settings = array(
1311
+                                array('port' => 7636, 'tls' => false),
1312
+                                array('port' =>  636, 'tls' => false),
1313
+                                array('port' => 7389, 'tls' => true),
1314
+                                array('port' =>  389, 'tls' => true),
1315
+                                array('port' => 7389, 'tls' => false),
1316
+                                array('port' =>  389, 'tls' => false),
1317
+                            );
1318
+        return $settings;
1319
+    }
1320
+
1321
+    /**
1322
+     * @return array
1323
+     */
1324
+    private function getPortSettingsToTry() {
1325
+        //389 ← LDAP / Unencrypted or StartTLS
1326
+        //636 ← LDAPS / SSL
1327
+        //7xxx ← UCS. need to be checked first, because both ports may be open
1328
+        $host = $this->configuration->ldapHost;
1329
+        $port = (int)$this->configuration->ldapPort;
1330
+        $portSettings = array();
1331
+
1332
+        //In case the port is already provided, we will check this first
1333
+        if($port > 0) {
1334
+            $hostInfo = parse_url($host);
1335
+            if(!(is_array($hostInfo)
1336
+                && isset($hostInfo['scheme'])
1337
+                && stripos($hostInfo['scheme'], 'ldaps') !== false)) {
1338
+                $portSettings[] = array('port' => $port, 'tls' => true);
1339
+            }
1340
+            $portSettings[] =array('port' => $port, 'tls' => false);
1341
+        }
1342
+
1343
+        //default ports
1344
+        $portSettings = array_merge($portSettings,
1345
+                                    $this->getDefaultLdapPortSettings());
1346
+
1347
+        return $portSettings;
1348
+    }
1349 1349
 
1350 1350
 
1351 1351
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/SharedMount.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -110,7 +110,7 @@  discard block
 block discarded – undo
110 110
 	 *
111 111
 	 * @param string $newPath
112 112
 	 * @param \OCP\Share\IShare $share
113
-	 * @return bool
113
+	 * @return boolean|null
114 114
 	 */
115 115
 	private function updateFileTarget($newPath, &$share) {
116 116
 		$share->setTarget($newPath);
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
 	 * @param string $path
127 127
 	 * @param View $view
128 128
 	 * @param SharedMount[] $mountpoints
129
-	 * @return mixed
129
+	 * @return string
130 130
 	 */
131 131
 	private function generateUniqueTarget($path, $view, array $mountpoints) {
132 132
 		$pathinfo = pathinfo($path);
Please login to merge, or discard this patch.
Indentation   +226 added lines, -226 removed lines patch added patch discarded remove patch
@@ -37,230 +37,230 @@
 block discarded – undo
37 37
  * Shared mount points can be moved by the user
38 38
  */
39 39
 class SharedMount extends MountPoint implements MoveableMount {
40
-	/**
41
-	 * @var \OCA\Files_Sharing\SharedStorage $storage
42
-	 */
43
-	protected $storage = null;
44
-
45
-	/**
46
-	 * @var \OC\Files\View
47
-	 */
48
-	private $recipientView;
49
-
50
-	/**
51
-	 * @var string
52
-	 */
53
-	private $user;
54
-
55
-	/** @var \OCP\Share\IShare */
56
-	private $superShare;
57
-
58
-	/** @var \OCP\Share\IShare[] */
59
-	private $groupedShares;
60
-
61
-	/**
62
-	 * @param string $storage
63
-	 * @param SharedMount[] $mountpoints
64
-	 * @param array|null $arguments
65
-	 * @param \OCP\Files\Storage\IStorageFactory $loader
66
-	 */
67
-	public function __construct($storage, array $mountpoints, $arguments = null, $loader = null) {
68
-		$this->user = $arguments['user'];
69
-		$this->recipientView = new View('/' . $this->user . '/files');
70
-
71
-		$this->superShare = $arguments['superShare'];
72
-		$this->groupedShares = $arguments['groupedShares'];
73
-
74
-		$newMountPoint = $this->verifyMountPoint($this->superShare, $mountpoints);
75
-		$absMountPoint = '/' . $this->user . '/files' . $newMountPoint;
76
-		$arguments['ownerView'] = new View('/' . $this->superShare->getShareOwner() . '/files');
77
-		parent::__construct($storage, $absMountPoint, $arguments, $loader);
78
-	}
79
-
80
-	/**
81
-	 * check if the parent folder exists otherwise move the mount point up
82
-	 *
83
-	 * @param \OCP\Share\IShare $share
84
-	 * @param SharedMount[] $mountpoints
85
-	 * @return string
86
-	 */
87
-	private function verifyMountPoint(\OCP\Share\IShare $share, array $mountpoints) {
88
-
89
-		$mountPoint = basename($share->getTarget());
90
-		$parent = dirname($share->getTarget());
91
-
92
-		if (!$this->recipientView->is_dir($parent)) {
93
-			$parent = Helper::getShareFolder($this->recipientView);
94
-		}
95
-
96
-		$newMountPoint = $this->generateUniqueTarget(
97
-			\OC\Files\Filesystem::normalizePath($parent . '/' . $mountPoint),
98
-			$this->recipientView,
99
-			$mountpoints
100
-		);
101
-
102
-		if ($newMountPoint !== $share->getTarget()) {
103
-			$this->updateFileTarget($newMountPoint, $share);
104
-		}
105
-
106
-		return $newMountPoint;
107
-	}
108
-
109
-	/**
110
-	 * update fileTarget in the database if the mount point changed
111
-	 *
112
-	 * @param string $newPath
113
-	 * @param \OCP\Share\IShare $share
114
-	 * @return bool
115
-	 */
116
-	private function updateFileTarget($newPath, &$share) {
117
-		$share->setTarget($newPath);
118
-
119
-		foreach ($this->groupedShares as $tmpShare) {
120
-			$tmpShare->setTarget($newPath);
121
-			\OC::$server->getShareManager()->moveShare($tmpShare, $this->user);
122
-		}
123
-	}
124
-
125
-
126
-	/**
127
-	 * @param string $path
128
-	 * @param View $view
129
-	 * @param SharedMount[] $mountpoints
130
-	 * @return mixed
131
-	 */
132
-	private function generateUniqueTarget($path, $view, array $mountpoints) {
133
-		$pathinfo = pathinfo($path);
134
-		$ext = isset($pathinfo['extension']) ? '.' . $pathinfo['extension'] : '';
135
-		$name = $pathinfo['filename'];
136
-		$dir = $pathinfo['dirname'];
137
-
138
-		// Helper function to find existing mount points
139
-		$mountpointExists = function ($path) use ($mountpoints) {
140
-			foreach ($mountpoints as $mountpoint) {
141
-				if ($mountpoint->getShare()->getTarget() === $path) {
142
-					return true;
143
-				}
144
-			}
145
-			return false;
146
-		};
147
-
148
-		$i = 2;
149
-		while ($view->file_exists($path) || $mountpointExists($path)) {
150
-			$path = Filesystem::normalizePath($dir . '/' . $name . ' (' . $i . ')' . $ext);
151
-			$i++;
152
-		}
153
-
154
-		return $path;
155
-	}
156
-
157
-	/**
158
-	 * Format a path to be relative to the /user/files/ directory
159
-	 *
160
-	 * @param string $path the absolute path
161
-	 * @return string e.g. turns '/admin/files/test.txt' into '/test.txt'
162
-	 * @throws \OCA\Files_Sharing\Exceptions\BrokenPath
163
-	 */
164
-	protected function stripUserFilesPath($path) {
165
-		$trimmed = ltrim($path, '/');
166
-		$split = explode('/', $trimmed);
167
-
168
-		// it is not a file relative to data/user/files
169
-		if (count($split) < 3 || $split[1] !== 'files') {
170
-			\OCP\Util::writeLog('file sharing',
171
-				'Can not strip userid and "files/" from path: ' . $path,
172
-				\OCP\Util::ERROR);
173
-			throw new \OCA\Files_Sharing\Exceptions\BrokenPath('Path does not start with /user/files', 10);
174
-		}
175
-
176
-		// skip 'user' and 'files'
177
-		$sliced = array_slice($split, 2);
178
-		$relPath = implode('/', $sliced);
179
-
180
-		return '/' . $relPath;
181
-	}
182
-
183
-	/**
184
-	 * Move the mount point to $target
185
-	 *
186
-	 * @param string $target the target mount point
187
-	 * @return bool
188
-	 */
189
-	public function moveMount($target) {
190
-
191
-		$relTargetPath = $this->stripUserFilesPath($target);
192
-		$share = $this->storage->getShare();
193
-
194
-		$result = true;
195
-
196
-		try {
197
-			$this->updateFileTarget($relTargetPath, $share);
198
-			$this->setMountPoint($target);
199
-			$this->storage->setMountPoint($relTargetPath);
200
-		} catch (\Exception $e) {
201
-			\OCP\Util::writeLog('file sharing',
202
-				'Could not rename mount point for shared folder "' . $this->getMountPoint() . '" to "' . $target . '"',
203
-				\OCP\Util::ERROR);
204
-		}
205
-
206
-		return $result;
207
-	}
208
-
209
-	/**
210
-	 * Remove the mount points
211
-	 *
212
-	 * @return bool
213
-	 */
214
-	public function removeMount() {
215
-		$mountManager = \OC\Files\Filesystem::getMountManager();
216
-		/** @var $storage \OCA\Files_Sharing\SharedStorage */
217
-		$storage = $this->getStorage();
218
-		$result = $storage->unshareStorage();
219
-		$mountManager->removeMount($this->mountPoint);
220
-
221
-		return $result;
222
-	}
223
-
224
-	/**
225
-	 * @return \OCP\Share\IShare
226
-	 */
227
-	public function getShare() {
228
-		return $this->superShare;
229
-	}
230
-
231
-	/**
232
-	 * Get the file id of the root of the storage
233
-	 *
234
-	 * @return int
235
-	 */
236
-	public function getStorageRootId() {
237
-		return $this->getShare()->getNodeId();
238
-	}
239
-
240
-	/**
241
-	 * @return int
242
-	 */
243
-	public function getNumericStorageId() {
244
-		if (!is_null($this->getShare()->getNodeCacheEntry())) {
245
-			return $this->getShare()->getNodeCacheEntry()->getStorageId();
246
-		} else {
247
-			$builder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
248
-
249
-			$query = $builder->select('storage')
250
-				->from('filecache')
251
-				->where($builder->expr()->eq('fileid', $builder->createNamedParameter($this->getStorageRootId())));
252
-
253
-			$result = $query->execute();
254
-			$row = $result->fetch();
255
-			$result->closeCursor();
256
-			if ($row) {
257
-				return (int)$row['storage'];
258
-			}
259
-			return -1;
260
-		}
261
-	}
262
-
263
-	public function getMountType() {
264
-		return 'shared';
265
-	}
40
+    /**
41
+     * @var \OCA\Files_Sharing\SharedStorage $storage
42
+     */
43
+    protected $storage = null;
44
+
45
+    /**
46
+     * @var \OC\Files\View
47
+     */
48
+    private $recipientView;
49
+
50
+    /**
51
+     * @var string
52
+     */
53
+    private $user;
54
+
55
+    /** @var \OCP\Share\IShare */
56
+    private $superShare;
57
+
58
+    /** @var \OCP\Share\IShare[] */
59
+    private $groupedShares;
60
+
61
+    /**
62
+     * @param string $storage
63
+     * @param SharedMount[] $mountpoints
64
+     * @param array|null $arguments
65
+     * @param \OCP\Files\Storage\IStorageFactory $loader
66
+     */
67
+    public function __construct($storage, array $mountpoints, $arguments = null, $loader = null) {
68
+        $this->user = $arguments['user'];
69
+        $this->recipientView = new View('/' . $this->user . '/files');
70
+
71
+        $this->superShare = $arguments['superShare'];
72
+        $this->groupedShares = $arguments['groupedShares'];
73
+
74
+        $newMountPoint = $this->verifyMountPoint($this->superShare, $mountpoints);
75
+        $absMountPoint = '/' . $this->user . '/files' . $newMountPoint;
76
+        $arguments['ownerView'] = new View('/' . $this->superShare->getShareOwner() . '/files');
77
+        parent::__construct($storage, $absMountPoint, $arguments, $loader);
78
+    }
79
+
80
+    /**
81
+     * check if the parent folder exists otherwise move the mount point up
82
+     *
83
+     * @param \OCP\Share\IShare $share
84
+     * @param SharedMount[] $mountpoints
85
+     * @return string
86
+     */
87
+    private function verifyMountPoint(\OCP\Share\IShare $share, array $mountpoints) {
88
+
89
+        $mountPoint = basename($share->getTarget());
90
+        $parent = dirname($share->getTarget());
91
+
92
+        if (!$this->recipientView->is_dir($parent)) {
93
+            $parent = Helper::getShareFolder($this->recipientView);
94
+        }
95
+
96
+        $newMountPoint = $this->generateUniqueTarget(
97
+            \OC\Files\Filesystem::normalizePath($parent . '/' . $mountPoint),
98
+            $this->recipientView,
99
+            $mountpoints
100
+        );
101
+
102
+        if ($newMountPoint !== $share->getTarget()) {
103
+            $this->updateFileTarget($newMountPoint, $share);
104
+        }
105
+
106
+        return $newMountPoint;
107
+    }
108
+
109
+    /**
110
+     * update fileTarget in the database if the mount point changed
111
+     *
112
+     * @param string $newPath
113
+     * @param \OCP\Share\IShare $share
114
+     * @return bool
115
+     */
116
+    private function updateFileTarget($newPath, &$share) {
117
+        $share->setTarget($newPath);
118
+
119
+        foreach ($this->groupedShares as $tmpShare) {
120
+            $tmpShare->setTarget($newPath);
121
+            \OC::$server->getShareManager()->moveShare($tmpShare, $this->user);
122
+        }
123
+    }
124
+
125
+
126
+    /**
127
+     * @param string $path
128
+     * @param View $view
129
+     * @param SharedMount[] $mountpoints
130
+     * @return mixed
131
+     */
132
+    private function generateUniqueTarget($path, $view, array $mountpoints) {
133
+        $pathinfo = pathinfo($path);
134
+        $ext = isset($pathinfo['extension']) ? '.' . $pathinfo['extension'] : '';
135
+        $name = $pathinfo['filename'];
136
+        $dir = $pathinfo['dirname'];
137
+
138
+        // Helper function to find existing mount points
139
+        $mountpointExists = function ($path) use ($mountpoints) {
140
+            foreach ($mountpoints as $mountpoint) {
141
+                if ($mountpoint->getShare()->getTarget() === $path) {
142
+                    return true;
143
+                }
144
+            }
145
+            return false;
146
+        };
147
+
148
+        $i = 2;
149
+        while ($view->file_exists($path) || $mountpointExists($path)) {
150
+            $path = Filesystem::normalizePath($dir . '/' . $name . ' (' . $i . ')' . $ext);
151
+            $i++;
152
+        }
153
+
154
+        return $path;
155
+    }
156
+
157
+    /**
158
+     * Format a path to be relative to the /user/files/ directory
159
+     *
160
+     * @param string $path the absolute path
161
+     * @return string e.g. turns '/admin/files/test.txt' into '/test.txt'
162
+     * @throws \OCA\Files_Sharing\Exceptions\BrokenPath
163
+     */
164
+    protected function stripUserFilesPath($path) {
165
+        $trimmed = ltrim($path, '/');
166
+        $split = explode('/', $trimmed);
167
+
168
+        // it is not a file relative to data/user/files
169
+        if (count($split) < 3 || $split[1] !== 'files') {
170
+            \OCP\Util::writeLog('file sharing',
171
+                'Can not strip userid and "files/" from path: ' . $path,
172
+                \OCP\Util::ERROR);
173
+            throw new \OCA\Files_Sharing\Exceptions\BrokenPath('Path does not start with /user/files', 10);
174
+        }
175
+
176
+        // skip 'user' and 'files'
177
+        $sliced = array_slice($split, 2);
178
+        $relPath = implode('/', $sliced);
179
+
180
+        return '/' . $relPath;
181
+    }
182
+
183
+    /**
184
+     * Move the mount point to $target
185
+     *
186
+     * @param string $target the target mount point
187
+     * @return bool
188
+     */
189
+    public function moveMount($target) {
190
+
191
+        $relTargetPath = $this->stripUserFilesPath($target);
192
+        $share = $this->storage->getShare();
193
+
194
+        $result = true;
195
+
196
+        try {
197
+            $this->updateFileTarget($relTargetPath, $share);
198
+            $this->setMountPoint($target);
199
+            $this->storage->setMountPoint($relTargetPath);
200
+        } catch (\Exception $e) {
201
+            \OCP\Util::writeLog('file sharing',
202
+                'Could not rename mount point for shared folder "' . $this->getMountPoint() . '" to "' . $target . '"',
203
+                \OCP\Util::ERROR);
204
+        }
205
+
206
+        return $result;
207
+    }
208
+
209
+    /**
210
+     * Remove the mount points
211
+     *
212
+     * @return bool
213
+     */
214
+    public function removeMount() {
215
+        $mountManager = \OC\Files\Filesystem::getMountManager();
216
+        /** @var $storage \OCA\Files_Sharing\SharedStorage */
217
+        $storage = $this->getStorage();
218
+        $result = $storage->unshareStorage();
219
+        $mountManager->removeMount($this->mountPoint);
220
+
221
+        return $result;
222
+    }
223
+
224
+    /**
225
+     * @return \OCP\Share\IShare
226
+     */
227
+    public function getShare() {
228
+        return $this->superShare;
229
+    }
230
+
231
+    /**
232
+     * Get the file id of the root of the storage
233
+     *
234
+     * @return int
235
+     */
236
+    public function getStorageRootId() {
237
+        return $this->getShare()->getNodeId();
238
+    }
239
+
240
+    /**
241
+     * @return int
242
+     */
243
+    public function getNumericStorageId() {
244
+        if (!is_null($this->getShare()->getNodeCacheEntry())) {
245
+            return $this->getShare()->getNodeCacheEntry()->getStorageId();
246
+        } else {
247
+            $builder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
248
+
249
+            $query = $builder->select('storage')
250
+                ->from('filecache')
251
+                ->where($builder->expr()->eq('fileid', $builder->createNamedParameter($this->getStorageRootId())));
252
+
253
+            $result = $query->execute();
254
+            $row = $result->fetch();
255
+            $result->closeCursor();
256
+            if ($row) {
257
+                return (int)$row['storage'];
258
+            }
259
+            return -1;
260
+        }
261
+    }
262
+
263
+    public function getMountType() {
264
+        return 'shared';
265
+    }
266 266
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -66,14 +66,14 @@  discard block
 block discarded – undo
66 66
 	 */
67 67
 	public function __construct($storage, array $mountpoints, $arguments = null, $loader = null) {
68 68
 		$this->user = $arguments['user'];
69
-		$this->recipientView = new View('/' . $this->user . '/files');
69
+		$this->recipientView = new View('/'.$this->user.'/files');
70 70
 
71 71
 		$this->superShare = $arguments['superShare'];
72 72
 		$this->groupedShares = $arguments['groupedShares'];
73 73
 
74 74
 		$newMountPoint = $this->verifyMountPoint($this->superShare, $mountpoints);
75
-		$absMountPoint = '/' . $this->user . '/files' . $newMountPoint;
76
-		$arguments['ownerView'] = new View('/' . $this->superShare->getShareOwner() . '/files');
75
+		$absMountPoint = '/'.$this->user.'/files'.$newMountPoint;
76
+		$arguments['ownerView'] = new View('/'.$this->superShare->getShareOwner().'/files');
77 77
 		parent::__construct($storage, $absMountPoint, $arguments, $loader);
78 78
 	}
79 79
 
@@ -94,7 +94,7 @@  discard block
 block discarded – undo
94 94
 		}
95 95
 
96 96
 		$newMountPoint = $this->generateUniqueTarget(
97
-			\OC\Files\Filesystem::normalizePath($parent . '/' . $mountPoint),
97
+			\OC\Files\Filesystem::normalizePath($parent.'/'.$mountPoint),
98 98
 			$this->recipientView,
99 99
 			$mountpoints
100 100
 		);
@@ -131,12 +131,12 @@  discard block
 block discarded – undo
131 131
 	 */
132 132
 	private function generateUniqueTarget($path, $view, array $mountpoints) {
133 133
 		$pathinfo = pathinfo($path);
134
-		$ext = isset($pathinfo['extension']) ? '.' . $pathinfo['extension'] : '';
134
+		$ext = isset($pathinfo['extension']) ? '.'.$pathinfo['extension'] : '';
135 135
 		$name = $pathinfo['filename'];
136 136
 		$dir = $pathinfo['dirname'];
137 137
 
138 138
 		// Helper function to find existing mount points
139
-		$mountpointExists = function ($path) use ($mountpoints) {
139
+		$mountpointExists = function($path) use ($mountpoints) {
140 140
 			foreach ($mountpoints as $mountpoint) {
141 141
 				if ($mountpoint->getShare()->getTarget() === $path) {
142 142
 					return true;
@@ -147,7 +147,7 @@  discard block
 block discarded – undo
147 147
 
148 148
 		$i = 2;
149 149
 		while ($view->file_exists($path) || $mountpointExists($path)) {
150
-			$path = Filesystem::normalizePath($dir . '/' . $name . ' (' . $i . ')' . $ext);
150
+			$path = Filesystem::normalizePath($dir.'/'.$name.' ('.$i.')'.$ext);
151 151
 			$i++;
152 152
 		}
153 153
 
@@ -168,7 +168,7 @@  discard block
 block discarded – undo
168 168
 		// it is not a file relative to data/user/files
169 169
 		if (count($split) < 3 || $split[1] !== 'files') {
170 170
 			\OCP\Util::writeLog('file sharing',
171
-				'Can not strip userid and "files/" from path: ' . $path,
171
+				'Can not strip userid and "files/" from path: '.$path,
172 172
 				\OCP\Util::ERROR);
173 173
 			throw new \OCA\Files_Sharing\Exceptions\BrokenPath('Path does not start with /user/files', 10);
174 174
 		}
@@ -177,7 +177,7 @@  discard block
 block discarded – undo
177 177
 		$sliced = array_slice($split, 2);
178 178
 		$relPath = implode('/', $sliced);
179 179
 
180
-		return '/' . $relPath;
180
+		return '/'.$relPath;
181 181
 	}
182 182
 
183 183
 	/**
@@ -199,7 +199,7 @@  discard block
 block discarded – undo
199 199
 			$this->storage->setMountPoint($relTargetPath);
200 200
 		} catch (\Exception $e) {
201 201
 			\OCP\Util::writeLog('file sharing',
202
-				'Could not rename mount point for shared folder "' . $this->getMountPoint() . '" to "' . $target . '"',
202
+				'Could not rename mount point for shared folder "'.$this->getMountPoint().'" to "'.$target.'"',
203 203
 				\OCP\Util::ERROR);
204 204
 		}
205 205
 
@@ -254,7 +254,7 @@  discard block
 block discarded – undo
254 254
 			$row = $result->fetch();
255 255
 			$result->closeCursor();
256 256
 			if ($row) {
257
-				return (int)$row['storage'];
257
+				return (int) $row['storage'];
258 258
 			}
259 259
 			return -1;
260 260
 		}
Please login to merge, or discard this patch.
lib/private/Cache/File.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -95,7 +95,7 @@
 block discarded – undo
95 95
 	 * @param string $key
96 96
 	 * @param mixed $value
97 97
 	 * @param int $ttl
98
-	 * @return bool|mixed
98
+	 * @return boolean
99 99
 	 * @throws \OC\ForbiddenException
100 100
 	 */
101 101
 	public function set($key, $value, $ttl = 0) {
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -51,10 +51,10 @@  discard block
 block discarded – undo
51 51
 			$rootView = new View();
52 52
 			$user = \OC::$server->getUserSession()->getUser();
53 53
 			Filesystem::initMountPoints($user->getUID());
54
-			if (!$rootView->file_exists('/' . $user->getUID() . '/cache')) {
55
-				$rootView->mkdir('/' . $user->getUID() . '/cache');
54
+			if (!$rootView->file_exists('/'.$user->getUID().'/cache')) {
55
+				$rootView->mkdir('/'.$user->getUID().'/cache');
56 56
 			}
57
-			$this->storage = new View('/' . $user->getUID() . '/cache');
57
+			$this->storage = new View('/'.$user->getUID().'/cache');
58 58
 			return $this->storage;
59 59
 		} else {
60 60
 			\OCP\Util::writeLog('core', 'Can\'t get cache storage, user not logged in', \OCP\Util::ERROR);
@@ -104,12 +104,12 @@  discard block
 block discarded – undo
104 104
 		// unique id to avoid chunk collision, just in case
105 105
 		$uniqueId = \OC::$server->getSecureRandom()->generate(
106 106
 			16,
107
-			ISecureRandom::CHAR_DIGITS . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER
107
+			ISecureRandom::CHAR_DIGITS.ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_UPPER
108 108
 		);
109 109
 
110 110
 		// use part file to prevent hasKey() to find the key
111 111
 		// while it is being written
112
-		$keyPart = $key . '.' . $uniqueId . '.part';
112
+		$keyPart = $key.'.'.$uniqueId.'.part';
113 113
 		if ($storage and $storage->file_put_contents($keyPart, $value)) {
114 114
 			if ($ttl === 0) {
115 115
 				$ttl = 86400; // 60*60*24
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
 			if (is_resource($dh)) {
159 159
 				while (($file = readdir($dh)) !== false) {
160 160
 					if ($file != '.' and $file != '..' and ($prefix === '' || strpos($file, $prefix) === 0)) {
161
-						$storage->unlink('/' . $file);
161
+						$storage->unlink('/'.$file);
162 162
 					}
163 163
 				}
164 164
 			}
@@ -183,17 +183,17 @@  discard block
 block discarded – undo
183 183
 			while (($file = readdir($dh)) !== false) {
184 184
 				if ($file != '.' and $file != '..') {
185 185
 					try {
186
-						$mtime = $storage->filemtime('/' . $file);
186
+						$mtime = $storage->filemtime('/'.$file);
187 187
 						if ($mtime < $now) {
188
-							$storage->unlink('/' . $file);
188
+							$storage->unlink('/'.$file);
189 189
 						}
190 190
 					} catch (\OCP\Lock\LockedException $e) {
191 191
 						// ignore locked chunks
192
-						\OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core'));
192
+						\OC::$server->getLogger()->debug('Could not cleanup locked chunk "'.$file.'"', array('app' => 'core'));
193 193
 					} catch (\OCP\Files\ForbiddenException $e) {
194
-						\OC::$server->getLogger()->debug('Could not cleanup forbidden chunk "' . $file . '"', array('app' => 'core'));
194
+						\OC::$server->getLogger()->debug('Could not cleanup forbidden chunk "'.$file.'"', array('app' => 'core'));
195 195
 					} catch (\OCP\Files\LockNotAcquiredException $e) {
196
-						\OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core'));
196
+						\OC::$server->getLogger()->debug('Could not cleanup locked chunk "'.$file.'"', array('app' => 'core'));
197 197
 					}
198 198
 				}
199 199
 			}
Please login to merge, or discard this patch.
Indentation   +157 added lines, -157 removed lines patch added patch discarded remove patch
@@ -33,170 +33,170 @@
 block discarded – undo
33 33
 
34 34
 class File implements ICache {
35 35
 
36
-	/** @var View */
37
-	protected $storage;
36
+    /** @var View */
37
+    protected $storage;
38 38
 
39
-	/**
40
-	 * Returns the cache storage for the logged in user
41
-	 *
42
-	 * @return \OC\Files\View cache storage
43
-	 * @throws \OC\ForbiddenException
44
-	 * @throws \OC\User\NoUserException
45
-	 */
46
-	protected function getStorage() {
47
-		if (isset($this->storage)) {
48
-			return $this->storage;
49
-		}
50
-		if (\OC::$server->getUserSession()->isLoggedIn()) {
51
-			$rootView = new View();
52
-			$user = \OC::$server->getUserSession()->getUser();
53
-			Filesystem::initMountPoints($user->getUID());
54
-			if (!$rootView->file_exists('/' . $user->getUID() . '/cache')) {
55
-				$rootView->mkdir('/' . $user->getUID() . '/cache');
56
-			}
57
-			$this->storage = new View('/' . $user->getUID() . '/cache');
58
-			return $this->storage;
59
-		} else {
60
-			\OCP\Util::writeLog('core', 'Can\'t get cache storage, user not logged in', \OCP\Util::ERROR);
61
-			throw new \OC\ForbiddenException('Can\t get cache storage, user not logged in');
62
-		}
63
-	}
39
+    /**
40
+     * Returns the cache storage for the logged in user
41
+     *
42
+     * @return \OC\Files\View cache storage
43
+     * @throws \OC\ForbiddenException
44
+     * @throws \OC\User\NoUserException
45
+     */
46
+    protected function getStorage() {
47
+        if (isset($this->storage)) {
48
+            return $this->storage;
49
+        }
50
+        if (\OC::$server->getUserSession()->isLoggedIn()) {
51
+            $rootView = new View();
52
+            $user = \OC::$server->getUserSession()->getUser();
53
+            Filesystem::initMountPoints($user->getUID());
54
+            if (!$rootView->file_exists('/' . $user->getUID() . '/cache')) {
55
+                $rootView->mkdir('/' . $user->getUID() . '/cache');
56
+            }
57
+            $this->storage = new View('/' . $user->getUID() . '/cache');
58
+            return $this->storage;
59
+        } else {
60
+            \OCP\Util::writeLog('core', 'Can\'t get cache storage, user not logged in', \OCP\Util::ERROR);
61
+            throw new \OC\ForbiddenException('Can\t get cache storage, user not logged in');
62
+        }
63
+    }
64 64
 
65
-	/**
66
-	 * @param string $key
67
-	 * @return mixed|null
68
-	 * @throws \OC\ForbiddenException
69
-	 */
70
-	public function get($key) {
71
-		$result = null;
72
-		if ($this->hasKey($key)) {
73
-			$storage = $this->getStorage();
74
-			$result = $storage->file_get_contents($key);
75
-		}
76
-		return $result;
77
-	}
65
+    /**
66
+     * @param string $key
67
+     * @return mixed|null
68
+     * @throws \OC\ForbiddenException
69
+     */
70
+    public function get($key) {
71
+        $result = null;
72
+        if ($this->hasKey($key)) {
73
+            $storage = $this->getStorage();
74
+            $result = $storage->file_get_contents($key);
75
+        }
76
+        return $result;
77
+    }
78 78
 
79
-	/**
80
-	 * Returns the size of the stored/cached data
81
-	 *
82
-	 * @param string $key
83
-	 * @return int
84
-	 */
85
-	public function size($key) {
86
-		$result = 0;
87
-		if ($this->hasKey($key)) {
88
-			$storage = $this->getStorage();
89
-			$result = $storage->filesize($key);
90
-		}
91
-		return $result;
92
-	}
79
+    /**
80
+     * Returns the size of the stored/cached data
81
+     *
82
+     * @param string $key
83
+     * @return int
84
+     */
85
+    public function size($key) {
86
+        $result = 0;
87
+        if ($this->hasKey($key)) {
88
+            $storage = $this->getStorage();
89
+            $result = $storage->filesize($key);
90
+        }
91
+        return $result;
92
+    }
93 93
 
94
-	/**
95
-	 * @param string $key
96
-	 * @param mixed $value
97
-	 * @param int $ttl
98
-	 * @return bool|mixed
99
-	 * @throws \OC\ForbiddenException
100
-	 */
101
-	public function set($key, $value, $ttl = 0) {
102
-		$storage = $this->getStorage();
103
-		$result = false;
104
-		// unique id to avoid chunk collision, just in case
105
-		$uniqueId = \OC::$server->getSecureRandom()->generate(
106
-			16,
107
-			ISecureRandom::CHAR_DIGITS . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER
108
-		);
94
+    /**
95
+     * @param string $key
96
+     * @param mixed $value
97
+     * @param int $ttl
98
+     * @return bool|mixed
99
+     * @throws \OC\ForbiddenException
100
+     */
101
+    public function set($key, $value, $ttl = 0) {
102
+        $storage = $this->getStorage();
103
+        $result = false;
104
+        // unique id to avoid chunk collision, just in case
105
+        $uniqueId = \OC::$server->getSecureRandom()->generate(
106
+            16,
107
+            ISecureRandom::CHAR_DIGITS . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER
108
+        );
109 109
 
110
-		// use part file to prevent hasKey() to find the key
111
-		// while it is being written
112
-		$keyPart = $key . '.' . $uniqueId . '.part';
113
-		if ($storage and $storage->file_put_contents($keyPart, $value)) {
114
-			if ($ttl === 0) {
115
-				$ttl = 86400; // 60*60*24
116
-			}
117
-			$result = $storage->touch($keyPart, time() + $ttl);
118
-			$result &= $storage->rename($keyPart, $key);
119
-		}
120
-		return $result;
121
-	}
110
+        // use part file to prevent hasKey() to find the key
111
+        // while it is being written
112
+        $keyPart = $key . '.' . $uniqueId . '.part';
113
+        if ($storage and $storage->file_put_contents($keyPart, $value)) {
114
+            if ($ttl === 0) {
115
+                $ttl = 86400; // 60*60*24
116
+            }
117
+            $result = $storage->touch($keyPart, time() + $ttl);
118
+            $result &= $storage->rename($keyPart, $key);
119
+        }
120
+        return $result;
121
+    }
122 122
 
123
-	/**
124
-	 * @param string $key
125
-	 * @return bool
126
-	 * @throws \OC\ForbiddenException
127
-	 */
128
-	public function hasKey($key) {
129
-		$storage = $this->getStorage();
130
-		if ($storage && $storage->is_file($key) && $storage->isReadable($key)) {
131
-			return true;
132
-		}
133
-		return false;
134
-	}
123
+    /**
124
+     * @param string $key
125
+     * @return bool
126
+     * @throws \OC\ForbiddenException
127
+     */
128
+    public function hasKey($key) {
129
+        $storage = $this->getStorage();
130
+        if ($storage && $storage->is_file($key) && $storage->isReadable($key)) {
131
+            return true;
132
+        }
133
+        return false;
134
+    }
135 135
 
136
-	/**
137
-	 * @param string $key
138
-	 * @return bool|mixed
139
-	 * @throws \OC\ForbiddenException
140
-	 */
141
-	public function remove($key) {
142
-		$storage = $this->getStorage();
143
-		if (!$storage) {
144
-			return false;
145
-		}
146
-		return $storage->unlink($key);
147
-	}
136
+    /**
137
+     * @param string $key
138
+     * @return bool|mixed
139
+     * @throws \OC\ForbiddenException
140
+     */
141
+    public function remove($key) {
142
+        $storage = $this->getStorage();
143
+        if (!$storage) {
144
+            return false;
145
+        }
146
+        return $storage->unlink($key);
147
+    }
148 148
 
149
-	/**
150
-	 * @param string $prefix
151
-	 * @return bool
152
-	 * @throws \OC\ForbiddenException
153
-	 */
154
-	public function clear($prefix = '') {
155
-		$storage = $this->getStorage();
156
-		if ($storage and $storage->is_dir('/')) {
157
-			$dh = $storage->opendir('/');
158
-			if (is_resource($dh)) {
159
-				while (($file = readdir($dh)) !== false) {
160
-					if ($file != '.' and $file != '..' and ($prefix === '' || strpos($file, $prefix) === 0)) {
161
-						$storage->unlink('/' . $file);
162
-					}
163
-				}
164
-			}
165
-		}
166
-		return true;
167
-	}
149
+    /**
150
+     * @param string $prefix
151
+     * @return bool
152
+     * @throws \OC\ForbiddenException
153
+     */
154
+    public function clear($prefix = '') {
155
+        $storage = $this->getStorage();
156
+        if ($storage and $storage->is_dir('/')) {
157
+            $dh = $storage->opendir('/');
158
+            if (is_resource($dh)) {
159
+                while (($file = readdir($dh)) !== false) {
160
+                    if ($file != '.' and $file != '..' and ($prefix === '' || strpos($file, $prefix) === 0)) {
161
+                        $storage->unlink('/' . $file);
162
+                    }
163
+                }
164
+            }
165
+        }
166
+        return true;
167
+    }
168 168
 
169
-	/**
170
-	 * Runs GC
171
-	 * @throws \OC\ForbiddenException
172
-	 */
173
-	public function gc() {
174
-		$storage = $this->getStorage();
175
-		if ($storage and $storage->is_dir('/')) {
176
-			// extra hour safety, in case of stray part chunks that take longer to write,
177
-			// because touch() is only called after the chunk was finished
178
-			$now = time() - 3600;
179
-			$dh = $storage->opendir('/');
180
-			if (!is_resource($dh)) {
181
-				return null;
182
-			}
183
-			while (($file = readdir($dh)) !== false) {
184
-				if ($file != '.' and $file != '..') {
185
-					try {
186
-						$mtime = $storage->filemtime('/' . $file);
187
-						if ($mtime < $now) {
188
-							$storage->unlink('/' . $file);
189
-						}
190
-					} catch (\OCP\Lock\LockedException $e) {
191
-						// ignore locked chunks
192
-						\OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core'));
193
-					} catch (\OCP\Files\ForbiddenException $e) {
194
-						\OC::$server->getLogger()->debug('Could not cleanup forbidden chunk "' . $file . '"', array('app' => 'core'));
195
-					} catch (\OCP\Files\LockNotAcquiredException $e) {
196
-						\OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core'));
197
-					}
198
-				}
199
-			}
200
-		}
201
-	}
169
+    /**
170
+     * Runs GC
171
+     * @throws \OC\ForbiddenException
172
+     */
173
+    public function gc() {
174
+        $storage = $this->getStorage();
175
+        if ($storage and $storage->is_dir('/')) {
176
+            // extra hour safety, in case of stray part chunks that take longer to write,
177
+            // because touch() is only called after the chunk was finished
178
+            $now = time() - 3600;
179
+            $dh = $storage->opendir('/');
180
+            if (!is_resource($dh)) {
181
+                return null;
182
+            }
183
+            while (($file = readdir($dh)) !== false) {
184
+                if ($file != '.' and $file != '..') {
185
+                    try {
186
+                        $mtime = $storage->filemtime('/' . $file);
187
+                        if ($mtime < $now) {
188
+                            $storage->unlink('/' . $file);
189
+                        }
190
+                    } catch (\OCP\Lock\LockedException $e) {
191
+                        // ignore locked chunks
192
+                        \OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core'));
193
+                    } catch (\OCP\Files\ForbiddenException $e) {
194
+                        \OC::$server->getLogger()->debug('Could not cleanup forbidden chunk "' . $file . '"', array('app' => 'core'));
195
+                    } catch (\OCP\Files\LockNotAcquiredException $e) {
196
+                        \OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core'));
197
+                    }
198
+                }
199
+            }
200
+        }
201
+    }
202 202
 }
Please login to merge, or discard this patch.
core/Controller/LostController.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -132,7 +132,7 @@
 block discarded – undo
132 132
 	}
133 133
 
134 134
 	/**
135
-	 * @param $message
135
+	 * @param string $message
136 136
 	 * @param array $additional
137 137
 	 * @return array
138 138
 	 */
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
 	 */
168 168
 	protected function checkPasswordResetToken($token, $userId) {
169 169
 		$user = $this->userManager->get($userId);
170
-		if($user === null || !$user->isEnabled()) {
170
+		if ($user === null || !$user->isEnabled()) {
171 171
 			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
172 172
 		}
173 173
 
@@ -180,11 +180,11 @@  discard block
 block discarded – undo
180 180
 		}
181 181
 
182 182
 		$splittedToken = explode(':', $decryptedToken);
183
-		if(count($splittedToken) !== 2) {
183
+		if (count($splittedToken) !== 2) {
184 184
 			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
185 185
 		}
186 186
 
187
-		if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*12) ||
187
+		if ($splittedToken[0] < ($this->timeFactory->getTime() - 60 * 60 * 12) ||
188 188
 			$user->getLastLogin() > $splittedToken[0]) {
189 189
 			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
190 190
 		}
@@ -199,7 +199,7 @@  discard block
 block discarded – undo
199 199
 	 * @param array $additional
200 200
 	 * @return array
201 201
 	 */
202
-	private function error($message, array $additional=array()) {
202
+	private function error($message, array $additional = array()) {
203 203
 		return array_merge(array('status' => 'error', 'msg' => $message), $additional);
204 204
 	}
205 205
 
@@ -218,7 +218,7 @@  discard block
 block discarded – undo
218 218
 	 * @param string $user
219 219
 	 * @return JSONResponse
220 220
 	 */
221
-	public function email($user){
221
+	public function email($user) {
222 222
 		if ($this->config->getSystemValue('lost_password_link', '') !== '') {
223 223
 			return new JSONResponse($this->error($this->l10n->t('Password reset is disabled')));
224 224
 		}
@@ -226,7 +226,7 @@  discard block
 block discarded – undo
226 226
 		// FIXME: use HTTP error codes
227 227
 		try {
228 228
 			$this->sendEmail($user);
229
-		} catch (\Exception $e){
229
+		} catch (\Exception $e) {
230 230
 			$response = new JSONResponse($this->error($e->getMessage()));
231 231
 			$response->throttle();
232 232
 			return $response;
@@ -268,7 +268,7 @@  discard block
 block discarded – undo
268 268
 
269 269
 			$this->config->deleteUserValue($userId, 'core', 'lostpassword');
270 270
 			@\OC::$server->getUserSession()->unsetMagicInCookie();
271
-		} catch (\Exception $e){
271
+		} catch (\Exception $e) {
272 272
 			return $this->error($e->getMessage());
273 273
 		}
274 274
 
@@ -299,8 +299,8 @@  discard block
 block discarded – undo
299 299
 			ISecureRandom::CHAR_LOWER.
300 300
 			ISecureRandom::CHAR_UPPER
301 301
 		);
302
-		$tokenValue = $this->timeFactory->getTime() .':'. $token;
303
-		$encryptedValue = $this->crypto->encrypt($tokenValue, $email . $this->config->getSystemValue('secret'));
302
+		$tokenValue = $this->timeFactory->getTime().':'.$token;
303
+		$encryptedValue = $this->crypto->encrypt($tokenValue, $email.$this->config->getSystemValue('secret'));
304 304
 		$this->config->setUserValue($user->getUID(), 'core', 'lostpassword', $encryptedValue);
305 305
 
306 306
 		$link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user->getUID(), 'token' => $token));
Please login to merge, or discard this patch.
Indentation   +315 added lines, -315 removed lines patch added patch discarded remove patch
@@ -56,319 +56,319 @@
 block discarded – undo
56 56
  */
57 57
 class LostController extends Controller {
58 58
 
59
-	/** @var IURLGenerator */
60
-	protected $urlGenerator;
61
-	/** @var IUserManager */
62
-	protected $userManager;
63
-	/** @var Defaults */
64
-	protected $defaults;
65
-	/** @var IL10N */
66
-	protected $l10n;
67
-	/** @var string */
68
-	protected $from;
69
-	/** @var IManager */
70
-	protected $encryptionManager;
71
-	/** @var IConfig */
72
-	protected $config;
73
-	/** @var ISecureRandom */
74
-	protected $secureRandom;
75
-	/** @var IMailer */
76
-	protected $mailer;
77
-	/** @var ITimeFactory */
78
-	protected $timeFactory;
79
-	/** @var ICrypto */
80
-	protected $crypto;
81
-
82
-	/**
83
-	 * @param string $appName
84
-	 * @param IRequest $request
85
-	 * @param IURLGenerator $urlGenerator
86
-	 * @param IUserManager $userManager
87
-	 * @param Defaults $defaults
88
-	 * @param IL10N $l10n
89
-	 * @param IConfig $config
90
-	 * @param ISecureRandom $secureRandom
91
-	 * @param string $defaultMailAddress
92
-	 * @param IManager $encryptionManager
93
-	 * @param IMailer $mailer
94
-	 * @param ITimeFactory $timeFactory
95
-	 * @param ICrypto $crypto
96
-	 */
97
-	public function __construct($appName,
98
-								IRequest $request,
99
-								IURLGenerator $urlGenerator,
100
-								IUserManager $userManager,
101
-								Defaults $defaults,
102
-								IL10N $l10n,
103
-								IConfig $config,
104
-								ISecureRandom $secureRandom,
105
-								$defaultMailAddress,
106
-								IManager $encryptionManager,
107
-								IMailer $mailer,
108
-								ITimeFactory $timeFactory,
109
-								ICrypto $crypto) {
110
-		parent::__construct($appName, $request);
111
-		$this->urlGenerator = $urlGenerator;
112
-		$this->userManager = $userManager;
113
-		$this->defaults = $defaults;
114
-		$this->l10n = $l10n;
115
-		$this->secureRandom = $secureRandom;
116
-		$this->from = $defaultMailAddress;
117
-		$this->encryptionManager = $encryptionManager;
118
-		$this->config = $config;
119
-		$this->mailer = $mailer;
120
-		$this->timeFactory = $timeFactory;
121
-		$this->crypto = $crypto;
122
-	}
123
-
124
-	/**
125
-	 * Someone wants to reset their password:
126
-	 *
127
-	 * @PublicPage
128
-	 * @NoCSRFRequired
129
-	 *
130
-	 * @param string $token
131
-	 * @param string $userId
132
-	 * @return TemplateResponse
133
-	 */
134
-	public function resetform($token, $userId) {
135
-		if ($this->config->getSystemValue('lost_password_link', '') !== '') {
136
-			return new TemplateResponse('core', 'error', [
137
-					'errors' => [['error' => $this->l10n->t('Password reset is disabled')]]
138
-				],
139
-				'guest'
140
-			);
141
-		}
142
-
143
-		try {
144
-			$this->checkPasswordResetToken($token, $userId);
145
-		} catch (\Exception $e) {
146
-			return new TemplateResponse(
147
-				'core', 'error', [
148
-					"errors" => array(array("error" => $e->getMessage()))
149
-				],
150
-				'guest'
151
-			);
152
-		}
153
-
154
-		return new TemplateResponse(
155
-			'core',
156
-			'lostpassword/resetpassword',
157
-			array(
158
-				'link' => $this->urlGenerator->linkToRouteAbsolute('core.lost.setPassword', array('userId' => $userId, 'token' => $token)),
159
-			),
160
-			'guest'
161
-		);
162
-	}
163
-
164
-	/**
165
-	 * @param string $token
166
-	 * @param string $userId
167
-	 * @throws \Exception
168
-	 */
169
-	protected function checkPasswordResetToken($token, $userId) {
170
-		$user = $this->userManager->get($userId);
171
-		if($user === null || !$user->isEnabled()) {
172
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
173
-		}
174
-
175
-		try {
176
-			$encryptedToken = $this->config->getUserValue($userId, 'core', 'lostpassword', null);
177
-			$mailAddress = !is_null($user->getEMailAddress()) ? $user->getEMailAddress() : '';
178
-			$decryptedToken = $this->crypto->decrypt($encryptedToken, $mailAddress.$this->config->getSystemValue('secret'));
179
-		} catch (\Exception $e) {
180
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
181
-		}
182
-
183
-		$splittedToken = explode(':', $decryptedToken);
184
-		if(count($splittedToken) !== 2) {
185
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
186
-		}
187
-
188
-		if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*12) ||
189
-			$user->getLastLogin() > $splittedToken[0]) {
190
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
191
-		}
192
-
193
-		if (!hash_equals($splittedToken[1], $token)) {
194
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
195
-		}
196
-	}
197
-
198
-	/**
199
-	 * @param $message
200
-	 * @param array $additional
201
-	 * @return array
202
-	 */
203
-	private function error($message, array $additional=array()) {
204
-		return array_merge(array('status' => 'error', 'msg' => $message), $additional);
205
-	}
206
-
207
-	/**
208
-	 * @return array
209
-	 */
210
-	private function success() {
211
-		return array('status'=>'success');
212
-	}
213
-
214
-	/**
215
-	 * @PublicPage
216
-	 * @BruteForceProtection(action=passwordResetEmail)
217
-	 * @AnonRateThrottle(limit=10, period=300)
218
-	 *
219
-	 * @param string $user
220
-	 * @return JSONResponse
221
-	 */
222
-	public function email($user){
223
-		if ($this->config->getSystemValue('lost_password_link', '') !== '') {
224
-			return new JSONResponse($this->error($this->l10n->t('Password reset is disabled')));
225
-		}
226
-
227
-		\OCP\Util::emitHook(
228
-			'\OCA\Files_Sharing\API\Server2Server',
229
-			'preLoginNameUsedAsUserName',
230
-			['uid' => &$user]
231
-		);
232
-
233
-		// FIXME: use HTTP error codes
234
-		try {
235
-			$this->sendEmail($user);
236
-		} catch (\Exception $e){
237
-			$response = new JSONResponse($this->error($e->getMessage()));
238
-			$response->throttle();
239
-			return $response;
240
-		}
241
-
242
-		$response = new JSONResponse($this->success());
243
-		$response->throttle();
244
-		return $response;
245
-	}
246
-
247
-	/**
248
-	 * @PublicPage
249
-	 * @param string $token
250
-	 * @param string $userId
251
-	 * @param string $password
252
-	 * @param boolean $proceed
253
-	 * @return array
254
-	 */
255
-	public function setPassword($token, $userId, $password, $proceed) {
256
-		if ($this->config->getSystemValue('lost_password_link', '') !== '') {
257
-			return $this->error($this->l10n->t('Password reset is disabled'));
258
-		}
259
-
260
-		if ($this->encryptionManager->isEnabled() && !$proceed) {
261
-			return $this->error('', array('encryption' => true));
262
-		}
263
-
264
-		try {
265
-			$this->checkPasswordResetToken($token, $userId);
266
-			$user = $this->userManager->get($userId);
267
-
268
-			\OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'pre_passwordReset', array('uid' => $userId, 'password' => $password));
269
-
270
-			if (!$user->setPassword($password)) {
271
-				throw new \Exception();
272
-			}
273
-
274
-			\OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'post_passwordReset', array('uid' => $userId, 'password' => $password));
275
-
276
-			$this->config->deleteUserValue($userId, 'core', 'lostpassword');
277
-			@\OC::$server->getUserSession()->unsetMagicInCookie();
278
-		} catch (\Exception $e){
279
-			return $this->error($e->getMessage());
280
-		}
281
-
282
-		return $this->success();
283
-	}
284
-
285
-	/**
286
-	 * @param string $input
287
-	 * @throws \Exception
288
-	 */
289
-	protected function sendEmail($input) {
290
-		$user = $this->findUserByIdOrMail($input);
291
-		$email = $user->getEMailAddress();
292
-
293
-		if (empty($email)) {
294
-			throw new \Exception(
295
-				$this->l10n->t('Could not send reset email because there is no email address for this username. Please contact your administrator.')
296
-			);
297
-		}
298
-
299
-		// Generate the token. It is stored encrypted in the database with the
300
-		// secret being the users' email address appended with the system secret.
301
-		// This makes the token automatically invalidate once the user changes
302
-		// their email address.
303
-		$token = $this->secureRandom->generate(
304
-			21,
305
-			ISecureRandom::CHAR_DIGITS.
306
-			ISecureRandom::CHAR_LOWER.
307
-			ISecureRandom::CHAR_UPPER
308
-		);
309
-		$tokenValue = $this->timeFactory->getTime() .':'. $token;
310
-		$encryptedValue = $this->crypto->encrypt($tokenValue, $email . $this->config->getSystemValue('secret'));
311
-		$this->config->setUserValue($user->getUID(), 'core', 'lostpassword', $encryptedValue);
312
-
313
-		$link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user->getUID(), 'token' => $token));
314
-
315
-		$emailTemplate = $this->mailer->createEMailTemplate('core.ResetPassword', [
316
-			'link' => $link,
317
-		]);
318
-
319
-		$emailTemplate->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
320
-		$emailTemplate->addHeader();
321
-		$emailTemplate->addHeading($this->l10n->t('Password reset'));
322
-
323
-		$emailTemplate->addBodyText(
324
-			htmlspecialchars($this->l10n->t('Click the following button to reset your password. If you have not requested the password reset, then ignore this email.')),
325
-			$this->l10n->t('Click the following link to reset your password. If you have not requested the password reset, then ignore this email.')
326
-		);
327
-
328
-		$emailTemplate->addBodyButton(
329
-			htmlspecialchars($this->l10n->t('Reset your password')),
330
-			$link,
331
-			false
332
-		);
333
-		$emailTemplate->addFooter();
334
-
335
-		try {
336
-			$message = $this->mailer->createMessage();
337
-			$message->setTo([$email => $user->getUID()]);
338
-			$message->setFrom([$this->from => $this->defaults->getName()]);
339
-			$message->useTemplate($emailTemplate);
340
-			$this->mailer->send($message);
341
-		} catch (\Exception $e) {
342
-			throw new \Exception($this->l10n->t(
343
-				'Couldn\'t send reset email. Please contact your administrator.'
344
-			));
345
-		}
346
-	}
347
-
348
-	/**
349
-	 * @param string $input
350
-	 * @return IUser
351
-	 * @throws \InvalidArgumentException
352
-	 */
353
-	protected function findUserByIdOrMail($input) {
354
-		$user = $this->userManager->get($input);
355
-		if ($user instanceof IUser) {
356
-			if (!$user->isEnabled()) {
357
-				throw new \InvalidArgumentException($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
358
-			}
359
-
360
-			return $user;
361
-		}
362
-		$users = $this->userManager->getByEmail($input);
363
-		if (count($users) === 1) {
364
-			$user = $users[0];
365
-			if (!$user->isEnabled()) {
366
-				throw new \InvalidArgumentException($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
367
-			}
368
-
369
-			return $user;
370
-		}
371
-
372
-		throw new \InvalidArgumentException($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
373
-	}
59
+    /** @var IURLGenerator */
60
+    protected $urlGenerator;
61
+    /** @var IUserManager */
62
+    protected $userManager;
63
+    /** @var Defaults */
64
+    protected $defaults;
65
+    /** @var IL10N */
66
+    protected $l10n;
67
+    /** @var string */
68
+    protected $from;
69
+    /** @var IManager */
70
+    protected $encryptionManager;
71
+    /** @var IConfig */
72
+    protected $config;
73
+    /** @var ISecureRandom */
74
+    protected $secureRandom;
75
+    /** @var IMailer */
76
+    protected $mailer;
77
+    /** @var ITimeFactory */
78
+    protected $timeFactory;
79
+    /** @var ICrypto */
80
+    protected $crypto;
81
+
82
+    /**
83
+     * @param string $appName
84
+     * @param IRequest $request
85
+     * @param IURLGenerator $urlGenerator
86
+     * @param IUserManager $userManager
87
+     * @param Defaults $defaults
88
+     * @param IL10N $l10n
89
+     * @param IConfig $config
90
+     * @param ISecureRandom $secureRandom
91
+     * @param string $defaultMailAddress
92
+     * @param IManager $encryptionManager
93
+     * @param IMailer $mailer
94
+     * @param ITimeFactory $timeFactory
95
+     * @param ICrypto $crypto
96
+     */
97
+    public function __construct($appName,
98
+                                IRequest $request,
99
+                                IURLGenerator $urlGenerator,
100
+                                IUserManager $userManager,
101
+                                Defaults $defaults,
102
+                                IL10N $l10n,
103
+                                IConfig $config,
104
+                                ISecureRandom $secureRandom,
105
+                                $defaultMailAddress,
106
+                                IManager $encryptionManager,
107
+                                IMailer $mailer,
108
+                                ITimeFactory $timeFactory,
109
+                                ICrypto $crypto) {
110
+        parent::__construct($appName, $request);
111
+        $this->urlGenerator = $urlGenerator;
112
+        $this->userManager = $userManager;
113
+        $this->defaults = $defaults;
114
+        $this->l10n = $l10n;
115
+        $this->secureRandom = $secureRandom;
116
+        $this->from = $defaultMailAddress;
117
+        $this->encryptionManager = $encryptionManager;
118
+        $this->config = $config;
119
+        $this->mailer = $mailer;
120
+        $this->timeFactory = $timeFactory;
121
+        $this->crypto = $crypto;
122
+    }
123
+
124
+    /**
125
+     * Someone wants to reset their password:
126
+     *
127
+     * @PublicPage
128
+     * @NoCSRFRequired
129
+     *
130
+     * @param string $token
131
+     * @param string $userId
132
+     * @return TemplateResponse
133
+     */
134
+    public function resetform($token, $userId) {
135
+        if ($this->config->getSystemValue('lost_password_link', '') !== '') {
136
+            return new TemplateResponse('core', 'error', [
137
+                    'errors' => [['error' => $this->l10n->t('Password reset is disabled')]]
138
+                ],
139
+                'guest'
140
+            );
141
+        }
142
+
143
+        try {
144
+            $this->checkPasswordResetToken($token, $userId);
145
+        } catch (\Exception $e) {
146
+            return new TemplateResponse(
147
+                'core', 'error', [
148
+                    "errors" => array(array("error" => $e->getMessage()))
149
+                ],
150
+                'guest'
151
+            );
152
+        }
153
+
154
+        return new TemplateResponse(
155
+            'core',
156
+            'lostpassword/resetpassword',
157
+            array(
158
+                'link' => $this->urlGenerator->linkToRouteAbsolute('core.lost.setPassword', array('userId' => $userId, 'token' => $token)),
159
+            ),
160
+            'guest'
161
+        );
162
+    }
163
+
164
+    /**
165
+     * @param string $token
166
+     * @param string $userId
167
+     * @throws \Exception
168
+     */
169
+    protected function checkPasswordResetToken($token, $userId) {
170
+        $user = $this->userManager->get($userId);
171
+        if($user === null || !$user->isEnabled()) {
172
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
173
+        }
174
+
175
+        try {
176
+            $encryptedToken = $this->config->getUserValue($userId, 'core', 'lostpassword', null);
177
+            $mailAddress = !is_null($user->getEMailAddress()) ? $user->getEMailAddress() : '';
178
+            $decryptedToken = $this->crypto->decrypt($encryptedToken, $mailAddress.$this->config->getSystemValue('secret'));
179
+        } catch (\Exception $e) {
180
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
181
+        }
182
+
183
+        $splittedToken = explode(':', $decryptedToken);
184
+        if(count($splittedToken) !== 2) {
185
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
186
+        }
187
+
188
+        if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*12) ||
189
+            $user->getLastLogin() > $splittedToken[0]) {
190
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
191
+        }
192
+
193
+        if (!hash_equals($splittedToken[1], $token)) {
194
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
195
+        }
196
+    }
197
+
198
+    /**
199
+     * @param $message
200
+     * @param array $additional
201
+     * @return array
202
+     */
203
+    private function error($message, array $additional=array()) {
204
+        return array_merge(array('status' => 'error', 'msg' => $message), $additional);
205
+    }
206
+
207
+    /**
208
+     * @return array
209
+     */
210
+    private function success() {
211
+        return array('status'=>'success');
212
+    }
213
+
214
+    /**
215
+     * @PublicPage
216
+     * @BruteForceProtection(action=passwordResetEmail)
217
+     * @AnonRateThrottle(limit=10, period=300)
218
+     *
219
+     * @param string $user
220
+     * @return JSONResponse
221
+     */
222
+    public function email($user){
223
+        if ($this->config->getSystemValue('lost_password_link', '') !== '') {
224
+            return new JSONResponse($this->error($this->l10n->t('Password reset is disabled')));
225
+        }
226
+
227
+        \OCP\Util::emitHook(
228
+            '\OCA\Files_Sharing\API\Server2Server',
229
+            'preLoginNameUsedAsUserName',
230
+            ['uid' => &$user]
231
+        );
232
+
233
+        // FIXME: use HTTP error codes
234
+        try {
235
+            $this->sendEmail($user);
236
+        } catch (\Exception $e){
237
+            $response = new JSONResponse($this->error($e->getMessage()));
238
+            $response->throttle();
239
+            return $response;
240
+        }
241
+
242
+        $response = new JSONResponse($this->success());
243
+        $response->throttle();
244
+        return $response;
245
+    }
246
+
247
+    /**
248
+     * @PublicPage
249
+     * @param string $token
250
+     * @param string $userId
251
+     * @param string $password
252
+     * @param boolean $proceed
253
+     * @return array
254
+     */
255
+    public function setPassword($token, $userId, $password, $proceed) {
256
+        if ($this->config->getSystemValue('lost_password_link', '') !== '') {
257
+            return $this->error($this->l10n->t('Password reset is disabled'));
258
+        }
259
+
260
+        if ($this->encryptionManager->isEnabled() && !$proceed) {
261
+            return $this->error('', array('encryption' => true));
262
+        }
263
+
264
+        try {
265
+            $this->checkPasswordResetToken($token, $userId);
266
+            $user = $this->userManager->get($userId);
267
+
268
+            \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'pre_passwordReset', array('uid' => $userId, 'password' => $password));
269
+
270
+            if (!$user->setPassword($password)) {
271
+                throw new \Exception();
272
+            }
273
+
274
+            \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'post_passwordReset', array('uid' => $userId, 'password' => $password));
275
+
276
+            $this->config->deleteUserValue($userId, 'core', 'lostpassword');
277
+            @\OC::$server->getUserSession()->unsetMagicInCookie();
278
+        } catch (\Exception $e){
279
+            return $this->error($e->getMessage());
280
+        }
281
+
282
+        return $this->success();
283
+    }
284
+
285
+    /**
286
+     * @param string $input
287
+     * @throws \Exception
288
+     */
289
+    protected function sendEmail($input) {
290
+        $user = $this->findUserByIdOrMail($input);
291
+        $email = $user->getEMailAddress();
292
+
293
+        if (empty($email)) {
294
+            throw new \Exception(
295
+                $this->l10n->t('Could not send reset email because there is no email address for this username. Please contact your administrator.')
296
+            );
297
+        }
298
+
299
+        // Generate the token. It is stored encrypted in the database with the
300
+        // secret being the users' email address appended with the system secret.
301
+        // This makes the token automatically invalidate once the user changes
302
+        // their email address.
303
+        $token = $this->secureRandom->generate(
304
+            21,
305
+            ISecureRandom::CHAR_DIGITS.
306
+            ISecureRandom::CHAR_LOWER.
307
+            ISecureRandom::CHAR_UPPER
308
+        );
309
+        $tokenValue = $this->timeFactory->getTime() .':'. $token;
310
+        $encryptedValue = $this->crypto->encrypt($tokenValue, $email . $this->config->getSystemValue('secret'));
311
+        $this->config->setUserValue($user->getUID(), 'core', 'lostpassword', $encryptedValue);
312
+
313
+        $link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user->getUID(), 'token' => $token));
314
+
315
+        $emailTemplate = $this->mailer->createEMailTemplate('core.ResetPassword', [
316
+            'link' => $link,
317
+        ]);
318
+
319
+        $emailTemplate->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
320
+        $emailTemplate->addHeader();
321
+        $emailTemplate->addHeading($this->l10n->t('Password reset'));
322
+
323
+        $emailTemplate->addBodyText(
324
+            htmlspecialchars($this->l10n->t('Click the following button to reset your password. If you have not requested the password reset, then ignore this email.')),
325
+            $this->l10n->t('Click the following link to reset your password. If you have not requested the password reset, then ignore this email.')
326
+        );
327
+
328
+        $emailTemplate->addBodyButton(
329
+            htmlspecialchars($this->l10n->t('Reset your password')),
330
+            $link,
331
+            false
332
+        );
333
+        $emailTemplate->addFooter();
334
+
335
+        try {
336
+            $message = $this->mailer->createMessage();
337
+            $message->setTo([$email => $user->getUID()]);
338
+            $message->setFrom([$this->from => $this->defaults->getName()]);
339
+            $message->useTemplate($emailTemplate);
340
+            $this->mailer->send($message);
341
+        } catch (\Exception $e) {
342
+            throw new \Exception($this->l10n->t(
343
+                'Couldn\'t send reset email. Please contact your administrator.'
344
+            ));
345
+        }
346
+    }
347
+
348
+    /**
349
+     * @param string $input
350
+     * @return IUser
351
+     * @throws \InvalidArgumentException
352
+     */
353
+    protected function findUserByIdOrMail($input) {
354
+        $user = $this->userManager->get($input);
355
+        if ($user instanceof IUser) {
356
+            if (!$user->isEnabled()) {
357
+                throw new \InvalidArgumentException($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
358
+            }
359
+
360
+            return $user;
361
+        }
362
+        $users = $this->userManager->getByEmail($input);
363
+        if (count($users) === 1) {
364
+            $user = $users[0];
365
+            if (!$user->isEnabled()) {
366
+                throw new \InvalidArgumentException($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
367
+            }
368
+
369
+            return $user;
370
+        }
371
+
372
+        throw new \InvalidArgumentException($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
373
+    }
374 374
 }
Please login to merge, or discard this patch.
lib/private/AppFramework/OCS/BaseResponse.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@
 block discarded – undo
24 24
 	/**
25 25
 	 * BaseResponse constructor.
26 26
 	 *
27
-	 * @param DataResponse|null $dataResponse
27
+	 * @param DataResponse $dataResponse
28 28
 	 * @param string $format
29 29
 	 * @param string|null $statusMessage
30 30
 	 * @param int|null $itemsCount
Please login to merge, or discard this patch.
Indentation   +56 added lines, -56 removed lines patch added patch discarded remove patch
@@ -27,70 +27,70 @@
 block discarded – undo
27 27
 use OCP\AppFramework\Http\Response;
28 28
 
29 29
 abstract class BaseResponse extends Response   {
30
-	/** @var array */
31
-	protected $data;
30
+    /** @var array */
31
+    protected $data;
32 32
 
33
-	/** @var string */
34
-	protected $format;
33
+    /** @var string */
34
+    protected $format;
35 35
 
36
-	/** @var string */
37
-	protected $statusMessage;
36
+    /** @var string */
37
+    protected $statusMessage;
38 38
 
39
-	/** @var int */
40
-	protected $itemsCount;
39
+    /** @var int */
40
+    protected $itemsCount;
41 41
 
42
-	/** @var int */
43
-	protected $itemsPerPage;
42
+    /** @var int */
43
+    protected $itemsPerPage;
44 44
 
45
-	/**
46
-	 * BaseResponse constructor.
47
-	 *
48
-	 * @param DataResponse|null $dataResponse
49
-	 * @param string $format
50
-	 * @param string|null $statusMessage
51
-	 * @param int|null $itemsCount
52
-	 * @param int|null $itemsPerPage
53
-	 */
54
-	public function __construct(DataResponse $dataResponse,
55
-								$format = 'xml',
56
-								$statusMessage = null,
57
-								$itemsCount = null,
58
-								$itemsPerPage = null) {
59
-		$this->format = $format;
60
-		$this->statusMessage = $statusMessage;
61
-		$this->itemsCount = $itemsCount;
62
-		$this->itemsPerPage = $itemsPerPage;
45
+    /**
46
+     * BaseResponse constructor.
47
+     *
48
+     * @param DataResponse|null $dataResponse
49
+     * @param string $format
50
+     * @param string|null $statusMessage
51
+     * @param int|null $itemsCount
52
+     * @param int|null $itemsPerPage
53
+     */
54
+    public function __construct(DataResponse $dataResponse,
55
+                                $format = 'xml',
56
+                                $statusMessage = null,
57
+                                $itemsCount = null,
58
+                                $itemsPerPage = null) {
59
+        $this->format = $format;
60
+        $this->statusMessage = $statusMessage;
61
+        $this->itemsCount = $itemsCount;
62
+        $this->itemsPerPage = $itemsPerPage;
63 63
 
64
-		$this->data = $dataResponse->getData();
64
+        $this->data = $dataResponse->getData();
65 65
 
66
-		$this->setHeaders($dataResponse->getHeaders());
67
-		$this->setStatus($dataResponse->getStatus());
68
-		$this->setETag($dataResponse->getETag());
69
-		$this->setLastModified($dataResponse->getLastModified());
70
-		$this->setCookies($dataResponse->getCookies());
71
-		$this->setContentSecurityPolicy(new EmptyContentSecurityPolicy());
66
+        $this->setHeaders($dataResponse->getHeaders());
67
+        $this->setStatus($dataResponse->getStatus());
68
+        $this->setETag($dataResponse->getETag());
69
+        $this->setLastModified($dataResponse->getLastModified());
70
+        $this->setCookies($dataResponse->getCookies());
71
+        $this->setContentSecurityPolicy(new EmptyContentSecurityPolicy());
72 72
 
73
-		if ($format === 'json') {
74
-			$this->addHeader(
75
-				'Content-Type', 'application/json; charset=utf-8'
76
-			);
77
-		} else {
78
-			$this->addHeader(
79
-				'Content-Type', 'application/xml; charset=utf-8'
80
-			);
81
-		}
82
-	}
73
+        if ($format === 'json') {
74
+            $this->addHeader(
75
+                'Content-Type', 'application/json; charset=utf-8'
76
+            );
77
+        } else {
78
+            $this->addHeader(
79
+                'Content-Type', 'application/xml; charset=utf-8'
80
+            );
81
+        }
82
+    }
83 83
 
84
-	/**
85
-	 * @param string[] $meta
86
-	 * @return string
87
-	 */
88
-	protected function renderResult($meta) {
89
-		// TODO rewrite functions
90
-		return \OC_API::renderResult($this->format, $meta, $this->data);
91
-	}
84
+    /**
85
+     * @param string[] $meta
86
+     * @return string
87
+     */
88
+    protected function renderResult($meta) {
89
+        // TODO rewrite functions
90
+        return \OC_API::renderResult($this->format, $meta, $this->data);
91
+    }
92 92
 
93
-	public function getOCSStatus() {
94
-		return parent::getStatus();
95
-	}
93
+    public function getOCSStatus() {
94
+        return parent::getStatus();
95
+    }
96 96
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -26,7 +26,7 @@
 block discarded – undo
26 26
 use OCP\AppFramework\Http\EmptyContentSecurityPolicy;
27 27
 use OCP\AppFramework\Http\Response;
28 28
 
29
-abstract class BaseResponse extends Response   {
29
+abstract class BaseResponse extends Response {
30 30
 	/** @var array */
31 31
 	protected $data;
32 32
 
Please login to merge, or discard this patch.
lib/private/Server.php 4 patches
Doc Comments   +2 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1143,7 +1143,7 @@  discard block
 block discarded – undo
1143 1143
 	 * Get the certificate manager for the user
1144 1144
 	 *
1145 1145
 	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1146
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1146
+	 * @return null|CertificateManager | null if $uid is null and no user is logged in
1147 1147
 	 */
1148 1148
 	public function getCertificateManager($userId = '') {
1149 1149
 		if ($userId === '') {
@@ -1464,6 +1464,7 @@  discard block
 block discarded – undo
1464 1464
 	}
1465 1465
 
1466 1466
 	/**
1467
+	 * @param string $app
1467 1468
 	 * @return \OCP\Files\IAppData
1468 1469
 	 */
1469 1470
 	public function getAppDataDir($app) {
Please login to merge, or discard this patch.
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -115,7 +115,6 @@
 block discarded – undo
115 115
 use OC\Template\JSCombiner;
116 116
 use OC\Template\SCSSCacher;
117 117
 use OCA\Theming\ThemingDefaults;
118
-
119 118
 use OCP\App\IAppManager;
120 119
 use OCP\AppFramework\Utility\ITimeFactory;
121 120
 use OCP\Collaboration\AutoComplete\IManager;
Please login to merge, or discard this patch.
Indentation   +1807 added lines, -1807 removed lines patch added patch discarded remove patch
@@ -150,1816 +150,1816 @@
 block discarded – undo
150 150
  * TODO: hookup all manager classes
151 151
  */
152 152
 class Server extends ServerContainer implements IServerContainer {
153
-	/** @var string */
154
-	private $webRoot;
155
-
156
-	/**
157
-	 * @param string $webRoot
158
-	 * @param \OC\Config $config
159
-	 */
160
-	public function __construct($webRoot, \OC\Config $config) {
161
-		parent::__construct();
162
-		$this->webRoot = $webRoot;
163
-
164
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
165
-			return $c;
166
-		});
167
-
168
-		$this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
169
-		$this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
170
-
171
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
172
-		$this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
173
-
174
-		$this->registerAlias(IActionFactory::class, ActionFactory::class);
175
-
176
-
177
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
178
-			return new PreviewManager(
179
-				$c->getConfig(),
180
-				$c->getRootFolder(),
181
-				$c->getAppDataDir('preview'),
182
-				$c->getEventDispatcher(),
183
-				$c->getSession()->get('user_id')
184
-			);
185
-		});
186
-		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
187
-
188
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
189
-			return new \OC\Preview\Watcher(
190
-				$c->getAppDataDir('preview')
191
-			);
192
-		});
193
-
194
-		$this->registerService('EncryptionManager', function (Server $c) {
195
-			$view = new View();
196
-			$util = new Encryption\Util(
197
-				$view,
198
-				$c->getUserManager(),
199
-				$c->getGroupManager(),
200
-				$c->getConfig()
201
-			);
202
-			return new Encryption\Manager(
203
-				$c->getConfig(),
204
-				$c->getLogger(),
205
-				$c->getL10N('core'),
206
-				new View(),
207
-				$util,
208
-				new ArrayCache()
209
-			);
210
-		});
211
-
212
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
213
-			$util = new Encryption\Util(
214
-				new View(),
215
-				$c->getUserManager(),
216
-				$c->getGroupManager(),
217
-				$c->getConfig()
218
-			);
219
-			return new Encryption\File(
220
-				$util,
221
-				$c->getRootFolder(),
222
-				$c->getShareManager()
223
-			);
224
-		});
225
-
226
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
227
-			$view = new View();
228
-			$util = new Encryption\Util(
229
-				$view,
230
-				$c->getUserManager(),
231
-				$c->getGroupManager(),
232
-				$c->getConfig()
233
-			);
234
-
235
-			return new Encryption\Keys\Storage($view, $util);
236
-		});
237
-		$this->registerService('TagMapper', function (Server $c) {
238
-			return new TagMapper($c->getDatabaseConnection());
239
-		});
240
-
241
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
242
-			$tagMapper = $c->query('TagMapper');
243
-			return new TagManager($tagMapper, $c->getUserSession());
244
-		});
245
-		$this->registerAlias('TagManager', \OCP\ITagManager::class);
246
-
247
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
248
-			$config = $c->getConfig();
249
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
250
-			return new $factoryClass($this);
251
-		});
252
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
253
-			return $c->query('SystemTagManagerFactory')->getManager();
254
-		});
255
-		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
256
-
257
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
258
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
259
-		});
260
-		$this->registerService('RootFolder', function (Server $c) {
261
-			$manager = \OC\Files\Filesystem::getMountManager(null);
262
-			$view = new View();
263
-			$root = new Root(
264
-				$manager,
265
-				$view,
266
-				null,
267
-				$c->getUserMountCache(),
268
-				$this->getLogger(),
269
-				$this->getUserManager()
270
-			);
271
-			$connector = new HookConnector($root, $view);
272
-			$connector->viewToNode();
273
-
274
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
275
-			$previewConnector->connectWatcher();
276
-
277
-			return $root;
278
-		});
279
-		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
280
-
281
-		$this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
282
-			return new LazyRoot(function () use ($c) {
283
-				return $c->query('RootFolder');
284
-			});
285
-		});
286
-		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
287
-
288
-		$this->registerService(\OC\User\Manager::class, function (Server $c) {
289
-			$config = $c->getConfig();
290
-			return new \OC\User\Manager($config);
291
-		});
292
-		$this->registerAlias('UserManager', \OC\User\Manager::class);
293
-		$this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
294
-
295
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
296
-			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
297
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
298
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
299
-			});
300
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
301
-				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
302
-			});
303
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
304
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
305
-			});
306
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
307
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
308
-			});
309
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
310
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
311
-			});
312
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
313
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
314
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
315
-				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
316
-			});
317
-			return $groupManager;
318
-		});
319
-		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
320
-
321
-		$this->registerService(Store::class, function (Server $c) {
322
-			$session = $c->getSession();
323
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
324
-				$tokenProvider = $c->query(IProvider::class);
325
-			} else {
326
-				$tokenProvider = null;
327
-			}
328
-			$logger = $c->getLogger();
329
-			return new Store($session, $logger, $tokenProvider);
330
-		});
331
-		$this->registerAlias(IStore::class, Store::class);
332
-		$this->registerService(Authentication\Token\DefaultTokenMapper::class, function (Server $c) {
333
-			$dbConnection = $c->getDatabaseConnection();
334
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
335
-		});
336
-		$this->registerService(Authentication\Token\DefaultTokenProvider::class, function (Server $c) {
337
-			$mapper = $c->query(Authentication\Token\DefaultTokenMapper::class);
338
-			$crypto = $c->getCrypto();
339
-			$config = $c->getConfig();
340
-			$logger = $c->getLogger();
341
-			$timeFactory = new TimeFactory();
342
-			return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
343
-		});
344
-		$this->registerAlias(IProvider::class, Authentication\Token\DefaultTokenProvider::class);
345
-
346
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
347
-			$manager = $c->getUserManager();
348
-			$session = new \OC\Session\Memory('');
349
-			$timeFactory = new TimeFactory();
350
-			// Token providers might require a working database. This code
351
-			// might however be called when ownCloud is not yet setup.
352
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
353
-				$defaultTokenProvider = $c->query(IProvider::class);
354
-			} else {
355
-				$defaultTokenProvider = null;
356
-			}
357
-
358
-			$dispatcher = $c->getEventDispatcher();
359
-
360
-			$userSession = new \OC\User\Session(
361
-				$manager,
362
-				$session,
363
-				$timeFactory,
364
-				$defaultTokenProvider,
365
-				$c->getConfig(),
366
-				$c->getSecureRandom(),
367
-				$c->getLockdownManager(),
368
-				$c->getLogger()
369
-			);
370
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
371
-				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
372
-			});
373
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
374
-				/** @var $user \OC\User\User */
375
-				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
376
-			});
377
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
378
-				/** @var $user \OC\User\User */
379
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
380
-				$dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
381
-			});
382
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
383
-				/** @var $user \OC\User\User */
384
-				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
385
-			});
386
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
387
-				/** @var $user \OC\User\User */
388
-				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
389
-			});
390
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
391
-				/** @var $user \OC\User\User */
392
-				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
393
-			});
394
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
395
-				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
396
-			});
397
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
398
-				/** @var $user \OC\User\User */
399
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
400
-			});
401
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
402
-				/** @var $user \OC\User\User */
403
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
404
-			});
405
-			$userSession->listen('\OC\User', 'logout', function () {
406
-				\OC_Hook::emit('OC_User', 'logout', array());
407
-			});
408
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
409
-				/** @var $user \OC\User\User */
410
-				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
411
-				$dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
412
-			});
413
-			return $userSession;
414
-		});
415
-		$this->registerAlias('UserSession', \OCP\IUserSession::class);
416
-
417
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
418
-			return new \OC\Authentication\TwoFactorAuth\Manager(
419
-				$c->getAppManager(),
420
-				$c->getSession(),
421
-				$c->getConfig(),
422
-				$c->getActivityManager(),
423
-				$c->getLogger(),
424
-				$c->query(IProvider::class),
425
-				$c->query(ITimeFactory::class),
426
-				$c->query(EventDispatcherInterface::class)
427
-			);
428
-		});
429
-
430
-		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
431
-		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
432
-
433
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
434
-			return new \OC\AllConfig(
435
-				$c->getSystemConfig()
436
-			);
437
-		});
438
-		$this->registerAlias('AllConfig', \OC\AllConfig::class);
439
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
440
-
441
-		$this->registerService('SystemConfig', function ($c) use ($config) {
442
-			return new \OC\SystemConfig($config);
443
-		});
444
-
445
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
446
-			return new \OC\AppConfig($c->getDatabaseConnection());
447
-		});
448
-		$this->registerAlias('AppConfig', \OC\AppConfig::class);
449
-		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
450
-
451
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
452
-			return new \OC\L10N\Factory(
453
-				$c->getConfig(),
454
-				$c->getRequest(),
455
-				$c->getUserSession(),
456
-				\OC::$SERVERROOT
457
-			);
458
-		});
459
-		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
460
-
461
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
462
-			$config = $c->getConfig();
463
-			$cacheFactory = $c->getMemCacheFactory();
464
-			$request = $c->getRequest();
465
-			return new \OC\URLGenerator(
466
-				$config,
467
-				$cacheFactory,
468
-				$request
469
-			);
470
-		});
471
-		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
472
-
473
-		$this->registerAlias('AppFetcher', AppFetcher::class);
474
-		$this->registerAlias('CategoryFetcher', CategoryFetcher::class);
475
-
476
-		$this->registerService(\OCP\ICache::class, function ($c) {
477
-			return new Cache\File();
478
-		});
479
-		$this->registerAlias('UserCache', \OCP\ICache::class);
480
-
481
-		$this->registerService(Factory::class, function (Server $c) {
482
-
483
-			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
484
-				ArrayCache::class,
485
-				ArrayCache::class,
486
-				ArrayCache::class
487
-			);
488
-			$config = $c->getConfig();
489
-			$request = $c->getRequest();
490
-			$urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
491
-
492
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
493
-				$v = \OC_App::getAppVersions();
494
-				$v['core'] = implode(',', \OC_Util::getVersion());
495
-				$version = implode(',', $v);
496
-				$instanceId = \OC_Util::getInstanceId();
497
-				$path = \OC::$SERVERROOT;
498
-				$prefix = md5($instanceId . '-' . $version . '-' . $path);
499
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
500
-					$config->getSystemValue('memcache.local', null),
501
-					$config->getSystemValue('memcache.distributed', null),
502
-					$config->getSystemValue('memcache.locking', null)
503
-				);
504
-			}
505
-			return $arrayCacheFactory;
506
-
507
-		});
508
-		$this->registerAlias('MemCacheFactory', Factory::class);
509
-		$this->registerAlias(ICacheFactory::class, Factory::class);
510
-
511
-		$this->registerService('RedisFactory', function (Server $c) {
512
-			$systemConfig = $c->getSystemConfig();
513
-			return new RedisFactory($systemConfig);
514
-		});
515
-
516
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
517
-			return new \OC\Activity\Manager(
518
-				$c->getRequest(),
519
-				$c->getUserSession(),
520
-				$c->getConfig(),
521
-				$c->query(IValidator::class)
522
-			);
523
-		});
524
-		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
525
-
526
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
527
-			return new \OC\Activity\EventMerger(
528
-				$c->getL10N('lib')
529
-			);
530
-		});
531
-		$this->registerAlias(IValidator::class, Validator::class);
532
-
533
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
534
-			return new AvatarManager(
535
-				$c->query(\OC\User\Manager::class),
536
-				$c->getAppDataDir('avatar'),
537
-				$c->getL10N('lib'),
538
-				$c->getLogger(),
539
-				$c->getConfig()
540
-			);
541
-		});
542
-		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
543
-
544
-		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
545
-
546
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
547
-			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
548
-			$logger = Log::getLogClass($logType);
549
-			call_user_func(array($logger, 'init'));
550
-			$config = $this->getSystemConfig();
551
-			$registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
552
-
553
-			return new Log($logger, $config, null, $registry);
554
-		});
555
-		$this->registerAlias('Logger', \OCP\ILogger::class);
556
-
557
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
558
-			$config = $c->getConfig();
559
-			return new \OC\BackgroundJob\JobList(
560
-				$c->getDatabaseConnection(),
561
-				$config,
562
-				new TimeFactory()
563
-			);
564
-		});
565
-		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
566
-
567
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
568
-			$cacheFactory = $c->getMemCacheFactory();
569
-			$logger = $c->getLogger();
570
-			if ($cacheFactory->isLocalCacheAvailable()) {
571
-				$router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
572
-			} else {
573
-				$router = new \OC\Route\Router($logger);
574
-			}
575
-			return $router;
576
-		});
577
-		$this->registerAlias('Router', \OCP\Route\IRouter::class);
578
-
579
-		$this->registerService(\OCP\ISearch::class, function ($c) {
580
-			return new Search();
581
-		});
582
-		$this->registerAlias('Search', \OCP\ISearch::class);
583
-
584
-		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function (Server $c) {
585
-			return new \OC\Security\RateLimiting\Limiter(
586
-				$this->getUserSession(),
587
-				$this->getRequest(),
588
-				new \OC\AppFramework\Utility\TimeFactory(),
589
-				$c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
590
-			);
591
-		});
592
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
593
-			return new \OC\Security\RateLimiting\Backend\MemoryCache(
594
-				$this->getMemCacheFactory(),
595
-				new \OC\AppFramework\Utility\TimeFactory()
596
-			);
597
-		});
598
-
599
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
600
-			return new SecureRandom();
601
-		});
602
-		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
603
-
604
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
605
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
606
-		});
607
-		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
608
-
609
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
610
-			return new Hasher($c->getConfig());
611
-		});
612
-		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
613
-
614
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
615
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
616
-		});
617
-		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
618
-
619
-		$this->registerService(IDBConnection::class, function (Server $c) {
620
-			$systemConfig = $c->getSystemConfig();
621
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
622
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
623
-			if (!$factory->isValidType($type)) {
624
-				throw new \OC\DatabaseException('Invalid database type');
625
-			}
626
-			$connectionParams = $factory->createConnectionParams();
627
-			$connection = $factory->getConnection($type, $connectionParams);
628
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
629
-			return $connection;
630
-		});
631
-		$this->registerAlias('DatabaseConnection', IDBConnection::class);
632
-
633
-
634
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
635
-			$user = \OC_User::getUser();
636
-			$uid = $user ? $user : null;
637
-			return new ClientService(
638
-				$c->getConfig(),
639
-				new \OC\Security\CertificateManager(
640
-					$uid,
641
-					new View(),
642
-					$c->getConfig(),
643
-					$c->getLogger(),
644
-					$c->getSecureRandom()
645
-				)
646
-			);
647
-		});
648
-		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
649
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
650
-			$eventLogger = new EventLogger();
651
-			if ($c->getSystemConfig()->getValue('debug', false)) {
652
-				// In debug mode, module is being activated by default
653
-				$eventLogger->activate();
654
-			}
655
-			return $eventLogger;
656
-		});
657
-		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
658
-
659
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
660
-			$queryLogger = new QueryLogger();
661
-			if ($c->getSystemConfig()->getValue('debug', false)) {
662
-				// In debug mode, module is being activated by default
663
-				$queryLogger->activate();
664
-			}
665
-			return $queryLogger;
666
-		});
667
-		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
668
-
669
-		$this->registerService(TempManager::class, function (Server $c) {
670
-			return new TempManager(
671
-				$c->getLogger(),
672
-				$c->getConfig()
673
-			);
674
-		});
675
-		$this->registerAlias('TempManager', TempManager::class);
676
-		$this->registerAlias(ITempManager::class, TempManager::class);
677
-
678
-		$this->registerService(AppManager::class, function (Server $c) {
679
-			return new \OC\App\AppManager(
680
-				$c->getUserSession(),
681
-				$c->query(\OC\AppConfig::class),
682
-				$c->getGroupManager(),
683
-				$c->getMemCacheFactory(),
684
-				$c->getEventDispatcher()
685
-			);
686
-		});
687
-		$this->registerAlias('AppManager', AppManager::class);
688
-		$this->registerAlias(IAppManager::class, AppManager::class);
689
-
690
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
691
-			return new DateTimeZone(
692
-				$c->getConfig(),
693
-				$c->getSession()
694
-			);
695
-		});
696
-		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
697
-
698
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
699
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
700
-
701
-			return new DateTimeFormatter(
702
-				$c->getDateTimeZone()->getTimeZone(),
703
-				$c->getL10N('lib', $language)
704
-			);
705
-		});
706
-		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
707
-
708
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
709
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
710
-			$listener = new UserMountCacheListener($mountCache);
711
-			$listener->listen($c->getUserManager());
712
-			return $mountCache;
713
-		});
714
-		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
715
-
716
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
717
-			$loader = \OC\Files\Filesystem::getLoader();
718
-			$mountCache = $c->query('UserMountCache');
719
-			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
720
-
721
-			// builtin providers
722
-
723
-			$config = $c->getConfig();
724
-			$manager->registerProvider(new CacheMountProvider($config));
725
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
726
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
727
-
728
-			return $manager;
729
-		});
730
-		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
731
-
732
-		$this->registerService('IniWrapper', function ($c) {
733
-			return new IniGetWrapper();
734
-		});
735
-		$this->registerService('AsyncCommandBus', function (Server $c) {
736
-			$busClass = $c->getConfig()->getSystemValue('commandbus');
737
-			if ($busClass) {
738
-				list($app, $class) = explode('::', $busClass, 2);
739
-				if ($c->getAppManager()->isInstalled($app)) {
740
-					\OC_App::loadApp($app);
741
-					return $c->query($class);
742
-				} else {
743
-					throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
744
-				}
745
-			} else {
746
-				$jobList = $c->getJobList();
747
-				return new CronBus($jobList);
748
-			}
749
-		});
750
-		$this->registerService('TrustedDomainHelper', function ($c) {
751
-			return new TrustedDomainHelper($this->getConfig());
752
-		});
753
-		$this->registerService('Throttler', function (Server $c) {
754
-			return new Throttler(
755
-				$c->getDatabaseConnection(),
756
-				new TimeFactory(),
757
-				$c->getLogger(),
758
-				$c->getConfig()
759
-			);
760
-		});
761
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
762
-			// IConfig and IAppManager requires a working database. This code
763
-			// might however be called when ownCloud is not yet setup.
764
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
765
-				$config = $c->getConfig();
766
-				$appManager = $c->getAppManager();
767
-			} else {
768
-				$config = null;
769
-				$appManager = null;
770
-			}
771
-
772
-			return new Checker(
773
-				new EnvironmentHelper(),
774
-				new FileAccessHelper(),
775
-				new AppLocator(),
776
-				$config,
777
-				$c->getMemCacheFactory(),
778
-				$appManager,
779
-				$c->getTempManager()
780
-			);
781
-		});
782
-		$this->registerService(\OCP\IRequest::class, function ($c) {
783
-			if (isset($this['urlParams'])) {
784
-				$urlParams = $this['urlParams'];
785
-			} else {
786
-				$urlParams = [];
787
-			}
788
-
789
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
790
-				&& in_array('fakeinput', stream_get_wrappers())
791
-			) {
792
-				$stream = 'fakeinput://data';
793
-			} else {
794
-				$stream = 'php://input';
795
-			}
796
-
797
-			return new Request(
798
-				[
799
-					'get' => $_GET,
800
-					'post' => $_POST,
801
-					'files' => $_FILES,
802
-					'server' => $_SERVER,
803
-					'env' => $_ENV,
804
-					'cookies' => $_COOKIE,
805
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
806
-						? $_SERVER['REQUEST_METHOD']
807
-						: '',
808
-					'urlParams' => $urlParams,
809
-				],
810
-				$this->getSecureRandom(),
811
-				$this->getConfig(),
812
-				$this->getCsrfTokenManager(),
813
-				$stream
814
-			);
815
-		});
816
-		$this->registerAlias('Request', \OCP\IRequest::class);
817
-
818
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
819
-			return new Mailer(
820
-				$c->getConfig(),
821
-				$c->getLogger(),
822
-				$c->query(Defaults::class),
823
-				$c->getURLGenerator(),
824
-				$c->getL10N('lib')
825
-			);
826
-		});
827
-		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
828
-
829
-		$this->registerService('LDAPProvider', function (Server $c) {
830
-			$config = $c->getConfig();
831
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
832
-			if (is_null($factoryClass)) {
833
-				throw new \Exception('ldapProviderFactory not set');
834
-			}
835
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
836
-			$factory = new $factoryClass($this);
837
-			return $factory->getLDAPProvider();
838
-		});
839
-		$this->registerService(ILockingProvider::class, function (Server $c) {
840
-			$ini = $c->getIniWrapper();
841
-			$config = $c->getConfig();
842
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
843
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
844
-				/** @var \OC\Memcache\Factory $memcacheFactory */
845
-				$memcacheFactory = $c->getMemCacheFactory();
846
-				$memcache = $memcacheFactory->createLocking('lock');
847
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
848
-					return new MemcacheLockingProvider($memcache, $ttl);
849
-				}
850
-				return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
851
-			}
852
-			return new NoopLockingProvider();
853
-		});
854
-		$this->registerAlias('LockingProvider', ILockingProvider::class);
855
-
856
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
857
-			return new \OC\Files\Mount\Manager();
858
-		});
859
-		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
860
-
861
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
862
-			return new \OC\Files\Type\Detection(
863
-				$c->getURLGenerator(),
864
-				\OC::$configDir,
865
-				\OC::$SERVERROOT . '/resources/config/'
866
-			);
867
-		});
868
-		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
869
-
870
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
871
-			return new \OC\Files\Type\Loader(
872
-				$c->getDatabaseConnection()
873
-			);
874
-		});
875
-		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
876
-		$this->registerService(BundleFetcher::class, function () {
877
-			return new BundleFetcher($this->getL10N('lib'));
878
-		});
879
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
880
-			return new Manager(
881
-				$c->query(IValidator::class)
882
-			);
883
-		});
884
-		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
885
-
886
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
887
-			$manager = new \OC\CapabilitiesManager($c->getLogger());
888
-			$manager->registerCapability(function () use ($c) {
889
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
890
-			});
891
-			$manager->registerCapability(function () use ($c) {
892
-				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
893
-			});
894
-			return $manager;
895
-		});
896
-		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
897
-
898
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
899
-			$config = $c->getConfig();
900
-			$factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
901
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
902
-			$factory = new $factoryClass($this);
903
-			$manager = $factory->getManager();
904
-
905
-			$manager->registerDisplayNameResolver('user', function($id) use ($c) {
906
-				$manager = $c->getUserManager();
907
-				$user = $manager->get($id);
908
-				if(is_null($user)) {
909
-					$l = $c->getL10N('core');
910
-					$displayName = $l->t('Unknown user');
911
-				} else {
912
-					$displayName = $user->getDisplayName();
913
-				}
914
-				return $displayName;
915
-			});
916
-
917
-			return $manager;
918
-		});
919
-		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
920
-
921
-		$this->registerService('ThemingDefaults', function (Server $c) {
922
-			/*
153
+    /** @var string */
154
+    private $webRoot;
155
+
156
+    /**
157
+     * @param string $webRoot
158
+     * @param \OC\Config $config
159
+     */
160
+    public function __construct($webRoot, \OC\Config $config) {
161
+        parent::__construct();
162
+        $this->webRoot = $webRoot;
163
+
164
+        $this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
165
+            return $c;
166
+        });
167
+
168
+        $this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
169
+        $this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
170
+
171
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
172
+        $this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
173
+
174
+        $this->registerAlias(IActionFactory::class, ActionFactory::class);
175
+
176
+
177
+        $this->registerService(\OCP\IPreview::class, function (Server $c) {
178
+            return new PreviewManager(
179
+                $c->getConfig(),
180
+                $c->getRootFolder(),
181
+                $c->getAppDataDir('preview'),
182
+                $c->getEventDispatcher(),
183
+                $c->getSession()->get('user_id')
184
+            );
185
+        });
186
+        $this->registerAlias('PreviewManager', \OCP\IPreview::class);
187
+
188
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
189
+            return new \OC\Preview\Watcher(
190
+                $c->getAppDataDir('preview')
191
+            );
192
+        });
193
+
194
+        $this->registerService('EncryptionManager', function (Server $c) {
195
+            $view = new View();
196
+            $util = new Encryption\Util(
197
+                $view,
198
+                $c->getUserManager(),
199
+                $c->getGroupManager(),
200
+                $c->getConfig()
201
+            );
202
+            return new Encryption\Manager(
203
+                $c->getConfig(),
204
+                $c->getLogger(),
205
+                $c->getL10N('core'),
206
+                new View(),
207
+                $util,
208
+                new ArrayCache()
209
+            );
210
+        });
211
+
212
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
213
+            $util = new Encryption\Util(
214
+                new View(),
215
+                $c->getUserManager(),
216
+                $c->getGroupManager(),
217
+                $c->getConfig()
218
+            );
219
+            return new Encryption\File(
220
+                $util,
221
+                $c->getRootFolder(),
222
+                $c->getShareManager()
223
+            );
224
+        });
225
+
226
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
227
+            $view = new View();
228
+            $util = new Encryption\Util(
229
+                $view,
230
+                $c->getUserManager(),
231
+                $c->getGroupManager(),
232
+                $c->getConfig()
233
+            );
234
+
235
+            return new Encryption\Keys\Storage($view, $util);
236
+        });
237
+        $this->registerService('TagMapper', function (Server $c) {
238
+            return new TagMapper($c->getDatabaseConnection());
239
+        });
240
+
241
+        $this->registerService(\OCP\ITagManager::class, function (Server $c) {
242
+            $tagMapper = $c->query('TagMapper');
243
+            return new TagManager($tagMapper, $c->getUserSession());
244
+        });
245
+        $this->registerAlias('TagManager', \OCP\ITagManager::class);
246
+
247
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
248
+            $config = $c->getConfig();
249
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
250
+            return new $factoryClass($this);
251
+        });
252
+        $this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
253
+            return $c->query('SystemTagManagerFactory')->getManager();
254
+        });
255
+        $this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
256
+
257
+        $this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
258
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
259
+        });
260
+        $this->registerService('RootFolder', function (Server $c) {
261
+            $manager = \OC\Files\Filesystem::getMountManager(null);
262
+            $view = new View();
263
+            $root = new Root(
264
+                $manager,
265
+                $view,
266
+                null,
267
+                $c->getUserMountCache(),
268
+                $this->getLogger(),
269
+                $this->getUserManager()
270
+            );
271
+            $connector = new HookConnector($root, $view);
272
+            $connector->viewToNode();
273
+
274
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
275
+            $previewConnector->connectWatcher();
276
+
277
+            return $root;
278
+        });
279
+        $this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
280
+
281
+        $this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
282
+            return new LazyRoot(function () use ($c) {
283
+                return $c->query('RootFolder');
284
+            });
285
+        });
286
+        $this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
287
+
288
+        $this->registerService(\OC\User\Manager::class, function (Server $c) {
289
+            $config = $c->getConfig();
290
+            return new \OC\User\Manager($config);
291
+        });
292
+        $this->registerAlias('UserManager', \OC\User\Manager::class);
293
+        $this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
294
+
295
+        $this->registerService(\OCP\IGroupManager::class, function (Server $c) {
296
+            $groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
297
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
298
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
299
+            });
300
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
301
+                \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
302
+            });
303
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
304
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
305
+            });
306
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
307
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
308
+            });
309
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
310
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
311
+            });
312
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
313
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
314
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
315
+                \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
316
+            });
317
+            return $groupManager;
318
+        });
319
+        $this->registerAlias('GroupManager', \OCP\IGroupManager::class);
320
+
321
+        $this->registerService(Store::class, function (Server $c) {
322
+            $session = $c->getSession();
323
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
324
+                $tokenProvider = $c->query(IProvider::class);
325
+            } else {
326
+                $tokenProvider = null;
327
+            }
328
+            $logger = $c->getLogger();
329
+            return new Store($session, $logger, $tokenProvider);
330
+        });
331
+        $this->registerAlias(IStore::class, Store::class);
332
+        $this->registerService(Authentication\Token\DefaultTokenMapper::class, function (Server $c) {
333
+            $dbConnection = $c->getDatabaseConnection();
334
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
335
+        });
336
+        $this->registerService(Authentication\Token\DefaultTokenProvider::class, function (Server $c) {
337
+            $mapper = $c->query(Authentication\Token\DefaultTokenMapper::class);
338
+            $crypto = $c->getCrypto();
339
+            $config = $c->getConfig();
340
+            $logger = $c->getLogger();
341
+            $timeFactory = new TimeFactory();
342
+            return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
343
+        });
344
+        $this->registerAlias(IProvider::class, Authentication\Token\DefaultTokenProvider::class);
345
+
346
+        $this->registerService(\OCP\IUserSession::class, function (Server $c) {
347
+            $manager = $c->getUserManager();
348
+            $session = new \OC\Session\Memory('');
349
+            $timeFactory = new TimeFactory();
350
+            // Token providers might require a working database. This code
351
+            // might however be called when ownCloud is not yet setup.
352
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
353
+                $defaultTokenProvider = $c->query(IProvider::class);
354
+            } else {
355
+                $defaultTokenProvider = null;
356
+            }
357
+
358
+            $dispatcher = $c->getEventDispatcher();
359
+
360
+            $userSession = new \OC\User\Session(
361
+                $manager,
362
+                $session,
363
+                $timeFactory,
364
+                $defaultTokenProvider,
365
+                $c->getConfig(),
366
+                $c->getSecureRandom(),
367
+                $c->getLockdownManager(),
368
+                $c->getLogger()
369
+            );
370
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
371
+                \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
372
+            });
373
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
374
+                /** @var $user \OC\User\User */
375
+                \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
376
+            });
377
+            $userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
378
+                /** @var $user \OC\User\User */
379
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
380
+                $dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
381
+            });
382
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
383
+                /** @var $user \OC\User\User */
384
+                \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
385
+            });
386
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
387
+                /** @var $user \OC\User\User */
388
+                \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
389
+            });
390
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
391
+                /** @var $user \OC\User\User */
392
+                \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
393
+            });
394
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
395
+                \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
396
+            });
397
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
398
+                /** @var $user \OC\User\User */
399
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
400
+            });
401
+            $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
402
+                /** @var $user \OC\User\User */
403
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
404
+            });
405
+            $userSession->listen('\OC\User', 'logout', function () {
406
+                \OC_Hook::emit('OC_User', 'logout', array());
407
+            });
408
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
409
+                /** @var $user \OC\User\User */
410
+                \OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
411
+                $dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
412
+            });
413
+            return $userSession;
414
+        });
415
+        $this->registerAlias('UserSession', \OCP\IUserSession::class);
416
+
417
+        $this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
418
+            return new \OC\Authentication\TwoFactorAuth\Manager(
419
+                $c->getAppManager(),
420
+                $c->getSession(),
421
+                $c->getConfig(),
422
+                $c->getActivityManager(),
423
+                $c->getLogger(),
424
+                $c->query(IProvider::class),
425
+                $c->query(ITimeFactory::class),
426
+                $c->query(EventDispatcherInterface::class)
427
+            );
428
+        });
429
+
430
+        $this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
431
+        $this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
432
+
433
+        $this->registerService(\OC\AllConfig::class, function (Server $c) {
434
+            return new \OC\AllConfig(
435
+                $c->getSystemConfig()
436
+            );
437
+        });
438
+        $this->registerAlias('AllConfig', \OC\AllConfig::class);
439
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
440
+
441
+        $this->registerService('SystemConfig', function ($c) use ($config) {
442
+            return new \OC\SystemConfig($config);
443
+        });
444
+
445
+        $this->registerService(\OC\AppConfig::class, function (Server $c) {
446
+            return new \OC\AppConfig($c->getDatabaseConnection());
447
+        });
448
+        $this->registerAlias('AppConfig', \OC\AppConfig::class);
449
+        $this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
450
+
451
+        $this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
452
+            return new \OC\L10N\Factory(
453
+                $c->getConfig(),
454
+                $c->getRequest(),
455
+                $c->getUserSession(),
456
+                \OC::$SERVERROOT
457
+            );
458
+        });
459
+        $this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
460
+
461
+        $this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
462
+            $config = $c->getConfig();
463
+            $cacheFactory = $c->getMemCacheFactory();
464
+            $request = $c->getRequest();
465
+            return new \OC\URLGenerator(
466
+                $config,
467
+                $cacheFactory,
468
+                $request
469
+            );
470
+        });
471
+        $this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
472
+
473
+        $this->registerAlias('AppFetcher', AppFetcher::class);
474
+        $this->registerAlias('CategoryFetcher', CategoryFetcher::class);
475
+
476
+        $this->registerService(\OCP\ICache::class, function ($c) {
477
+            return new Cache\File();
478
+        });
479
+        $this->registerAlias('UserCache', \OCP\ICache::class);
480
+
481
+        $this->registerService(Factory::class, function (Server $c) {
482
+
483
+            $arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
484
+                ArrayCache::class,
485
+                ArrayCache::class,
486
+                ArrayCache::class
487
+            );
488
+            $config = $c->getConfig();
489
+            $request = $c->getRequest();
490
+            $urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
491
+
492
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
493
+                $v = \OC_App::getAppVersions();
494
+                $v['core'] = implode(',', \OC_Util::getVersion());
495
+                $version = implode(',', $v);
496
+                $instanceId = \OC_Util::getInstanceId();
497
+                $path = \OC::$SERVERROOT;
498
+                $prefix = md5($instanceId . '-' . $version . '-' . $path);
499
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
500
+                    $config->getSystemValue('memcache.local', null),
501
+                    $config->getSystemValue('memcache.distributed', null),
502
+                    $config->getSystemValue('memcache.locking', null)
503
+                );
504
+            }
505
+            return $arrayCacheFactory;
506
+
507
+        });
508
+        $this->registerAlias('MemCacheFactory', Factory::class);
509
+        $this->registerAlias(ICacheFactory::class, Factory::class);
510
+
511
+        $this->registerService('RedisFactory', function (Server $c) {
512
+            $systemConfig = $c->getSystemConfig();
513
+            return new RedisFactory($systemConfig);
514
+        });
515
+
516
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
517
+            return new \OC\Activity\Manager(
518
+                $c->getRequest(),
519
+                $c->getUserSession(),
520
+                $c->getConfig(),
521
+                $c->query(IValidator::class)
522
+            );
523
+        });
524
+        $this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
525
+
526
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
527
+            return new \OC\Activity\EventMerger(
528
+                $c->getL10N('lib')
529
+            );
530
+        });
531
+        $this->registerAlias(IValidator::class, Validator::class);
532
+
533
+        $this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
534
+            return new AvatarManager(
535
+                $c->query(\OC\User\Manager::class),
536
+                $c->getAppDataDir('avatar'),
537
+                $c->getL10N('lib'),
538
+                $c->getLogger(),
539
+                $c->getConfig()
540
+            );
541
+        });
542
+        $this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
543
+
544
+        $this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
545
+
546
+        $this->registerService(\OCP\ILogger::class, function (Server $c) {
547
+            $logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
548
+            $logger = Log::getLogClass($logType);
549
+            call_user_func(array($logger, 'init'));
550
+            $config = $this->getSystemConfig();
551
+            $registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
552
+
553
+            return new Log($logger, $config, null, $registry);
554
+        });
555
+        $this->registerAlias('Logger', \OCP\ILogger::class);
556
+
557
+        $this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
558
+            $config = $c->getConfig();
559
+            return new \OC\BackgroundJob\JobList(
560
+                $c->getDatabaseConnection(),
561
+                $config,
562
+                new TimeFactory()
563
+            );
564
+        });
565
+        $this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
566
+
567
+        $this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
568
+            $cacheFactory = $c->getMemCacheFactory();
569
+            $logger = $c->getLogger();
570
+            if ($cacheFactory->isLocalCacheAvailable()) {
571
+                $router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
572
+            } else {
573
+                $router = new \OC\Route\Router($logger);
574
+            }
575
+            return $router;
576
+        });
577
+        $this->registerAlias('Router', \OCP\Route\IRouter::class);
578
+
579
+        $this->registerService(\OCP\ISearch::class, function ($c) {
580
+            return new Search();
581
+        });
582
+        $this->registerAlias('Search', \OCP\ISearch::class);
583
+
584
+        $this->registerService(\OC\Security\RateLimiting\Limiter::class, function (Server $c) {
585
+            return new \OC\Security\RateLimiting\Limiter(
586
+                $this->getUserSession(),
587
+                $this->getRequest(),
588
+                new \OC\AppFramework\Utility\TimeFactory(),
589
+                $c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
590
+            );
591
+        });
592
+        $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
593
+            return new \OC\Security\RateLimiting\Backend\MemoryCache(
594
+                $this->getMemCacheFactory(),
595
+                new \OC\AppFramework\Utility\TimeFactory()
596
+            );
597
+        });
598
+
599
+        $this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
600
+            return new SecureRandom();
601
+        });
602
+        $this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
603
+
604
+        $this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
605
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
606
+        });
607
+        $this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
608
+
609
+        $this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
610
+            return new Hasher($c->getConfig());
611
+        });
612
+        $this->registerAlias('Hasher', \OCP\Security\IHasher::class);
613
+
614
+        $this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
615
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
616
+        });
617
+        $this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
618
+
619
+        $this->registerService(IDBConnection::class, function (Server $c) {
620
+            $systemConfig = $c->getSystemConfig();
621
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
622
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
623
+            if (!$factory->isValidType($type)) {
624
+                throw new \OC\DatabaseException('Invalid database type');
625
+            }
626
+            $connectionParams = $factory->createConnectionParams();
627
+            $connection = $factory->getConnection($type, $connectionParams);
628
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
629
+            return $connection;
630
+        });
631
+        $this->registerAlias('DatabaseConnection', IDBConnection::class);
632
+
633
+
634
+        $this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
635
+            $user = \OC_User::getUser();
636
+            $uid = $user ? $user : null;
637
+            return new ClientService(
638
+                $c->getConfig(),
639
+                new \OC\Security\CertificateManager(
640
+                    $uid,
641
+                    new View(),
642
+                    $c->getConfig(),
643
+                    $c->getLogger(),
644
+                    $c->getSecureRandom()
645
+                )
646
+            );
647
+        });
648
+        $this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
649
+        $this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
650
+            $eventLogger = new EventLogger();
651
+            if ($c->getSystemConfig()->getValue('debug', false)) {
652
+                // In debug mode, module is being activated by default
653
+                $eventLogger->activate();
654
+            }
655
+            return $eventLogger;
656
+        });
657
+        $this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
658
+
659
+        $this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
660
+            $queryLogger = new QueryLogger();
661
+            if ($c->getSystemConfig()->getValue('debug', false)) {
662
+                // In debug mode, module is being activated by default
663
+                $queryLogger->activate();
664
+            }
665
+            return $queryLogger;
666
+        });
667
+        $this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
668
+
669
+        $this->registerService(TempManager::class, function (Server $c) {
670
+            return new TempManager(
671
+                $c->getLogger(),
672
+                $c->getConfig()
673
+            );
674
+        });
675
+        $this->registerAlias('TempManager', TempManager::class);
676
+        $this->registerAlias(ITempManager::class, TempManager::class);
677
+
678
+        $this->registerService(AppManager::class, function (Server $c) {
679
+            return new \OC\App\AppManager(
680
+                $c->getUserSession(),
681
+                $c->query(\OC\AppConfig::class),
682
+                $c->getGroupManager(),
683
+                $c->getMemCacheFactory(),
684
+                $c->getEventDispatcher()
685
+            );
686
+        });
687
+        $this->registerAlias('AppManager', AppManager::class);
688
+        $this->registerAlias(IAppManager::class, AppManager::class);
689
+
690
+        $this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
691
+            return new DateTimeZone(
692
+                $c->getConfig(),
693
+                $c->getSession()
694
+            );
695
+        });
696
+        $this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
697
+
698
+        $this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
699
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
700
+
701
+            return new DateTimeFormatter(
702
+                $c->getDateTimeZone()->getTimeZone(),
703
+                $c->getL10N('lib', $language)
704
+            );
705
+        });
706
+        $this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
707
+
708
+        $this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
709
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
710
+            $listener = new UserMountCacheListener($mountCache);
711
+            $listener->listen($c->getUserManager());
712
+            return $mountCache;
713
+        });
714
+        $this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
715
+
716
+        $this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
717
+            $loader = \OC\Files\Filesystem::getLoader();
718
+            $mountCache = $c->query('UserMountCache');
719
+            $manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
720
+
721
+            // builtin providers
722
+
723
+            $config = $c->getConfig();
724
+            $manager->registerProvider(new CacheMountProvider($config));
725
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
726
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
727
+
728
+            return $manager;
729
+        });
730
+        $this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
731
+
732
+        $this->registerService('IniWrapper', function ($c) {
733
+            return new IniGetWrapper();
734
+        });
735
+        $this->registerService('AsyncCommandBus', function (Server $c) {
736
+            $busClass = $c->getConfig()->getSystemValue('commandbus');
737
+            if ($busClass) {
738
+                list($app, $class) = explode('::', $busClass, 2);
739
+                if ($c->getAppManager()->isInstalled($app)) {
740
+                    \OC_App::loadApp($app);
741
+                    return $c->query($class);
742
+                } else {
743
+                    throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
744
+                }
745
+            } else {
746
+                $jobList = $c->getJobList();
747
+                return new CronBus($jobList);
748
+            }
749
+        });
750
+        $this->registerService('TrustedDomainHelper', function ($c) {
751
+            return new TrustedDomainHelper($this->getConfig());
752
+        });
753
+        $this->registerService('Throttler', function (Server $c) {
754
+            return new Throttler(
755
+                $c->getDatabaseConnection(),
756
+                new TimeFactory(),
757
+                $c->getLogger(),
758
+                $c->getConfig()
759
+            );
760
+        });
761
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
762
+            // IConfig and IAppManager requires a working database. This code
763
+            // might however be called when ownCloud is not yet setup.
764
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
765
+                $config = $c->getConfig();
766
+                $appManager = $c->getAppManager();
767
+            } else {
768
+                $config = null;
769
+                $appManager = null;
770
+            }
771
+
772
+            return new Checker(
773
+                new EnvironmentHelper(),
774
+                new FileAccessHelper(),
775
+                new AppLocator(),
776
+                $config,
777
+                $c->getMemCacheFactory(),
778
+                $appManager,
779
+                $c->getTempManager()
780
+            );
781
+        });
782
+        $this->registerService(\OCP\IRequest::class, function ($c) {
783
+            if (isset($this['urlParams'])) {
784
+                $urlParams = $this['urlParams'];
785
+            } else {
786
+                $urlParams = [];
787
+            }
788
+
789
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
790
+                && in_array('fakeinput', stream_get_wrappers())
791
+            ) {
792
+                $stream = 'fakeinput://data';
793
+            } else {
794
+                $stream = 'php://input';
795
+            }
796
+
797
+            return new Request(
798
+                [
799
+                    'get' => $_GET,
800
+                    'post' => $_POST,
801
+                    'files' => $_FILES,
802
+                    'server' => $_SERVER,
803
+                    'env' => $_ENV,
804
+                    'cookies' => $_COOKIE,
805
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
806
+                        ? $_SERVER['REQUEST_METHOD']
807
+                        : '',
808
+                    'urlParams' => $urlParams,
809
+                ],
810
+                $this->getSecureRandom(),
811
+                $this->getConfig(),
812
+                $this->getCsrfTokenManager(),
813
+                $stream
814
+            );
815
+        });
816
+        $this->registerAlias('Request', \OCP\IRequest::class);
817
+
818
+        $this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
819
+            return new Mailer(
820
+                $c->getConfig(),
821
+                $c->getLogger(),
822
+                $c->query(Defaults::class),
823
+                $c->getURLGenerator(),
824
+                $c->getL10N('lib')
825
+            );
826
+        });
827
+        $this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
828
+
829
+        $this->registerService('LDAPProvider', function (Server $c) {
830
+            $config = $c->getConfig();
831
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
832
+            if (is_null($factoryClass)) {
833
+                throw new \Exception('ldapProviderFactory not set');
834
+            }
835
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
836
+            $factory = new $factoryClass($this);
837
+            return $factory->getLDAPProvider();
838
+        });
839
+        $this->registerService(ILockingProvider::class, function (Server $c) {
840
+            $ini = $c->getIniWrapper();
841
+            $config = $c->getConfig();
842
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
843
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
844
+                /** @var \OC\Memcache\Factory $memcacheFactory */
845
+                $memcacheFactory = $c->getMemCacheFactory();
846
+                $memcache = $memcacheFactory->createLocking('lock');
847
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
848
+                    return new MemcacheLockingProvider($memcache, $ttl);
849
+                }
850
+                return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
851
+            }
852
+            return new NoopLockingProvider();
853
+        });
854
+        $this->registerAlias('LockingProvider', ILockingProvider::class);
855
+
856
+        $this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
857
+            return new \OC\Files\Mount\Manager();
858
+        });
859
+        $this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
860
+
861
+        $this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
862
+            return new \OC\Files\Type\Detection(
863
+                $c->getURLGenerator(),
864
+                \OC::$configDir,
865
+                \OC::$SERVERROOT . '/resources/config/'
866
+            );
867
+        });
868
+        $this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
869
+
870
+        $this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
871
+            return new \OC\Files\Type\Loader(
872
+                $c->getDatabaseConnection()
873
+            );
874
+        });
875
+        $this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
876
+        $this->registerService(BundleFetcher::class, function () {
877
+            return new BundleFetcher($this->getL10N('lib'));
878
+        });
879
+        $this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
880
+            return new Manager(
881
+                $c->query(IValidator::class)
882
+            );
883
+        });
884
+        $this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
885
+
886
+        $this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
887
+            $manager = new \OC\CapabilitiesManager($c->getLogger());
888
+            $manager->registerCapability(function () use ($c) {
889
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
890
+            });
891
+            $manager->registerCapability(function () use ($c) {
892
+                return $c->query(\OC\Security\Bruteforce\Capabilities::class);
893
+            });
894
+            return $manager;
895
+        });
896
+        $this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
897
+
898
+        $this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
899
+            $config = $c->getConfig();
900
+            $factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
901
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
902
+            $factory = new $factoryClass($this);
903
+            $manager = $factory->getManager();
904
+
905
+            $manager->registerDisplayNameResolver('user', function($id) use ($c) {
906
+                $manager = $c->getUserManager();
907
+                $user = $manager->get($id);
908
+                if(is_null($user)) {
909
+                    $l = $c->getL10N('core');
910
+                    $displayName = $l->t('Unknown user');
911
+                } else {
912
+                    $displayName = $user->getDisplayName();
913
+                }
914
+                return $displayName;
915
+            });
916
+
917
+            return $manager;
918
+        });
919
+        $this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
920
+
921
+        $this->registerService('ThemingDefaults', function (Server $c) {
922
+            /*
923 923
 			 * Dark magic for autoloader.
924 924
 			 * If we do a class_exists it will try to load the class which will
925 925
 			 * make composer cache the result. Resulting in errors when enabling
926 926
 			 * the theming app.
927 927
 			 */
928
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
929
-			if (isset($prefixes['OCA\\Theming\\'])) {
930
-				$classExists = true;
931
-			} else {
932
-				$classExists = false;
933
-			}
934
-
935
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
936
-				return new ThemingDefaults(
937
-					$c->getConfig(),
938
-					$c->getL10N('theming'),
939
-					$c->getURLGenerator(),
940
-					$c->getAppDataDir('theming'),
941
-					$c->getMemCacheFactory(),
942
-					new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming')),
943
-					$this->getAppManager()
944
-				);
945
-			}
946
-			return new \OC_Defaults();
947
-		});
948
-		$this->registerService(SCSSCacher::class, function (Server $c) {
949
-			/** @var Factory $cacheFactory */
950
-			$cacheFactory = $c->query(Factory::class);
951
-			return new SCSSCacher(
952
-				$c->getLogger(),
953
-				$c->query(\OC\Files\AppData\Factory::class),
954
-				$c->getURLGenerator(),
955
-				$c->getConfig(),
956
-				$c->getThemingDefaults(),
957
-				\OC::$SERVERROOT,
958
-				$this->getMemCacheFactory()
959
-			);
960
-		});
961
-		$this->registerService(JSCombiner::class, function (Server $c) {
962
-			/** @var Factory $cacheFactory */
963
-			$cacheFactory = $c->query(Factory::class);
964
-			return new JSCombiner(
965
-				$c->getAppDataDir('js'),
966
-				$c->getURLGenerator(),
967
-				$this->getMemCacheFactory(),
968
-				$c->getSystemConfig(),
969
-				$c->getLogger()
970
-			);
971
-		});
972
-		$this->registerService(EventDispatcher::class, function () {
973
-			return new EventDispatcher();
974
-		});
975
-		$this->registerAlias('EventDispatcher', EventDispatcher::class);
976
-		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
977
-
978
-		$this->registerService('CryptoWrapper', function (Server $c) {
979
-			// FIXME: Instantiiated here due to cyclic dependency
980
-			$request = new Request(
981
-				[
982
-					'get' => $_GET,
983
-					'post' => $_POST,
984
-					'files' => $_FILES,
985
-					'server' => $_SERVER,
986
-					'env' => $_ENV,
987
-					'cookies' => $_COOKIE,
988
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
989
-						? $_SERVER['REQUEST_METHOD']
990
-						: null,
991
-				],
992
-				$c->getSecureRandom(),
993
-				$c->getConfig()
994
-			);
995
-
996
-			return new CryptoWrapper(
997
-				$c->getConfig(),
998
-				$c->getCrypto(),
999
-				$c->getSecureRandom(),
1000
-				$request
1001
-			);
1002
-		});
1003
-		$this->registerService('CsrfTokenManager', function (Server $c) {
1004
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1005
-
1006
-			return new CsrfTokenManager(
1007
-				$tokenGenerator,
1008
-				$c->query(SessionStorage::class)
1009
-			);
1010
-		});
1011
-		$this->registerService(SessionStorage::class, function (Server $c) {
1012
-			return new SessionStorage($c->getSession());
1013
-		});
1014
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1015
-			return new ContentSecurityPolicyManager();
1016
-		});
1017
-		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1018
-
1019
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1020
-			return new ContentSecurityPolicyNonceManager(
1021
-				$c->getCsrfTokenManager(),
1022
-				$c->getRequest()
1023
-			);
1024
-		});
1025
-
1026
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1027
-			$config = $c->getConfig();
1028
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1029
-			/** @var \OCP\Share\IProviderFactory $factory */
1030
-			$factory = new $factoryClass($this);
1031
-
1032
-			$manager = new \OC\Share20\Manager(
1033
-				$c->getLogger(),
1034
-				$c->getConfig(),
1035
-				$c->getSecureRandom(),
1036
-				$c->getHasher(),
1037
-				$c->getMountManager(),
1038
-				$c->getGroupManager(),
1039
-				$c->getL10N('lib'),
1040
-				$c->getL10NFactory(),
1041
-				$factory,
1042
-				$c->getUserManager(),
1043
-				$c->getLazyRootFolder(),
1044
-				$c->getEventDispatcher(),
1045
-				$c->getMailer(),
1046
-				$c->getURLGenerator(),
1047
-				$c->getThemingDefaults()
1048
-			);
1049
-
1050
-			return $manager;
1051
-		});
1052
-		$this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1053
-
1054
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1055
-			$instance = new Collaboration\Collaborators\Search($c);
1056
-
1057
-			// register default plugins
1058
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1059
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1060
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1061
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1062
-
1063
-			return $instance;
1064
-		});
1065
-		$this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1066
-
1067
-		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1068
-
1069
-		$this->registerService('SettingsManager', function (Server $c) {
1070
-			$manager = new \OC\Settings\Manager(
1071
-				$c->getLogger(),
1072
-				$c->getDatabaseConnection(),
1073
-				$c->getL10N('lib'),
1074
-				$c->getConfig(),
1075
-				$c->getEncryptionManager(),
1076
-				$c->getUserManager(),
1077
-				$c->getLockingProvider(),
1078
-				$c->getRequest(),
1079
-				$c->getURLGenerator(),
1080
-				$c->query(AccountManager::class),
1081
-				$c->getGroupManager(),
1082
-				$c->getL10NFactory(),
1083
-				$c->getAppManager()
1084
-			);
1085
-			return $manager;
1086
-		});
1087
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1088
-			return new \OC\Files\AppData\Factory(
1089
-				$c->getRootFolder(),
1090
-				$c->getSystemConfig()
1091
-			);
1092
-		});
1093
-
1094
-		$this->registerService('LockdownManager', function (Server $c) {
1095
-			return new LockdownManager(function () use ($c) {
1096
-				return $c->getSession();
1097
-			});
1098
-		});
1099
-
1100
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1101
-			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1102
-		});
1103
-
1104
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1105
-			return new CloudIdManager();
1106
-		});
1107
-
1108
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1109
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1110
-
1111
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1112
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1113
-
1114
-		$this->registerService(Defaults::class, function (Server $c) {
1115
-			return new Defaults(
1116
-				$c->getThemingDefaults()
1117
-			);
1118
-		});
1119
-		$this->registerAlias('Defaults', \OCP\Defaults::class);
1120
-
1121
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1122
-			return $c->query(\OCP\IUserSession::class)->getSession();
1123
-		});
1124
-
1125
-		$this->registerService(IShareHelper::class, function (Server $c) {
1126
-			return new ShareHelper(
1127
-				$c->query(\OCP\Share\IManager::class)
1128
-			);
1129
-		});
1130
-
1131
-		$this->registerService(Installer::class, function(Server $c) {
1132
-			return new Installer(
1133
-				$c->getAppFetcher(),
1134
-				$c->getHTTPClientService(),
1135
-				$c->getTempManager(),
1136
-				$c->getLogger(),
1137
-				$c->getConfig()
1138
-			);
1139
-		});
1140
-
1141
-		$this->registerService(IApiFactory::class, function(Server $c) {
1142
-			return new ApiFactory($c->getHTTPClientService());
1143
-		});
1144
-
1145
-		$this->registerService(IInstanceFactory::class, function(Server $c) {
1146
-			$memcacheFactory = $c->getMemCacheFactory();
1147
-			return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1148
-		});
1149
-
1150
-		$this->registerService(IContactsStore::class, function(Server $c) {
1151
-			return new ContactsStore(
1152
-				$c->getContactsManager(),
1153
-				$c->getConfig(),
1154
-				$c->getUserManager(),
1155
-				$c->getGroupManager()
1156
-			);
1157
-		});
1158
-		$this->registerAlias(IContactsStore::class, ContactsStore::class);
1159
-
1160
-		$this->connectDispatcher();
1161
-	}
1162
-
1163
-	/**
1164
-	 * @return \OCP\Calendar\IManager
1165
-	 */
1166
-	public function getCalendarManager() {
1167
-		return $this->query('CalendarManager');
1168
-	}
1169
-
1170
-	private function connectDispatcher() {
1171
-		$dispatcher = $this->getEventDispatcher();
1172
-
1173
-		// Delete avatar on user deletion
1174
-		$dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1175
-			$logger = $this->getLogger();
1176
-			$manager = $this->getAvatarManager();
1177
-			/** @var IUser $user */
1178
-			$user = $e->getSubject();
1179
-
1180
-			try {
1181
-				$avatar = $manager->getAvatar($user->getUID());
1182
-				$avatar->remove();
1183
-			} catch (NotFoundException $e) {
1184
-				// no avatar to remove
1185
-			} catch (\Exception $e) {
1186
-				// Ignore exceptions
1187
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1188
-			}
1189
-		});
1190
-
1191
-		$dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1192
-			$manager = $this->getAvatarManager();
1193
-			/** @var IUser $user */
1194
-			$user = $e->getSubject();
1195
-			$feature = $e->getArgument('feature');
1196
-			$oldValue = $e->getArgument('oldValue');
1197
-			$value = $e->getArgument('value');
1198
-
1199
-			try {
1200
-				$avatar = $manager->getAvatar($user->getUID());
1201
-				$avatar->userChanged($feature, $oldValue, $value);
1202
-			} catch (NotFoundException $e) {
1203
-				// no avatar to remove
1204
-			}
1205
-		});
1206
-	}
1207
-
1208
-	/**
1209
-	 * @return \OCP\Contacts\IManager
1210
-	 */
1211
-	public function getContactsManager() {
1212
-		return $this->query('ContactsManager');
1213
-	}
1214
-
1215
-	/**
1216
-	 * @return \OC\Encryption\Manager
1217
-	 */
1218
-	public function getEncryptionManager() {
1219
-		return $this->query('EncryptionManager');
1220
-	}
1221
-
1222
-	/**
1223
-	 * @return \OC\Encryption\File
1224
-	 */
1225
-	public function getEncryptionFilesHelper() {
1226
-		return $this->query('EncryptionFileHelper');
1227
-	}
1228
-
1229
-	/**
1230
-	 * @return \OCP\Encryption\Keys\IStorage
1231
-	 */
1232
-	public function getEncryptionKeyStorage() {
1233
-		return $this->query('EncryptionKeyStorage');
1234
-	}
1235
-
1236
-	/**
1237
-	 * The current request object holding all information about the request
1238
-	 * currently being processed is returned from this method.
1239
-	 * In case the current execution was not initiated by a web request null is returned
1240
-	 *
1241
-	 * @return \OCP\IRequest
1242
-	 */
1243
-	public function getRequest() {
1244
-		return $this->query('Request');
1245
-	}
1246
-
1247
-	/**
1248
-	 * Returns the preview manager which can create preview images for a given file
1249
-	 *
1250
-	 * @return \OCP\IPreview
1251
-	 */
1252
-	public function getPreviewManager() {
1253
-		return $this->query('PreviewManager');
1254
-	}
1255
-
1256
-	/**
1257
-	 * Returns the tag manager which can get and set tags for different object types
1258
-	 *
1259
-	 * @see \OCP\ITagManager::load()
1260
-	 * @return \OCP\ITagManager
1261
-	 */
1262
-	public function getTagManager() {
1263
-		return $this->query('TagManager');
1264
-	}
1265
-
1266
-	/**
1267
-	 * Returns the system-tag manager
1268
-	 *
1269
-	 * @return \OCP\SystemTag\ISystemTagManager
1270
-	 *
1271
-	 * @since 9.0.0
1272
-	 */
1273
-	public function getSystemTagManager() {
1274
-		return $this->query('SystemTagManager');
1275
-	}
1276
-
1277
-	/**
1278
-	 * Returns the system-tag object mapper
1279
-	 *
1280
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
1281
-	 *
1282
-	 * @since 9.0.0
1283
-	 */
1284
-	public function getSystemTagObjectMapper() {
1285
-		return $this->query('SystemTagObjectMapper');
1286
-	}
1287
-
1288
-	/**
1289
-	 * Returns the avatar manager, used for avatar functionality
1290
-	 *
1291
-	 * @return \OCP\IAvatarManager
1292
-	 */
1293
-	public function getAvatarManager() {
1294
-		return $this->query('AvatarManager');
1295
-	}
1296
-
1297
-	/**
1298
-	 * Returns the root folder of ownCloud's data directory
1299
-	 *
1300
-	 * @return \OCP\Files\IRootFolder
1301
-	 */
1302
-	public function getRootFolder() {
1303
-		return $this->query('LazyRootFolder');
1304
-	}
1305
-
1306
-	/**
1307
-	 * Returns the root folder of ownCloud's data directory
1308
-	 * This is the lazy variant so this gets only initialized once it
1309
-	 * is actually used.
1310
-	 *
1311
-	 * @return \OCP\Files\IRootFolder
1312
-	 */
1313
-	public function getLazyRootFolder() {
1314
-		return $this->query('LazyRootFolder');
1315
-	}
1316
-
1317
-	/**
1318
-	 * Returns a view to ownCloud's files folder
1319
-	 *
1320
-	 * @param string $userId user ID
1321
-	 * @return \OCP\Files\Folder|null
1322
-	 */
1323
-	public function getUserFolder($userId = null) {
1324
-		if ($userId === null) {
1325
-			$user = $this->getUserSession()->getUser();
1326
-			if (!$user) {
1327
-				return null;
1328
-			}
1329
-			$userId = $user->getUID();
1330
-		}
1331
-		$root = $this->getRootFolder();
1332
-		return $root->getUserFolder($userId);
1333
-	}
1334
-
1335
-	/**
1336
-	 * Returns an app-specific view in ownClouds data directory
1337
-	 *
1338
-	 * @return \OCP\Files\Folder
1339
-	 * @deprecated since 9.2.0 use IAppData
1340
-	 */
1341
-	public function getAppFolder() {
1342
-		$dir = '/' . \OC_App::getCurrentApp();
1343
-		$root = $this->getRootFolder();
1344
-		if (!$root->nodeExists($dir)) {
1345
-			$folder = $root->newFolder($dir);
1346
-		} else {
1347
-			$folder = $root->get($dir);
1348
-		}
1349
-		return $folder;
1350
-	}
1351
-
1352
-	/**
1353
-	 * @return \OC\User\Manager
1354
-	 */
1355
-	public function getUserManager() {
1356
-		return $this->query('UserManager');
1357
-	}
1358
-
1359
-	/**
1360
-	 * @return \OC\Group\Manager
1361
-	 */
1362
-	public function getGroupManager() {
1363
-		return $this->query('GroupManager');
1364
-	}
1365
-
1366
-	/**
1367
-	 * @return \OC\User\Session
1368
-	 */
1369
-	public function getUserSession() {
1370
-		return $this->query('UserSession');
1371
-	}
1372
-
1373
-	/**
1374
-	 * @return \OCP\ISession
1375
-	 */
1376
-	public function getSession() {
1377
-		return $this->query('UserSession')->getSession();
1378
-	}
1379
-
1380
-	/**
1381
-	 * @param \OCP\ISession $session
1382
-	 */
1383
-	public function setSession(\OCP\ISession $session) {
1384
-		$this->query(SessionStorage::class)->setSession($session);
1385
-		$this->query('UserSession')->setSession($session);
1386
-		$this->query(Store::class)->setSession($session);
1387
-	}
1388
-
1389
-	/**
1390
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1391
-	 */
1392
-	public function getTwoFactorAuthManager() {
1393
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1394
-	}
1395
-
1396
-	/**
1397
-	 * @return \OC\NavigationManager
1398
-	 */
1399
-	public function getNavigationManager() {
1400
-		return $this->query('NavigationManager');
1401
-	}
1402
-
1403
-	/**
1404
-	 * @return \OCP\IConfig
1405
-	 */
1406
-	public function getConfig() {
1407
-		return $this->query('AllConfig');
1408
-	}
1409
-
1410
-	/**
1411
-	 * @return \OC\SystemConfig
1412
-	 */
1413
-	public function getSystemConfig() {
1414
-		return $this->query('SystemConfig');
1415
-	}
1416
-
1417
-	/**
1418
-	 * Returns the app config manager
1419
-	 *
1420
-	 * @return \OCP\IAppConfig
1421
-	 */
1422
-	public function getAppConfig() {
1423
-		return $this->query('AppConfig');
1424
-	}
1425
-
1426
-	/**
1427
-	 * @return \OCP\L10N\IFactory
1428
-	 */
1429
-	public function getL10NFactory() {
1430
-		return $this->query('L10NFactory');
1431
-	}
1432
-
1433
-	/**
1434
-	 * get an L10N instance
1435
-	 *
1436
-	 * @param string $app appid
1437
-	 * @param string $lang
1438
-	 * @return IL10N
1439
-	 */
1440
-	public function getL10N($app, $lang = null) {
1441
-		return $this->getL10NFactory()->get($app, $lang);
1442
-	}
1443
-
1444
-	/**
1445
-	 * @return \OCP\IURLGenerator
1446
-	 */
1447
-	public function getURLGenerator() {
1448
-		return $this->query('URLGenerator');
1449
-	}
1450
-
1451
-	/**
1452
-	 * @return AppFetcher
1453
-	 */
1454
-	public function getAppFetcher() {
1455
-		return $this->query(AppFetcher::class);
1456
-	}
1457
-
1458
-	/**
1459
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1460
-	 * getMemCacheFactory() instead.
1461
-	 *
1462
-	 * @return \OCP\ICache
1463
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1464
-	 */
1465
-	public function getCache() {
1466
-		return $this->query('UserCache');
1467
-	}
1468
-
1469
-	/**
1470
-	 * Returns an \OCP\CacheFactory instance
1471
-	 *
1472
-	 * @return \OCP\ICacheFactory
1473
-	 */
1474
-	public function getMemCacheFactory() {
1475
-		return $this->query('MemCacheFactory');
1476
-	}
1477
-
1478
-	/**
1479
-	 * Returns an \OC\RedisFactory instance
1480
-	 *
1481
-	 * @return \OC\RedisFactory
1482
-	 */
1483
-	public function getGetRedisFactory() {
1484
-		return $this->query('RedisFactory');
1485
-	}
1486
-
1487
-
1488
-	/**
1489
-	 * Returns the current session
1490
-	 *
1491
-	 * @return \OCP\IDBConnection
1492
-	 */
1493
-	public function getDatabaseConnection() {
1494
-		return $this->query('DatabaseConnection');
1495
-	}
1496
-
1497
-	/**
1498
-	 * Returns the activity manager
1499
-	 *
1500
-	 * @return \OCP\Activity\IManager
1501
-	 */
1502
-	public function getActivityManager() {
1503
-		return $this->query('ActivityManager');
1504
-	}
1505
-
1506
-	/**
1507
-	 * Returns an job list for controlling background jobs
1508
-	 *
1509
-	 * @return \OCP\BackgroundJob\IJobList
1510
-	 */
1511
-	public function getJobList() {
1512
-		return $this->query('JobList');
1513
-	}
1514
-
1515
-	/**
1516
-	 * Returns a logger instance
1517
-	 *
1518
-	 * @return \OCP\ILogger
1519
-	 */
1520
-	public function getLogger() {
1521
-		return $this->query('Logger');
1522
-	}
1523
-
1524
-	/**
1525
-	 * Returns a router for generating and matching urls
1526
-	 *
1527
-	 * @return \OCP\Route\IRouter
1528
-	 */
1529
-	public function getRouter() {
1530
-		return $this->query('Router');
1531
-	}
1532
-
1533
-	/**
1534
-	 * Returns a search instance
1535
-	 *
1536
-	 * @return \OCP\ISearch
1537
-	 */
1538
-	public function getSearch() {
1539
-		return $this->query('Search');
1540
-	}
1541
-
1542
-	/**
1543
-	 * Returns a SecureRandom instance
1544
-	 *
1545
-	 * @return \OCP\Security\ISecureRandom
1546
-	 */
1547
-	public function getSecureRandom() {
1548
-		return $this->query('SecureRandom');
1549
-	}
1550
-
1551
-	/**
1552
-	 * Returns a Crypto instance
1553
-	 *
1554
-	 * @return \OCP\Security\ICrypto
1555
-	 */
1556
-	public function getCrypto() {
1557
-		return $this->query('Crypto');
1558
-	}
1559
-
1560
-	/**
1561
-	 * Returns a Hasher instance
1562
-	 *
1563
-	 * @return \OCP\Security\IHasher
1564
-	 */
1565
-	public function getHasher() {
1566
-		return $this->query('Hasher');
1567
-	}
1568
-
1569
-	/**
1570
-	 * Returns a CredentialsManager instance
1571
-	 *
1572
-	 * @return \OCP\Security\ICredentialsManager
1573
-	 */
1574
-	public function getCredentialsManager() {
1575
-		return $this->query('CredentialsManager');
1576
-	}
1577
-
1578
-	/**
1579
-	 * Get the certificate manager for the user
1580
-	 *
1581
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1582
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1583
-	 */
1584
-	public function getCertificateManager($userId = '') {
1585
-		if ($userId === '') {
1586
-			$userSession = $this->getUserSession();
1587
-			$user = $userSession->getUser();
1588
-			if (is_null($user)) {
1589
-				return null;
1590
-			}
1591
-			$userId = $user->getUID();
1592
-		}
1593
-		return new CertificateManager(
1594
-			$userId,
1595
-			new View(),
1596
-			$this->getConfig(),
1597
-			$this->getLogger(),
1598
-			$this->getSecureRandom()
1599
-		);
1600
-	}
1601
-
1602
-	/**
1603
-	 * Returns an instance of the HTTP client service
1604
-	 *
1605
-	 * @return \OCP\Http\Client\IClientService
1606
-	 */
1607
-	public function getHTTPClientService() {
1608
-		return $this->query('HttpClientService');
1609
-	}
1610
-
1611
-	/**
1612
-	 * Create a new event source
1613
-	 *
1614
-	 * @return \OCP\IEventSource
1615
-	 */
1616
-	public function createEventSource() {
1617
-		return new \OC_EventSource();
1618
-	}
1619
-
1620
-	/**
1621
-	 * Get the active event logger
1622
-	 *
1623
-	 * The returned logger only logs data when debug mode is enabled
1624
-	 *
1625
-	 * @return \OCP\Diagnostics\IEventLogger
1626
-	 */
1627
-	public function getEventLogger() {
1628
-		return $this->query('EventLogger');
1629
-	}
1630
-
1631
-	/**
1632
-	 * Get the active query logger
1633
-	 *
1634
-	 * The returned logger only logs data when debug mode is enabled
1635
-	 *
1636
-	 * @return \OCP\Diagnostics\IQueryLogger
1637
-	 */
1638
-	public function getQueryLogger() {
1639
-		return $this->query('QueryLogger');
1640
-	}
1641
-
1642
-	/**
1643
-	 * Get the manager for temporary files and folders
1644
-	 *
1645
-	 * @return \OCP\ITempManager
1646
-	 */
1647
-	public function getTempManager() {
1648
-		return $this->query('TempManager');
1649
-	}
1650
-
1651
-	/**
1652
-	 * Get the app manager
1653
-	 *
1654
-	 * @return \OCP\App\IAppManager
1655
-	 */
1656
-	public function getAppManager() {
1657
-		return $this->query('AppManager');
1658
-	}
1659
-
1660
-	/**
1661
-	 * Creates a new mailer
1662
-	 *
1663
-	 * @return \OCP\Mail\IMailer
1664
-	 */
1665
-	public function getMailer() {
1666
-		return $this->query('Mailer');
1667
-	}
1668
-
1669
-	/**
1670
-	 * Get the webroot
1671
-	 *
1672
-	 * @return string
1673
-	 */
1674
-	public function getWebRoot() {
1675
-		return $this->webRoot;
1676
-	}
1677
-
1678
-	/**
1679
-	 * @return \OC\OCSClient
1680
-	 */
1681
-	public function getOcsClient() {
1682
-		return $this->query('OcsClient');
1683
-	}
1684
-
1685
-	/**
1686
-	 * @return \OCP\IDateTimeZone
1687
-	 */
1688
-	public function getDateTimeZone() {
1689
-		return $this->query('DateTimeZone');
1690
-	}
1691
-
1692
-	/**
1693
-	 * @return \OCP\IDateTimeFormatter
1694
-	 */
1695
-	public function getDateTimeFormatter() {
1696
-		return $this->query('DateTimeFormatter');
1697
-	}
1698
-
1699
-	/**
1700
-	 * @return \OCP\Files\Config\IMountProviderCollection
1701
-	 */
1702
-	public function getMountProviderCollection() {
1703
-		return $this->query('MountConfigManager');
1704
-	}
1705
-
1706
-	/**
1707
-	 * Get the IniWrapper
1708
-	 *
1709
-	 * @return IniGetWrapper
1710
-	 */
1711
-	public function getIniWrapper() {
1712
-		return $this->query('IniWrapper');
1713
-	}
1714
-
1715
-	/**
1716
-	 * @return \OCP\Command\IBus
1717
-	 */
1718
-	public function getCommandBus() {
1719
-		return $this->query('AsyncCommandBus');
1720
-	}
1721
-
1722
-	/**
1723
-	 * Get the trusted domain helper
1724
-	 *
1725
-	 * @return TrustedDomainHelper
1726
-	 */
1727
-	public function getTrustedDomainHelper() {
1728
-		return $this->query('TrustedDomainHelper');
1729
-	}
1730
-
1731
-	/**
1732
-	 * Get the locking provider
1733
-	 *
1734
-	 * @return \OCP\Lock\ILockingProvider
1735
-	 * @since 8.1.0
1736
-	 */
1737
-	public function getLockingProvider() {
1738
-		return $this->query('LockingProvider');
1739
-	}
1740
-
1741
-	/**
1742
-	 * @return \OCP\Files\Mount\IMountManager
1743
-	 **/
1744
-	function getMountManager() {
1745
-		return $this->query('MountManager');
1746
-	}
1747
-
1748
-	/** @return \OCP\Files\Config\IUserMountCache */
1749
-	function getUserMountCache() {
1750
-		return $this->query('UserMountCache');
1751
-	}
1752
-
1753
-	/**
1754
-	 * Get the MimeTypeDetector
1755
-	 *
1756
-	 * @return \OCP\Files\IMimeTypeDetector
1757
-	 */
1758
-	public function getMimeTypeDetector() {
1759
-		return $this->query('MimeTypeDetector');
1760
-	}
1761
-
1762
-	/**
1763
-	 * Get the MimeTypeLoader
1764
-	 *
1765
-	 * @return \OCP\Files\IMimeTypeLoader
1766
-	 */
1767
-	public function getMimeTypeLoader() {
1768
-		return $this->query('MimeTypeLoader');
1769
-	}
1770
-
1771
-	/**
1772
-	 * Get the manager of all the capabilities
1773
-	 *
1774
-	 * @return \OC\CapabilitiesManager
1775
-	 */
1776
-	public function getCapabilitiesManager() {
1777
-		return $this->query('CapabilitiesManager');
1778
-	}
1779
-
1780
-	/**
1781
-	 * Get the EventDispatcher
1782
-	 *
1783
-	 * @return EventDispatcherInterface
1784
-	 * @since 8.2.0
1785
-	 */
1786
-	public function getEventDispatcher() {
1787
-		return $this->query('EventDispatcher');
1788
-	}
1789
-
1790
-	/**
1791
-	 * Get the Notification Manager
1792
-	 *
1793
-	 * @return \OCP\Notification\IManager
1794
-	 * @since 8.2.0
1795
-	 */
1796
-	public function getNotificationManager() {
1797
-		return $this->query('NotificationManager');
1798
-	}
1799
-
1800
-	/**
1801
-	 * @return \OCP\Comments\ICommentsManager
1802
-	 */
1803
-	public function getCommentsManager() {
1804
-		return $this->query('CommentsManager');
1805
-	}
1806
-
1807
-	/**
1808
-	 * @return \OCA\Theming\ThemingDefaults
1809
-	 */
1810
-	public function getThemingDefaults() {
1811
-		return $this->query('ThemingDefaults');
1812
-	}
1813
-
1814
-	/**
1815
-	 * @return \OC\IntegrityCheck\Checker
1816
-	 */
1817
-	public function getIntegrityCodeChecker() {
1818
-		return $this->query('IntegrityCodeChecker');
1819
-	}
1820
-
1821
-	/**
1822
-	 * @return \OC\Session\CryptoWrapper
1823
-	 */
1824
-	public function getSessionCryptoWrapper() {
1825
-		return $this->query('CryptoWrapper');
1826
-	}
1827
-
1828
-	/**
1829
-	 * @return CsrfTokenManager
1830
-	 */
1831
-	public function getCsrfTokenManager() {
1832
-		return $this->query('CsrfTokenManager');
1833
-	}
1834
-
1835
-	/**
1836
-	 * @return Throttler
1837
-	 */
1838
-	public function getBruteForceThrottler() {
1839
-		return $this->query('Throttler');
1840
-	}
1841
-
1842
-	/**
1843
-	 * @return IContentSecurityPolicyManager
1844
-	 */
1845
-	public function getContentSecurityPolicyManager() {
1846
-		return $this->query('ContentSecurityPolicyManager');
1847
-	}
1848
-
1849
-	/**
1850
-	 * @return ContentSecurityPolicyNonceManager
1851
-	 */
1852
-	public function getContentSecurityPolicyNonceManager() {
1853
-		return $this->query('ContentSecurityPolicyNonceManager');
1854
-	}
1855
-
1856
-	/**
1857
-	 * Not a public API as of 8.2, wait for 9.0
1858
-	 *
1859
-	 * @return \OCA\Files_External\Service\BackendService
1860
-	 */
1861
-	public function getStoragesBackendService() {
1862
-		return $this->query('OCA\\Files_External\\Service\\BackendService');
1863
-	}
1864
-
1865
-	/**
1866
-	 * Not a public API as of 8.2, wait for 9.0
1867
-	 *
1868
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1869
-	 */
1870
-	public function getGlobalStoragesService() {
1871
-		return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1872
-	}
1873
-
1874
-	/**
1875
-	 * Not a public API as of 8.2, wait for 9.0
1876
-	 *
1877
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1878
-	 */
1879
-	public function getUserGlobalStoragesService() {
1880
-		return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1881
-	}
1882
-
1883
-	/**
1884
-	 * Not a public API as of 8.2, wait for 9.0
1885
-	 *
1886
-	 * @return \OCA\Files_External\Service\UserStoragesService
1887
-	 */
1888
-	public function getUserStoragesService() {
1889
-		return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1890
-	}
1891
-
1892
-	/**
1893
-	 * @return \OCP\Share\IManager
1894
-	 */
1895
-	public function getShareManager() {
1896
-		return $this->query('ShareManager');
1897
-	}
1898
-
1899
-	/**
1900
-	 * @return \OCP\Collaboration\Collaborators\ISearch
1901
-	 */
1902
-	public function getCollaboratorSearch() {
1903
-		return $this->query('CollaboratorSearch');
1904
-	}
1905
-
1906
-	/**
1907
-	 * @return \OCP\Collaboration\AutoComplete\IManager
1908
-	 */
1909
-	public function getAutoCompleteManager(){
1910
-		return $this->query(IManager::class);
1911
-	}
1912
-
1913
-	/**
1914
-	 * Returns the LDAP Provider
1915
-	 *
1916
-	 * @return \OCP\LDAP\ILDAPProvider
1917
-	 */
1918
-	public function getLDAPProvider() {
1919
-		return $this->query('LDAPProvider');
1920
-	}
1921
-
1922
-	/**
1923
-	 * @return \OCP\Settings\IManager
1924
-	 */
1925
-	public function getSettingsManager() {
1926
-		return $this->query('SettingsManager');
1927
-	}
1928
-
1929
-	/**
1930
-	 * @return \OCP\Files\IAppData
1931
-	 */
1932
-	public function getAppDataDir($app) {
1933
-		/** @var \OC\Files\AppData\Factory $factory */
1934
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
1935
-		return $factory->get($app);
1936
-	}
1937
-
1938
-	/**
1939
-	 * @return \OCP\Lockdown\ILockdownManager
1940
-	 */
1941
-	public function getLockdownManager() {
1942
-		return $this->query('LockdownManager');
1943
-	}
1944
-
1945
-	/**
1946
-	 * @return \OCP\Federation\ICloudIdManager
1947
-	 */
1948
-	public function getCloudIdManager() {
1949
-		return $this->query(ICloudIdManager::class);
1950
-	}
1951
-
1952
-	/**
1953
-	 * @return \OCP\Remote\Api\IApiFactory
1954
-	 */
1955
-	public function getRemoteApiFactory() {
1956
-		return $this->query(IApiFactory::class);
1957
-	}
1958
-
1959
-	/**
1960
-	 * @return \OCP\Remote\IInstanceFactory
1961
-	 */
1962
-	public function getRemoteInstanceFactory() {
1963
-		return $this->query(IInstanceFactory::class);
1964
-	}
928
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
929
+            if (isset($prefixes['OCA\\Theming\\'])) {
930
+                $classExists = true;
931
+            } else {
932
+                $classExists = false;
933
+            }
934
+
935
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
936
+                return new ThemingDefaults(
937
+                    $c->getConfig(),
938
+                    $c->getL10N('theming'),
939
+                    $c->getURLGenerator(),
940
+                    $c->getAppDataDir('theming'),
941
+                    $c->getMemCacheFactory(),
942
+                    new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming')),
943
+                    $this->getAppManager()
944
+                );
945
+            }
946
+            return new \OC_Defaults();
947
+        });
948
+        $this->registerService(SCSSCacher::class, function (Server $c) {
949
+            /** @var Factory $cacheFactory */
950
+            $cacheFactory = $c->query(Factory::class);
951
+            return new SCSSCacher(
952
+                $c->getLogger(),
953
+                $c->query(\OC\Files\AppData\Factory::class),
954
+                $c->getURLGenerator(),
955
+                $c->getConfig(),
956
+                $c->getThemingDefaults(),
957
+                \OC::$SERVERROOT,
958
+                $this->getMemCacheFactory()
959
+            );
960
+        });
961
+        $this->registerService(JSCombiner::class, function (Server $c) {
962
+            /** @var Factory $cacheFactory */
963
+            $cacheFactory = $c->query(Factory::class);
964
+            return new JSCombiner(
965
+                $c->getAppDataDir('js'),
966
+                $c->getURLGenerator(),
967
+                $this->getMemCacheFactory(),
968
+                $c->getSystemConfig(),
969
+                $c->getLogger()
970
+            );
971
+        });
972
+        $this->registerService(EventDispatcher::class, function () {
973
+            return new EventDispatcher();
974
+        });
975
+        $this->registerAlias('EventDispatcher', EventDispatcher::class);
976
+        $this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
977
+
978
+        $this->registerService('CryptoWrapper', function (Server $c) {
979
+            // FIXME: Instantiiated here due to cyclic dependency
980
+            $request = new Request(
981
+                [
982
+                    'get' => $_GET,
983
+                    'post' => $_POST,
984
+                    'files' => $_FILES,
985
+                    'server' => $_SERVER,
986
+                    'env' => $_ENV,
987
+                    'cookies' => $_COOKIE,
988
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
989
+                        ? $_SERVER['REQUEST_METHOD']
990
+                        : null,
991
+                ],
992
+                $c->getSecureRandom(),
993
+                $c->getConfig()
994
+            );
995
+
996
+            return new CryptoWrapper(
997
+                $c->getConfig(),
998
+                $c->getCrypto(),
999
+                $c->getSecureRandom(),
1000
+                $request
1001
+            );
1002
+        });
1003
+        $this->registerService('CsrfTokenManager', function (Server $c) {
1004
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1005
+
1006
+            return new CsrfTokenManager(
1007
+                $tokenGenerator,
1008
+                $c->query(SessionStorage::class)
1009
+            );
1010
+        });
1011
+        $this->registerService(SessionStorage::class, function (Server $c) {
1012
+            return new SessionStorage($c->getSession());
1013
+        });
1014
+        $this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1015
+            return new ContentSecurityPolicyManager();
1016
+        });
1017
+        $this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1018
+
1019
+        $this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1020
+            return new ContentSecurityPolicyNonceManager(
1021
+                $c->getCsrfTokenManager(),
1022
+                $c->getRequest()
1023
+            );
1024
+        });
1025
+
1026
+        $this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1027
+            $config = $c->getConfig();
1028
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1029
+            /** @var \OCP\Share\IProviderFactory $factory */
1030
+            $factory = new $factoryClass($this);
1031
+
1032
+            $manager = new \OC\Share20\Manager(
1033
+                $c->getLogger(),
1034
+                $c->getConfig(),
1035
+                $c->getSecureRandom(),
1036
+                $c->getHasher(),
1037
+                $c->getMountManager(),
1038
+                $c->getGroupManager(),
1039
+                $c->getL10N('lib'),
1040
+                $c->getL10NFactory(),
1041
+                $factory,
1042
+                $c->getUserManager(),
1043
+                $c->getLazyRootFolder(),
1044
+                $c->getEventDispatcher(),
1045
+                $c->getMailer(),
1046
+                $c->getURLGenerator(),
1047
+                $c->getThemingDefaults()
1048
+            );
1049
+
1050
+            return $manager;
1051
+        });
1052
+        $this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1053
+
1054
+        $this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1055
+            $instance = new Collaboration\Collaborators\Search($c);
1056
+
1057
+            // register default plugins
1058
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1059
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1060
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1061
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1062
+
1063
+            return $instance;
1064
+        });
1065
+        $this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1066
+
1067
+        $this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1068
+
1069
+        $this->registerService('SettingsManager', function (Server $c) {
1070
+            $manager = new \OC\Settings\Manager(
1071
+                $c->getLogger(),
1072
+                $c->getDatabaseConnection(),
1073
+                $c->getL10N('lib'),
1074
+                $c->getConfig(),
1075
+                $c->getEncryptionManager(),
1076
+                $c->getUserManager(),
1077
+                $c->getLockingProvider(),
1078
+                $c->getRequest(),
1079
+                $c->getURLGenerator(),
1080
+                $c->query(AccountManager::class),
1081
+                $c->getGroupManager(),
1082
+                $c->getL10NFactory(),
1083
+                $c->getAppManager()
1084
+            );
1085
+            return $manager;
1086
+        });
1087
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1088
+            return new \OC\Files\AppData\Factory(
1089
+                $c->getRootFolder(),
1090
+                $c->getSystemConfig()
1091
+            );
1092
+        });
1093
+
1094
+        $this->registerService('LockdownManager', function (Server $c) {
1095
+            return new LockdownManager(function () use ($c) {
1096
+                return $c->getSession();
1097
+            });
1098
+        });
1099
+
1100
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1101
+            return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1102
+        });
1103
+
1104
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
1105
+            return new CloudIdManager();
1106
+        });
1107
+
1108
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1109
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1110
+
1111
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1112
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1113
+
1114
+        $this->registerService(Defaults::class, function (Server $c) {
1115
+            return new Defaults(
1116
+                $c->getThemingDefaults()
1117
+            );
1118
+        });
1119
+        $this->registerAlias('Defaults', \OCP\Defaults::class);
1120
+
1121
+        $this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1122
+            return $c->query(\OCP\IUserSession::class)->getSession();
1123
+        });
1124
+
1125
+        $this->registerService(IShareHelper::class, function (Server $c) {
1126
+            return new ShareHelper(
1127
+                $c->query(\OCP\Share\IManager::class)
1128
+            );
1129
+        });
1130
+
1131
+        $this->registerService(Installer::class, function(Server $c) {
1132
+            return new Installer(
1133
+                $c->getAppFetcher(),
1134
+                $c->getHTTPClientService(),
1135
+                $c->getTempManager(),
1136
+                $c->getLogger(),
1137
+                $c->getConfig()
1138
+            );
1139
+        });
1140
+
1141
+        $this->registerService(IApiFactory::class, function(Server $c) {
1142
+            return new ApiFactory($c->getHTTPClientService());
1143
+        });
1144
+
1145
+        $this->registerService(IInstanceFactory::class, function(Server $c) {
1146
+            $memcacheFactory = $c->getMemCacheFactory();
1147
+            return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1148
+        });
1149
+
1150
+        $this->registerService(IContactsStore::class, function(Server $c) {
1151
+            return new ContactsStore(
1152
+                $c->getContactsManager(),
1153
+                $c->getConfig(),
1154
+                $c->getUserManager(),
1155
+                $c->getGroupManager()
1156
+            );
1157
+        });
1158
+        $this->registerAlias(IContactsStore::class, ContactsStore::class);
1159
+
1160
+        $this->connectDispatcher();
1161
+    }
1162
+
1163
+    /**
1164
+     * @return \OCP\Calendar\IManager
1165
+     */
1166
+    public function getCalendarManager() {
1167
+        return $this->query('CalendarManager');
1168
+    }
1169
+
1170
+    private function connectDispatcher() {
1171
+        $dispatcher = $this->getEventDispatcher();
1172
+
1173
+        // Delete avatar on user deletion
1174
+        $dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1175
+            $logger = $this->getLogger();
1176
+            $manager = $this->getAvatarManager();
1177
+            /** @var IUser $user */
1178
+            $user = $e->getSubject();
1179
+
1180
+            try {
1181
+                $avatar = $manager->getAvatar($user->getUID());
1182
+                $avatar->remove();
1183
+            } catch (NotFoundException $e) {
1184
+                // no avatar to remove
1185
+            } catch (\Exception $e) {
1186
+                // Ignore exceptions
1187
+                $logger->info('Could not cleanup avatar of ' . $user->getUID());
1188
+            }
1189
+        });
1190
+
1191
+        $dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1192
+            $manager = $this->getAvatarManager();
1193
+            /** @var IUser $user */
1194
+            $user = $e->getSubject();
1195
+            $feature = $e->getArgument('feature');
1196
+            $oldValue = $e->getArgument('oldValue');
1197
+            $value = $e->getArgument('value');
1198
+
1199
+            try {
1200
+                $avatar = $manager->getAvatar($user->getUID());
1201
+                $avatar->userChanged($feature, $oldValue, $value);
1202
+            } catch (NotFoundException $e) {
1203
+                // no avatar to remove
1204
+            }
1205
+        });
1206
+    }
1207
+
1208
+    /**
1209
+     * @return \OCP\Contacts\IManager
1210
+     */
1211
+    public function getContactsManager() {
1212
+        return $this->query('ContactsManager');
1213
+    }
1214
+
1215
+    /**
1216
+     * @return \OC\Encryption\Manager
1217
+     */
1218
+    public function getEncryptionManager() {
1219
+        return $this->query('EncryptionManager');
1220
+    }
1221
+
1222
+    /**
1223
+     * @return \OC\Encryption\File
1224
+     */
1225
+    public function getEncryptionFilesHelper() {
1226
+        return $this->query('EncryptionFileHelper');
1227
+    }
1228
+
1229
+    /**
1230
+     * @return \OCP\Encryption\Keys\IStorage
1231
+     */
1232
+    public function getEncryptionKeyStorage() {
1233
+        return $this->query('EncryptionKeyStorage');
1234
+    }
1235
+
1236
+    /**
1237
+     * The current request object holding all information about the request
1238
+     * currently being processed is returned from this method.
1239
+     * In case the current execution was not initiated by a web request null is returned
1240
+     *
1241
+     * @return \OCP\IRequest
1242
+     */
1243
+    public function getRequest() {
1244
+        return $this->query('Request');
1245
+    }
1246
+
1247
+    /**
1248
+     * Returns the preview manager which can create preview images for a given file
1249
+     *
1250
+     * @return \OCP\IPreview
1251
+     */
1252
+    public function getPreviewManager() {
1253
+        return $this->query('PreviewManager');
1254
+    }
1255
+
1256
+    /**
1257
+     * Returns the tag manager which can get and set tags for different object types
1258
+     *
1259
+     * @see \OCP\ITagManager::load()
1260
+     * @return \OCP\ITagManager
1261
+     */
1262
+    public function getTagManager() {
1263
+        return $this->query('TagManager');
1264
+    }
1265
+
1266
+    /**
1267
+     * Returns the system-tag manager
1268
+     *
1269
+     * @return \OCP\SystemTag\ISystemTagManager
1270
+     *
1271
+     * @since 9.0.0
1272
+     */
1273
+    public function getSystemTagManager() {
1274
+        return $this->query('SystemTagManager');
1275
+    }
1276
+
1277
+    /**
1278
+     * Returns the system-tag object mapper
1279
+     *
1280
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
1281
+     *
1282
+     * @since 9.0.0
1283
+     */
1284
+    public function getSystemTagObjectMapper() {
1285
+        return $this->query('SystemTagObjectMapper');
1286
+    }
1287
+
1288
+    /**
1289
+     * Returns the avatar manager, used for avatar functionality
1290
+     *
1291
+     * @return \OCP\IAvatarManager
1292
+     */
1293
+    public function getAvatarManager() {
1294
+        return $this->query('AvatarManager');
1295
+    }
1296
+
1297
+    /**
1298
+     * Returns the root folder of ownCloud's data directory
1299
+     *
1300
+     * @return \OCP\Files\IRootFolder
1301
+     */
1302
+    public function getRootFolder() {
1303
+        return $this->query('LazyRootFolder');
1304
+    }
1305
+
1306
+    /**
1307
+     * Returns the root folder of ownCloud's data directory
1308
+     * This is the lazy variant so this gets only initialized once it
1309
+     * is actually used.
1310
+     *
1311
+     * @return \OCP\Files\IRootFolder
1312
+     */
1313
+    public function getLazyRootFolder() {
1314
+        return $this->query('LazyRootFolder');
1315
+    }
1316
+
1317
+    /**
1318
+     * Returns a view to ownCloud's files folder
1319
+     *
1320
+     * @param string $userId user ID
1321
+     * @return \OCP\Files\Folder|null
1322
+     */
1323
+    public function getUserFolder($userId = null) {
1324
+        if ($userId === null) {
1325
+            $user = $this->getUserSession()->getUser();
1326
+            if (!$user) {
1327
+                return null;
1328
+            }
1329
+            $userId = $user->getUID();
1330
+        }
1331
+        $root = $this->getRootFolder();
1332
+        return $root->getUserFolder($userId);
1333
+    }
1334
+
1335
+    /**
1336
+     * Returns an app-specific view in ownClouds data directory
1337
+     *
1338
+     * @return \OCP\Files\Folder
1339
+     * @deprecated since 9.2.0 use IAppData
1340
+     */
1341
+    public function getAppFolder() {
1342
+        $dir = '/' . \OC_App::getCurrentApp();
1343
+        $root = $this->getRootFolder();
1344
+        if (!$root->nodeExists($dir)) {
1345
+            $folder = $root->newFolder($dir);
1346
+        } else {
1347
+            $folder = $root->get($dir);
1348
+        }
1349
+        return $folder;
1350
+    }
1351
+
1352
+    /**
1353
+     * @return \OC\User\Manager
1354
+     */
1355
+    public function getUserManager() {
1356
+        return $this->query('UserManager');
1357
+    }
1358
+
1359
+    /**
1360
+     * @return \OC\Group\Manager
1361
+     */
1362
+    public function getGroupManager() {
1363
+        return $this->query('GroupManager');
1364
+    }
1365
+
1366
+    /**
1367
+     * @return \OC\User\Session
1368
+     */
1369
+    public function getUserSession() {
1370
+        return $this->query('UserSession');
1371
+    }
1372
+
1373
+    /**
1374
+     * @return \OCP\ISession
1375
+     */
1376
+    public function getSession() {
1377
+        return $this->query('UserSession')->getSession();
1378
+    }
1379
+
1380
+    /**
1381
+     * @param \OCP\ISession $session
1382
+     */
1383
+    public function setSession(\OCP\ISession $session) {
1384
+        $this->query(SessionStorage::class)->setSession($session);
1385
+        $this->query('UserSession')->setSession($session);
1386
+        $this->query(Store::class)->setSession($session);
1387
+    }
1388
+
1389
+    /**
1390
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1391
+     */
1392
+    public function getTwoFactorAuthManager() {
1393
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1394
+    }
1395
+
1396
+    /**
1397
+     * @return \OC\NavigationManager
1398
+     */
1399
+    public function getNavigationManager() {
1400
+        return $this->query('NavigationManager');
1401
+    }
1402
+
1403
+    /**
1404
+     * @return \OCP\IConfig
1405
+     */
1406
+    public function getConfig() {
1407
+        return $this->query('AllConfig');
1408
+    }
1409
+
1410
+    /**
1411
+     * @return \OC\SystemConfig
1412
+     */
1413
+    public function getSystemConfig() {
1414
+        return $this->query('SystemConfig');
1415
+    }
1416
+
1417
+    /**
1418
+     * Returns the app config manager
1419
+     *
1420
+     * @return \OCP\IAppConfig
1421
+     */
1422
+    public function getAppConfig() {
1423
+        return $this->query('AppConfig');
1424
+    }
1425
+
1426
+    /**
1427
+     * @return \OCP\L10N\IFactory
1428
+     */
1429
+    public function getL10NFactory() {
1430
+        return $this->query('L10NFactory');
1431
+    }
1432
+
1433
+    /**
1434
+     * get an L10N instance
1435
+     *
1436
+     * @param string $app appid
1437
+     * @param string $lang
1438
+     * @return IL10N
1439
+     */
1440
+    public function getL10N($app, $lang = null) {
1441
+        return $this->getL10NFactory()->get($app, $lang);
1442
+    }
1443
+
1444
+    /**
1445
+     * @return \OCP\IURLGenerator
1446
+     */
1447
+    public function getURLGenerator() {
1448
+        return $this->query('URLGenerator');
1449
+    }
1450
+
1451
+    /**
1452
+     * @return AppFetcher
1453
+     */
1454
+    public function getAppFetcher() {
1455
+        return $this->query(AppFetcher::class);
1456
+    }
1457
+
1458
+    /**
1459
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1460
+     * getMemCacheFactory() instead.
1461
+     *
1462
+     * @return \OCP\ICache
1463
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1464
+     */
1465
+    public function getCache() {
1466
+        return $this->query('UserCache');
1467
+    }
1468
+
1469
+    /**
1470
+     * Returns an \OCP\CacheFactory instance
1471
+     *
1472
+     * @return \OCP\ICacheFactory
1473
+     */
1474
+    public function getMemCacheFactory() {
1475
+        return $this->query('MemCacheFactory');
1476
+    }
1477
+
1478
+    /**
1479
+     * Returns an \OC\RedisFactory instance
1480
+     *
1481
+     * @return \OC\RedisFactory
1482
+     */
1483
+    public function getGetRedisFactory() {
1484
+        return $this->query('RedisFactory');
1485
+    }
1486
+
1487
+
1488
+    /**
1489
+     * Returns the current session
1490
+     *
1491
+     * @return \OCP\IDBConnection
1492
+     */
1493
+    public function getDatabaseConnection() {
1494
+        return $this->query('DatabaseConnection');
1495
+    }
1496
+
1497
+    /**
1498
+     * Returns the activity manager
1499
+     *
1500
+     * @return \OCP\Activity\IManager
1501
+     */
1502
+    public function getActivityManager() {
1503
+        return $this->query('ActivityManager');
1504
+    }
1505
+
1506
+    /**
1507
+     * Returns an job list for controlling background jobs
1508
+     *
1509
+     * @return \OCP\BackgroundJob\IJobList
1510
+     */
1511
+    public function getJobList() {
1512
+        return $this->query('JobList');
1513
+    }
1514
+
1515
+    /**
1516
+     * Returns a logger instance
1517
+     *
1518
+     * @return \OCP\ILogger
1519
+     */
1520
+    public function getLogger() {
1521
+        return $this->query('Logger');
1522
+    }
1523
+
1524
+    /**
1525
+     * Returns a router for generating and matching urls
1526
+     *
1527
+     * @return \OCP\Route\IRouter
1528
+     */
1529
+    public function getRouter() {
1530
+        return $this->query('Router');
1531
+    }
1532
+
1533
+    /**
1534
+     * Returns a search instance
1535
+     *
1536
+     * @return \OCP\ISearch
1537
+     */
1538
+    public function getSearch() {
1539
+        return $this->query('Search');
1540
+    }
1541
+
1542
+    /**
1543
+     * Returns a SecureRandom instance
1544
+     *
1545
+     * @return \OCP\Security\ISecureRandom
1546
+     */
1547
+    public function getSecureRandom() {
1548
+        return $this->query('SecureRandom');
1549
+    }
1550
+
1551
+    /**
1552
+     * Returns a Crypto instance
1553
+     *
1554
+     * @return \OCP\Security\ICrypto
1555
+     */
1556
+    public function getCrypto() {
1557
+        return $this->query('Crypto');
1558
+    }
1559
+
1560
+    /**
1561
+     * Returns a Hasher instance
1562
+     *
1563
+     * @return \OCP\Security\IHasher
1564
+     */
1565
+    public function getHasher() {
1566
+        return $this->query('Hasher');
1567
+    }
1568
+
1569
+    /**
1570
+     * Returns a CredentialsManager instance
1571
+     *
1572
+     * @return \OCP\Security\ICredentialsManager
1573
+     */
1574
+    public function getCredentialsManager() {
1575
+        return $this->query('CredentialsManager');
1576
+    }
1577
+
1578
+    /**
1579
+     * Get the certificate manager for the user
1580
+     *
1581
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1582
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1583
+     */
1584
+    public function getCertificateManager($userId = '') {
1585
+        if ($userId === '') {
1586
+            $userSession = $this->getUserSession();
1587
+            $user = $userSession->getUser();
1588
+            if (is_null($user)) {
1589
+                return null;
1590
+            }
1591
+            $userId = $user->getUID();
1592
+        }
1593
+        return new CertificateManager(
1594
+            $userId,
1595
+            new View(),
1596
+            $this->getConfig(),
1597
+            $this->getLogger(),
1598
+            $this->getSecureRandom()
1599
+        );
1600
+    }
1601
+
1602
+    /**
1603
+     * Returns an instance of the HTTP client service
1604
+     *
1605
+     * @return \OCP\Http\Client\IClientService
1606
+     */
1607
+    public function getHTTPClientService() {
1608
+        return $this->query('HttpClientService');
1609
+    }
1610
+
1611
+    /**
1612
+     * Create a new event source
1613
+     *
1614
+     * @return \OCP\IEventSource
1615
+     */
1616
+    public function createEventSource() {
1617
+        return new \OC_EventSource();
1618
+    }
1619
+
1620
+    /**
1621
+     * Get the active event logger
1622
+     *
1623
+     * The returned logger only logs data when debug mode is enabled
1624
+     *
1625
+     * @return \OCP\Diagnostics\IEventLogger
1626
+     */
1627
+    public function getEventLogger() {
1628
+        return $this->query('EventLogger');
1629
+    }
1630
+
1631
+    /**
1632
+     * Get the active query logger
1633
+     *
1634
+     * The returned logger only logs data when debug mode is enabled
1635
+     *
1636
+     * @return \OCP\Diagnostics\IQueryLogger
1637
+     */
1638
+    public function getQueryLogger() {
1639
+        return $this->query('QueryLogger');
1640
+    }
1641
+
1642
+    /**
1643
+     * Get the manager for temporary files and folders
1644
+     *
1645
+     * @return \OCP\ITempManager
1646
+     */
1647
+    public function getTempManager() {
1648
+        return $this->query('TempManager');
1649
+    }
1650
+
1651
+    /**
1652
+     * Get the app manager
1653
+     *
1654
+     * @return \OCP\App\IAppManager
1655
+     */
1656
+    public function getAppManager() {
1657
+        return $this->query('AppManager');
1658
+    }
1659
+
1660
+    /**
1661
+     * Creates a new mailer
1662
+     *
1663
+     * @return \OCP\Mail\IMailer
1664
+     */
1665
+    public function getMailer() {
1666
+        return $this->query('Mailer');
1667
+    }
1668
+
1669
+    /**
1670
+     * Get the webroot
1671
+     *
1672
+     * @return string
1673
+     */
1674
+    public function getWebRoot() {
1675
+        return $this->webRoot;
1676
+    }
1677
+
1678
+    /**
1679
+     * @return \OC\OCSClient
1680
+     */
1681
+    public function getOcsClient() {
1682
+        return $this->query('OcsClient');
1683
+    }
1684
+
1685
+    /**
1686
+     * @return \OCP\IDateTimeZone
1687
+     */
1688
+    public function getDateTimeZone() {
1689
+        return $this->query('DateTimeZone');
1690
+    }
1691
+
1692
+    /**
1693
+     * @return \OCP\IDateTimeFormatter
1694
+     */
1695
+    public function getDateTimeFormatter() {
1696
+        return $this->query('DateTimeFormatter');
1697
+    }
1698
+
1699
+    /**
1700
+     * @return \OCP\Files\Config\IMountProviderCollection
1701
+     */
1702
+    public function getMountProviderCollection() {
1703
+        return $this->query('MountConfigManager');
1704
+    }
1705
+
1706
+    /**
1707
+     * Get the IniWrapper
1708
+     *
1709
+     * @return IniGetWrapper
1710
+     */
1711
+    public function getIniWrapper() {
1712
+        return $this->query('IniWrapper');
1713
+    }
1714
+
1715
+    /**
1716
+     * @return \OCP\Command\IBus
1717
+     */
1718
+    public function getCommandBus() {
1719
+        return $this->query('AsyncCommandBus');
1720
+    }
1721
+
1722
+    /**
1723
+     * Get the trusted domain helper
1724
+     *
1725
+     * @return TrustedDomainHelper
1726
+     */
1727
+    public function getTrustedDomainHelper() {
1728
+        return $this->query('TrustedDomainHelper');
1729
+    }
1730
+
1731
+    /**
1732
+     * Get the locking provider
1733
+     *
1734
+     * @return \OCP\Lock\ILockingProvider
1735
+     * @since 8.1.0
1736
+     */
1737
+    public function getLockingProvider() {
1738
+        return $this->query('LockingProvider');
1739
+    }
1740
+
1741
+    /**
1742
+     * @return \OCP\Files\Mount\IMountManager
1743
+     **/
1744
+    function getMountManager() {
1745
+        return $this->query('MountManager');
1746
+    }
1747
+
1748
+    /** @return \OCP\Files\Config\IUserMountCache */
1749
+    function getUserMountCache() {
1750
+        return $this->query('UserMountCache');
1751
+    }
1752
+
1753
+    /**
1754
+     * Get the MimeTypeDetector
1755
+     *
1756
+     * @return \OCP\Files\IMimeTypeDetector
1757
+     */
1758
+    public function getMimeTypeDetector() {
1759
+        return $this->query('MimeTypeDetector');
1760
+    }
1761
+
1762
+    /**
1763
+     * Get the MimeTypeLoader
1764
+     *
1765
+     * @return \OCP\Files\IMimeTypeLoader
1766
+     */
1767
+    public function getMimeTypeLoader() {
1768
+        return $this->query('MimeTypeLoader');
1769
+    }
1770
+
1771
+    /**
1772
+     * Get the manager of all the capabilities
1773
+     *
1774
+     * @return \OC\CapabilitiesManager
1775
+     */
1776
+    public function getCapabilitiesManager() {
1777
+        return $this->query('CapabilitiesManager');
1778
+    }
1779
+
1780
+    /**
1781
+     * Get the EventDispatcher
1782
+     *
1783
+     * @return EventDispatcherInterface
1784
+     * @since 8.2.0
1785
+     */
1786
+    public function getEventDispatcher() {
1787
+        return $this->query('EventDispatcher');
1788
+    }
1789
+
1790
+    /**
1791
+     * Get the Notification Manager
1792
+     *
1793
+     * @return \OCP\Notification\IManager
1794
+     * @since 8.2.0
1795
+     */
1796
+    public function getNotificationManager() {
1797
+        return $this->query('NotificationManager');
1798
+    }
1799
+
1800
+    /**
1801
+     * @return \OCP\Comments\ICommentsManager
1802
+     */
1803
+    public function getCommentsManager() {
1804
+        return $this->query('CommentsManager');
1805
+    }
1806
+
1807
+    /**
1808
+     * @return \OCA\Theming\ThemingDefaults
1809
+     */
1810
+    public function getThemingDefaults() {
1811
+        return $this->query('ThemingDefaults');
1812
+    }
1813
+
1814
+    /**
1815
+     * @return \OC\IntegrityCheck\Checker
1816
+     */
1817
+    public function getIntegrityCodeChecker() {
1818
+        return $this->query('IntegrityCodeChecker');
1819
+    }
1820
+
1821
+    /**
1822
+     * @return \OC\Session\CryptoWrapper
1823
+     */
1824
+    public function getSessionCryptoWrapper() {
1825
+        return $this->query('CryptoWrapper');
1826
+    }
1827
+
1828
+    /**
1829
+     * @return CsrfTokenManager
1830
+     */
1831
+    public function getCsrfTokenManager() {
1832
+        return $this->query('CsrfTokenManager');
1833
+    }
1834
+
1835
+    /**
1836
+     * @return Throttler
1837
+     */
1838
+    public function getBruteForceThrottler() {
1839
+        return $this->query('Throttler');
1840
+    }
1841
+
1842
+    /**
1843
+     * @return IContentSecurityPolicyManager
1844
+     */
1845
+    public function getContentSecurityPolicyManager() {
1846
+        return $this->query('ContentSecurityPolicyManager');
1847
+    }
1848
+
1849
+    /**
1850
+     * @return ContentSecurityPolicyNonceManager
1851
+     */
1852
+    public function getContentSecurityPolicyNonceManager() {
1853
+        return $this->query('ContentSecurityPolicyNonceManager');
1854
+    }
1855
+
1856
+    /**
1857
+     * Not a public API as of 8.2, wait for 9.0
1858
+     *
1859
+     * @return \OCA\Files_External\Service\BackendService
1860
+     */
1861
+    public function getStoragesBackendService() {
1862
+        return $this->query('OCA\\Files_External\\Service\\BackendService');
1863
+    }
1864
+
1865
+    /**
1866
+     * Not a public API as of 8.2, wait for 9.0
1867
+     *
1868
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1869
+     */
1870
+    public function getGlobalStoragesService() {
1871
+        return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1872
+    }
1873
+
1874
+    /**
1875
+     * Not a public API as of 8.2, wait for 9.0
1876
+     *
1877
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1878
+     */
1879
+    public function getUserGlobalStoragesService() {
1880
+        return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1881
+    }
1882
+
1883
+    /**
1884
+     * Not a public API as of 8.2, wait for 9.0
1885
+     *
1886
+     * @return \OCA\Files_External\Service\UserStoragesService
1887
+     */
1888
+    public function getUserStoragesService() {
1889
+        return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1890
+    }
1891
+
1892
+    /**
1893
+     * @return \OCP\Share\IManager
1894
+     */
1895
+    public function getShareManager() {
1896
+        return $this->query('ShareManager');
1897
+    }
1898
+
1899
+    /**
1900
+     * @return \OCP\Collaboration\Collaborators\ISearch
1901
+     */
1902
+    public function getCollaboratorSearch() {
1903
+        return $this->query('CollaboratorSearch');
1904
+    }
1905
+
1906
+    /**
1907
+     * @return \OCP\Collaboration\AutoComplete\IManager
1908
+     */
1909
+    public function getAutoCompleteManager(){
1910
+        return $this->query(IManager::class);
1911
+    }
1912
+
1913
+    /**
1914
+     * Returns the LDAP Provider
1915
+     *
1916
+     * @return \OCP\LDAP\ILDAPProvider
1917
+     */
1918
+    public function getLDAPProvider() {
1919
+        return $this->query('LDAPProvider');
1920
+    }
1921
+
1922
+    /**
1923
+     * @return \OCP\Settings\IManager
1924
+     */
1925
+    public function getSettingsManager() {
1926
+        return $this->query('SettingsManager');
1927
+    }
1928
+
1929
+    /**
1930
+     * @return \OCP\Files\IAppData
1931
+     */
1932
+    public function getAppDataDir($app) {
1933
+        /** @var \OC\Files\AppData\Factory $factory */
1934
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
1935
+        return $factory->get($app);
1936
+    }
1937
+
1938
+    /**
1939
+     * @return \OCP\Lockdown\ILockdownManager
1940
+     */
1941
+    public function getLockdownManager() {
1942
+        return $this->query('LockdownManager');
1943
+    }
1944
+
1945
+    /**
1946
+     * @return \OCP\Federation\ICloudIdManager
1947
+     */
1948
+    public function getCloudIdManager() {
1949
+        return $this->query(ICloudIdManager::class);
1950
+    }
1951
+
1952
+    /**
1953
+     * @return \OCP\Remote\Api\IApiFactory
1954
+     */
1955
+    public function getRemoteApiFactory() {
1956
+        return $this->query(IApiFactory::class);
1957
+    }
1958
+
1959
+    /**
1960
+     * @return \OCP\Remote\IInstanceFactory
1961
+     */
1962
+    public function getRemoteInstanceFactory() {
1963
+        return $this->query(IInstanceFactory::class);
1964
+    }
1965 1965
 }
Please login to merge, or discard this patch.
Spacing   +113 added lines, -113 removed lines patch added patch discarded remove patch
@@ -161,7 +161,7 @@  discard block
 block discarded – undo
161 161
 		parent::__construct();
162 162
 		$this->webRoot = $webRoot;
163 163
 
164
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
164
+		$this->registerService(\OCP\IServerContainer::class, function(IServerContainer $c) {
165 165
 			return $c;
166 166
 		});
167 167
 
@@ -174,7 +174,7 @@  discard block
 block discarded – undo
174 174
 		$this->registerAlias(IActionFactory::class, ActionFactory::class);
175 175
 
176 176
 
177
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
177
+		$this->registerService(\OCP\IPreview::class, function(Server $c) {
178 178
 			return new PreviewManager(
179 179
 				$c->getConfig(),
180 180
 				$c->getRootFolder(),
@@ -185,13 +185,13 @@  discard block
 block discarded – undo
185 185
 		});
186 186
 		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
187 187
 
188
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
188
+		$this->registerService(\OC\Preview\Watcher::class, function(Server $c) {
189 189
 			return new \OC\Preview\Watcher(
190 190
 				$c->getAppDataDir('preview')
191 191
 			);
192 192
 		});
193 193
 
194
-		$this->registerService('EncryptionManager', function (Server $c) {
194
+		$this->registerService('EncryptionManager', function(Server $c) {
195 195
 			$view = new View();
196 196
 			$util = new Encryption\Util(
197 197
 				$view,
@@ -209,7 +209,7 @@  discard block
 block discarded – undo
209 209
 			);
210 210
 		});
211 211
 
212
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
212
+		$this->registerService('EncryptionFileHelper', function(Server $c) {
213 213
 			$util = new Encryption\Util(
214 214
 				new View(),
215 215
 				$c->getUserManager(),
@@ -223,7 +223,7 @@  discard block
 block discarded – undo
223 223
 			);
224 224
 		});
225 225
 
226
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
226
+		$this->registerService('EncryptionKeyStorage', function(Server $c) {
227 227
 			$view = new View();
228 228
 			$util = new Encryption\Util(
229 229
 				$view,
@@ -234,30 +234,30 @@  discard block
 block discarded – undo
234 234
 
235 235
 			return new Encryption\Keys\Storage($view, $util);
236 236
 		});
237
-		$this->registerService('TagMapper', function (Server $c) {
237
+		$this->registerService('TagMapper', function(Server $c) {
238 238
 			return new TagMapper($c->getDatabaseConnection());
239 239
 		});
240 240
 
241
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
241
+		$this->registerService(\OCP\ITagManager::class, function(Server $c) {
242 242
 			$tagMapper = $c->query('TagMapper');
243 243
 			return new TagManager($tagMapper, $c->getUserSession());
244 244
 		});
245 245
 		$this->registerAlias('TagManager', \OCP\ITagManager::class);
246 246
 
247
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
247
+		$this->registerService('SystemTagManagerFactory', function(Server $c) {
248 248
 			$config = $c->getConfig();
249 249
 			$factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
250 250
 			return new $factoryClass($this);
251 251
 		});
252
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
252
+		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function(Server $c) {
253 253
 			return $c->query('SystemTagManagerFactory')->getManager();
254 254
 		});
255 255
 		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
256 256
 
257
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
257
+		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function(Server $c) {
258 258
 			return $c->query('SystemTagManagerFactory')->getObjectMapper();
259 259
 		});
260
-		$this->registerService('RootFolder', function (Server $c) {
260
+		$this->registerService('RootFolder', function(Server $c) {
261 261
 			$manager = \OC\Files\Filesystem::getMountManager(null);
262 262
 			$view = new View();
263 263
 			$root = new Root(
@@ -278,38 +278,38 @@  discard block
 block discarded – undo
278 278
 		});
279 279
 		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
280 280
 
281
-		$this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
282
-			return new LazyRoot(function () use ($c) {
281
+		$this->registerService(\OCP\Files\IRootFolder::class, function(Server $c) {
282
+			return new LazyRoot(function() use ($c) {
283 283
 				return $c->query('RootFolder');
284 284
 			});
285 285
 		});
286 286
 		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
287 287
 
288
-		$this->registerService(\OC\User\Manager::class, function (Server $c) {
288
+		$this->registerService(\OC\User\Manager::class, function(Server $c) {
289 289
 			$config = $c->getConfig();
290 290
 			return new \OC\User\Manager($config);
291 291
 		});
292 292
 		$this->registerAlias('UserManager', \OC\User\Manager::class);
293 293
 		$this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
294 294
 
295
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
295
+		$this->registerService(\OCP\IGroupManager::class, function(Server $c) {
296 296
 			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
297
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
297
+			$groupManager->listen('\OC\Group', 'preCreate', function($gid) {
298 298
 				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
299 299
 			});
300
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
300
+			$groupManager->listen('\OC\Group', 'postCreate', function(\OC\Group\Group $gid) {
301 301
 				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
302 302
 			});
303
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
303
+			$groupManager->listen('\OC\Group', 'preDelete', function(\OC\Group\Group $group) {
304 304
 				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
305 305
 			});
306
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
306
+			$groupManager->listen('\OC\Group', 'postDelete', function(\OC\Group\Group $group) {
307 307
 				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
308 308
 			});
309
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
309
+			$groupManager->listen('\OC\Group', 'preAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
310 310
 				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
311 311
 			});
312
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
312
+			$groupManager->listen('\OC\Group', 'postAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
313 313
 				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
314 314
 				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
315 315
 				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
@@ -318,7 +318,7 @@  discard block
 block discarded – undo
318 318
 		});
319 319
 		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
320 320
 
321
-		$this->registerService(Store::class, function (Server $c) {
321
+		$this->registerService(Store::class, function(Server $c) {
322 322
 			$session = $c->getSession();
323 323
 			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
324 324
 				$tokenProvider = $c->query(IProvider::class);
@@ -329,11 +329,11 @@  discard block
 block discarded – undo
329 329
 			return new Store($session, $logger, $tokenProvider);
330 330
 		});
331 331
 		$this->registerAlias(IStore::class, Store::class);
332
-		$this->registerService(Authentication\Token\DefaultTokenMapper::class, function (Server $c) {
332
+		$this->registerService(Authentication\Token\DefaultTokenMapper::class, function(Server $c) {
333 333
 			$dbConnection = $c->getDatabaseConnection();
334 334
 			return new Authentication\Token\DefaultTokenMapper($dbConnection);
335 335
 		});
336
-		$this->registerService(Authentication\Token\DefaultTokenProvider::class, function (Server $c) {
336
+		$this->registerService(Authentication\Token\DefaultTokenProvider::class, function(Server $c) {
337 337
 			$mapper = $c->query(Authentication\Token\DefaultTokenMapper::class);
338 338
 			$crypto = $c->getCrypto();
339 339
 			$config = $c->getConfig();
@@ -343,7 +343,7 @@  discard block
 block discarded – undo
343 343
 		});
344 344
 		$this->registerAlias(IProvider::class, Authentication\Token\DefaultTokenProvider::class);
345 345
 
346
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
346
+		$this->registerService(\OCP\IUserSession::class, function(Server $c) {
347 347
 			$manager = $c->getUserManager();
348 348
 			$session = new \OC\Session\Memory('');
349 349
 			$timeFactory = new TimeFactory();
@@ -367,45 +367,45 @@  discard block
 block discarded – undo
367 367
 				$c->getLockdownManager(),
368 368
 				$c->getLogger()
369 369
 			);
370
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
370
+			$userSession->listen('\OC\User', 'preCreateUser', function($uid, $password) {
371 371
 				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
372 372
 			});
373
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
373
+			$userSession->listen('\OC\User', 'postCreateUser', function($user, $password) {
374 374
 				/** @var $user \OC\User\User */
375 375
 				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
376 376
 			});
377
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
377
+			$userSession->listen('\OC\User', 'preDelete', function($user) use ($dispatcher) {
378 378
 				/** @var $user \OC\User\User */
379 379
 				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
380 380
 				$dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
381 381
 			});
382
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
382
+			$userSession->listen('\OC\User', 'postDelete', function($user) {
383 383
 				/** @var $user \OC\User\User */
384 384
 				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
385 385
 			});
386
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
386
+			$userSession->listen('\OC\User', 'preSetPassword', function($user, $password, $recoveryPassword) {
387 387
 				/** @var $user \OC\User\User */
388 388
 				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
389 389
 			});
390
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
390
+			$userSession->listen('\OC\User', 'postSetPassword', function($user, $password, $recoveryPassword) {
391 391
 				/** @var $user \OC\User\User */
392 392
 				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
393 393
 			});
394
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
394
+			$userSession->listen('\OC\User', 'preLogin', function($uid, $password) {
395 395
 				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
396 396
 			});
397
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
397
+			$userSession->listen('\OC\User', 'postLogin', function($user, $password) {
398 398
 				/** @var $user \OC\User\User */
399 399
 				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
400 400
 			});
401
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
401
+			$userSession->listen('\OC\User', 'postRememberedLogin', function($user, $password) {
402 402
 				/** @var $user \OC\User\User */
403 403
 				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
404 404
 			});
405
-			$userSession->listen('\OC\User', 'logout', function () {
405
+			$userSession->listen('\OC\User', 'logout', function() {
406 406
 				\OC_Hook::emit('OC_User', 'logout', array());
407 407
 			});
408
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
408
+			$userSession->listen('\OC\User', 'changeUser', function($user, $feature, $value, $oldValue) use ($dispatcher) {
409 409
 				/** @var $user \OC\User\User */
410 410
 				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
411 411
 				$dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
@@ -414,7 +414,7 @@  discard block
 block discarded – undo
414 414
 		});
415 415
 		$this->registerAlias('UserSession', \OCP\IUserSession::class);
416 416
 
417
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
417
+		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function(Server $c) {
418 418
 			return new \OC\Authentication\TwoFactorAuth\Manager(
419 419
 				$c->getAppManager(),
420 420
 				$c->getSession(),
@@ -430,7 +430,7 @@  discard block
 block discarded – undo
430 430
 		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
431 431
 		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
432 432
 
433
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
433
+		$this->registerService(\OC\AllConfig::class, function(Server $c) {
434 434
 			return new \OC\AllConfig(
435 435
 				$c->getSystemConfig()
436 436
 			);
@@ -438,17 +438,17 @@  discard block
 block discarded – undo
438 438
 		$this->registerAlias('AllConfig', \OC\AllConfig::class);
439 439
 		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
440 440
 
441
-		$this->registerService('SystemConfig', function ($c) use ($config) {
441
+		$this->registerService('SystemConfig', function($c) use ($config) {
442 442
 			return new \OC\SystemConfig($config);
443 443
 		});
444 444
 
445
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
445
+		$this->registerService(\OC\AppConfig::class, function(Server $c) {
446 446
 			return new \OC\AppConfig($c->getDatabaseConnection());
447 447
 		});
448 448
 		$this->registerAlias('AppConfig', \OC\AppConfig::class);
449 449
 		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
450 450
 
451
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
451
+		$this->registerService(\OCP\L10N\IFactory::class, function(Server $c) {
452 452
 			return new \OC\L10N\Factory(
453 453
 				$c->getConfig(),
454 454
 				$c->getRequest(),
@@ -458,7 +458,7 @@  discard block
 block discarded – undo
458 458
 		});
459 459
 		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
460 460
 
461
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
461
+		$this->registerService(\OCP\IURLGenerator::class, function(Server $c) {
462 462
 			$config = $c->getConfig();
463 463
 			$cacheFactory = $c->getMemCacheFactory();
464 464
 			$request = $c->getRequest();
@@ -473,12 +473,12 @@  discard block
 block discarded – undo
473 473
 		$this->registerAlias('AppFetcher', AppFetcher::class);
474 474
 		$this->registerAlias('CategoryFetcher', CategoryFetcher::class);
475 475
 
476
-		$this->registerService(\OCP\ICache::class, function ($c) {
476
+		$this->registerService(\OCP\ICache::class, function($c) {
477 477
 			return new Cache\File();
478 478
 		});
479 479
 		$this->registerAlias('UserCache', \OCP\ICache::class);
480 480
 
481
-		$this->registerService(Factory::class, function (Server $c) {
481
+		$this->registerService(Factory::class, function(Server $c) {
482 482
 
483 483
 			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
484 484
 				ArrayCache::class,
@@ -495,7 +495,7 @@  discard block
 block discarded – undo
495 495
 				$version = implode(',', $v);
496 496
 				$instanceId = \OC_Util::getInstanceId();
497 497
 				$path = \OC::$SERVERROOT;
498
-				$prefix = md5($instanceId . '-' . $version . '-' . $path);
498
+				$prefix = md5($instanceId.'-'.$version.'-'.$path);
499 499
 				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
500 500
 					$config->getSystemValue('memcache.local', null),
501 501
 					$config->getSystemValue('memcache.distributed', null),
@@ -508,12 +508,12 @@  discard block
 block discarded – undo
508 508
 		$this->registerAlias('MemCacheFactory', Factory::class);
509 509
 		$this->registerAlias(ICacheFactory::class, Factory::class);
510 510
 
511
-		$this->registerService('RedisFactory', function (Server $c) {
511
+		$this->registerService('RedisFactory', function(Server $c) {
512 512
 			$systemConfig = $c->getSystemConfig();
513 513
 			return new RedisFactory($systemConfig);
514 514
 		});
515 515
 
516
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
516
+		$this->registerService(\OCP\Activity\IManager::class, function(Server $c) {
517 517
 			return new \OC\Activity\Manager(
518 518
 				$c->getRequest(),
519 519
 				$c->getUserSession(),
@@ -523,14 +523,14 @@  discard block
 block discarded – undo
523 523
 		});
524 524
 		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
525 525
 
526
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
526
+		$this->registerService(\OCP\Activity\IEventMerger::class, function(Server $c) {
527 527
 			return new \OC\Activity\EventMerger(
528 528
 				$c->getL10N('lib')
529 529
 			);
530 530
 		});
531 531
 		$this->registerAlias(IValidator::class, Validator::class);
532 532
 
533
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
533
+		$this->registerService(\OCP\IAvatarManager::class, function(Server $c) {
534 534
 			return new AvatarManager(
535 535
 				$c->query(\OC\User\Manager::class),
536 536
 				$c->getAppDataDir('avatar'),
@@ -543,7 +543,7 @@  discard block
 block discarded – undo
543 543
 
544 544
 		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
545 545
 
546
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
546
+		$this->registerService(\OCP\ILogger::class, function(Server $c) {
547 547
 			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
548 548
 			$logger = Log::getLogClass($logType);
549 549
 			call_user_func(array($logger, 'init'));
@@ -554,7 +554,7 @@  discard block
 block discarded – undo
554 554
 		});
555 555
 		$this->registerAlias('Logger', \OCP\ILogger::class);
556 556
 
557
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
557
+		$this->registerService(\OCP\BackgroundJob\IJobList::class, function(Server $c) {
558 558
 			$config = $c->getConfig();
559 559
 			return new \OC\BackgroundJob\JobList(
560 560
 				$c->getDatabaseConnection(),
@@ -564,7 +564,7 @@  discard block
 block discarded – undo
564 564
 		});
565 565
 		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
566 566
 
567
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
567
+		$this->registerService(\OCP\Route\IRouter::class, function(Server $c) {
568 568
 			$cacheFactory = $c->getMemCacheFactory();
569 569
 			$logger = $c->getLogger();
570 570
 			if ($cacheFactory->isLocalCacheAvailable()) {
@@ -576,12 +576,12 @@  discard block
 block discarded – undo
576 576
 		});
577 577
 		$this->registerAlias('Router', \OCP\Route\IRouter::class);
578 578
 
579
-		$this->registerService(\OCP\ISearch::class, function ($c) {
579
+		$this->registerService(\OCP\ISearch::class, function($c) {
580 580
 			return new Search();
581 581
 		});
582 582
 		$this->registerAlias('Search', \OCP\ISearch::class);
583 583
 
584
-		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function (Server $c) {
584
+		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function(Server $c) {
585 585
 			return new \OC\Security\RateLimiting\Limiter(
586 586
 				$this->getUserSession(),
587 587
 				$this->getRequest(),
@@ -589,34 +589,34 @@  discard block
 block discarded – undo
589 589
 				$c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
590 590
 			);
591 591
 		});
592
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
592
+		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function($c) {
593 593
 			return new \OC\Security\RateLimiting\Backend\MemoryCache(
594 594
 				$this->getMemCacheFactory(),
595 595
 				new \OC\AppFramework\Utility\TimeFactory()
596 596
 			);
597 597
 		});
598 598
 
599
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
599
+		$this->registerService(\OCP\Security\ISecureRandom::class, function($c) {
600 600
 			return new SecureRandom();
601 601
 		});
602 602
 		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
603 603
 
604
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
604
+		$this->registerService(\OCP\Security\ICrypto::class, function(Server $c) {
605 605
 			return new Crypto($c->getConfig(), $c->getSecureRandom());
606 606
 		});
607 607
 		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
608 608
 
609
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
609
+		$this->registerService(\OCP\Security\IHasher::class, function(Server $c) {
610 610
 			return new Hasher($c->getConfig());
611 611
 		});
612 612
 		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
613 613
 
614
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
614
+		$this->registerService(\OCP\Security\ICredentialsManager::class, function(Server $c) {
615 615
 			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
616 616
 		});
617 617
 		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
618 618
 
619
-		$this->registerService(IDBConnection::class, function (Server $c) {
619
+		$this->registerService(IDBConnection::class, function(Server $c) {
620 620
 			$systemConfig = $c->getSystemConfig();
621 621
 			$factory = new \OC\DB\ConnectionFactory($systemConfig);
622 622
 			$type = $systemConfig->getValue('dbtype', 'sqlite');
@@ -631,7 +631,7 @@  discard block
 block discarded – undo
631 631
 		$this->registerAlias('DatabaseConnection', IDBConnection::class);
632 632
 
633 633
 
634
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
634
+		$this->registerService(\OCP\Http\Client\IClientService::class, function(Server $c) {
635 635
 			$user = \OC_User::getUser();
636 636
 			$uid = $user ? $user : null;
637 637
 			return new ClientService(
@@ -646,7 +646,7 @@  discard block
 block discarded – undo
646 646
 			);
647 647
 		});
648 648
 		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
649
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
649
+		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function(Server $c) {
650 650
 			$eventLogger = new EventLogger();
651 651
 			if ($c->getSystemConfig()->getValue('debug', false)) {
652 652
 				// In debug mode, module is being activated by default
@@ -656,7 +656,7 @@  discard block
 block discarded – undo
656 656
 		});
657 657
 		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
658 658
 
659
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
659
+		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function(Server $c) {
660 660
 			$queryLogger = new QueryLogger();
661 661
 			if ($c->getSystemConfig()->getValue('debug', false)) {
662 662
 				// In debug mode, module is being activated by default
@@ -666,7 +666,7 @@  discard block
 block discarded – undo
666 666
 		});
667 667
 		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
668 668
 
669
-		$this->registerService(TempManager::class, function (Server $c) {
669
+		$this->registerService(TempManager::class, function(Server $c) {
670 670
 			return new TempManager(
671 671
 				$c->getLogger(),
672 672
 				$c->getConfig()
@@ -675,7 +675,7 @@  discard block
 block discarded – undo
675 675
 		$this->registerAlias('TempManager', TempManager::class);
676 676
 		$this->registerAlias(ITempManager::class, TempManager::class);
677 677
 
678
-		$this->registerService(AppManager::class, function (Server $c) {
678
+		$this->registerService(AppManager::class, function(Server $c) {
679 679
 			return new \OC\App\AppManager(
680 680
 				$c->getUserSession(),
681 681
 				$c->query(\OC\AppConfig::class),
@@ -687,7 +687,7 @@  discard block
 block discarded – undo
687 687
 		$this->registerAlias('AppManager', AppManager::class);
688 688
 		$this->registerAlias(IAppManager::class, AppManager::class);
689 689
 
690
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
690
+		$this->registerService(\OCP\IDateTimeZone::class, function(Server $c) {
691 691
 			return new DateTimeZone(
692 692
 				$c->getConfig(),
693 693
 				$c->getSession()
@@ -695,7 +695,7 @@  discard block
 block discarded – undo
695 695
 		});
696 696
 		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
697 697
 
698
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
698
+		$this->registerService(\OCP\IDateTimeFormatter::class, function(Server $c) {
699 699
 			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
700 700
 
701 701
 			return new DateTimeFormatter(
@@ -705,7 +705,7 @@  discard block
 block discarded – undo
705 705
 		});
706 706
 		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
707 707
 
708
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
708
+		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function(Server $c) {
709 709
 			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
710 710
 			$listener = new UserMountCacheListener($mountCache);
711 711
 			$listener->listen($c->getUserManager());
@@ -713,7 +713,7 @@  discard block
 block discarded – undo
713 713
 		});
714 714
 		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
715 715
 
716
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
716
+		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function(Server $c) {
717 717
 			$loader = \OC\Files\Filesystem::getLoader();
718 718
 			$mountCache = $c->query('UserMountCache');
719 719
 			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
@@ -729,10 +729,10 @@  discard block
 block discarded – undo
729 729
 		});
730 730
 		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
731 731
 
732
-		$this->registerService('IniWrapper', function ($c) {
732
+		$this->registerService('IniWrapper', function($c) {
733 733
 			return new IniGetWrapper();
734 734
 		});
735
-		$this->registerService('AsyncCommandBus', function (Server $c) {
735
+		$this->registerService('AsyncCommandBus', function(Server $c) {
736 736
 			$busClass = $c->getConfig()->getSystemValue('commandbus');
737 737
 			if ($busClass) {
738 738
 				list($app, $class) = explode('::', $busClass, 2);
@@ -747,10 +747,10 @@  discard block
 block discarded – undo
747 747
 				return new CronBus($jobList);
748 748
 			}
749 749
 		});
750
-		$this->registerService('TrustedDomainHelper', function ($c) {
750
+		$this->registerService('TrustedDomainHelper', function($c) {
751 751
 			return new TrustedDomainHelper($this->getConfig());
752 752
 		});
753
-		$this->registerService('Throttler', function (Server $c) {
753
+		$this->registerService('Throttler', function(Server $c) {
754 754
 			return new Throttler(
755 755
 				$c->getDatabaseConnection(),
756 756
 				new TimeFactory(),
@@ -758,7 +758,7 @@  discard block
 block discarded – undo
758 758
 				$c->getConfig()
759 759
 			);
760 760
 		});
761
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
761
+		$this->registerService('IntegrityCodeChecker', function(Server $c) {
762 762
 			// IConfig and IAppManager requires a working database. This code
763 763
 			// might however be called when ownCloud is not yet setup.
764 764
 			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
@@ -779,7 +779,7 @@  discard block
 block discarded – undo
779 779
 				$c->getTempManager()
780 780
 			);
781 781
 		});
782
-		$this->registerService(\OCP\IRequest::class, function ($c) {
782
+		$this->registerService(\OCP\IRequest::class, function($c) {
783 783
 			if (isset($this['urlParams'])) {
784 784
 				$urlParams = $this['urlParams'];
785 785
 			} else {
@@ -815,7 +815,7 @@  discard block
 block discarded – undo
815 815
 		});
816 816
 		$this->registerAlias('Request', \OCP\IRequest::class);
817 817
 
818
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
818
+		$this->registerService(\OCP\Mail\IMailer::class, function(Server $c) {
819 819
 			return new Mailer(
820 820
 				$c->getConfig(),
821 821
 				$c->getLogger(),
@@ -826,7 +826,7 @@  discard block
 block discarded – undo
826 826
 		});
827 827
 		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
828 828
 
829
-		$this->registerService('LDAPProvider', function (Server $c) {
829
+		$this->registerService('LDAPProvider', function(Server $c) {
830 830
 			$config = $c->getConfig();
831 831
 			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
832 832
 			if (is_null($factoryClass)) {
@@ -836,7 +836,7 @@  discard block
 block discarded – undo
836 836
 			$factory = new $factoryClass($this);
837 837
 			return $factory->getLDAPProvider();
838 838
 		});
839
-		$this->registerService(ILockingProvider::class, function (Server $c) {
839
+		$this->registerService(ILockingProvider::class, function(Server $c) {
840 840
 			$ini = $c->getIniWrapper();
841 841
 			$config = $c->getConfig();
842 842
 			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
@@ -853,49 +853,49 @@  discard block
 block discarded – undo
853 853
 		});
854 854
 		$this->registerAlias('LockingProvider', ILockingProvider::class);
855 855
 
856
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
856
+		$this->registerService(\OCP\Files\Mount\IMountManager::class, function() {
857 857
 			return new \OC\Files\Mount\Manager();
858 858
 		});
859 859
 		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
860 860
 
861
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
861
+		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function(Server $c) {
862 862
 			return new \OC\Files\Type\Detection(
863 863
 				$c->getURLGenerator(),
864 864
 				\OC::$configDir,
865
-				\OC::$SERVERROOT . '/resources/config/'
865
+				\OC::$SERVERROOT.'/resources/config/'
866 866
 			);
867 867
 		});
868 868
 		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
869 869
 
870
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
870
+		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function(Server $c) {
871 871
 			return new \OC\Files\Type\Loader(
872 872
 				$c->getDatabaseConnection()
873 873
 			);
874 874
 		});
875 875
 		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
876
-		$this->registerService(BundleFetcher::class, function () {
876
+		$this->registerService(BundleFetcher::class, function() {
877 877
 			return new BundleFetcher($this->getL10N('lib'));
878 878
 		});
879
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
879
+		$this->registerService(\OCP\Notification\IManager::class, function(Server $c) {
880 880
 			return new Manager(
881 881
 				$c->query(IValidator::class)
882 882
 			);
883 883
 		});
884 884
 		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
885 885
 
886
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
886
+		$this->registerService(\OC\CapabilitiesManager::class, function(Server $c) {
887 887
 			$manager = new \OC\CapabilitiesManager($c->getLogger());
888
-			$manager->registerCapability(function () use ($c) {
888
+			$manager->registerCapability(function() use ($c) {
889 889
 				return new \OC\OCS\CoreCapabilities($c->getConfig());
890 890
 			});
891
-			$manager->registerCapability(function () use ($c) {
891
+			$manager->registerCapability(function() use ($c) {
892 892
 				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
893 893
 			});
894 894
 			return $manager;
895 895
 		});
896 896
 		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
897 897
 
898
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
898
+		$this->registerService(\OCP\Comments\ICommentsManager::class, function(Server $c) {
899 899
 			$config = $c->getConfig();
900 900
 			$factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
901 901
 			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
@@ -905,7 +905,7 @@  discard block
 block discarded – undo
905 905
 			$manager->registerDisplayNameResolver('user', function($id) use ($c) {
906 906
 				$manager = $c->getUserManager();
907 907
 				$user = $manager->get($id);
908
-				if(is_null($user)) {
908
+				if (is_null($user)) {
909 909
 					$l = $c->getL10N('core');
910 910
 					$displayName = $l->t('Unknown user');
911 911
 				} else {
@@ -918,7 +918,7 @@  discard block
 block discarded – undo
918 918
 		});
919 919
 		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
920 920
 
921
-		$this->registerService('ThemingDefaults', function (Server $c) {
921
+		$this->registerService('ThemingDefaults', function(Server $c) {
922 922
 			/*
923 923
 			 * Dark magic for autoloader.
924 924
 			 * If we do a class_exists it will try to load the class which will
@@ -945,7 +945,7 @@  discard block
 block discarded – undo
945 945
 			}
946 946
 			return new \OC_Defaults();
947 947
 		});
948
-		$this->registerService(SCSSCacher::class, function (Server $c) {
948
+		$this->registerService(SCSSCacher::class, function(Server $c) {
949 949
 			/** @var Factory $cacheFactory */
950 950
 			$cacheFactory = $c->query(Factory::class);
951 951
 			return new SCSSCacher(
@@ -958,7 +958,7 @@  discard block
 block discarded – undo
958 958
 				$this->getMemCacheFactory()
959 959
 			);
960 960
 		});
961
-		$this->registerService(JSCombiner::class, function (Server $c) {
961
+		$this->registerService(JSCombiner::class, function(Server $c) {
962 962
 			/** @var Factory $cacheFactory */
963 963
 			$cacheFactory = $c->query(Factory::class);
964 964
 			return new JSCombiner(
@@ -969,13 +969,13 @@  discard block
 block discarded – undo
969 969
 				$c->getLogger()
970 970
 			);
971 971
 		});
972
-		$this->registerService(EventDispatcher::class, function () {
972
+		$this->registerService(EventDispatcher::class, function() {
973 973
 			return new EventDispatcher();
974 974
 		});
975 975
 		$this->registerAlias('EventDispatcher', EventDispatcher::class);
976 976
 		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
977 977
 
978
-		$this->registerService('CryptoWrapper', function (Server $c) {
978
+		$this->registerService('CryptoWrapper', function(Server $c) {
979 979
 			// FIXME: Instantiiated here due to cyclic dependency
980 980
 			$request = new Request(
981 981
 				[
@@ -1000,7 +1000,7 @@  discard block
 block discarded – undo
1000 1000
 				$request
1001 1001
 			);
1002 1002
 		});
1003
-		$this->registerService('CsrfTokenManager', function (Server $c) {
1003
+		$this->registerService('CsrfTokenManager', function(Server $c) {
1004 1004
 			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1005 1005
 
1006 1006
 			return new CsrfTokenManager(
@@ -1008,22 +1008,22 @@  discard block
 block discarded – undo
1008 1008
 				$c->query(SessionStorage::class)
1009 1009
 			);
1010 1010
 		});
1011
-		$this->registerService(SessionStorage::class, function (Server $c) {
1011
+		$this->registerService(SessionStorage::class, function(Server $c) {
1012 1012
 			return new SessionStorage($c->getSession());
1013 1013
 		});
1014
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1014
+		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function(Server $c) {
1015 1015
 			return new ContentSecurityPolicyManager();
1016 1016
 		});
1017 1017
 		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1018 1018
 
1019
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1019
+		$this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
1020 1020
 			return new ContentSecurityPolicyNonceManager(
1021 1021
 				$c->getCsrfTokenManager(),
1022 1022
 				$c->getRequest()
1023 1023
 			);
1024 1024
 		});
1025 1025
 
1026
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1026
+		$this->registerService(\OCP\Share\IManager::class, function(Server $c) {
1027 1027
 			$config = $c->getConfig();
1028 1028
 			$factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1029 1029
 			/** @var \OCP\Share\IProviderFactory $factory */
@@ -1066,7 +1066,7 @@  discard block
 block discarded – undo
1066 1066
 
1067 1067
 		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1068 1068
 
1069
-		$this->registerService('SettingsManager', function (Server $c) {
1069
+		$this->registerService('SettingsManager', function(Server $c) {
1070 1070
 			$manager = new \OC\Settings\Manager(
1071 1071
 				$c->getLogger(),
1072 1072
 				$c->getDatabaseConnection(),
@@ -1084,24 +1084,24 @@  discard block
 block discarded – undo
1084 1084
 			);
1085 1085
 			return $manager;
1086 1086
 		});
1087
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1087
+		$this->registerService(\OC\Files\AppData\Factory::class, function(Server $c) {
1088 1088
 			return new \OC\Files\AppData\Factory(
1089 1089
 				$c->getRootFolder(),
1090 1090
 				$c->getSystemConfig()
1091 1091
 			);
1092 1092
 		});
1093 1093
 
1094
-		$this->registerService('LockdownManager', function (Server $c) {
1095
-			return new LockdownManager(function () use ($c) {
1094
+		$this->registerService('LockdownManager', function(Server $c) {
1095
+			return new LockdownManager(function() use ($c) {
1096 1096
 				return $c->getSession();
1097 1097
 			});
1098 1098
 		});
1099 1099
 
1100
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1100
+		$this->registerService(\OCP\OCS\IDiscoveryService::class, function(Server $c) {
1101 1101
 			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1102 1102
 		});
1103 1103
 
1104
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1104
+		$this->registerService(ICloudIdManager::class, function(Server $c) {
1105 1105
 			return new CloudIdManager();
1106 1106
 		});
1107 1107
 
@@ -1111,18 +1111,18 @@  discard block
 block discarded – undo
1111 1111
 		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1112 1112
 		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1113 1113
 
1114
-		$this->registerService(Defaults::class, function (Server $c) {
1114
+		$this->registerService(Defaults::class, function(Server $c) {
1115 1115
 			return new Defaults(
1116 1116
 				$c->getThemingDefaults()
1117 1117
 			);
1118 1118
 		});
1119 1119
 		$this->registerAlias('Defaults', \OCP\Defaults::class);
1120 1120
 
1121
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1121
+		$this->registerService(\OCP\ISession::class, function(SimpleContainer $c) {
1122 1122
 			return $c->query(\OCP\IUserSession::class)->getSession();
1123 1123
 		});
1124 1124
 
1125
-		$this->registerService(IShareHelper::class, function (Server $c) {
1125
+		$this->registerService(IShareHelper::class, function(Server $c) {
1126 1126
 			return new ShareHelper(
1127 1127
 				$c->query(\OCP\Share\IManager::class)
1128 1128
 			);
@@ -1184,11 +1184,11 @@  discard block
 block discarded – undo
1184 1184
 				// no avatar to remove
1185 1185
 			} catch (\Exception $e) {
1186 1186
 				// Ignore exceptions
1187
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1187
+				$logger->info('Could not cleanup avatar of '.$user->getUID());
1188 1188
 			}
1189 1189
 		});
1190 1190
 
1191
-		$dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1191
+		$dispatcher->addListener('OCP\IUser::changeUser', function(GenericEvent $e) {
1192 1192
 			$manager = $this->getAvatarManager();
1193 1193
 			/** @var IUser $user */
1194 1194
 			$user = $e->getSubject();
@@ -1339,7 +1339,7 @@  discard block
 block discarded – undo
1339 1339
 	 * @deprecated since 9.2.0 use IAppData
1340 1340
 	 */
1341 1341
 	public function getAppFolder() {
1342
-		$dir = '/' . \OC_App::getCurrentApp();
1342
+		$dir = '/'.\OC_App::getCurrentApp();
1343 1343
 		$root = $this->getRootFolder();
1344 1344
 		if (!$root->nodeExists($dir)) {
1345 1345
 			$folder = $root->newFolder($dir);
@@ -1906,7 +1906,7 @@  discard block
 block discarded – undo
1906 1906
 	/**
1907 1907
 	 * @return \OCP\Collaboration\AutoComplete\IManager
1908 1908
 	 */
1909
-	public function getAutoCompleteManager(){
1909
+	public function getAutoCompleteManager() {
1910 1910
 		return $this->query(IManager::class);
1911 1911
 	}
1912 1912
 
Please login to merge, or discard this patch.