Completed
Pull Request — master (#9224)
by Jan-Christoph
38:54 queued 20:20
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.
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.
Indentation   +1314 added lines, -1314 removed lines patch added patch discarded remove patch
@@ -41,1320 +41,1320 @@
 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 int
93
-	 * @throws \Exception
94
-	 */
95
-	public function countEntries(string $filter, string $type): int {
96
-		$reqs = ['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 = ['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 (int)$result;
117
-	}
118
-
119
-	/**
120
-	 * formats the return value of a count operation to the string to be
121
-	 * inserted.
122
-	 *
123
-	 * @param int $count
124
-	 * @return string
125
-	 */
126
-	private function formatCountResult(int $count): string {
127
-		if($count > 1000) {
128
-			return '> 1000';
129
-		}
130
-		return (string)$count;
131
-	}
132
-
133
-	public function countGroups() {
134
-		$filter = $this->configuration->ldapGroupFilter;
135
-
136
-		if(empty($filter)) {
137
-			$output = self::$l->n('%s group found', '%s groups found', 0, array(0));
138
-			$this->result->addChange('ldap_group_count', $output);
139
-			return $this->result;
140
-		}
141
-
142
-		try {
143
-			$groupsTotal = $this->countEntries($filter, 'groups');
144
-		} catch (\Exception $e) {
145
-			//400 can be ignored, 500 is forwarded
146
-			if($e->getCode() === 500) {
147
-				throw $e;
148
-			}
149
-			return false;
150
-		}
151
-		$output = self::$l->n(
152
-			'%s group found',
153
-			'%s groups found',
154
-			$groupsTotal,
155
-			[$this->formatCountResult($groupsTotal)]
156
-		);
157
-		$this->result->addChange('ldap_group_count', $output);
158
-		return $this->result;
159
-	}
160
-
161
-	/**
162
-	 * @return WizardResult
163
-	 * @throws \Exception
164
-	 */
165
-	public function countUsers() {
166
-		$filter = $this->access->getFilterForUserCount();
167
-
168
-		$usersTotal = $this->countEntries($filter, 'users');
169
-		$output = self::$l->n(
170
-			'%s user found',
171
-			'%s users found',
172
-			$usersTotal,
173
-			[$this->formatCountResult($usersTotal)]
174
-		);
175
-		$this->result->addChange('ldap_user_count', $output);
176
-		return $this->result;
177
-	}
178
-
179
-	/**
180
-	 * counts any objects in the currently set base dn
181
-	 *
182
-	 * @return WizardResult
183
-	 * @throws \Exception
184
-	 */
185
-	public function countInBaseDN() {
186
-		// we don't need to provide a filter in this case
187
-		$total = $this->countEntries('', 'objects');
188
-		if($total === false) {
189
-			throw new \Exception('invalid results received');
190
-		}
191
-		$this->result->addChange('ldap_test_base', $total);
192
-		return $this->result;
193
-	}
194
-
195
-	/**
196
-	 * counts users with a specified attribute
197
-	 * @param string $attr
198
-	 * @param bool $existsCheck
199
-	 * @return int|bool
200
-	 */
201
-	public function countUsersWithAttribute($attr, $existsCheck = false) {
202
-		if(!$this->checkRequirements(array('ldapHost',
203
-										   'ldapPort',
204
-										   'ldapBase',
205
-										   'ldapUserFilter',
206
-										   ))) {
207
-			return  false;
208
-		}
209
-
210
-		$filter = $this->access->combineFilterWithAnd(array(
211
-			$this->configuration->ldapUserFilter,
212
-			$attr . '=*'
213
-		));
214
-
215
-		$limit = ($existsCheck === false) ? null : 1;
216
-
217
-		return $this->access->countUsers($filter, array('dn'), $limit);
218
-	}
219
-
220
-	/**
221
-	 * detects the display name attribute. If a setting is already present that
222
-	 * returns at least one hit, the detection will be canceled.
223
-	 * @return WizardResult|bool
224
-	 * @throws \Exception
225
-	 */
226
-	public function detectUserDisplayNameAttribute() {
227
-		if(!$this->checkRequirements(array('ldapHost',
228
-										'ldapPort',
229
-										'ldapBase',
230
-										'ldapUserFilter',
231
-										))) {
232
-			return  false;
233
-		}
234
-
235
-		$attr = $this->configuration->ldapUserDisplayName;
236
-		if ($attr !== '' && $attr !== 'displayName') {
237
-			// most likely not the default value with upper case N,
238
-			// verify it still produces a result
239
-			$count = (int)$this->countUsersWithAttribute($attr, true);
240
-			if($count > 0) {
241
-				//no change, but we sent it back to make sure the user interface
242
-				//is still correct, even if the ajax call was cancelled meanwhile
243
-				$this->result->addChange('ldap_display_name', $attr);
244
-				return $this->result;
245
-			}
246
-		}
247
-
248
-		// first attribute that has at least one result wins
249
-		$displayNameAttrs = array('displayname', 'cn');
250
-		foreach ($displayNameAttrs as $attr) {
251
-			$count = (int)$this->countUsersWithAttribute($attr, true);
252
-
253
-			if($count > 0) {
254
-				$this->applyFind('ldap_display_name', $attr);
255
-				return $this->result;
256
-			}
257
-		}
258
-
259
-		throw new \Exception(self::$l->t('Could not detect user display name attribute. Please specify it yourself in advanced LDAP settings.'));
260
-	}
261
-
262
-	/**
263
-	 * detects the most often used email attribute for users applying to the
264
-	 * user list filter. If a setting is already present that returns at least
265
-	 * one hit, the detection will be canceled.
266
-	 * @return WizardResult|bool
267
-	 */
268
-	public function detectEmailAttribute() {
269
-		if(!$this->checkRequirements(array('ldapHost',
270
-										   'ldapPort',
271
-										   'ldapBase',
272
-										   'ldapUserFilter',
273
-										   ))) {
274
-			return  false;
275
-		}
276
-
277
-		$attr = $this->configuration->ldapEmailAttribute;
278
-		if ($attr !== '') {
279
-			$count = (int)$this->countUsersWithAttribute($attr, true);
280
-			if($count > 0) {
281
-				return false;
282
-			}
283
-			$writeLog = true;
284
-		} else {
285
-			$writeLog = false;
286
-		}
287
-
288
-		$emailAttributes = array('mail', 'mailPrimaryAddress');
289
-		$winner = '';
290
-		$maxUsers = 0;
291
-		foreach($emailAttributes as $attr) {
292
-			$count = $this->countUsersWithAttribute($attr);
293
-			if($count > $maxUsers) {
294
-				$maxUsers = $count;
295
-				$winner = $attr;
296
-			}
297
-		}
298
-
299
-		if($winner !== '') {
300
-			$this->applyFind('ldap_email_attr', $winner);
301
-			if($writeLog) {
302
-				\OCP\Util::writeLog('user_ldap', 'The mail attribute has ' .
303
-					'automatically been reset, because the original value ' .
304
-					'did not return any results.', \OCP\Util::INFO);
305
-			}
306
-		}
307
-
308
-		return $this->result;
309
-	}
310
-
311
-	/**
312
-	 * @return WizardResult
313
-	 * @throws \Exception
314
-	 */
315
-	public function determineAttributes() {
316
-		if(!$this->checkRequirements(array('ldapHost',
317
-										   'ldapPort',
318
-										   'ldapBase',
319
-										   'ldapUserFilter',
320
-										   ))) {
321
-			return  false;
322
-		}
323
-
324
-		$attributes = $this->getUserAttributes();
325
-
326
-		natcasesort($attributes);
327
-		$attributes = array_values($attributes);
328
-
329
-		$this->result->addOptions('ldap_loginfilter_attributes', $attributes);
330
-
331
-		$selected = $this->configuration->ldapLoginFilterAttributes;
332
-		if(is_array($selected) && !empty($selected)) {
333
-			$this->result->addChange('ldap_loginfilter_attributes', $selected);
334
-		}
335
-
336
-		return $this->result;
337
-	}
338
-
339
-	/**
340
-	 * detects the available LDAP attributes
341
-	 * @return array|false The instance's WizardResult instance
342
-	 * @throws \Exception
343
-	 */
344
-	private function getUserAttributes() {
345
-		if(!$this->checkRequirements(array('ldapHost',
346
-										   'ldapPort',
347
-										   'ldapBase',
348
-										   'ldapUserFilter',
349
-										   ))) {
350
-			return  false;
351
-		}
352
-		$cr = $this->getConnection();
353
-		if(!$cr) {
354
-			throw new \Exception('Could not connect to LDAP');
355
-		}
356
-
357
-		$base = $this->configuration->ldapBase[0];
358
-		$filter = $this->configuration->ldapUserFilter;
359
-		$rr = $this->ldap->search($cr, $base, $filter, array(), 1, 1);
360
-		if(!$this->ldap->isResource($rr)) {
361
-			return false;
362
-		}
363
-		$er = $this->ldap->firstEntry($cr, $rr);
364
-		$attributes = $this->ldap->getAttributes($cr, $er);
365
-		$pureAttributes = array();
366
-		for($i = 0; $i < $attributes['count']; $i++) {
367
-			$pureAttributes[] = $attributes[$i];
368
-		}
369
-
370
-		return $pureAttributes;
371
-	}
372
-
373
-	/**
374
-	 * detects the available LDAP groups
375
-	 * @return WizardResult|false the instance's WizardResult instance
376
-	 */
377
-	public function determineGroupsForGroups() {
378
-		return $this->determineGroups('ldap_groupfilter_groups',
379
-									  'ldapGroupFilterGroups',
380
-									  false);
381
-	}
382
-
383
-	/**
384
-	 * detects the available LDAP groups
385
-	 * @return WizardResult|false the instance's WizardResult instance
386
-	 */
387
-	public function determineGroupsForUsers() {
388
-		return $this->determineGroups('ldap_userfilter_groups',
389
-									  'ldapUserFilterGroups');
390
-	}
391
-
392
-	/**
393
-	 * detects the available LDAP groups
394
-	 * @param string $dbKey
395
-	 * @param string $confKey
396
-	 * @param bool $testMemberOf
397
-	 * @return WizardResult|false the instance's WizardResult instance
398
-	 * @throws \Exception
399
-	 */
400
-	private function determineGroups($dbKey, $confKey, $testMemberOf = true) {
401
-		if(!$this->checkRequirements(array('ldapHost',
402
-										   'ldapPort',
403
-										   'ldapBase',
404
-										   ))) {
405
-			return  false;
406
-		}
407
-		$cr = $this->getConnection();
408
-		if(!$cr) {
409
-			throw new \Exception('Could not connect to LDAP');
410
-		}
411
-
412
-		$this->fetchGroups($dbKey, $confKey);
413
-
414
-		if($testMemberOf) {
415
-			$this->configuration->hasMemberOfFilterSupport = $this->testMemberOf();
416
-			$this->result->markChange();
417
-			if(!$this->configuration->hasMemberOfFilterSupport) {
418
-				throw new \Exception('memberOf is not supported by the server');
419
-			}
420
-		}
421
-
422
-		return $this->result;
423
-	}
424
-
425
-	/**
426
-	 * fetches all groups from LDAP and adds them to the result object
427
-	 *
428
-	 * @param string $dbKey
429
-	 * @param string $confKey
430
-	 * @return array $groupEntries
431
-	 * @throws \Exception
432
-	 */
433
-	public function fetchGroups($dbKey, $confKey) {
434
-		$obclasses = array('posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames', 'groupOfUniqueNames');
435
-
436
-		$filterParts = array();
437
-		foreach($obclasses as $obclass) {
438
-			$filterParts[] = 'objectclass='.$obclass;
439
-		}
440
-		//we filter for everything
441
-		//- that looks like a group and
442
-		//- has the group display name set
443
-		$filter = $this->access->combineFilterWithOr($filterParts);
444
-		$filter = $this->access->combineFilterWithAnd(array($filter, 'cn=*'));
445
-
446
-		$groupNames = array();
447
-		$groupEntries = array();
448
-		$limit = 400;
449
-		$offset = 0;
450
-		do {
451
-			// we need to request dn additionally here, otherwise memberOf
452
-			// detection will fail later
453
-			$result = $this->access->searchGroups($filter, array('cn', 'dn'), $limit, $offset);
454
-			foreach($result as $item) {
455
-				if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
456
-					// just in case - no issue known
457
-					continue;
458
-				}
459
-				$groupNames[] = $item['cn'][0];
460
-				$groupEntries[] = $item;
461
-			}
462
-			$offset += $limit;
463
-		} while ($this->access->hasMoreResults());
464
-
465
-		if(count($groupNames) > 0) {
466
-			natsort($groupNames);
467
-			$this->result->addOptions($dbKey, array_values($groupNames));
468
-		} else {
469
-			throw new \Exception(self::$l->t('Could not find the desired feature'));
470
-		}
471
-
472
-		$setFeatures = $this->configuration->$confKey;
473
-		if(is_array($setFeatures) && !empty($setFeatures)) {
474
-			//something is already configured? pre-select it.
475
-			$this->result->addChange($dbKey, $setFeatures);
476
-		}
477
-		return $groupEntries;
478
-	}
479
-
480
-	public function determineGroupMemberAssoc() {
481
-		if(!$this->checkRequirements(array('ldapHost',
482
-										   'ldapPort',
483
-										   'ldapGroupFilter',
484
-										   ))) {
485
-			return  false;
486
-		}
487
-		$attribute = $this->detectGroupMemberAssoc();
488
-		if($attribute === false) {
489
-			return false;
490
-		}
491
-		$this->configuration->setConfiguration(array('ldapGroupMemberAssocAttr' => $attribute));
492
-		$this->result->addChange('ldap_group_member_assoc_attribute', $attribute);
493
-
494
-		return $this->result;
495
-	}
496
-
497
-	/**
498
-	 * Detects the available object classes
499
-	 * @return WizardResult|false the instance's WizardResult instance
500
-	 * @throws \Exception
501
-	 */
502
-	public function determineGroupObjectClasses() {
503
-		if(!$this->checkRequirements(array('ldapHost',
504
-										   'ldapPort',
505
-										   'ldapBase',
506
-										   ))) {
507
-			return  false;
508
-		}
509
-		$cr = $this->getConnection();
510
-		if(!$cr) {
511
-			throw new \Exception('Could not connect to LDAP');
512
-		}
513
-
514
-		$obclasses = array('groupOfNames', 'groupOfUniqueNames', 'group', 'posixGroup', '*');
515
-		$this->determineFeature($obclasses,
516
-								'objectclass',
517
-								'ldap_groupfilter_objectclass',
518
-								'ldapGroupFilterObjectclass',
519
-								false);
520
-
521
-		return $this->result;
522
-	}
523
-
524
-	/**
525
-	 * detects the available object classes
526
-	 * @return WizardResult
527
-	 * @throws \Exception
528
-	 */
529
-	public function determineUserObjectClasses() {
530
-		if(!$this->checkRequirements(array('ldapHost',
531
-										   'ldapPort',
532
-										   'ldapBase',
533
-										   ))) {
534
-			return  false;
535
-		}
536
-		$cr = $this->getConnection();
537
-		if(!$cr) {
538
-			throw new \Exception('Could not connect to LDAP');
539
-		}
540
-
541
-		$obclasses = array('inetOrgPerson', 'person', 'organizationalPerson',
542
-						   'user', 'posixAccount', '*');
543
-		$filter = $this->configuration->ldapUserFilter;
544
-		//if filter is empty, it is probably the first time the wizard is called
545
-		//then, apply suggestions.
546
-		$this->determineFeature($obclasses,
547
-								'objectclass',
548
-								'ldap_userfilter_objectclass',
549
-								'ldapUserFilterObjectclass',
550
-								empty($filter));
551
-
552
-		return $this->result;
553
-	}
554
-
555
-	/**
556
-	 * @return WizardResult|false
557
-	 * @throws \Exception
558
-	 */
559
-	public function getGroupFilter() {
560
-		if(!$this->checkRequirements(array('ldapHost',
561
-										   'ldapPort',
562
-										   'ldapBase',
563
-										   ))) {
564
-			return false;
565
-		}
566
-		//make sure the use display name is set
567
-		$displayName = $this->configuration->ldapGroupDisplayName;
568
-		if ($displayName === '') {
569
-			$d = $this->configuration->getDefaults();
570
-			$this->applyFind('ldap_group_display_name',
571
-							 $d['ldap_group_display_name']);
572
-		}
573
-		$filter = $this->composeLdapFilter(self::LFILTER_GROUP_LIST);
574
-
575
-		$this->applyFind('ldap_group_filter', $filter);
576
-		return $this->result;
577
-	}
578
-
579
-	/**
580
-	 * @return WizardResult|false
581
-	 * @throws \Exception
582
-	 */
583
-	public function getUserListFilter() {
584
-		if(!$this->checkRequirements(array('ldapHost',
585
-										   'ldapPort',
586
-										   'ldapBase',
587
-										   ))) {
588
-			return false;
589
-		}
590
-		//make sure the use display name is set
591
-		$displayName = $this->configuration->ldapUserDisplayName;
592
-		if ($displayName === '') {
593
-			$d = $this->configuration->getDefaults();
594
-			$this->applyFind('ldap_display_name', $d['ldap_display_name']);
595
-		}
596
-		$filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
597
-		if(!$filter) {
598
-			throw new \Exception('Cannot create filter');
599
-		}
600
-
601
-		$this->applyFind('ldap_userlist_filter', $filter);
602
-		return $this->result;
603
-	}
604
-
605
-	/**
606
-	 * @return bool|WizardResult
607
-	 * @throws \Exception
608
-	 */
609
-	public function getUserLoginFilter() {
610
-		if(!$this->checkRequirements(array('ldapHost',
611
-										   'ldapPort',
612
-										   'ldapBase',
613
-										   'ldapUserFilter',
614
-										   ))) {
615
-			return false;
616
-		}
617
-
618
-		$filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
619
-		if(!$filter) {
620
-			throw new \Exception('Cannot create filter');
621
-		}
622
-
623
-		$this->applyFind('ldap_login_filter', $filter);
624
-		return $this->result;
625
-	}
626
-
627
-	/**
628
-	 * @return bool|WizardResult
629
-	 * @param string $loginName
630
-	 * @throws \Exception
631
-	 */
632
-	public function testLoginName($loginName) {
633
-		if(!$this->checkRequirements(array('ldapHost',
634
-			'ldapPort',
635
-			'ldapBase',
636
-			'ldapLoginFilter',
637
-		))) {
638
-			return false;
639
-		}
640
-
641
-		$cr = $this->access->connection->getConnectionResource();
642
-		if(!$this->ldap->isResource($cr)) {
643
-			throw new \Exception('connection error');
644
-		}
645
-
646
-		if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
647
-			=== false) {
648
-			throw new \Exception('missing placeholder');
649
-		}
650
-
651
-		$users = $this->access->countUsersByLoginName($loginName);
652
-		if($this->ldap->errno($cr) !== 0) {
653
-			throw new \Exception($this->ldap->error($cr));
654
-		}
655
-		$filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
656
-		$this->result->addChange('ldap_test_loginname', $users);
657
-		$this->result->addChange('ldap_test_effective_filter', $filter);
658
-		return $this->result;
659
-	}
660
-
661
-	/**
662
-	 * Tries to determine the port, requires given Host, User DN and Password
663
-	 * @return WizardResult|false WizardResult on success, false otherwise
664
-	 * @throws \Exception
665
-	 */
666
-	public function guessPortAndTLS() {
667
-		if(!$this->checkRequirements(array('ldapHost',
668
-										   ))) {
669
-			return false;
670
-		}
671
-		$this->checkHost();
672
-		$portSettings = $this->getPortSettingsToTry();
673
-
674
-		if(!is_array($portSettings)) {
675
-			throw new \Exception(print_r($portSettings, true));
676
-		}
677
-
678
-		//proceed from the best configuration and return on first success
679
-		foreach($portSettings as $setting) {
680
-			$p = $setting['port'];
681
-			$t = $setting['tls'];
682
-			\OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, \OCP\Util::DEBUG);
683
-			//connectAndBind may throw Exception, it needs to be catched by the
684
-			//callee of this method
685
-
686
-			try {
687
-				$settingsFound = $this->connectAndBind($p, $t);
688
-			} catch (\Exception $e) {
689
-				// any reply other than -1 (= cannot connect) is already okay,
690
-				// because then we found the server
691
-				// unavailable startTLS returns -11
692
-				if($e->getCode() > 0) {
693
-					$settingsFound = true;
694
-				} else {
695
-					throw $e;
696
-				}
697
-			}
698
-
699
-			if ($settingsFound === true) {
700
-				$config = array(
701
-					'ldapPort' => $p,
702
-					'ldapTLS' => (int)$t
703
-				);
704
-				$this->configuration->setConfiguration($config);
705
-				\OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, \OCP\Util::DEBUG);
706
-				$this->result->addChange('ldap_port', $p);
707
-				return $this->result;
708
-			}
709
-		}
710
-
711
-		//custom port, undetected (we do not brute force)
712
-		return false;
713
-	}
714
-
715
-	/**
716
-	 * tries to determine a base dn from User DN or LDAP Host
717
-	 * @return WizardResult|false WizardResult on success, false otherwise
718
-	 */
719
-	public function guessBaseDN() {
720
-		if(!$this->checkRequirements(array('ldapHost',
721
-										   'ldapPort',
722
-										   ))) {
723
-			return false;
724
-		}
725
-
726
-		//check whether a DN is given in the agent name (99.9% of all cases)
727
-		$base = null;
728
-		$i = stripos($this->configuration->ldapAgentName, 'dc=');
729
-		if($i !== false) {
730
-			$base = substr($this->configuration->ldapAgentName, $i);
731
-			if($this->testBaseDN($base)) {
732
-				$this->applyFind('ldap_base', $base);
733
-				return $this->result;
734
-			}
735
-		}
736
-
737
-		//this did not help :(
738
-		//Let's see whether we can parse the Host URL and convert the domain to
739
-		//a base DN
740
-		$helper = new Helper(\OC::$server->getConfig());
741
-		$domain = $helper->getDomainFromURL($this->configuration->ldapHost);
742
-		if(!$domain) {
743
-			return false;
744
-		}
745
-
746
-		$dparts = explode('.', $domain);
747
-		while(count($dparts) > 0) {
748
-			$base2 = 'dc=' . implode(',dc=', $dparts);
749
-			if ($base !== $base2 && $this->testBaseDN($base2)) {
750
-				$this->applyFind('ldap_base', $base2);
751
-				return $this->result;
752
-			}
753
-			array_shift($dparts);
754
-		}
755
-
756
-		return false;
757
-	}
758
-
759
-	/**
760
-	 * sets the found value for the configuration key in the WizardResult
761
-	 * as well as in the Configuration instance
762
-	 * @param string $key the configuration key
763
-	 * @param string $value the (detected) value
764
-	 *
765
-	 */
766
-	private function applyFind($key, $value) {
767
-		$this->result->addChange($key, $value);
768
-		$this->configuration->setConfiguration(array($key => $value));
769
-	}
770
-
771
-	/**
772
-	 * Checks, whether a port was entered in the Host configuration
773
-	 * field. In this case the port will be stripped off, but also stored as
774
-	 * setting.
775
-	 */
776
-	private function checkHost() {
777
-		$host = $this->configuration->ldapHost;
778
-		$hostInfo = parse_url($host);
779
-
780
-		//removes Port from Host
781
-		if(is_array($hostInfo) && isset($hostInfo['port'])) {
782
-			$port = $hostInfo['port'];
783
-			$host = str_replace(':'.$port, '', $host);
784
-			$this->applyFind('ldap_host', $host);
785
-			$this->applyFind('ldap_port', $port);
786
-		}
787
-	}
788
-
789
-	/**
790
-	 * tries to detect the group member association attribute which is
791
-	 * one of 'uniqueMember', 'memberUid', 'member', 'gidNumber'
792
-	 * @return string|false, string with the attribute name, false on error
793
-	 * @throws \Exception
794
-	 */
795
-	private function detectGroupMemberAssoc() {
796
-		$possibleAttrs = array('uniqueMember', 'memberUid', 'member', 'gidNumber');
797
-		$filter = $this->configuration->ldapGroupFilter;
798
-		if(empty($filter)) {
799
-			return false;
800
-		}
801
-		$cr = $this->getConnection();
802
-		if(!$cr) {
803
-			throw new \Exception('Could not connect to LDAP');
804
-		}
805
-		$base = $this->configuration->ldapBase[0];
806
-		$rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
807
-		if(!$this->ldap->isResource($rr)) {
808
-			return false;
809
-		}
810
-		$er = $this->ldap->firstEntry($cr, $rr);
811
-		while(is_resource($er)) {
812
-			$this->ldap->getDN($cr, $er);
813
-			$attrs = $this->ldap->getAttributes($cr, $er);
814
-			$result = array();
815
-			$possibleAttrsCount = count($possibleAttrs);
816
-			for($i = 0; $i < $possibleAttrsCount; $i++) {
817
-				if(isset($attrs[$possibleAttrs[$i]])) {
818
-					$result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
819
-				}
820
-			}
821
-			if(!empty($result)) {
822
-				natsort($result);
823
-				return key($result);
824
-			}
825
-
826
-			$er = $this->ldap->nextEntry($cr, $er);
827
-		}
828
-
829
-		return false;
830
-	}
831
-
832
-	/**
833
-	 * Checks whether for a given BaseDN results will be returned
834
-	 * @param string $base the BaseDN to test
835
-	 * @return bool true on success, false otherwise
836
-	 * @throws \Exception
837
-	 */
838
-	private function testBaseDN($base) {
839
-		$cr = $this->getConnection();
840
-		if(!$cr) {
841
-			throw new \Exception('Could not connect to LDAP');
842
-		}
843
-
844
-		//base is there, let's validate it. If we search for anything, we should
845
-		//get a result set > 0 on a proper base
846
-		$rr = $this->ldap->search($cr, $base, 'objectClass=*', array('dn'), 0, 1);
847
-		if(!$this->ldap->isResource($rr)) {
848
-			$errorNo  = $this->ldap->errno($cr);
849
-			$errorMsg = $this->ldap->error($cr);
850
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base.
851
-							' Error '.$errorNo.': '.$errorMsg, \OCP\Util::INFO);
852
-			return false;
853
-		}
854
-		$entries = $this->ldap->countEntries($cr, $rr);
855
-		return ($entries !== false) && ($entries > 0);
856
-	}
857
-
858
-	/**
859
-	 * Checks whether the server supports memberOf in LDAP Filter.
860
-	 * Note: at least in OpenLDAP, availability of memberOf is dependent on
861
-	 * a configured objectClass. I.e. not necessarily for all available groups
862
-	 * memberOf does work.
863
-	 *
864
-	 * @return bool true if it does, false otherwise
865
-	 * @throws \Exception
866
-	 */
867
-	private function testMemberOf() {
868
-		$cr = $this->getConnection();
869
-		if(!$cr) {
870
-			throw new \Exception('Could not connect to LDAP');
871
-		}
872
-		$result = $this->access->countUsers('memberOf=*', array('memberOf'), 1);
873
-		if(is_int($result) &&  $result > 0) {
874
-			return true;
875
-		}
876
-		return false;
877
-	}
878
-
879
-	/**
880
-	 * creates an LDAP Filter from given configuration
881
-	 * @param integer $filterType int, for which use case the filter shall be created
882
-	 * can be any of self::LFILTER_USER_LIST, self::LFILTER_LOGIN or
883
-	 * self::LFILTER_GROUP_LIST
884
-	 * @return string|false string with the filter on success, false otherwise
885
-	 * @throws \Exception
886
-	 */
887
-	private function composeLdapFilter($filterType) {
888
-		$filter = '';
889
-		$parts = 0;
890
-		switch ($filterType) {
891
-			case self::LFILTER_USER_LIST:
892
-				$objcs = $this->configuration->ldapUserFilterObjectclass;
893
-				//glue objectclasses
894
-				if(is_array($objcs) && count($objcs) > 0) {
895
-					$filter .= '(|';
896
-					foreach($objcs as $objc) {
897
-						$filter .= '(objectclass=' . $objc . ')';
898
-					}
899
-					$filter .= ')';
900
-					$parts++;
901
-				}
902
-				//glue group memberships
903
-				if($this->configuration->hasMemberOfFilterSupport) {
904
-					$cns = $this->configuration->ldapUserFilterGroups;
905
-					if(is_array($cns) && count($cns) > 0) {
906
-						$filter .= '(|';
907
-						$cr = $this->getConnection();
908
-						if(!$cr) {
909
-							throw new \Exception('Could not connect to LDAP');
910
-						}
911
-						$base = $this->configuration->ldapBase[0];
912
-						foreach($cns as $cn) {
913
-							$rr = $this->ldap->search($cr, $base, 'cn=' . $cn, array('dn', 'primaryGroupToken'));
914
-							if(!$this->ldap->isResource($rr)) {
915
-								continue;
916
-							}
917
-							$er = $this->ldap->firstEntry($cr, $rr);
918
-							$attrs = $this->ldap->getAttributes($cr, $er);
919
-							$dn = $this->ldap->getDN($cr, $er);
920
-							if ($dn === false || $dn === '') {
921
-								continue;
922
-							}
923
-							$filterPart = '(memberof=' . $dn . ')';
924
-							if(isset($attrs['primaryGroupToken'])) {
925
-								$pgt = $attrs['primaryGroupToken'][0];
926
-								$primaryFilterPart = '(primaryGroupID=' . $pgt .')';
927
-								$filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
928
-							}
929
-							$filter .= $filterPart;
930
-						}
931
-						$filter .= ')';
932
-					}
933
-					$parts++;
934
-				}
935
-				//wrap parts in AND condition
936
-				if($parts > 1) {
937
-					$filter = '(&' . $filter . ')';
938
-				}
939
-				if ($filter === '') {
940
-					$filter = '(objectclass=*)';
941
-				}
942
-				break;
943
-
944
-			case self::LFILTER_GROUP_LIST:
945
-				$objcs = $this->configuration->ldapGroupFilterObjectclass;
946
-				//glue objectclasses
947
-				if(is_array($objcs) && count($objcs) > 0) {
948
-					$filter .= '(|';
949
-					foreach($objcs as $objc) {
950
-						$filter .= '(objectclass=' . $objc . ')';
951
-					}
952
-					$filter .= ')';
953
-					$parts++;
954
-				}
955
-				//glue group memberships
956
-				$cns = $this->configuration->ldapGroupFilterGroups;
957
-				if(is_array($cns) && count($cns) > 0) {
958
-					$filter .= '(|';
959
-					foreach($cns as $cn) {
960
-						$filter .= '(cn=' . $cn . ')';
961
-					}
962
-					$filter .= ')';
963
-				}
964
-				$parts++;
965
-				//wrap parts in AND condition
966
-				if($parts > 1) {
967
-					$filter = '(&' . $filter . ')';
968
-				}
969
-				break;
970
-
971
-			case self::LFILTER_LOGIN:
972
-				$ulf = $this->configuration->ldapUserFilter;
973
-				$loginpart = '=%uid';
974
-				$filterUsername = '';
975
-				$userAttributes = $this->getUserAttributes();
976
-				$userAttributes = array_change_key_case(array_flip($userAttributes));
977
-				$parts = 0;
978
-
979
-				if($this->configuration->ldapLoginFilterUsername === '1') {
980
-					$attr = '';
981
-					if(isset($userAttributes['uid'])) {
982
-						$attr = 'uid';
983
-					} else if(isset($userAttributes['samaccountname'])) {
984
-						$attr = 'samaccountname';
985
-					} else if(isset($userAttributes['cn'])) {
986
-						//fallback
987
-						$attr = 'cn';
988
-					}
989
-					if ($attr !== '') {
990
-						$filterUsername = '(' . $attr . $loginpart . ')';
991
-						$parts++;
992
-					}
993
-				}
994
-
995
-				$filterEmail = '';
996
-				if($this->configuration->ldapLoginFilterEmail === '1') {
997
-					$filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
998
-					$parts++;
999
-				}
1000
-
1001
-				$filterAttributes = '';
1002
-				$attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
1003
-				if(is_array($attrsToFilter) && count($attrsToFilter) > 0) {
1004
-					$filterAttributes = '(|';
1005
-					foreach($attrsToFilter as $attribute) {
1006
-						$filterAttributes .= '(' . $attribute . $loginpart . ')';
1007
-					}
1008
-					$filterAttributes .= ')';
1009
-					$parts++;
1010
-				}
1011
-
1012
-				$filterLogin = '';
1013
-				if($parts > 1) {
1014
-					$filterLogin = '(|';
1015
-				}
1016
-				$filterLogin .= $filterUsername;
1017
-				$filterLogin .= $filterEmail;
1018
-				$filterLogin .= $filterAttributes;
1019
-				if($parts > 1) {
1020
-					$filterLogin .= ')';
1021
-				}
1022
-
1023
-				$filter = '(&'.$ulf.$filterLogin.')';
1024
-				break;
1025
-		}
1026
-
1027
-		\OCP\Util::writeLog('user_ldap', 'Wiz: Final filter '.$filter, \OCP\Util::DEBUG);
1028
-
1029
-		return $filter;
1030
-	}
1031
-
1032
-	/**
1033
-	 * Connects and Binds to an LDAP Server
1034
-	 *
1035
-	 * @param int $port the port to connect with
1036
-	 * @param bool $tls whether startTLS is to be used
1037
-	 * @return bool
1038
-	 * @throws \Exception
1039
-	 */
1040
-	private function connectAndBind($port, $tls) {
1041
-		//connect, does not really trigger any server communication
1042
-		$host = $this->configuration->ldapHost;
1043
-		$hostInfo = parse_url($host);
1044
-		if(!$hostInfo) {
1045
-			throw new \Exception(self::$l->t('Invalid Host'));
1046
-		}
1047
-		\OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', \OCP\Util::DEBUG);
1048
-		$cr = $this->ldap->connect($host, $port);
1049
-		if(!is_resource($cr)) {
1050
-			throw new \Exception(self::$l->t('Invalid Host'));
1051
-		}
1052
-
1053
-		//set LDAP options
1054
-		$this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1055
-		$this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1056
-		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1057
-
1058
-		try {
1059
-			if($tls) {
1060
-				$isTlsWorking = @$this->ldap->startTls($cr);
1061
-				if(!$isTlsWorking) {
1062
-					return false;
1063
-				}
1064
-			}
1065
-
1066
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Attemping to Bind ', \OCP\Util::DEBUG);
1067
-			//interesting part: do the bind!
1068
-			$login = $this->ldap->bind($cr,
1069
-				$this->configuration->ldapAgentName,
1070
-				$this->configuration->ldapAgentPassword
1071
-			);
1072
-			$errNo = $this->ldap->errno($cr);
1073
-			$error = ldap_error($cr);
1074
-			$this->ldap->unbind($cr);
1075
-		} catch(ServerNotAvailableException $e) {
1076
-			return false;
1077
-		}
1078
-
1079
-		if($login === true) {
1080
-			$this->ldap->unbind($cr);
1081
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . (int)$tls, \OCP\Util::DEBUG);
1082
-			return true;
1083
-		}
1084
-
1085
-		if($errNo === -1) {
1086
-			//host, port or TLS wrong
1087
-			return false;
1088
-		}
1089
-		throw new \Exception($error, $errNo);
1090
-	}
1091
-
1092
-	/**
1093
-	 * checks whether a valid combination of agent and password has been
1094
-	 * provided (either two values or nothing for anonymous connect)
1095
-	 * @return bool, true if everything is fine, false otherwise
1096
-	 */
1097
-	private function checkAgentRequirements() {
1098
-		$agent = $this->configuration->ldapAgentName;
1099
-		$pwd = $this->configuration->ldapAgentPassword;
1100
-
1101
-		return
1102
-			($agent !== '' && $pwd !== '')
1103
-			||  ($agent === '' && $pwd === '')
1104
-		;
1105
-	}
1106
-
1107
-	/**
1108
-	 * @param array $reqs
1109
-	 * @return bool
1110
-	 */
1111
-	private function checkRequirements($reqs) {
1112
-		$this->checkAgentRequirements();
1113
-		foreach($reqs as $option) {
1114
-			$value = $this->configuration->$option;
1115
-			if(empty($value)) {
1116
-				return false;
1117
-			}
1118
-		}
1119
-		return true;
1120
-	}
1121
-
1122
-	/**
1123
-	 * does a cumulativeSearch on LDAP to get different values of a
1124
-	 * specified attribute
1125
-	 * @param string[] $filters array, the filters that shall be used in the search
1126
-	 * @param string $attr the attribute of which a list of values shall be returned
1127
-	 * @param int $dnReadLimit the amount of how many DNs should be analyzed.
1128
-	 * The lower, the faster
1129
-	 * @param string $maxF string. if not null, this variable will have the filter that
1130
-	 * yields most result entries
1131
-	 * @return array|false an array with the values on success, false otherwise
1132
-	 */
1133
-	public function cumulativeSearchOnAttribute($filters, $attr, $dnReadLimit = 3, &$maxF = null) {
1134
-		$dnRead = array();
1135
-		$foundItems = array();
1136
-		$maxEntries = 0;
1137
-		if(!is_array($this->configuration->ldapBase)
1138
-		   || !isset($this->configuration->ldapBase[0])) {
1139
-			return false;
1140
-		}
1141
-		$base = $this->configuration->ldapBase[0];
1142
-		$cr = $this->getConnection();
1143
-		if(!$this->ldap->isResource($cr)) {
1144
-			return false;
1145
-		}
1146
-		$lastFilter = null;
1147
-		if(isset($filters[count($filters)-1])) {
1148
-			$lastFilter = $filters[count($filters)-1];
1149
-		}
1150
-		foreach($filters as $filter) {
1151
-			if($lastFilter === $filter && count($foundItems) > 0) {
1152
-				//skip when the filter is a wildcard and results were found
1153
-				continue;
1154
-			}
1155
-			// 20k limit for performance and reason
1156
-			$rr = $this->ldap->search($cr, $base, $filter, array($attr), 0, 20000);
1157
-			if(!$this->ldap->isResource($rr)) {
1158
-				continue;
1159
-			}
1160
-			$entries = $this->ldap->countEntries($cr, $rr);
1161
-			$getEntryFunc = 'firstEntry';
1162
-			if(($entries !== false) && ($entries > 0)) {
1163
-				if(!is_null($maxF) && $entries > $maxEntries) {
1164
-					$maxEntries = $entries;
1165
-					$maxF = $filter;
1166
-				}
1167
-				$dnReadCount = 0;
1168
-				do {
1169
-					$entry = $this->ldap->$getEntryFunc($cr, $rr);
1170
-					$getEntryFunc = 'nextEntry';
1171
-					if(!$this->ldap->isResource($entry)) {
1172
-						continue 2;
1173
-					}
1174
-					$rr = $entry; //will be expected by nextEntry next round
1175
-					$attributes = $this->ldap->getAttributes($cr, $entry);
1176
-					$dn = $this->ldap->getDN($cr, $entry);
1177
-					if($dn === false || in_array($dn, $dnRead)) {
1178
-						continue;
1179
-					}
1180
-					$newItems = array();
1181
-					$state = $this->getAttributeValuesFromEntry($attributes,
1182
-																$attr,
1183
-																$newItems);
1184
-					$dnReadCount++;
1185
-					$foundItems = array_merge($foundItems, $newItems);
1186
-					$this->resultCache[$dn][$attr] = $newItems;
1187
-					$dnRead[] = $dn;
1188
-				} while(($state === self::LRESULT_PROCESSED_SKIP
1189
-						|| $this->ldap->isResource($entry))
1190
-						&& ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit));
1191
-			}
1192
-		}
1193
-
1194
-		return array_unique($foundItems);
1195
-	}
1196
-
1197
-	/**
1198
-	 * determines if and which $attr are available on the LDAP server
1199
-	 * @param string[] $objectclasses the objectclasses to use as search filter
1200
-	 * @param string $attr the attribute to look for
1201
-	 * @param string $dbkey the dbkey of the setting the feature is connected to
1202
-	 * @param string $confkey the confkey counterpart for the $dbkey as used in the
1203
-	 * Configuration class
1204
-	 * @param bool $po whether the objectClass with most result entries
1205
-	 * shall be pre-selected via the result
1206
-	 * @return array|false list of found items.
1207
-	 * @throws \Exception
1208
-	 */
1209
-	private function determineFeature($objectclasses, $attr, $dbkey, $confkey, $po = false) {
1210
-		$cr = $this->getConnection();
1211
-		if(!$cr) {
1212
-			throw new \Exception('Could not connect to LDAP');
1213
-		}
1214
-		$p = 'objectclass=';
1215
-		foreach($objectclasses as $key => $value) {
1216
-			$objectclasses[$key] = $p.$value;
1217
-		}
1218
-		$maxEntryObjC = '';
1219
-
1220
-		//how deep to dig?
1221
-		//When looking for objectclasses, testing few entries is sufficient,
1222
-		$dig = 3;
1223
-
1224
-		$availableFeatures =
1225
-			$this->cumulativeSearchOnAttribute($objectclasses, $attr,
1226
-											   $dig, $maxEntryObjC);
1227
-		if(is_array($availableFeatures)
1228
-		   && count($availableFeatures) > 0) {
1229
-			natcasesort($availableFeatures);
1230
-			//natcasesort keeps indices, but we must get rid of them for proper
1231
-			//sorting in the web UI. Therefore: array_values
1232
-			$this->result->addOptions($dbkey, array_values($availableFeatures));
1233
-		} else {
1234
-			throw new \Exception(self::$l->t('Could not find the desired feature'));
1235
-		}
1236
-
1237
-		$setFeatures = $this->configuration->$confkey;
1238
-		if(is_array($setFeatures) && !empty($setFeatures)) {
1239
-			//something is already configured? pre-select it.
1240
-			$this->result->addChange($dbkey, $setFeatures);
1241
-		} else if ($po && $maxEntryObjC !== '') {
1242
-			//pre-select objectclass with most result entries
1243
-			$maxEntryObjC = str_replace($p, '', $maxEntryObjC);
1244
-			$this->applyFind($dbkey, $maxEntryObjC);
1245
-			$this->result->addChange($dbkey, $maxEntryObjC);
1246
-		}
1247
-
1248
-		return $availableFeatures;
1249
-	}
1250
-
1251
-	/**
1252
-	 * appends a list of values fr
1253
-	 * @param resource $result the return value from ldap_get_attributes
1254
-	 * @param string $attribute the attribute values to look for
1255
-	 * @param array &$known new values will be appended here
1256
-	 * @return int, state on of the class constants LRESULT_PROCESSED_OK,
1257
-	 * LRESULT_PROCESSED_INVALID or LRESULT_PROCESSED_SKIP
1258
-	 */
1259
-	private function getAttributeValuesFromEntry($result, $attribute, &$known) {
1260
-		if(!is_array($result)
1261
-		   || !isset($result['count'])
1262
-		   || !$result['count'] > 0) {
1263
-			return self::LRESULT_PROCESSED_INVALID;
1264
-		}
1265
-
1266
-		// strtolower on all keys for proper comparison
1267
-		$result = \OCP\Util::mb_array_change_key_case($result);
1268
-		$attribute = strtolower($attribute);
1269
-		if(isset($result[$attribute])) {
1270
-			foreach($result[$attribute] as $key => $val) {
1271
-				if($key === 'count') {
1272
-					continue;
1273
-				}
1274
-				if(!in_array($val, $known)) {
1275
-					$known[] = $val;
1276
-				}
1277
-			}
1278
-			return self::LRESULT_PROCESSED_OK;
1279
-		} else {
1280
-			return self::LRESULT_PROCESSED_SKIP;
1281
-		}
1282
-	}
1283
-
1284
-	/**
1285
-	 * @return bool|mixed
1286
-	 */
1287
-	private function getConnection() {
1288
-		if(!is_null($this->cr)) {
1289
-			return $this->cr;
1290
-		}
1291
-
1292
-		$cr = $this->ldap->connect(
1293
-			$this->configuration->ldapHost,
1294
-			$this->configuration->ldapPort
1295
-		);
1296
-
1297
-		$this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1298
-		$this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1299
-		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1300
-		if($this->configuration->ldapTLS === 1) {
1301
-			$this->ldap->startTls($cr);
1302
-		}
1303
-
1304
-		$lo = @$this->ldap->bind($cr,
1305
-								 $this->configuration->ldapAgentName,
1306
-								 $this->configuration->ldapAgentPassword);
1307
-		if($lo === true) {
1308
-			$this->$cr = $cr;
1309
-			return $cr;
1310
-		}
1311
-
1312
-		return false;
1313
-	}
1314
-
1315
-	/**
1316
-	 * @return array
1317
-	 */
1318
-	private function getDefaultLdapPortSettings() {
1319
-		static $settings = array(
1320
-								array('port' => 7636, 'tls' => false),
1321
-								array('port' =>  636, 'tls' => false),
1322
-								array('port' => 7389, 'tls' => true),
1323
-								array('port' =>  389, 'tls' => true),
1324
-								array('port' => 7389, 'tls' => false),
1325
-								array('port' =>  389, 'tls' => false),
1326
-						  );
1327
-		return $settings;
1328
-	}
1329
-
1330
-	/**
1331
-	 * @return array
1332
-	 */
1333
-	private function getPortSettingsToTry() {
1334
-		//389 ← LDAP / Unencrypted or StartTLS
1335
-		//636 ← LDAPS / SSL
1336
-		//7xxx ← UCS. need to be checked first, because both ports may be open
1337
-		$host = $this->configuration->ldapHost;
1338
-		$port = (int)$this->configuration->ldapPort;
1339
-		$portSettings = array();
1340
-
1341
-		//In case the port is already provided, we will check this first
1342
-		if($port > 0) {
1343
-			$hostInfo = parse_url($host);
1344
-			if(!(is_array($hostInfo)
1345
-				&& isset($hostInfo['scheme'])
1346
-				&& stripos($hostInfo['scheme'], 'ldaps') !== false)) {
1347
-				$portSettings[] = array('port' => $port, 'tls' => true);
1348
-			}
1349
-			$portSettings[] =array('port' => $port, 'tls' => false);
1350
-		}
1351
-
1352
-		//default ports
1353
-		$portSettings = array_merge($portSettings,
1354
-		                            $this->getDefaultLdapPortSettings());
1355
-
1356
-		return $portSettings;
1357
-	}
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 int
93
+     * @throws \Exception
94
+     */
95
+    public function countEntries(string $filter, string $type): int {
96
+        $reqs = ['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 = ['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 (int)$result;
117
+    }
118
+
119
+    /**
120
+     * formats the return value of a count operation to the string to be
121
+     * inserted.
122
+     *
123
+     * @param int $count
124
+     * @return string
125
+     */
126
+    private function formatCountResult(int $count): string {
127
+        if($count > 1000) {
128
+            return '> 1000';
129
+        }
130
+        return (string)$count;
131
+    }
132
+
133
+    public function countGroups() {
134
+        $filter = $this->configuration->ldapGroupFilter;
135
+
136
+        if(empty($filter)) {
137
+            $output = self::$l->n('%s group found', '%s groups found', 0, array(0));
138
+            $this->result->addChange('ldap_group_count', $output);
139
+            return $this->result;
140
+        }
141
+
142
+        try {
143
+            $groupsTotal = $this->countEntries($filter, 'groups');
144
+        } catch (\Exception $e) {
145
+            //400 can be ignored, 500 is forwarded
146
+            if($e->getCode() === 500) {
147
+                throw $e;
148
+            }
149
+            return false;
150
+        }
151
+        $output = self::$l->n(
152
+            '%s group found',
153
+            '%s groups found',
154
+            $groupsTotal,
155
+            [$this->formatCountResult($groupsTotal)]
156
+        );
157
+        $this->result->addChange('ldap_group_count', $output);
158
+        return $this->result;
159
+    }
160
+
161
+    /**
162
+     * @return WizardResult
163
+     * @throws \Exception
164
+     */
165
+    public function countUsers() {
166
+        $filter = $this->access->getFilterForUserCount();
167
+
168
+        $usersTotal = $this->countEntries($filter, 'users');
169
+        $output = self::$l->n(
170
+            '%s user found',
171
+            '%s users found',
172
+            $usersTotal,
173
+            [$this->formatCountResult($usersTotal)]
174
+        );
175
+        $this->result->addChange('ldap_user_count', $output);
176
+        return $this->result;
177
+    }
178
+
179
+    /**
180
+     * counts any objects in the currently set base dn
181
+     *
182
+     * @return WizardResult
183
+     * @throws \Exception
184
+     */
185
+    public function countInBaseDN() {
186
+        // we don't need to provide a filter in this case
187
+        $total = $this->countEntries('', 'objects');
188
+        if($total === false) {
189
+            throw new \Exception('invalid results received');
190
+        }
191
+        $this->result->addChange('ldap_test_base', $total);
192
+        return $this->result;
193
+    }
194
+
195
+    /**
196
+     * counts users with a specified attribute
197
+     * @param string $attr
198
+     * @param bool $existsCheck
199
+     * @return int|bool
200
+     */
201
+    public function countUsersWithAttribute($attr, $existsCheck = false) {
202
+        if(!$this->checkRequirements(array('ldapHost',
203
+                                            'ldapPort',
204
+                                            'ldapBase',
205
+                                            'ldapUserFilter',
206
+                                            ))) {
207
+            return  false;
208
+        }
209
+
210
+        $filter = $this->access->combineFilterWithAnd(array(
211
+            $this->configuration->ldapUserFilter,
212
+            $attr . '=*'
213
+        ));
214
+
215
+        $limit = ($existsCheck === false) ? null : 1;
216
+
217
+        return $this->access->countUsers($filter, array('dn'), $limit);
218
+    }
219
+
220
+    /**
221
+     * detects the display name attribute. If a setting is already present that
222
+     * returns at least one hit, the detection will be canceled.
223
+     * @return WizardResult|bool
224
+     * @throws \Exception
225
+     */
226
+    public function detectUserDisplayNameAttribute() {
227
+        if(!$this->checkRequirements(array('ldapHost',
228
+                                        'ldapPort',
229
+                                        'ldapBase',
230
+                                        'ldapUserFilter',
231
+                                        ))) {
232
+            return  false;
233
+        }
234
+
235
+        $attr = $this->configuration->ldapUserDisplayName;
236
+        if ($attr !== '' && $attr !== 'displayName') {
237
+            // most likely not the default value with upper case N,
238
+            // verify it still produces a result
239
+            $count = (int)$this->countUsersWithAttribute($attr, true);
240
+            if($count > 0) {
241
+                //no change, but we sent it back to make sure the user interface
242
+                //is still correct, even if the ajax call was cancelled meanwhile
243
+                $this->result->addChange('ldap_display_name', $attr);
244
+                return $this->result;
245
+            }
246
+        }
247
+
248
+        // first attribute that has at least one result wins
249
+        $displayNameAttrs = array('displayname', 'cn');
250
+        foreach ($displayNameAttrs as $attr) {
251
+            $count = (int)$this->countUsersWithAttribute($attr, true);
252
+
253
+            if($count > 0) {
254
+                $this->applyFind('ldap_display_name', $attr);
255
+                return $this->result;
256
+            }
257
+        }
258
+
259
+        throw new \Exception(self::$l->t('Could not detect user display name attribute. Please specify it yourself in advanced LDAP settings.'));
260
+    }
261
+
262
+    /**
263
+     * detects the most often used email attribute for users applying to the
264
+     * user list filter. If a setting is already present that returns at least
265
+     * one hit, the detection will be canceled.
266
+     * @return WizardResult|bool
267
+     */
268
+    public function detectEmailAttribute() {
269
+        if(!$this->checkRequirements(array('ldapHost',
270
+                                            'ldapPort',
271
+                                            'ldapBase',
272
+                                            'ldapUserFilter',
273
+                                            ))) {
274
+            return  false;
275
+        }
276
+
277
+        $attr = $this->configuration->ldapEmailAttribute;
278
+        if ($attr !== '') {
279
+            $count = (int)$this->countUsersWithAttribute($attr, true);
280
+            if($count > 0) {
281
+                return false;
282
+            }
283
+            $writeLog = true;
284
+        } else {
285
+            $writeLog = false;
286
+        }
287
+
288
+        $emailAttributes = array('mail', 'mailPrimaryAddress');
289
+        $winner = '';
290
+        $maxUsers = 0;
291
+        foreach($emailAttributes as $attr) {
292
+            $count = $this->countUsersWithAttribute($attr);
293
+            if($count > $maxUsers) {
294
+                $maxUsers = $count;
295
+                $winner = $attr;
296
+            }
297
+        }
298
+
299
+        if($winner !== '') {
300
+            $this->applyFind('ldap_email_attr', $winner);
301
+            if($writeLog) {
302
+                \OCP\Util::writeLog('user_ldap', 'The mail attribute has ' .
303
+                    'automatically been reset, because the original value ' .
304
+                    'did not return any results.', \OCP\Util::INFO);
305
+            }
306
+        }
307
+
308
+        return $this->result;
309
+    }
310
+
311
+    /**
312
+     * @return WizardResult
313
+     * @throws \Exception
314
+     */
315
+    public function determineAttributes() {
316
+        if(!$this->checkRequirements(array('ldapHost',
317
+                                            'ldapPort',
318
+                                            'ldapBase',
319
+                                            'ldapUserFilter',
320
+                                            ))) {
321
+            return  false;
322
+        }
323
+
324
+        $attributes = $this->getUserAttributes();
325
+
326
+        natcasesort($attributes);
327
+        $attributes = array_values($attributes);
328
+
329
+        $this->result->addOptions('ldap_loginfilter_attributes', $attributes);
330
+
331
+        $selected = $this->configuration->ldapLoginFilterAttributes;
332
+        if(is_array($selected) && !empty($selected)) {
333
+            $this->result->addChange('ldap_loginfilter_attributes', $selected);
334
+        }
335
+
336
+        return $this->result;
337
+    }
338
+
339
+    /**
340
+     * detects the available LDAP attributes
341
+     * @return array|false The instance's WizardResult instance
342
+     * @throws \Exception
343
+     */
344
+    private function getUserAttributes() {
345
+        if(!$this->checkRequirements(array('ldapHost',
346
+                                            'ldapPort',
347
+                                            'ldapBase',
348
+                                            'ldapUserFilter',
349
+                                            ))) {
350
+            return  false;
351
+        }
352
+        $cr = $this->getConnection();
353
+        if(!$cr) {
354
+            throw new \Exception('Could not connect to LDAP');
355
+        }
356
+
357
+        $base = $this->configuration->ldapBase[0];
358
+        $filter = $this->configuration->ldapUserFilter;
359
+        $rr = $this->ldap->search($cr, $base, $filter, array(), 1, 1);
360
+        if(!$this->ldap->isResource($rr)) {
361
+            return false;
362
+        }
363
+        $er = $this->ldap->firstEntry($cr, $rr);
364
+        $attributes = $this->ldap->getAttributes($cr, $er);
365
+        $pureAttributes = array();
366
+        for($i = 0; $i < $attributes['count']; $i++) {
367
+            $pureAttributes[] = $attributes[$i];
368
+        }
369
+
370
+        return $pureAttributes;
371
+    }
372
+
373
+    /**
374
+     * detects the available LDAP groups
375
+     * @return WizardResult|false the instance's WizardResult instance
376
+     */
377
+    public function determineGroupsForGroups() {
378
+        return $this->determineGroups('ldap_groupfilter_groups',
379
+                                        'ldapGroupFilterGroups',
380
+                                        false);
381
+    }
382
+
383
+    /**
384
+     * detects the available LDAP groups
385
+     * @return WizardResult|false the instance's WizardResult instance
386
+     */
387
+    public function determineGroupsForUsers() {
388
+        return $this->determineGroups('ldap_userfilter_groups',
389
+                                        'ldapUserFilterGroups');
390
+    }
391
+
392
+    /**
393
+     * detects the available LDAP groups
394
+     * @param string $dbKey
395
+     * @param string $confKey
396
+     * @param bool $testMemberOf
397
+     * @return WizardResult|false the instance's WizardResult instance
398
+     * @throws \Exception
399
+     */
400
+    private function determineGroups($dbKey, $confKey, $testMemberOf = true) {
401
+        if(!$this->checkRequirements(array('ldapHost',
402
+                                            'ldapPort',
403
+                                            'ldapBase',
404
+                                            ))) {
405
+            return  false;
406
+        }
407
+        $cr = $this->getConnection();
408
+        if(!$cr) {
409
+            throw new \Exception('Could not connect to LDAP');
410
+        }
411
+
412
+        $this->fetchGroups($dbKey, $confKey);
413
+
414
+        if($testMemberOf) {
415
+            $this->configuration->hasMemberOfFilterSupport = $this->testMemberOf();
416
+            $this->result->markChange();
417
+            if(!$this->configuration->hasMemberOfFilterSupport) {
418
+                throw new \Exception('memberOf is not supported by the server');
419
+            }
420
+        }
421
+
422
+        return $this->result;
423
+    }
424
+
425
+    /**
426
+     * fetches all groups from LDAP and adds them to the result object
427
+     *
428
+     * @param string $dbKey
429
+     * @param string $confKey
430
+     * @return array $groupEntries
431
+     * @throws \Exception
432
+     */
433
+    public function fetchGroups($dbKey, $confKey) {
434
+        $obclasses = array('posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames', 'groupOfUniqueNames');
435
+
436
+        $filterParts = array();
437
+        foreach($obclasses as $obclass) {
438
+            $filterParts[] = 'objectclass='.$obclass;
439
+        }
440
+        //we filter for everything
441
+        //- that looks like a group and
442
+        //- has the group display name set
443
+        $filter = $this->access->combineFilterWithOr($filterParts);
444
+        $filter = $this->access->combineFilterWithAnd(array($filter, 'cn=*'));
445
+
446
+        $groupNames = array();
447
+        $groupEntries = array();
448
+        $limit = 400;
449
+        $offset = 0;
450
+        do {
451
+            // we need to request dn additionally here, otherwise memberOf
452
+            // detection will fail later
453
+            $result = $this->access->searchGroups($filter, array('cn', 'dn'), $limit, $offset);
454
+            foreach($result as $item) {
455
+                if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
456
+                    // just in case - no issue known
457
+                    continue;
458
+                }
459
+                $groupNames[] = $item['cn'][0];
460
+                $groupEntries[] = $item;
461
+            }
462
+            $offset += $limit;
463
+        } while ($this->access->hasMoreResults());
464
+
465
+        if(count($groupNames) > 0) {
466
+            natsort($groupNames);
467
+            $this->result->addOptions($dbKey, array_values($groupNames));
468
+        } else {
469
+            throw new \Exception(self::$l->t('Could not find the desired feature'));
470
+        }
471
+
472
+        $setFeatures = $this->configuration->$confKey;
473
+        if(is_array($setFeatures) && !empty($setFeatures)) {
474
+            //something is already configured? pre-select it.
475
+            $this->result->addChange($dbKey, $setFeatures);
476
+        }
477
+        return $groupEntries;
478
+    }
479
+
480
+    public function determineGroupMemberAssoc() {
481
+        if(!$this->checkRequirements(array('ldapHost',
482
+                                            'ldapPort',
483
+                                            'ldapGroupFilter',
484
+                                            ))) {
485
+            return  false;
486
+        }
487
+        $attribute = $this->detectGroupMemberAssoc();
488
+        if($attribute === false) {
489
+            return false;
490
+        }
491
+        $this->configuration->setConfiguration(array('ldapGroupMemberAssocAttr' => $attribute));
492
+        $this->result->addChange('ldap_group_member_assoc_attribute', $attribute);
493
+
494
+        return $this->result;
495
+    }
496
+
497
+    /**
498
+     * Detects the available object classes
499
+     * @return WizardResult|false the instance's WizardResult instance
500
+     * @throws \Exception
501
+     */
502
+    public function determineGroupObjectClasses() {
503
+        if(!$this->checkRequirements(array('ldapHost',
504
+                                            'ldapPort',
505
+                                            'ldapBase',
506
+                                            ))) {
507
+            return  false;
508
+        }
509
+        $cr = $this->getConnection();
510
+        if(!$cr) {
511
+            throw new \Exception('Could not connect to LDAP');
512
+        }
513
+
514
+        $obclasses = array('groupOfNames', 'groupOfUniqueNames', 'group', 'posixGroup', '*');
515
+        $this->determineFeature($obclasses,
516
+                                'objectclass',
517
+                                'ldap_groupfilter_objectclass',
518
+                                'ldapGroupFilterObjectclass',
519
+                                false);
520
+
521
+        return $this->result;
522
+    }
523
+
524
+    /**
525
+     * detects the available object classes
526
+     * @return WizardResult
527
+     * @throws \Exception
528
+     */
529
+    public function determineUserObjectClasses() {
530
+        if(!$this->checkRequirements(array('ldapHost',
531
+                                            'ldapPort',
532
+                                            'ldapBase',
533
+                                            ))) {
534
+            return  false;
535
+        }
536
+        $cr = $this->getConnection();
537
+        if(!$cr) {
538
+            throw new \Exception('Could not connect to LDAP');
539
+        }
540
+
541
+        $obclasses = array('inetOrgPerson', 'person', 'organizationalPerson',
542
+                            'user', 'posixAccount', '*');
543
+        $filter = $this->configuration->ldapUserFilter;
544
+        //if filter is empty, it is probably the first time the wizard is called
545
+        //then, apply suggestions.
546
+        $this->determineFeature($obclasses,
547
+                                'objectclass',
548
+                                'ldap_userfilter_objectclass',
549
+                                'ldapUserFilterObjectclass',
550
+                                empty($filter));
551
+
552
+        return $this->result;
553
+    }
554
+
555
+    /**
556
+     * @return WizardResult|false
557
+     * @throws \Exception
558
+     */
559
+    public function getGroupFilter() {
560
+        if(!$this->checkRequirements(array('ldapHost',
561
+                                            'ldapPort',
562
+                                            'ldapBase',
563
+                                            ))) {
564
+            return false;
565
+        }
566
+        //make sure the use display name is set
567
+        $displayName = $this->configuration->ldapGroupDisplayName;
568
+        if ($displayName === '') {
569
+            $d = $this->configuration->getDefaults();
570
+            $this->applyFind('ldap_group_display_name',
571
+                                $d['ldap_group_display_name']);
572
+        }
573
+        $filter = $this->composeLdapFilter(self::LFILTER_GROUP_LIST);
574
+
575
+        $this->applyFind('ldap_group_filter', $filter);
576
+        return $this->result;
577
+    }
578
+
579
+    /**
580
+     * @return WizardResult|false
581
+     * @throws \Exception
582
+     */
583
+    public function getUserListFilter() {
584
+        if(!$this->checkRequirements(array('ldapHost',
585
+                                            'ldapPort',
586
+                                            'ldapBase',
587
+                                            ))) {
588
+            return false;
589
+        }
590
+        //make sure the use display name is set
591
+        $displayName = $this->configuration->ldapUserDisplayName;
592
+        if ($displayName === '') {
593
+            $d = $this->configuration->getDefaults();
594
+            $this->applyFind('ldap_display_name', $d['ldap_display_name']);
595
+        }
596
+        $filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
597
+        if(!$filter) {
598
+            throw new \Exception('Cannot create filter');
599
+        }
600
+
601
+        $this->applyFind('ldap_userlist_filter', $filter);
602
+        return $this->result;
603
+    }
604
+
605
+    /**
606
+     * @return bool|WizardResult
607
+     * @throws \Exception
608
+     */
609
+    public function getUserLoginFilter() {
610
+        if(!$this->checkRequirements(array('ldapHost',
611
+                                            'ldapPort',
612
+                                            'ldapBase',
613
+                                            'ldapUserFilter',
614
+                                            ))) {
615
+            return false;
616
+        }
617
+
618
+        $filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
619
+        if(!$filter) {
620
+            throw new \Exception('Cannot create filter');
621
+        }
622
+
623
+        $this->applyFind('ldap_login_filter', $filter);
624
+        return $this->result;
625
+    }
626
+
627
+    /**
628
+     * @return bool|WizardResult
629
+     * @param string $loginName
630
+     * @throws \Exception
631
+     */
632
+    public function testLoginName($loginName) {
633
+        if(!$this->checkRequirements(array('ldapHost',
634
+            'ldapPort',
635
+            'ldapBase',
636
+            'ldapLoginFilter',
637
+        ))) {
638
+            return false;
639
+        }
640
+
641
+        $cr = $this->access->connection->getConnectionResource();
642
+        if(!$this->ldap->isResource($cr)) {
643
+            throw new \Exception('connection error');
644
+        }
645
+
646
+        if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
647
+            === false) {
648
+            throw new \Exception('missing placeholder');
649
+        }
650
+
651
+        $users = $this->access->countUsersByLoginName($loginName);
652
+        if($this->ldap->errno($cr) !== 0) {
653
+            throw new \Exception($this->ldap->error($cr));
654
+        }
655
+        $filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
656
+        $this->result->addChange('ldap_test_loginname', $users);
657
+        $this->result->addChange('ldap_test_effective_filter', $filter);
658
+        return $this->result;
659
+    }
660
+
661
+    /**
662
+     * Tries to determine the port, requires given Host, User DN and Password
663
+     * @return WizardResult|false WizardResult on success, false otherwise
664
+     * @throws \Exception
665
+     */
666
+    public function guessPortAndTLS() {
667
+        if(!$this->checkRequirements(array('ldapHost',
668
+                                            ))) {
669
+            return false;
670
+        }
671
+        $this->checkHost();
672
+        $portSettings = $this->getPortSettingsToTry();
673
+
674
+        if(!is_array($portSettings)) {
675
+            throw new \Exception(print_r($portSettings, true));
676
+        }
677
+
678
+        //proceed from the best configuration and return on first success
679
+        foreach($portSettings as $setting) {
680
+            $p = $setting['port'];
681
+            $t = $setting['tls'];
682
+            \OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, \OCP\Util::DEBUG);
683
+            //connectAndBind may throw Exception, it needs to be catched by the
684
+            //callee of this method
685
+
686
+            try {
687
+                $settingsFound = $this->connectAndBind($p, $t);
688
+            } catch (\Exception $e) {
689
+                // any reply other than -1 (= cannot connect) is already okay,
690
+                // because then we found the server
691
+                // unavailable startTLS returns -11
692
+                if($e->getCode() > 0) {
693
+                    $settingsFound = true;
694
+                } else {
695
+                    throw $e;
696
+                }
697
+            }
698
+
699
+            if ($settingsFound === true) {
700
+                $config = array(
701
+                    'ldapPort' => $p,
702
+                    'ldapTLS' => (int)$t
703
+                );
704
+                $this->configuration->setConfiguration($config);
705
+                \OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, \OCP\Util::DEBUG);
706
+                $this->result->addChange('ldap_port', $p);
707
+                return $this->result;
708
+            }
709
+        }
710
+
711
+        //custom port, undetected (we do not brute force)
712
+        return false;
713
+    }
714
+
715
+    /**
716
+     * tries to determine a base dn from User DN or LDAP Host
717
+     * @return WizardResult|false WizardResult on success, false otherwise
718
+     */
719
+    public function guessBaseDN() {
720
+        if(!$this->checkRequirements(array('ldapHost',
721
+                                            'ldapPort',
722
+                                            ))) {
723
+            return false;
724
+        }
725
+
726
+        //check whether a DN is given in the agent name (99.9% of all cases)
727
+        $base = null;
728
+        $i = stripos($this->configuration->ldapAgentName, 'dc=');
729
+        if($i !== false) {
730
+            $base = substr($this->configuration->ldapAgentName, $i);
731
+            if($this->testBaseDN($base)) {
732
+                $this->applyFind('ldap_base', $base);
733
+                return $this->result;
734
+            }
735
+        }
736
+
737
+        //this did not help :(
738
+        //Let's see whether we can parse the Host URL and convert the domain to
739
+        //a base DN
740
+        $helper = new Helper(\OC::$server->getConfig());
741
+        $domain = $helper->getDomainFromURL($this->configuration->ldapHost);
742
+        if(!$domain) {
743
+            return false;
744
+        }
745
+
746
+        $dparts = explode('.', $domain);
747
+        while(count($dparts) > 0) {
748
+            $base2 = 'dc=' . implode(',dc=', $dparts);
749
+            if ($base !== $base2 && $this->testBaseDN($base2)) {
750
+                $this->applyFind('ldap_base', $base2);
751
+                return $this->result;
752
+            }
753
+            array_shift($dparts);
754
+        }
755
+
756
+        return false;
757
+    }
758
+
759
+    /**
760
+     * sets the found value for the configuration key in the WizardResult
761
+     * as well as in the Configuration instance
762
+     * @param string $key the configuration key
763
+     * @param string $value the (detected) value
764
+     *
765
+     */
766
+    private function applyFind($key, $value) {
767
+        $this->result->addChange($key, $value);
768
+        $this->configuration->setConfiguration(array($key => $value));
769
+    }
770
+
771
+    /**
772
+     * Checks, whether a port was entered in the Host configuration
773
+     * field. In this case the port will be stripped off, but also stored as
774
+     * setting.
775
+     */
776
+    private function checkHost() {
777
+        $host = $this->configuration->ldapHost;
778
+        $hostInfo = parse_url($host);
779
+
780
+        //removes Port from Host
781
+        if(is_array($hostInfo) && isset($hostInfo['port'])) {
782
+            $port = $hostInfo['port'];
783
+            $host = str_replace(':'.$port, '', $host);
784
+            $this->applyFind('ldap_host', $host);
785
+            $this->applyFind('ldap_port', $port);
786
+        }
787
+    }
788
+
789
+    /**
790
+     * tries to detect the group member association attribute which is
791
+     * one of 'uniqueMember', 'memberUid', 'member', 'gidNumber'
792
+     * @return string|false, string with the attribute name, false on error
793
+     * @throws \Exception
794
+     */
795
+    private function detectGroupMemberAssoc() {
796
+        $possibleAttrs = array('uniqueMember', 'memberUid', 'member', 'gidNumber');
797
+        $filter = $this->configuration->ldapGroupFilter;
798
+        if(empty($filter)) {
799
+            return false;
800
+        }
801
+        $cr = $this->getConnection();
802
+        if(!$cr) {
803
+            throw new \Exception('Could not connect to LDAP');
804
+        }
805
+        $base = $this->configuration->ldapBase[0];
806
+        $rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
807
+        if(!$this->ldap->isResource($rr)) {
808
+            return false;
809
+        }
810
+        $er = $this->ldap->firstEntry($cr, $rr);
811
+        while(is_resource($er)) {
812
+            $this->ldap->getDN($cr, $er);
813
+            $attrs = $this->ldap->getAttributes($cr, $er);
814
+            $result = array();
815
+            $possibleAttrsCount = count($possibleAttrs);
816
+            for($i = 0; $i < $possibleAttrsCount; $i++) {
817
+                if(isset($attrs[$possibleAttrs[$i]])) {
818
+                    $result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
819
+                }
820
+            }
821
+            if(!empty($result)) {
822
+                natsort($result);
823
+                return key($result);
824
+            }
825
+
826
+            $er = $this->ldap->nextEntry($cr, $er);
827
+        }
828
+
829
+        return false;
830
+    }
831
+
832
+    /**
833
+     * Checks whether for a given BaseDN results will be returned
834
+     * @param string $base the BaseDN to test
835
+     * @return bool true on success, false otherwise
836
+     * @throws \Exception
837
+     */
838
+    private function testBaseDN($base) {
839
+        $cr = $this->getConnection();
840
+        if(!$cr) {
841
+            throw new \Exception('Could not connect to LDAP');
842
+        }
843
+
844
+        //base is there, let's validate it. If we search for anything, we should
845
+        //get a result set > 0 on a proper base
846
+        $rr = $this->ldap->search($cr, $base, 'objectClass=*', array('dn'), 0, 1);
847
+        if(!$this->ldap->isResource($rr)) {
848
+            $errorNo  = $this->ldap->errno($cr);
849
+            $errorMsg = $this->ldap->error($cr);
850
+            \OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base.
851
+                            ' Error '.$errorNo.': '.$errorMsg, \OCP\Util::INFO);
852
+            return false;
853
+        }
854
+        $entries = $this->ldap->countEntries($cr, $rr);
855
+        return ($entries !== false) && ($entries > 0);
856
+    }
857
+
858
+    /**
859
+     * Checks whether the server supports memberOf in LDAP Filter.
860
+     * Note: at least in OpenLDAP, availability of memberOf is dependent on
861
+     * a configured objectClass. I.e. not necessarily for all available groups
862
+     * memberOf does work.
863
+     *
864
+     * @return bool true if it does, false otherwise
865
+     * @throws \Exception
866
+     */
867
+    private function testMemberOf() {
868
+        $cr = $this->getConnection();
869
+        if(!$cr) {
870
+            throw new \Exception('Could not connect to LDAP');
871
+        }
872
+        $result = $this->access->countUsers('memberOf=*', array('memberOf'), 1);
873
+        if(is_int($result) &&  $result > 0) {
874
+            return true;
875
+        }
876
+        return false;
877
+    }
878
+
879
+    /**
880
+     * creates an LDAP Filter from given configuration
881
+     * @param integer $filterType int, for which use case the filter shall be created
882
+     * can be any of self::LFILTER_USER_LIST, self::LFILTER_LOGIN or
883
+     * self::LFILTER_GROUP_LIST
884
+     * @return string|false string with the filter on success, false otherwise
885
+     * @throws \Exception
886
+     */
887
+    private function composeLdapFilter($filterType) {
888
+        $filter = '';
889
+        $parts = 0;
890
+        switch ($filterType) {
891
+            case self::LFILTER_USER_LIST:
892
+                $objcs = $this->configuration->ldapUserFilterObjectclass;
893
+                //glue objectclasses
894
+                if(is_array($objcs) && count($objcs) > 0) {
895
+                    $filter .= '(|';
896
+                    foreach($objcs as $objc) {
897
+                        $filter .= '(objectclass=' . $objc . ')';
898
+                    }
899
+                    $filter .= ')';
900
+                    $parts++;
901
+                }
902
+                //glue group memberships
903
+                if($this->configuration->hasMemberOfFilterSupport) {
904
+                    $cns = $this->configuration->ldapUserFilterGroups;
905
+                    if(is_array($cns) && count($cns) > 0) {
906
+                        $filter .= '(|';
907
+                        $cr = $this->getConnection();
908
+                        if(!$cr) {
909
+                            throw new \Exception('Could not connect to LDAP');
910
+                        }
911
+                        $base = $this->configuration->ldapBase[0];
912
+                        foreach($cns as $cn) {
913
+                            $rr = $this->ldap->search($cr, $base, 'cn=' . $cn, array('dn', 'primaryGroupToken'));
914
+                            if(!$this->ldap->isResource($rr)) {
915
+                                continue;
916
+                            }
917
+                            $er = $this->ldap->firstEntry($cr, $rr);
918
+                            $attrs = $this->ldap->getAttributes($cr, $er);
919
+                            $dn = $this->ldap->getDN($cr, $er);
920
+                            if ($dn === false || $dn === '') {
921
+                                continue;
922
+                            }
923
+                            $filterPart = '(memberof=' . $dn . ')';
924
+                            if(isset($attrs['primaryGroupToken'])) {
925
+                                $pgt = $attrs['primaryGroupToken'][0];
926
+                                $primaryFilterPart = '(primaryGroupID=' . $pgt .')';
927
+                                $filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
928
+                            }
929
+                            $filter .= $filterPart;
930
+                        }
931
+                        $filter .= ')';
932
+                    }
933
+                    $parts++;
934
+                }
935
+                //wrap parts in AND condition
936
+                if($parts > 1) {
937
+                    $filter = '(&' . $filter . ')';
938
+                }
939
+                if ($filter === '') {
940
+                    $filter = '(objectclass=*)';
941
+                }
942
+                break;
943
+
944
+            case self::LFILTER_GROUP_LIST:
945
+                $objcs = $this->configuration->ldapGroupFilterObjectclass;
946
+                //glue objectclasses
947
+                if(is_array($objcs) && count($objcs) > 0) {
948
+                    $filter .= '(|';
949
+                    foreach($objcs as $objc) {
950
+                        $filter .= '(objectclass=' . $objc . ')';
951
+                    }
952
+                    $filter .= ')';
953
+                    $parts++;
954
+                }
955
+                //glue group memberships
956
+                $cns = $this->configuration->ldapGroupFilterGroups;
957
+                if(is_array($cns) && count($cns) > 0) {
958
+                    $filter .= '(|';
959
+                    foreach($cns as $cn) {
960
+                        $filter .= '(cn=' . $cn . ')';
961
+                    }
962
+                    $filter .= ')';
963
+                }
964
+                $parts++;
965
+                //wrap parts in AND condition
966
+                if($parts > 1) {
967
+                    $filter = '(&' . $filter . ')';
968
+                }
969
+                break;
970
+
971
+            case self::LFILTER_LOGIN:
972
+                $ulf = $this->configuration->ldapUserFilter;
973
+                $loginpart = '=%uid';
974
+                $filterUsername = '';
975
+                $userAttributes = $this->getUserAttributes();
976
+                $userAttributes = array_change_key_case(array_flip($userAttributes));
977
+                $parts = 0;
978
+
979
+                if($this->configuration->ldapLoginFilterUsername === '1') {
980
+                    $attr = '';
981
+                    if(isset($userAttributes['uid'])) {
982
+                        $attr = 'uid';
983
+                    } else if(isset($userAttributes['samaccountname'])) {
984
+                        $attr = 'samaccountname';
985
+                    } else if(isset($userAttributes['cn'])) {
986
+                        //fallback
987
+                        $attr = 'cn';
988
+                    }
989
+                    if ($attr !== '') {
990
+                        $filterUsername = '(' . $attr . $loginpart . ')';
991
+                        $parts++;
992
+                    }
993
+                }
994
+
995
+                $filterEmail = '';
996
+                if($this->configuration->ldapLoginFilterEmail === '1') {
997
+                    $filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
998
+                    $parts++;
999
+                }
1000
+
1001
+                $filterAttributes = '';
1002
+                $attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
1003
+                if(is_array($attrsToFilter) && count($attrsToFilter) > 0) {
1004
+                    $filterAttributes = '(|';
1005
+                    foreach($attrsToFilter as $attribute) {
1006
+                        $filterAttributes .= '(' . $attribute . $loginpart . ')';
1007
+                    }
1008
+                    $filterAttributes .= ')';
1009
+                    $parts++;
1010
+                }
1011
+
1012
+                $filterLogin = '';
1013
+                if($parts > 1) {
1014
+                    $filterLogin = '(|';
1015
+                }
1016
+                $filterLogin .= $filterUsername;
1017
+                $filterLogin .= $filterEmail;
1018
+                $filterLogin .= $filterAttributes;
1019
+                if($parts > 1) {
1020
+                    $filterLogin .= ')';
1021
+                }
1022
+
1023
+                $filter = '(&'.$ulf.$filterLogin.')';
1024
+                break;
1025
+        }
1026
+
1027
+        \OCP\Util::writeLog('user_ldap', 'Wiz: Final filter '.$filter, \OCP\Util::DEBUG);
1028
+
1029
+        return $filter;
1030
+    }
1031
+
1032
+    /**
1033
+     * Connects and Binds to an LDAP Server
1034
+     *
1035
+     * @param int $port the port to connect with
1036
+     * @param bool $tls whether startTLS is to be used
1037
+     * @return bool
1038
+     * @throws \Exception
1039
+     */
1040
+    private function connectAndBind($port, $tls) {
1041
+        //connect, does not really trigger any server communication
1042
+        $host = $this->configuration->ldapHost;
1043
+        $hostInfo = parse_url($host);
1044
+        if(!$hostInfo) {
1045
+            throw new \Exception(self::$l->t('Invalid Host'));
1046
+        }
1047
+        \OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', \OCP\Util::DEBUG);
1048
+        $cr = $this->ldap->connect($host, $port);
1049
+        if(!is_resource($cr)) {
1050
+            throw new \Exception(self::$l->t('Invalid Host'));
1051
+        }
1052
+
1053
+        //set LDAP options
1054
+        $this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1055
+        $this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1056
+        $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1057
+
1058
+        try {
1059
+            if($tls) {
1060
+                $isTlsWorking = @$this->ldap->startTls($cr);
1061
+                if(!$isTlsWorking) {
1062
+                    return false;
1063
+                }
1064
+            }
1065
+
1066
+            \OCP\Util::writeLog('user_ldap', 'Wiz: Attemping to Bind ', \OCP\Util::DEBUG);
1067
+            //interesting part: do the bind!
1068
+            $login = $this->ldap->bind($cr,
1069
+                $this->configuration->ldapAgentName,
1070
+                $this->configuration->ldapAgentPassword
1071
+            );
1072
+            $errNo = $this->ldap->errno($cr);
1073
+            $error = ldap_error($cr);
1074
+            $this->ldap->unbind($cr);
1075
+        } catch(ServerNotAvailableException $e) {
1076
+            return false;
1077
+        }
1078
+
1079
+        if($login === true) {
1080
+            $this->ldap->unbind($cr);
1081
+            \OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . (int)$tls, \OCP\Util::DEBUG);
1082
+            return true;
1083
+        }
1084
+
1085
+        if($errNo === -1) {
1086
+            //host, port or TLS wrong
1087
+            return false;
1088
+        }
1089
+        throw new \Exception($error, $errNo);
1090
+    }
1091
+
1092
+    /**
1093
+     * checks whether a valid combination of agent and password has been
1094
+     * provided (either two values or nothing for anonymous connect)
1095
+     * @return bool, true if everything is fine, false otherwise
1096
+     */
1097
+    private function checkAgentRequirements() {
1098
+        $agent = $this->configuration->ldapAgentName;
1099
+        $pwd = $this->configuration->ldapAgentPassword;
1100
+
1101
+        return
1102
+            ($agent !== '' && $pwd !== '')
1103
+            ||  ($agent === '' && $pwd === '')
1104
+        ;
1105
+    }
1106
+
1107
+    /**
1108
+     * @param array $reqs
1109
+     * @return bool
1110
+     */
1111
+    private function checkRequirements($reqs) {
1112
+        $this->checkAgentRequirements();
1113
+        foreach($reqs as $option) {
1114
+            $value = $this->configuration->$option;
1115
+            if(empty($value)) {
1116
+                return false;
1117
+            }
1118
+        }
1119
+        return true;
1120
+    }
1121
+
1122
+    /**
1123
+     * does a cumulativeSearch on LDAP to get different values of a
1124
+     * specified attribute
1125
+     * @param string[] $filters array, the filters that shall be used in the search
1126
+     * @param string $attr the attribute of which a list of values shall be returned
1127
+     * @param int $dnReadLimit the amount of how many DNs should be analyzed.
1128
+     * The lower, the faster
1129
+     * @param string $maxF string. if not null, this variable will have the filter that
1130
+     * yields most result entries
1131
+     * @return array|false an array with the values on success, false otherwise
1132
+     */
1133
+    public function cumulativeSearchOnAttribute($filters, $attr, $dnReadLimit = 3, &$maxF = null) {
1134
+        $dnRead = array();
1135
+        $foundItems = array();
1136
+        $maxEntries = 0;
1137
+        if(!is_array($this->configuration->ldapBase)
1138
+           || !isset($this->configuration->ldapBase[0])) {
1139
+            return false;
1140
+        }
1141
+        $base = $this->configuration->ldapBase[0];
1142
+        $cr = $this->getConnection();
1143
+        if(!$this->ldap->isResource($cr)) {
1144
+            return false;
1145
+        }
1146
+        $lastFilter = null;
1147
+        if(isset($filters[count($filters)-1])) {
1148
+            $lastFilter = $filters[count($filters)-1];
1149
+        }
1150
+        foreach($filters as $filter) {
1151
+            if($lastFilter === $filter && count($foundItems) > 0) {
1152
+                //skip when the filter is a wildcard and results were found
1153
+                continue;
1154
+            }
1155
+            // 20k limit for performance and reason
1156
+            $rr = $this->ldap->search($cr, $base, $filter, array($attr), 0, 20000);
1157
+            if(!$this->ldap->isResource($rr)) {
1158
+                continue;
1159
+            }
1160
+            $entries = $this->ldap->countEntries($cr, $rr);
1161
+            $getEntryFunc = 'firstEntry';
1162
+            if(($entries !== false) && ($entries > 0)) {
1163
+                if(!is_null($maxF) && $entries > $maxEntries) {
1164
+                    $maxEntries = $entries;
1165
+                    $maxF = $filter;
1166
+                }
1167
+                $dnReadCount = 0;
1168
+                do {
1169
+                    $entry = $this->ldap->$getEntryFunc($cr, $rr);
1170
+                    $getEntryFunc = 'nextEntry';
1171
+                    if(!$this->ldap->isResource($entry)) {
1172
+                        continue 2;
1173
+                    }
1174
+                    $rr = $entry; //will be expected by nextEntry next round
1175
+                    $attributes = $this->ldap->getAttributes($cr, $entry);
1176
+                    $dn = $this->ldap->getDN($cr, $entry);
1177
+                    if($dn === false || in_array($dn, $dnRead)) {
1178
+                        continue;
1179
+                    }
1180
+                    $newItems = array();
1181
+                    $state = $this->getAttributeValuesFromEntry($attributes,
1182
+                                                                $attr,
1183
+                                                                $newItems);
1184
+                    $dnReadCount++;
1185
+                    $foundItems = array_merge($foundItems, $newItems);
1186
+                    $this->resultCache[$dn][$attr] = $newItems;
1187
+                    $dnRead[] = $dn;
1188
+                } while(($state === self::LRESULT_PROCESSED_SKIP
1189
+                        || $this->ldap->isResource($entry))
1190
+                        && ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit));
1191
+            }
1192
+        }
1193
+
1194
+        return array_unique($foundItems);
1195
+    }
1196
+
1197
+    /**
1198
+     * determines if and which $attr are available on the LDAP server
1199
+     * @param string[] $objectclasses the objectclasses to use as search filter
1200
+     * @param string $attr the attribute to look for
1201
+     * @param string $dbkey the dbkey of the setting the feature is connected to
1202
+     * @param string $confkey the confkey counterpart for the $dbkey as used in the
1203
+     * Configuration class
1204
+     * @param bool $po whether the objectClass with most result entries
1205
+     * shall be pre-selected via the result
1206
+     * @return array|false list of found items.
1207
+     * @throws \Exception
1208
+     */
1209
+    private function determineFeature($objectclasses, $attr, $dbkey, $confkey, $po = false) {
1210
+        $cr = $this->getConnection();
1211
+        if(!$cr) {
1212
+            throw new \Exception('Could not connect to LDAP');
1213
+        }
1214
+        $p = 'objectclass=';
1215
+        foreach($objectclasses as $key => $value) {
1216
+            $objectclasses[$key] = $p.$value;
1217
+        }
1218
+        $maxEntryObjC = '';
1219
+
1220
+        //how deep to dig?
1221
+        //When looking for objectclasses, testing few entries is sufficient,
1222
+        $dig = 3;
1223
+
1224
+        $availableFeatures =
1225
+            $this->cumulativeSearchOnAttribute($objectclasses, $attr,
1226
+                                                $dig, $maxEntryObjC);
1227
+        if(is_array($availableFeatures)
1228
+           && count($availableFeatures) > 0) {
1229
+            natcasesort($availableFeatures);
1230
+            //natcasesort keeps indices, but we must get rid of them for proper
1231
+            //sorting in the web UI. Therefore: array_values
1232
+            $this->result->addOptions($dbkey, array_values($availableFeatures));
1233
+        } else {
1234
+            throw new \Exception(self::$l->t('Could not find the desired feature'));
1235
+        }
1236
+
1237
+        $setFeatures = $this->configuration->$confkey;
1238
+        if(is_array($setFeatures) && !empty($setFeatures)) {
1239
+            //something is already configured? pre-select it.
1240
+            $this->result->addChange($dbkey, $setFeatures);
1241
+        } else if ($po && $maxEntryObjC !== '') {
1242
+            //pre-select objectclass with most result entries
1243
+            $maxEntryObjC = str_replace($p, '', $maxEntryObjC);
1244
+            $this->applyFind($dbkey, $maxEntryObjC);
1245
+            $this->result->addChange($dbkey, $maxEntryObjC);
1246
+        }
1247
+
1248
+        return $availableFeatures;
1249
+    }
1250
+
1251
+    /**
1252
+     * appends a list of values fr
1253
+     * @param resource $result the return value from ldap_get_attributes
1254
+     * @param string $attribute the attribute values to look for
1255
+     * @param array &$known new values will be appended here
1256
+     * @return int, state on of the class constants LRESULT_PROCESSED_OK,
1257
+     * LRESULT_PROCESSED_INVALID or LRESULT_PROCESSED_SKIP
1258
+     */
1259
+    private function getAttributeValuesFromEntry($result, $attribute, &$known) {
1260
+        if(!is_array($result)
1261
+           || !isset($result['count'])
1262
+           || !$result['count'] > 0) {
1263
+            return self::LRESULT_PROCESSED_INVALID;
1264
+        }
1265
+
1266
+        // strtolower on all keys for proper comparison
1267
+        $result = \OCP\Util::mb_array_change_key_case($result);
1268
+        $attribute = strtolower($attribute);
1269
+        if(isset($result[$attribute])) {
1270
+            foreach($result[$attribute] as $key => $val) {
1271
+                if($key === 'count') {
1272
+                    continue;
1273
+                }
1274
+                if(!in_array($val, $known)) {
1275
+                    $known[] = $val;
1276
+                }
1277
+            }
1278
+            return self::LRESULT_PROCESSED_OK;
1279
+        } else {
1280
+            return self::LRESULT_PROCESSED_SKIP;
1281
+        }
1282
+    }
1283
+
1284
+    /**
1285
+     * @return bool|mixed
1286
+     */
1287
+    private function getConnection() {
1288
+        if(!is_null($this->cr)) {
1289
+            return $this->cr;
1290
+        }
1291
+
1292
+        $cr = $this->ldap->connect(
1293
+            $this->configuration->ldapHost,
1294
+            $this->configuration->ldapPort
1295
+        );
1296
+
1297
+        $this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1298
+        $this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1299
+        $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1300
+        if($this->configuration->ldapTLS === 1) {
1301
+            $this->ldap->startTls($cr);
1302
+        }
1303
+
1304
+        $lo = @$this->ldap->bind($cr,
1305
+                                    $this->configuration->ldapAgentName,
1306
+                                    $this->configuration->ldapAgentPassword);
1307
+        if($lo === true) {
1308
+            $this->$cr = $cr;
1309
+            return $cr;
1310
+        }
1311
+
1312
+        return false;
1313
+    }
1314
+
1315
+    /**
1316
+     * @return array
1317
+     */
1318
+    private function getDefaultLdapPortSettings() {
1319
+        static $settings = array(
1320
+                                array('port' => 7636, 'tls' => false),
1321
+                                array('port' =>  636, 'tls' => false),
1322
+                                array('port' => 7389, 'tls' => true),
1323
+                                array('port' =>  389, 'tls' => true),
1324
+                                array('port' => 7389, 'tls' => false),
1325
+                                array('port' =>  389, 'tls' => false),
1326
+                            );
1327
+        return $settings;
1328
+    }
1329
+
1330
+    /**
1331
+     * @return array
1332
+     */
1333
+    private function getPortSettingsToTry() {
1334
+        //389 ← LDAP / Unencrypted or StartTLS
1335
+        //636 ← LDAPS / SSL
1336
+        //7xxx ← UCS. need to be checked first, because both ports may be open
1337
+        $host = $this->configuration->ldapHost;
1338
+        $port = (int)$this->configuration->ldapPort;
1339
+        $portSettings = array();
1340
+
1341
+        //In case the port is already provided, we will check this first
1342
+        if($port > 0) {
1343
+            $hostInfo = parse_url($host);
1344
+            if(!(is_array($hostInfo)
1345
+                && isset($hostInfo['scheme'])
1346
+                && stripos($hostInfo['scheme'], 'ldaps') !== false)) {
1347
+                $portSettings[] = array('port' => $port, 'tls' => true);
1348
+            }
1349
+            $portSettings[] =array('port' => $port, 'tls' => false);
1350
+        }
1351
+
1352
+        //default ports
1353
+        $portSettings = array_merge($portSettings,
1354
+                                    $this->getDefaultLdapPortSettings());
1355
+
1356
+        return $portSettings;
1357
+    }
1358 1358
 
1359 1359
 
1360 1360
 }
Please login to merge, or discard this patch.
Spacing   +156 added lines, -156 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(string $filter, string $type): int {
96 96
 		$reqs = ['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 = ['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);
@@ -113,7 +113,7 @@  discard block
 block discarded – undo
113 113
 			throw new \Exception('Internal error: Invalid object type', 500);
114 114
 		}
115 115
 
116
-		return (int)$result;
116
+		return (int) $result;
117 117
 	}
118 118
 
119 119
 	/**
@@ -124,16 +124,16 @@  discard block
 block discarded – undo
124 124
 	 * @return string
125 125
 	 */
126 126
 	private function formatCountResult(int $count): string {
127
-		if($count > 1000) {
127
+		if ($count > 1000) {
128 128
 			return '> 1000';
129 129
 		}
130
-		return (string)$count;
130
+		return (string) $count;
131 131
 	}
132 132
 
133 133
 	public function countGroups() {
134 134
 		$filter = $this->configuration->ldapGroupFilter;
135 135
 
136
-		if(empty($filter)) {
136
+		if (empty($filter)) {
137 137
 			$output = self::$l->n('%s group found', '%s groups found', 0, array(0));
138 138
 			$this->result->addChange('ldap_group_count', $output);
139 139
 			return $this->result;
@@ -143,7 +143,7 @@  discard block
 block discarded – undo
143 143
 			$groupsTotal = $this->countEntries($filter, 'groups');
144 144
 		} catch (\Exception $e) {
145 145
 			//400 can be ignored, 500 is forwarded
146
-			if($e->getCode() === 500) {
146
+			if ($e->getCode() === 500) {
147 147
 				throw $e;
148 148
 			}
149 149
 			return false;
@@ -185,7 +185,7 @@  discard block
 block discarded – undo
185 185
 	public function countInBaseDN() {
186 186
 		// we don't need to provide a filter in this case
187 187
 		$total = $this->countEntries('', 'objects');
188
-		if($total === false) {
188
+		if ($total === false) {
189 189
 			throw new \Exception('invalid results received');
190 190
 		}
191 191
 		$this->result->addChange('ldap_test_base', $total);
@@ -199,7 +199,7 @@  discard block
 block discarded – undo
199 199
 	 * @return int|bool
200 200
 	 */
201 201
 	public function countUsersWithAttribute($attr, $existsCheck = false) {
202
-		if(!$this->checkRequirements(array('ldapHost',
202
+		if (!$this->checkRequirements(array('ldapHost',
203 203
 										   'ldapPort',
204 204
 										   'ldapBase',
205 205
 										   'ldapUserFilter',
@@ -209,7 +209,7 @@  discard block
 block discarded – undo
209 209
 
210 210
 		$filter = $this->access->combineFilterWithAnd(array(
211 211
 			$this->configuration->ldapUserFilter,
212
-			$attr . '=*'
212
+			$attr.'=*'
213 213
 		));
214 214
 
215 215
 		$limit = ($existsCheck === false) ? null : 1;
@@ -224,7 +224,7 @@  discard block
 block discarded – undo
224 224
 	 * @throws \Exception
225 225
 	 */
226 226
 	public function detectUserDisplayNameAttribute() {
227
-		if(!$this->checkRequirements(array('ldapHost',
227
+		if (!$this->checkRequirements(array('ldapHost',
228 228
 										'ldapPort',
229 229
 										'ldapBase',
230 230
 										'ldapUserFilter',
@@ -236,8 +236,8 @@  discard block
 block discarded – undo
236 236
 		if ($attr !== '' && $attr !== 'displayName') {
237 237
 			// most likely not the default value with upper case N,
238 238
 			// verify it still produces a result
239
-			$count = (int)$this->countUsersWithAttribute($attr, true);
240
-			if($count > 0) {
239
+			$count = (int) $this->countUsersWithAttribute($attr, true);
240
+			if ($count > 0) {
241 241
 				//no change, but we sent it back to make sure the user interface
242 242
 				//is still correct, even if the ajax call was cancelled meanwhile
243 243
 				$this->result->addChange('ldap_display_name', $attr);
@@ -248,9 +248,9 @@  discard block
 block discarded – undo
248 248
 		// first attribute that has at least one result wins
249 249
 		$displayNameAttrs = array('displayname', 'cn');
250 250
 		foreach ($displayNameAttrs as $attr) {
251
-			$count = (int)$this->countUsersWithAttribute($attr, true);
251
+			$count = (int) $this->countUsersWithAttribute($attr, true);
252 252
 
253
-			if($count > 0) {
253
+			if ($count > 0) {
254 254
 				$this->applyFind('ldap_display_name', $attr);
255 255
 				return $this->result;
256 256
 			}
@@ -266,7 +266,7 @@  discard block
 block discarded – undo
266 266
 	 * @return WizardResult|bool
267 267
 	 */
268 268
 	public function detectEmailAttribute() {
269
-		if(!$this->checkRequirements(array('ldapHost',
269
+		if (!$this->checkRequirements(array('ldapHost',
270 270
 										   'ldapPort',
271 271
 										   'ldapBase',
272 272
 										   'ldapUserFilter',
@@ -276,8 +276,8 @@  discard block
 block discarded – undo
276 276
 
277 277
 		$attr = $this->configuration->ldapEmailAttribute;
278 278
 		if ($attr !== '') {
279
-			$count = (int)$this->countUsersWithAttribute($attr, true);
280
-			if($count > 0) {
279
+			$count = (int) $this->countUsersWithAttribute($attr, true);
280
+			if ($count > 0) {
281 281
 				return false;
282 282
 			}
283 283
 			$writeLog = true;
@@ -288,19 +288,19 @@  discard block
 block discarded – undo
288 288
 		$emailAttributes = array('mail', 'mailPrimaryAddress');
289 289
 		$winner = '';
290 290
 		$maxUsers = 0;
291
-		foreach($emailAttributes as $attr) {
291
+		foreach ($emailAttributes as $attr) {
292 292
 			$count = $this->countUsersWithAttribute($attr);
293
-			if($count > $maxUsers) {
293
+			if ($count > $maxUsers) {
294 294
 				$maxUsers = $count;
295 295
 				$winner = $attr;
296 296
 			}
297 297
 		}
298 298
 
299
-		if($winner !== '') {
299
+		if ($winner !== '') {
300 300
 			$this->applyFind('ldap_email_attr', $winner);
301
-			if($writeLog) {
302
-				\OCP\Util::writeLog('user_ldap', 'The mail attribute has ' .
303
-					'automatically been reset, because the original value ' .
301
+			if ($writeLog) {
302
+				\OCP\Util::writeLog('user_ldap', 'The mail attribute has '.
303
+					'automatically been reset, because the original value '.
304 304
 					'did not return any results.', \OCP\Util::INFO);
305 305
 			}
306 306
 		}
@@ -313,7 +313,7 @@  discard block
 block discarded – undo
313 313
 	 * @throws \Exception
314 314
 	 */
315 315
 	public function determineAttributes() {
316
-		if(!$this->checkRequirements(array('ldapHost',
316
+		if (!$this->checkRequirements(array('ldapHost',
317 317
 										   'ldapPort',
318 318
 										   'ldapBase',
319 319
 										   'ldapUserFilter',
@@ -329,7 +329,7 @@  discard block
 block discarded – undo
329 329
 		$this->result->addOptions('ldap_loginfilter_attributes', $attributes);
330 330
 
331 331
 		$selected = $this->configuration->ldapLoginFilterAttributes;
332
-		if(is_array($selected) && !empty($selected)) {
332
+		if (is_array($selected) && !empty($selected)) {
333 333
 			$this->result->addChange('ldap_loginfilter_attributes', $selected);
334 334
 		}
335 335
 
@@ -342,7 +342,7 @@  discard block
 block discarded – undo
342 342
 	 * @throws \Exception
343 343
 	 */
344 344
 	private function getUserAttributes() {
345
-		if(!$this->checkRequirements(array('ldapHost',
345
+		if (!$this->checkRequirements(array('ldapHost',
346 346
 										   'ldapPort',
347 347
 										   'ldapBase',
348 348
 										   'ldapUserFilter',
@@ -350,20 +350,20 @@  discard block
 block discarded – undo
350 350
 			return  false;
351 351
 		}
352 352
 		$cr = $this->getConnection();
353
-		if(!$cr) {
353
+		if (!$cr) {
354 354
 			throw new \Exception('Could not connect to LDAP');
355 355
 		}
356 356
 
357 357
 		$base = $this->configuration->ldapBase[0];
358 358
 		$filter = $this->configuration->ldapUserFilter;
359 359
 		$rr = $this->ldap->search($cr, $base, $filter, array(), 1, 1);
360
-		if(!$this->ldap->isResource($rr)) {
360
+		if (!$this->ldap->isResource($rr)) {
361 361
 			return false;
362 362
 		}
363 363
 		$er = $this->ldap->firstEntry($cr, $rr);
364 364
 		$attributes = $this->ldap->getAttributes($cr, $er);
365 365
 		$pureAttributes = array();
366
-		for($i = 0; $i < $attributes['count']; $i++) {
366
+		for ($i = 0; $i < $attributes['count']; $i++) {
367 367
 			$pureAttributes[] = $attributes[$i];
368 368
 		}
369 369
 
@@ -398,23 +398,23 @@  discard block
 block discarded – undo
398 398
 	 * @throws \Exception
399 399
 	 */
400 400
 	private function determineGroups($dbKey, $confKey, $testMemberOf = true) {
401
-		if(!$this->checkRequirements(array('ldapHost',
401
+		if (!$this->checkRequirements(array('ldapHost',
402 402
 										   'ldapPort',
403 403
 										   'ldapBase',
404 404
 										   ))) {
405 405
 			return  false;
406 406
 		}
407 407
 		$cr = $this->getConnection();
408
-		if(!$cr) {
408
+		if (!$cr) {
409 409
 			throw new \Exception('Could not connect to LDAP');
410 410
 		}
411 411
 
412 412
 		$this->fetchGroups($dbKey, $confKey);
413 413
 
414
-		if($testMemberOf) {
414
+		if ($testMemberOf) {
415 415
 			$this->configuration->hasMemberOfFilterSupport = $this->testMemberOf();
416 416
 			$this->result->markChange();
417
-			if(!$this->configuration->hasMemberOfFilterSupport) {
417
+			if (!$this->configuration->hasMemberOfFilterSupport) {
418 418
 				throw new \Exception('memberOf is not supported by the server');
419 419
 			}
420 420
 		}
@@ -434,7 +434,7 @@  discard block
 block discarded – undo
434 434
 		$obclasses = array('posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames', 'groupOfUniqueNames');
435 435
 
436 436
 		$filterParts = array();
437
-		foreach($obclasses as $obclass) {
437
+		foreach ($obclasses as $obclass) {
438 438
 			$filterParts[] = 'objectclass='.$obclass;
439 439
 		}
440 440
 		//we filter for everything
@@ -451,8 +451,8 @@  discard block
 block discarded – undo
451 451
 			// we need to request dn additionally here, otherwise memberOf
452 452
 			// detection will fail later
453 453
 			$result = $this->access->searchGroups($filter, array('cn', 'dn'), $limit, $offset);
454
-			foreach($result as $item) {
455
-				if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
454
+			foreach ($result as $item) {
455
+				if (!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
456 456
 					// just in case - no issue known
457 457
 					continue;
458 458
 				}
@@ -462,7 +462,7 @@  discard block
 block discarded – undo
462 462
 			$offset += $limit;
463 463
 		} while ($this->access->hasMoreResults());
464 464
 
465
-		if(count($groupNames) > 0) {
465
+		if (count($groupNames) > 0) {
466 466
 			natsort($groupNames);
467 467
 			$this->result->addOptions($dbKey, array_values($groupNames));
468 468
 		} else {
@@ -470,7 +470,7 @@  discard block
 block discarded – undo
470 470
 		}
471 471
 
472 472
 		$setFeatures = $this->configuration->$confKey;
473
-		if(is_array($setFeatures) && !empty($setFeatures)) {
473
+		if (is_array($setFeatures) && !empty($setFeatures)) {
474 474
 			//something is already configured? pre-select it.
475 475
 			$this->result->addChange($dbKey, $setFeatures);
476 476
 		}
@@ -478,14 +478,14 @@  discard block
 block discarded – undo
478 478
 	}
479 479
 
480 480
 	public function determineGroupMemberAssoc() {
481
-		if(!$this->checkRequirements(array('ldapHost',
481
+		if (!$this->checkRequirements(array('ldapHost',
482 482
 										   'ldapPort',
483 483
 										   'ldapGroupFilter',
484 484
 										   ))) {
485 485
 			return  false;
486 486
 		}
487 487
 		$attribute = $this->detectGroupMemberAssoc();
488
-		if($attribute === false) {
488
+		if ($attribute === false) {
489 489
 			return false;
490 490
 		}
491 491
 		$this->configuration->setConfiguration(array('ldapGroupMemberAssocAttr' => $attribute));
@@ -500,14 +500,14 @@  discard block
 block discarded – undo
500 500
 	 * @throws \Exception
501 501
 	 */
502 502
 	public function determineGroupObjectClasses() {
503
-		if(!$this->checkRequirements(array('ldapHost',
503
+		if (!$this->checkRequirements(array('ldapHost',
504 504
 										   'ldapPort',
505 505
 										   'ldapBase',
506 506
 										   ))) {
507 507
 			return  false;
508 508
 		}
509 509
 		$cr = $this->getConnection();
510
-		if(!$cr) {
510
+		if (!$cr) {
511 511
 			throw new \Exception('Could not connect to LDAP');
512 512
 		}
513 513
 
@@ -527,14 +527,14 @@  discard block
 block discarded – undo
527 527
 	 * @throws \Exception
528 528
 	 */
529 529
 	public function determineUserObjectClasses() {
530
-		if(!$this->checkRequirements(array('ldapHost',
530
+		if (!$this->checkRequirements(array('ldapHost',
531 531
 										   'ldapPort',
532 532
 										   'ldapBase',
533 533
 										   ))) {
534 534
 			return  false;
535 535
 		}
536 536
 		$cr = $this->getConnection();
537
-		if(!$cr) {
537
+		if (!$cr) {
538 538
 			throw new \Exception('Could not connect to LDAP');
539 539
 		}
540 540
 
@@ -557,7 +557,7 @@  discard block
 block discarded – undo
557 557
 	 * @throws \Exception
558 558
 	 */
559 559
 	public function getGroupFilter() {
560
-		if(!$this->checkRequirements(array('ldapHost',
560
+		if (!$this->checkRequirements(array('ldapHost',
561 561
 										   'ldapPort',
562 562
 										   'ldapBase',
563 563
 										   ))) {
@@ -581,7 +581,7 @@  discard block
 block discarded – undo
581 581
 	 * @throws \Exception
582 582
 	 */
583 583
 	public function getUserListFilter() {
584
-		if(!$this->checkRequirements(array('ldapHost',
584
+		if (!$this->checkRequirements(array('ldapHost',
585 585
 										   'ldapPort',
586 586
 										   'ldapBase',
587 587
 										   ))) {
@@ -594,7 +594,7 @@  discard block
 block discarded – undo
594 594
 			$this->applyFind('ldap_display_name', $d['ldap_display_name']);
595 595
 		}
596 596
 		$filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
597
-		if(!$filter) {
597
+		if (!$filter) {
598 598
 			throw new \Exception('Cannot create filter');
599 599
 		}
600 600
 
@@ -607,7 +607,7 @@  discard block
 block discarded – undo
607 607
 	 * @throws \Exception
608 608
 	 */
609 609
 	public function getUserLoginFilter() {
610
-		if(!$this->checkRequirements(array('ldapHost',
610
+		if (!$this->checkRequirements(array('ldapHost',
611 611
 										   'ldapPort',
612 612
 										   'ldapBase',
613 613
 										   'ldapUserFilter',
@@ -616,7 +616,7 @@  discard block
 block discarded – undo
616 616
 		}
617 617
 
618 618
 		$filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
619
-		if(!$filter) {
619
+		if (!$filter) {
620 620
 			throw new \Exception('Cannot create filter');
621 621
 		}
622 622
 
@@ -630,7 +630,7 @@  discard block
 block discarded – undo
630 630
 	 * @throws \Exception
631 631
 	 */
632 632
 	public function testLoginName($loginName) {
633
-		if(!$this->checkRequirements(array('ldapHost',
633
+		if (!$this->checkRequirements(array('ldapHost',
634 634
 			'ldapPort',
635 635
 			'ldapBase',
636 636
 			'ldapLoginFilter',
@@ -639,17 +639,17 @@  discard block
 block discarded – undo
639 639
 		}
640 640
 
641 641
 		$cr = $this->access->connection->getConnectionResource();
642
-		if(!$this->ldap->isResource($cr)) {
642
+		if (!$this->ldap->isResource($cr)) {
643 643
 			throw new \Exception('connection error');
644 644
 		}
645 645
 
646
-		if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
646
+		if (mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
647 647
 			=== false) {
648 648
 			throw new \Exception('missing placeholder');
649 649
 		}
650 650
 
651 651
 		$users = $this->access->countUsersByLoginName($loginName);
652
-		if($this->ldap->errno($cr) !== 0) {
652
+		if ($this->ldap->errno($cr) !== 0) {
653 653
 			throw new \Exception($this->ldap->error($cr));
654 654
 		}
655 655
 		$filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
@@ -664,22 +664,22 @@  discard block
 block discarded – undo
664 664
 	 * @throws \Exception
665 665
 	 */
666 666
 	public function guessPortAndTLS() {
667
-		if(!$this->checkRequirements(array('ldapHost',
667
+		if (!$this->checkRequirements(array('ldapHost',
668 668
 										   ))) {
669 669
 			return false;
670 670
 		}
671 671
 		$this->checkHost();
672 672
 		$portSettings = $this->getPortSettingsToTry();
673 673
 
674
-		if(!is_array($portSettings)) {
674
+		if (!is_array($portSettings)) {
675 675
 			throw new \Exception(print_r($portSettings, true));
676 676
 		}
677 677
 
678 678
 		//proceed from the best configuration and return on first success
679
-		foreach($portSettings as $setting) {
679
+		foreach ($portSettings as $setting) {
680 680
 			$p = $setting['port'];
681 681
 			$t = $setting['tls'];
682
-			\OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, \OCP\Util::DEBUG);
682
+			\OCP\Util::writeLog('user_ldap', 'Wiz: trying port '.$p.', TLS '.$t, \OCP\Util::DEBUG);
683 683
 			//connectAndBind may throw Exception, it needs to be catched by the
684 684
 			//callee of this method
685 685
 
@@ -689,7 +689,7 @@  discard block
 block discarded – undo
689 689
 				// any reply other than -1 (= cannot connect) is already okay,
690 690
 				// because then we found the server
691 691
 				// unavailable startTLS returns -11
692
-				if($e->getCode() > 0) {
692
+				if ($e->getCode() > 0) {
693 693
 					$settingsFound = true;
694 694
 				} else {
695 695
 					throw $e;
@@ -699,10 +699,10 @@  discard block
 block discarded – undo
699 699
 			if ($settingsFound === true) {
700 700
 				$config = array(
701 701
 					'ldapPort' => $p,
702
-					'ldapTLS' => (int)$t
702
+					'ldapTLS' => (int) $t
703 703
 				);
704 704
 				$this->configuration->setConfiguration($config);
705
-				\OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, \OCP\Util::DEBUG);
705
+				\OCP\Util::writeLog('user_ldap', 'Wiz: detected Port '.$p, \OCP\Util::DEBUG);
706 706
 				$this->result->addChange('ldap_port', $p);
707 707
 				return $this->result;
708 708
 			}
@@ -717,7 +717,7 @@  discard block
 block discarded – undo
717 717
 	 * @return WizardResult|false WizardResult on success, false otherwise
718 718
 	 */
719 719
 	public function guessBaseDN() {
720
-		if(!$this->checkRequirements(array('ldapHost',
720
+		if (!$this->checkRequirements(array('ldapHost',
721 721
 										   'ldapPort',
722 722
 										   ))) {
723 723
 			return false;
@@ -726,9 +726,9 @@  discard block
 block discarded – undo
726 726
 		//check whether a DN is given in the agent name (99.9% of all cases)
727 727
 		$base = null;
728 728
 		$i = stripos($this->configuration->ldapAgentName, 'dc=');
729
-		if($i !== false) {
729
+		if ($i !== false) {
730 730
 			$base = substr($this->configuration->ldapAgentName, $i);
731
-			if($this->testBaseDN($base)) {
731
+			if ($this->testBaseDN($base)) {
732 732
 				$this->applyFind('ldap_base', $base);
733 733
 				return $this->result;
734 734
 			}
@@ -739,13 +739,13 @@  discard block
 block discarded – undo
739 739
 		//a base DN
740 740
 		$helper = new Helper(\OC::$server->getConfig());
741 741
 		$domain = $helper->getDomainFromURL($this->configuration->ldapHost);
742
-		if(!$domain) {
742
+		if (!$domain) {
743 743
 			return false;
744 744
 		}
745 745
 
746 746
 		$dparts = explode('.', $domain);
747
-		while(count($dparts) > 0) {
748
-			$base2 = 'dc=' . implode(',dc=', $dparts);
747
+		while (count($dparts) > 0) {
748
+			$base2 = 'dc='.implode(',dc=', $dparts);
749 749
 			if ($base !== $base2 && $this->testBaseDN($base2)) {
750 750
 				$this->applyFind('ldap_base', $base2);
751 751
 				return $this->result;
@@ -778,7 +778,7 @@  discard block
 block discarded – undo
778 778
 		$hostInfo = parse_url($host);
779 779
 
780 780
 		//removes Port from Host
781
-		if(is_array($hostInfo) && isset($hostInfo['port'])) {
781
+		if (is_array($hostInfo) && isset($hostInfo['port'])) {
782 782
 			$port = $hostInfo['port'];
783 783
 			$host = str_replace(':'.$port, '', $host);
784 784
 			$this->applyFind('ldap_host', $host);
@@ -795,30 +795,30 @@  discard block
 block discarded – undo
795 795
 	private function detectGroupMemberAssoc() {
796 796
 		$possibleAttrs = array('uniqueMember', 'memberUid', 'member', 'gidNumber');
797 797
 		$filter = $this->configuration->ldapGroupFilter;
798
-		if(empty($filter)) {
798
+		if (empty($filter)) {
799 799
 			return false;
800 800
 		}
801 801
 		$cr = $this->getConnection();
802
-		if(!$cr) {
802
+		if (!$cr) {
803 803
 			throw new \Exception('Could not connect to LDAP');
804 804
 		}
805 805
 		$base = $this->configuration->ldapBase[0];
806 806
 		$rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
807
-		if(!$this->ldap->isResource($rr)) {
807
+		if (!$this->ldap->isResource($rr)) {
808 808
 			return false;
809 809
 		}
810 810
 		$er = $this->ldap->firstEntry($cr, $rr);
811
-		while(is_resource($er)) {
811
+		while (is_resource($er)) {
812 812
 			$this->ldap->getDN($cr, $er);
813 813
 			$attrs = $this->ldap->getAttributes($cr, $er);
814 814
 			$result = array();
815 815
 			$possibleAttrsCount = count($possibleAttrs);
816
-			for($i = 0; $i < $possibleAttrsCount; $i++) {
817
-				if(isset($attrs[$possibleAttrs[$i]])) {
816
+			for ($i = 0; $i < $possibleAttrsCount; $i++) {
817
+				if (isset($attrs[$possibleAttrs[$i]])) {
818 818
 					$result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
819 819
 				}
820 820
 			}
821
-			if(!empty($result)) {
821
+			if (!empty($result)) {
822 822
 				natsort($result);
823 823
 				return key($result);
824 824
 			}
@@ -837,14 +837,14 @@  discard block
 block discarded – undo
837 837
 	 */
838 838
 	private function testBaseDN($base) {
839 839
 		$cr = $this->getConnection();
840
-		if(!$cr) {
840
+		if (!$cr) {
841 841
 			throw new \Exception('Could not connect to LDAP');
842 842
 		}
843 843
 
844 844
 		//base is there, let's validate it. If we search for anything, we should
845 845
 		//get a result set > 0 on a proper base
846 846
 		$rr = $this->ldap->search($cr, $base, 'objectClass=*', array('dn'), 0, 1);
847
-		if(!$this->ldap->isResource($rr)) {
847
+		if (!$this->ldap->isResource($rr)) {
848 848
 			$errorNo  = $this->ldap->errno($cr);
849 849
 			$errorMsg = $this->ldap->error($cr);
850 850
 			\OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base.
@@ -866,11 +866,11 @@  discard block
 block discarded – undo
866 866
 	 */
867 867
 	private function testMemberOf() {
868 868
 		$cr = $this->getConnection();
869
-		if(!$cr) {
869
+		if (!$cr) {
870 870
 			throw new \Exception('Could not connect to LDAP');
871 871
 		}
872 872
 		$result = $this->access->countUsers('memberOf=*', array('memberOf'), 1);
873
-		if(is_int($result) &&  $result > 0) {
873
+		if (is_int($result) && $result > 0) {
874 874
 			return true;
875 875
 		}
876 876
 		return false;
@@ -891,27 +891,27 @@  discard block
 block discarded – undo
891 891
 			case self::LFILTER_USER_LIST:
892 892
 				$objcs = $this->configuration->ldapUserFilterObjectclass;
893 893
 				//glue objectclasses
894
-				if(is_array($objcs) && count($objcs) > 0) {
894
+				if (is_array($objcs) && count($objcs) > 0) {
895 895
 					$filter .= '(|';
896
-					foreach($objcs as $objc) {
897
-						$filter .= '(objectclass=' . $objc . ')';
896
+					foreach ($objcs as $objc) {
897
+						$filter .= '(objectclass='.$objc.')';
898 898
 					}
899 899
 					$filter .= ')';
900 900
 					$parts++;
901 901
 				}
902 902
 				//glue group memberships
903
-				if($this->configuration->hasMemberOfFilterSupport) {
903
+				if ($this->configuration->hasMemberOfFilterSupport) {
904 904
 					$cns = $this->configuration->ldapUserFilterGroups;
905
-					if(is_array($cns) && count($cns) > 0) {
905
+					if (is_array($cns) && count($cns) > 0) {
906 906
 						$filter .= '(|';
907 907
 						$cr = $this->getConnection();
908
-						if(!$cr) {
908
+						if (!$cr) {
909 909
 							throw new \Exception('Could not connect to LDAP');
910 910
 						}
911 911
 						$base = $this->configuration->ldapBase[0];
912
-						foreach($cns as $cn) {
913
-							$rr = $this->ldap->search($cr, $base, 'cn=' . $cn, array('dn', 'primaryGroupToken'));
914
-							if(!$this->ldap->isResource($rr)) {
912
+						foreach ($cns as $cn) {
913
+							$rr = $this->ldap->search($cr, $base, 'cn='.$cn, array('dn', 'primaryGroupToken'));
914
+							if (!$this->ldap->isResource($rr)) {
915 915
 								continue;
916 916
 							}
917 917
 							$er = $this->ldap->firstEntry($cr, $rr);
@@ -920,11 +920,11 @@  discard block
 block discarded – undo
920 920
 							if ($dn === false || $dn === '') {
921 921
 								continue;
922 922
 							}
923
-							$filterPart = '(memberof=' . $dn . ')';
924
-							if(isset($attrs['primaryGroupToken'])) {
923
+							$filterPart = '(memberof='.$dn.')';
924
+							if (isset($attrs['primaryGroupToken'])) {
925 925
 								$pgt = $attrs['primaryGroupToken'][0];
926
-								$primaryFilterPart = '(primaryGroupID=' . $pgt .')';
927
-								$filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
926
+								$primaryFilterPart = '(primaryGroupID='.$pgt.')';
927
+								$filterPart = '(|'.$filterPart.$primaryFilterPart.')';
928 928
 							}
929 929
 							$filter .= $filterPart;
930 930
 						}
@@ -933,8 +933,8 @@  discard block
 block discarded – undo
933 933
 					$parts++;
934 934
 				}
935 935
 				//wrap parts in AND condition
936
-				if($parts > 1) {
937
-					$filter = '(&' . $filter . ')';
936
+				if ($parts > 1) {
937
+					$filter = '(&'.$filter.')';
938 938
 				}
939 939
 				if ($filter === '') {
940 940
 					$filter = '(objectclass=*)';
@@ -944,27 +944,27 @@  discard block
 block discarded – undo
944 944
 			case self::LFILTER_GROUP_LIST:
945 945
 				$objcs = $this->configuration->ldapGroupFilterObjectclass;
946 946
 				//glue objectclasses
947
-				if(is_array($objcs) && count($objcs) > 0) {
947
+				if (is_array($objcs) && count($objcs) > 0) {
948 948
 					$filter .= '(|';
949
-					foreach($objcs as $objc) {
950
-						$filter .= '(objectclass=' . $objc . ')';
949
+					foreach ($objcs as $objc) {
950
+						$filter .= '(objectclass='.$objc.')';
951 951
 					}
952 952
 					$filter .= ')';
953 953
 					$parts++;
954 954
 				}
955 955
 				//glue group memberships
956 956
 				$cns = $this->configuration->ldapGroupFilterGroups;
957
-				if(is_array($cns) && count($cns) > 0) {
957
+				if (is_array($cns) && count($cns) > 0) {
958 958
 					$filter .= '(|';
959
-					foreach($cns as $cn) {
960
-						$filter .= '(cn=' . $cn . ')';
959
+					foreach ($cns as $cn) {
960
+						$filter .= '(cn='.$cn.')';
961 961
 					}
962 962
 					$filter .= ')';
963 963
 				}
964 964
 				$parts++;
965 965
 				//wrap parts in AND condition
966
-				if($parts > 1) {
967
-					$filter = '(&' . $filter . ')';
966
+				if ($parts > 1) {
967
+					$filter = '(&'.$filter.')';
968 968
 				}
969 969
 				break;
970 970
 
@@ -976,47 +976,47 @@  discard block
 block discarded – undo
976 976
 				$userAttributes = array_change_key_case(array_flip($userAttributes));
977 977
 				$parts = 0;
978 978
 
979
-				if($this->configuration->ldapLoginFilterUsername === '1') {
979
+				if ($this->configuration->ldapLoginFilterUsername === '1') {
980 980
 					$attr = '';
981
-					if(isset($userAttributes['uid'])) {
981
+					if (isset($userAttributes['uid'])) {
982 982
 						$attr = 'uid';
983
-					} else if(isset($userAttributes['samaccountname'])) {
983
+					} else if (isset($userAttributes['samaccountname'])) {
984 984
 						$attr = 'samaccountname';
985
-					} else if(isset($userAttributes['cn'])) {
985
+					} else if (isset($userAttributes['cn'])) {
986 986
 						//fallback
987 987
 						$attr = 'cn';
988 988
 					}
989 989
 					if ($attr !== '') {
990
-						$filterUsername = '(' . $attr . $loginpart . ')';
990
+						$filterUsername = '('.$attr.$loginpart.')';
991 991
 						$parts++;
992 992
 					}
993 993
 				}
994 994
 
995 995
 				$filterEmail = '';
996
-				if($this->configuration->ldapLoginFilterEmail === '1') {
996
+				if ($this->configuration->ldapLoginFilterEmail === '1') {
997 997
 					$filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
998 998
 					$parts++;
999 999
 				}
1000 1000
 
1001 1001
 				$filterAttributes = '';
1002 1002
 				$attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
1003
-				if(is_array($attrsToFilter) && count($attrsToFilter) > 0) {
1003
+				if (is_array($attrsToFilter) && count($attrsToFilter) > 0) {
1004 1004
 					$filterAttributes = '(|';
1005
-					foreach($attrsToFilter as $attribute) {
1006
-						$filterAttributes .= '(' . $attribute . $loginpart . ')';
1005
+					foreach ($attrsToFilter as $attribute) {
1006
+						$filterAttributes .= '('.$attribute.$loginpart.')';
1007 1007
 					}
1008 1008
 					$filterAttributes .= ')';
1009 1009
 					$parts++;
1010 1010
 				}
1011 1011
 
1012 1012
 				$filterLogin = '';
1013
-				if($parts > 1) {
1013
+				if ($parts > 1) {
1014 1014
 					$filterLogin = '(|';
1015 1015
 				}
1016 1016
 				$filterLogin .= $filterUsername;
1017 1017
 				$filterLogin .= $filterEmail;
1018 1018
 				$filterLogin .= $filterAttributes;
1019
-				if($parts > 1) {
1019
+				if ($parts > 1) {
1020 1020
 					$filterLogin .= ')';
1021 1021
 				}
1022 1022
 
@@ -1041,12 +1041,12 @@  discard block
 block discarded – undo
1041 1041
 		//connect, does not really trigger any server communication
1042 1042
 		$host = $this->configuration->ldapHost;
1043 1043
 		$hostInfo = parse_url($host);
1044
-		if(!$hostInfo) {
1044
+		if (!$hostInfo) {
1045 1045
 			throw new \Exception(self::$l->t('Invalid Host'));
1046 1046
 		}
1047 1047
 		\OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', \OCP\Util::DEBUG);
1048 1048
 		$cr = $this->ldap->connect($host, $port);
1049
-		if(!is_resource($cr)) {
1049
+		if (!is_resource($cr)) {
1050 1050
 			throw new \Exception(self::$l->t('Invalid Host'));
1051 1051
 		}
1052 1052
 
@@ -1056,9 +1056,9 @@  discard block
 block discarded – undo
1056 1056
 		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1057 1057
 
1058 1058
 		try {
1059
-			if($tls) {
1059
+			if ($tls) {
1060 1060
 				$isTlsWorking = @$this->ldap->startTls($cr);
1061
-				if(!$isTlsWorking) {
1061
+				if (!$isTlsWorking) {
1062 1062
 					return false;
1063 1063
 				}
1064 1064
 			}
@@ -1072,17 +1072,17 @@  discard block
 block discarded – undo
1072 1072
 			$errNo = $this->ldap->errno($cr);
1073 1073
 			$error = ldap_error($cr);
1074 1074
 			$this->ldap->unbind($cr);
1075
-		} catch(ServerNotAvailableException $e) {
1075
+		} catch (ServerNotAvailableException $e) {
1076 1076
 			return false;
1077 1077
 		}
1078 1078
 
1079
-		if($login === true) {
1079
+		if ($login === true) {
1080 1080
 			$this->ldap->unbind($cr);
1081
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . (int)$tls, \OCP\Util::DEBUG);
1081
+			\OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '.$port.' TLS '.(int) $tls, \OCP\Util::DEBUG);
1082 1082
 			return true;
1083 1083
 		}
1084 1084
 
1085
-		if($errNo === -1) {
1085
+		if ($errNo === -1) {
1086 1086
 			//host, port or TLS wrong
1087 1087
 			return false;
1088 1088
 		}
@@ -1110,9 +1110,9 @@  discard block
 block discarded – undo
1110 1110
 	 */
1111 1111
 	private function checkRequirements($reqs) {
1112 1112
 		$this->checkAgentRequirements();
1113
-		foreach($reqs as $option) {
1113
+		foreach ($reqs as $option) {
1114 1114
 			$value = $this->configuration->$option;
1115
-			if(empty($value)) {
1115
+			if (empty($value)) {
1116 1116
 				return false;
1117 1117
 			}
1118 1118
 		}
@@ -1134,33 +1134,33 @@  discard block
 block discarded – undo
1134 1134
 		$dnRead = array();
1135 1135
 		$foundItems = array();
1136 1136
 		$maxEntries = 0;
1137
-		if(!is_array($this->configuration->ldapBase)
1137
+		if (!is_array($this->configuration->ldapBase)
1138 1138
 		   || !isset($this->configuration->ldapBase[0])) {
1139 1139
 			return false;
1140 1140
 		}
1141 1141
 		$base = $this->configuration->ldapBase[0];
1142 1142
 		$cr = $this->getConnection();
1143
-		if(!$this->ldap->isResource($cr)) {
1143
+		if (!$this->ldap->isResource($cr)) {
1144 1144
 			return false;
1145 1145
 		}
1146 1146
 		$lastFilter = null;
1147
-		if(isset($filters[count($filters)-1])) {
1148
-			$lastFilter = $filters[count($filters)-1];
1147
+		if (isset($filters[count($filters) - 1])) {
1148
+			$lastFilter = $filters[count($filters) - 1];
1149 1149
 		}
1150
-		foreach($filters as $filter) {
1151
-			if($lastFilter === $filter && count($foundItems) > 0) {
1150
+		foreach ($filters as $filter) {
1151
+			if ($lastFilter === $filter && count($foundItems) > 0) {
1152 1152
 				//skip when the filter is a wildcard and results were found
1153 1153
 				continue;
1154 1154
 			}
1155 1155
 			// 20k limit for performance and reason
1156 1156
 			$rr = $this->ldap->search($cr, $base, $filter, array($attr), 0, 20000);
1157
-			if(!$this->ldap->isResource($rr)) {
1157
+			if (!$this->ldap->isResource($rr)) {
1158 1158
 				continue;
1159 1159
 			}
1160 1160
 			$entries = $this->ldap->countEntries($cr, $rr);
1161 1161
 			$getEntryFunc = 'firstEntry';
1162
-			if(($entries !== false) && ($entries > 0)) {
1163
-				if(!is_null($maxF) && $entries > $maxEntries) {
1162
+			if (($entries !== false) && ($entries > 0)) {
1163
+				if (!is_null($maxF) && $entries > $maxEntries) {
1164 1164
 					$maxEntries = $entries;
1165 1165
 					$maxF = $filter;
1166 1166
 				}
@@ -1168,13 +1168,13 @@  discard block
 block discarded – undo
1168 1168
 				do {
1169 1169
 					$entry = $this->ldap->$getEntryFunc($cr, $rr);
1170 1170
 					$getEntryFunc = 'nextEntry';
1171
-					if(!$this->ldap->isResource($entry)) {
1171
+					if (!$this->ldap->isResource($entry)) {
1172 1172
 						continue 2;
1173 1173
 					}
1174 1174
 					$rr = $entry; //will be expected by nextEntry next round
1175 1175
 					$attributes = $this->ldap->getAttributes($cr, $entry);
1176 1176
 					$dn = $this->ldap->getDN($cr, $entry);
1177
-					if($dn === false || in_array($dn, $dnRead)) {
1177
+					if ($dn === false || in_array($dn, $dnRead)) {
1178 1178
 						continue;
1179 1179
 					}
1180 1180
 					$newItems = array();
@@ -1185,7 +1185,7 @@  discard block
 block discarded – undo
1185 1185
 					$foundItems = array_merge($foundItems, $newItems);
1186 1186
 					$this->resultCache[$dn][$attr] = $newItems;
1187 1187
 					$dnRead[] = $dn;
1188
-				} while(($state === self::LRESULT_PROCESSED_SKIP
1188
+				} while (($state === self::LRESULT_PROCESSED_SKIP
1189 1189
 						|| $this->ldap->isResource($entry))
1190 1190
 						&& ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit));
1191 1191
 			}
@@ -1208,11 +1208,11 @@  discard block
 block discarded – undo
1208 1208
 	 */
1209 1209
 	private function determineFeature($objectclasses, $attr, $dbkey, $confkey, $po = false) {
1210 1210
 		$cr = $this->getConnection();
1211
-		if(!$cr) {
1211
+		if (!$cr) {
1212 1212
 			throw new \Exception('Could not connect to LDAP');
1213 1213
 		}
1214 1214
 		$p = 'objectclass=';
1215
-		foreach($objectclasses as $key => $value) {
1215
+		foreach ($objectclasses as $key => $value) {
1216 1216
 			$objectclasses[$key] = $p.$value;
1217 1217
 		}
1218 1218
 		$maxEntryObjC = '';
@@ -1224,7 +1224,7 @@  discard block
 block discarded – undo
1224 1224
 		$availableFeatures =
1225 1225
 			$this->cumulativeSearchOnAttribute($objectclasses, $attr,
1226 1226
 											   $dig, $maxEntryObjC);
1227
-		if(is_array($availableFeatures)
1227
+		if (is_array($availableFeatures)
1228 1228
 		   && count($availableFeatures) > 0) {
1229 1229
 			natcasesort($availableFeatures);
1230 1230
 			//natcasesort keeps indices, but we must get rid of them for proper
@@ -1235,7 +1235,7 @@  discard block
 block discarded – undo
1235 1235
 		}
1236 1236
 
1237 1237
 		$setFeatures = $this->configuration->$confkey;
1238
-		if(is_array($setFeatures) && !empty($setFeatures)) {
1238
+		if (is_array($setFeatures) && !empty($setFeatures)) {
1239 1239
 			//something is already configured? pre-select it.
1240 1240
 			$this->result->addChange($dbkey, $setFeatures);
1241 1241
 		} else if ($po && $maxEntryObjC !== '') {
@@ -1257,7 +1257,7 @@  discard block
 block discarded – undo
1257 1257
 	 * LRESULT_PROCESSED_INVALID or LRESULT_PROCESSED_SKIP
1258 1258
 	 */
1259 1259
 	private function getAttributeValuesFromEntry($result, $attribute, &$known) {
1260
-		if(!is_array($result)
1260
+		if (!is_array($result)
1261 1261
 		   || !isset($result['count'])
1262 1262
 		   || !$result['count'] > 0) {
1263 1263
 			return self::LRESULT_PROCESSED_INVALID;
@@ -1266,12 +1266,12 @@  discard block
 block discarded – undo
1266 1266
 		// strtolower on all keys for proper comparison
1267 1267
 		$result = \OCP\Util::mb_array_change_key_case($result);
1268 1268
 		$attribute = strtolower($attribute);
1269
-		if(isset($result[$attribute])) {
1270
-			foreach($result[$attribute] as $key => $val) {
1271
-				if($key === 'count') {
1269
+		if (isset($result[$attribute])) {
1270
+			foreach ($result[$attribute] as $key => $val) {
1271
+				if ($key === 'count') {
1272 1272
 					continue;
1273 1273
 				}
1274
-				if(!in_array($val, $known)) {
1274
+				if (!in_array($val, $known)) {
1275 1275
 					$known[] = $val;
1276 1276
 				}
1277 1277
 			}
@@ -1285,7 +1285,7 @@  discard block
 block discarded – undo
1285 1285
 	 * @return bool|mixed
1286 1286
 	 */
1287 1287
 	private function getConnection() {
1288
-		if(!is_null($this->cr)) {
1288
+		if (!is_null($this->cr)) {
1289 1289
 			return $this->cr;
1290 1290
 		}
1291 1291
 
@@ -1297,14 +1297,14 @@  discard block
 block discarded – undo
1297 1297
 		$this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1298 1298
 		$this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1299 1299
 		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1300
-		if($this->configuration->ldapTLS === 1) {
1300
+		if ($this->configuration->ldapTLS === 1) {
1301 1301
 			$this->ldap->startTls($cr);
1302 1302
 		}
1303 1303
 
1304 1304
 		$lo = @$this->ldap->bind($cr,
1305 1305
 								 $this->configuration->ldapAgentName,
1306 1306
 								 $this->configuration->ldapAgentPassword);
1307
-		if($lo === true) {
1307
+		if ($lo === true) {
1308 1308
 			$this->$cr = $cr;
1309 1309
 			return $cr;
1310 1310
 		}
@@ -1335,18 +1335,18 @@  discard block
 block discarded – undo
1335 1335
 		//636 ← LDAPS / SSL
1336 1336
 		//7xxx ← UCS. need to be checked first, because both ports may be open
1337 1337
 		$host = $this->configuration->ldapHost;
1338
-		$port = (int)$this->configuration->ldapPort;
1338
+		$port = (int) $this->configuration->ldapPort;
1339 1339
 		$portSettings = array();
1340 1340
 
1341 1341
 		//In case the port is already provided, we will check this first
1342
-		if($port > 0) {
1342
+		if ($port > 0) {
1343 1343
 			$hostInfo = parse_url($host);
1344
-			if(!(is_array($hostInfo)
1344
+			if (!(is_array($hostInfo)
1345 1345
 				&& isset($hostInfo['scheme'])
1346 1346
 				&& stripos($hostInfo['scheme'], 'ldaps') !== false)) {
1347 1347
 				$portSettings[] = array('port' => $port, 'tls' => true);
1348 1348
 			}
1349
-			$portSettings[] =array('port' => $port, 'tls' => false);
1349
+			$portSettings[] = array('port' => $port, 'tls' => false);
1350 1350
 		}
1351 1351
 
1352 1352
 		//default ports
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.
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.
Indentation   +1813 added lines, -1813 removed lines patch added patch discarded remove patch
@@ -150,1822 +150,1822 @@
 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(
851
-					$c->getDatabaseConnection(),
852
-					$c->getLogger(),
853
-					new TimeFactory(),
854
-					$ttl,
855
-					!\OC::$CLI
856
-				);
857
-			}
858
-			return new NoopLockingProvider();
859
-		});
860
-		$this->registerAlias('LockingProvider', ILockingProvider::class);
861
-
862
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
863
-			return new \OC\Files\Mount\Manager();
864
-		});
865
-		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
866
-
867
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
868
-			return new \OC\Files\Type\Detection(
869
-				$c->getURLGenerator(),
870
-				\OC::$configDir,
871
-				\OC::$SERVERROOT . '/resources/config/'
872
-			);
873
-		});
874
-		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
875
-
876
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
877
-			return new \OC\Files\Type\Loader(
878
-				$c->getDatabaseConnection()
879
-			);
880
-		});
881
-		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
882
-		$this->registerService(BundleFetcher::class, function () {
883
-			return new BundleFetcher($this->getL10N('lib'));
884
-		});
885
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
886
-			return new Manager(
887
-				$c->query(IValidator::class)
888
-			);
889
-		});
890
-		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
891
-
892
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
893
-			$manager = new \OC\CapabilitiesManager($c->getLogger());
894
-			$manager->registerCapability(function () use ($c) {
895
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
896
-			});
897
-			$manager->registerCapability(function () use ($c) {
898
-				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
899
-			});
900
-			return $manager;
901
-		});
902
-		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
903
-
904
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
905
-			$config = $c->getConfig();
906
-			$factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
907
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
908
-			$factory = new $factoryClass($this);
909
-			$manager = $factory->getManager();
910
-
911
-			$manager->registerDisplayNameResolver('user', function($id) use ($c) {
912
-				$manager = $c->getUserManager();
913
-				$user = $manager->get($id);
914
-				if(is_null($user)) {
915
-					$l = $c->getL10N('core');
916
-					$displayName = $l->t('Unknown user');
917
-				} else {
918
-					$displayName = $user->getDisplayName();
919
-				}
920
-				return $displayName;
921
-			});
922
-
923
-			return $manager;
924
-		});
925
-		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
926
-
927
-		$this->registerService('ThemingDefaults', function (Server $c) {
928
-			/*
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(
851
+                    $c->getDatabaseConnection(),
852
+                    $c->getLogger(),
853
+                    new TimeFactory(),
854
+                    $ttl,
855
+                    !\OC::$CLI
856
+                );
857
+            }
858
+            return new NoopLockingProvider();
859
+        });
860
+        $this->registerAlias('LockingProvider', ILockingProvider::class);
861
+
862
+        $this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
863
+            return new \OC\Files\Mount\Manager();
864
+        });
865
+        $this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
866
+
867
+        $this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
868
+            return new \OC\Files\Type\Detection(
869
+                $c->getURLGenerator(),
870
+                \OC::$configDir,
871
+                \OC::$SERVERROOT . '/resources/config/'
872
+            );
873
+        });
874
+        $this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
875
+
876
+        $this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
877
+            return new \OC\Files\Type\Loader(
878
+                $c->getDatabaseConnection()
879
+            );
880
+        });
881
+        $this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
882
+        $this->registerService(BundleFetcher::class, function () {
883
+            return new BundleFetcher($this->getL10N('lib'));
884
+        });
885
+        $this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
886
+            return new Manager(
887
+                $c->query(IValidator::class)
888
+            );
889
+        });
890
+        $this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
891
+
892
+        $this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
893
+            $manager = new \OC\CapabilitiesManager($c->getLogger());
894
+            $manager->registerCapability(function () use ($c) {
895
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
896
+            });
897
+            $manager->registerCapability(function () use ($c) {
898
+                return $c->query(\OC\Security\Bruteforce\Capabilities::class);
899
+            });
900
+            return $manager;
901
+        });
902
+        $this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
903
+
904
+        $this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
905
+            $config = $c->getConfig();
906
+            $factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
907
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
908
+            $factory = new $factoryClass($this);
909
+            $manager = $factory->getManager();
910
+
911
+            $manager->registerDisplayNameResolver('user', function($id) use ($c) {
912
+                $manager = $c->getUserManager();
913
+                $user = $manager->get($id);
914
+                if(is_null($user)) {
915
+                    $l = $c->getL10N('core');
916
+                    $displayName = $l->t('Unknown user');
917
+                } else {
918
+                    $displayName = $user->getDisplayName();
919
+                }
920
+                return $displayName;
921
+            });
922
+
923
+            return $manager;
924
+        });
925
+        $this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
926
+
927
+        $this->registerService('ThemingDefaults', function (Server $c) {
928
+            /*
929 929
 			 * Dark magic for autoloader.
930 930
 			 * If we do a class_exists it will try to load the class which will
931 931
 			 * make composer cache the result. Resulting in errors when enabling
932 932
 			 * the theming app.
933 933
 			 */
934
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
935
-			if (isset($prefixes['OCA\\Theming\\'])) {
936
-				$classExists = true;
937
-			} else {
938
-				$classExists = false;
939
-			}
940
-
941
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
942
-				return new ThemingDefaults(
943
-					$c->getConfig(),
944
-					$c->getL10N('theming'),
945
-					$c->getURLGenerator(),
946
-					$c->getAppDataDir('theming'),
947
-					$c->getMemCacheFactory(),
948
-					new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming')),
949
-					$this->getAppManager()
950
-				);
951
-			}
952
-			return new \OC_Defaults();
953
-		});
954
-		$this->registerService(SCSSCacher::class, function (Server $c) {
955
-			/** @var Factory $cacheFactory */
956
-			$cacheFactory = $c->query(Factory::class);
957
-			return new SCSSCacher(
958
-				$c->getLogger(),
959
-				$c->query(\OC\Files\AppData\Factory::class),
960
-				$c->getURLGenerator(),
961
-				$c->getConfig(),
962
-				$c->getThemingDefaults(),
963
-				\OC::$SERVERROOT,
964
-				$this->getMemCacheFactory()
965
-			);
966
-		});
967
-		$this->registerService(JSCombiner::class, function (Server $c) {
968
-			/** @var Factory $cacheFactory */
969
-			$cacheFactory = $c->query(Factory::class);
970
-			return new JSCombiner(
971
-				$c->getAppDataDir('js'),
972
-				$c->getURLGenerator(),
973
-				$this->getMemCacheFactory(),
974
-				$c->getSystemConfig(),
975
-				$c->getLogger()
976
-			);
977
-		});
978
-		$this->registerService(EventDispatcher::class, function () {
979
-			return new EventDispatcher();
980
-		});
981
-		$this->registerAlias('EventDispatcher', EventDispatcher::class);
982
-		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
983
-
984
-		$this->registerService('CryptoWrapper', function (Server $c) {
985
-			// FIXME: Instantiiated here due to cyclic dependency
986
-			$request = new Request(
987
-				[
988
-					'get' => $_GET,
989
-					'post' => $_POST,
990
-					'files' => $_FILES,
991
-					'server' => $_SERVER,
992
-					'env' => $_ENV,
993
-					'cookies' => $_COOKIE,
994
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
995
-						? $_SERVER['REQUEST_METHOD']
996
-						: null,
997
-				],
998
-				$c->getSecureRandom(),
999
-				$c->getConfig()
1000
-			);
1001
-
1002
-			return new CryptoWrapper(
1003
-				$c->getConfig(),
1004
-				$c->getCrypto(),
1005
-				$c->getSecureRandom(),
1006
-				$request
1007
-			);
1008
-		});
1009
-		$this->registerService('CsrfTokenManager', function (Server $c) {
1010
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1011
-
1012
-			return new CsrfTokenManager(
1013
-				$tokenGenerator,
1014
-				$c->query(SessionStorage::class)
1015
-			);
1016
-		});
1017
-		$this->registerService(SessionStorage::class, function (Server $c) {
1018
-			return new SessionStorage($c->getSession());
1019
-		});
1020
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1021
-			return new ContentSecurityPolicyManager();
1022
-		});
1023
-		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1024
-
1025
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1026
-			return new ContentSecurityPolicyNonceManager(
1027
-				$c->getCsrfTokenManager(),
1028
-				$c->getRequest()
1029
-			);
1030
-		});
1031
-
1032
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1033
-			$config = $c->getConfig();
1034
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1035
-			/** @var \OCP\Share\IProviderFactory $factory */
1036
-			$factory = new $factoryClass($this);
1037
-
1038
-			$manager = new \OC\Share20\Manager(
1039
-				$c->getLogger(),
1040
-				$c->getConfig(),
1041
-				$c->getSecureRandom(),
1042
-				$c->getHasher(),
1043
-				$c->getMountManager(),
1044
-				$c->getGroupManager(),
1045
-				$c->getL10N('lib'),
1046
-				$c->getL10NFactory(),
1047
-				$factory,
1048
-				$c->getUserManager(),
1049
-				$c->getLazyRootFolder(),
1050
-				$c->getEventDispatcher(),
1051
-				$c->getMailer(),
1052
-				$c->getURLGenerator(),
1053
-				$c->getThemingDefaults()
1054
-			);
1055
-
1056
-			return $manager;
1057
-		});
1058
-		$this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1059
-
1060
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1061
-			$instance = new Collaboration\Collaborators\Search($c);
1062
-
1063
-			// register default plugins
1064
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1065
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1066
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1067
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1068
-
1069
-			return $instance;
1070
-		});
1071
-		$this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1072
-
1073
-		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1074
-
1075
-		$this->registerService('SettingsManager', function (Server $c) {
1076
-			$manager = new \OC\Settings\Manager(
1077
-				$c->getLogger(),
1078
-				$c->getDatabaseConnection(),
1079
-				$c->getL10N('lib'),
1080
-				$c->getConfig(),
1081
-				$c->getEncryptionManager(),
1082
-				$c->getUserManager(),
1083
-				$c->getLockingProvider(),
1084
-				$c->getRequest(),
1085
-				$c->getURLGenerator(),
1086
-				$c->query(AccountManager::class),
1087
-				$c->getGroupManager(),
1088
-				$c->getL10NFactory(),
1089
-				$c->getAppManager()
1090
-			);
1091
-			return $manager;
1092
-		});
1093
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1094
-			return new \OC\Files\AppData\Factory(
1095
-				$c->getRootFolder(),
1096
-				$c->getSystemConfig()
1097
-			);
1098
-		});
1099
-
1100
-		$this->registerService('LockdownManager', function (Server $c) {
1101
-			return new LockdownManager(function () use ($c) {
1102
-				return $c->getSession();
1103
-			});
1104
-		});
1105
-
1106
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1107
-			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1108
-		});
1109
-
1110
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1111
-			return new CloudIdManager();
1112
-		});
1113
-
1114
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1115
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1116
-
1117
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1118
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1119
-
1120
-		$this->registerService(Defaults::class, function (Server $c) {
1121
-			return new Defaults(
1122
-				$c->getThemingDefaults()
1123
-			);
1124
-		});
1125
-		$this->registerAlias('Defaults', \OCP\Defaults::class);
1126
-
1127
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1128
-			return $c->query(\OCP\IUserSession::class)->getSession();
1129
-		});
1130
-
1131
-		$this->registerService(IShareHelper::class, function (Server $c) {
1132
-			return new ShareHelper(
1133
-				$c->query(\OCP\Share\IManager::class)
1134
-			);
1135
-		});
1136
-
1137
-		$this->registerService(Installer::class, function(Server $c) {
1138
-			return new Installer(
1139
-				$c->getAppFetcher(),
1140
-				$c->getHTTPClientService(),
1141
-				$c->getTempManager(),
1142
-				$c->getLogger(),
1143
-				$c->getConfig()
1144
-			);
1145
-		});
1146
-
1147
-		$this->registerService(IApiFactory::class, function(Server $c) {
1148
-			return new ApiFactory($c->getHTTPClientService());
1149
-		});
1150
-
1151
-		$this->registerService(IInstanceFactory::class, function(Server $c) {
1152
-			$memcacheFactory = $c->getMemCacheFactory();
1153
-			return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1154
-		});
1155
-
1156
-		$this->registerService(IContactsStore::class, function(Server $c) {
1157
-			return new ContactsStore(
1158
-				$c->getContactsManager(),
1159
-				$c->getConfig(),
1160
-				$c->getUserManager(),
1161
-				$c->getGroupManager()
1162
-			);
1163
-		});
1164
-		$this->registerAlias(IContactsStore::class, ContactsStore::class);
1165
-
1166
-		$this->connectDispatcher();
1167
-	}
1168
-
1169
-	/**
1170
-	 * @return \OCP\Calendar\IManager
1171
-	 */
1172
-	public function getCalendarManager() {
1173
-		return $this->query('CalendarManager');
1174
-	}
1175
-
1176
-	private function connectDispatcher() {
1177
-		$dispatcher = $this->getEventDispatcher();
1178
-
1179
-		// Delete avatar on user deletion
1180
-		$dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1181
-			$logger = $this->getLogger();
1182
-			$manager = $this->getAvatarManager();
1183
-			/** @var IUser $user */
1184
-			$user = $e->getSubject();
1185
-
1186
-			try {
1187
-				$avatar = $manager->getAvatar($user->getUID());
1188
-				$avatar->remove();
1189
-			} catch (NotFoundException $e) {
1190
-				// no avatar to remove
1191
-			} catch (\Exception $e) {
1192
-				// Ignore exceptions
1193
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1194
-			}
1195
-		});
1196
-
1197
-		$dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1198
-			$manager = $this->getAvatarManager();
1199
-			/** @var IUser $user */
1200
-			$user = $e->getSubject();
1201
-			$feature = $e->getArgument('feature');
1202
-			$oldValue = $e->getArgument('oldValue');
1203
-			$value = $e->getArgument('value');
1204
-
1205
-			try {
1206
-				$avatar = $manager->getAvatar($user->getUID());
1207
-				$avatar->userChanged($feature, $oldValue, $value);
1208
-			} catch (NotFoundException $e) {
1209
-				// no avatar to remove
1210
-			}
1211
-		});
1212
-	}
1213
-
1214
-	/**
1215
-	 * @return \OCP\Contacts\IManager
1216
-	 */
1217
-	public function getContactsManager() {
1218
-		return $this->query('ContactsManager');
1219
-	}
1220
-
1221
-	/**
1222
-	 * @return \OC\Encryption\Manager
1223
-	 */
1224
-	public function getEncryptionManager() {
1225
-		return $this->query('EncryptionManager');
1226
-	}
1227
-
1228
-	/**
1229
-	 * @return \OC\Encryption\File
1230
-	 */
1231
-	public function getEncryptionFilesHelper() {
1232
-		return $this->query('EncryptionFileHelper');
1233
-	}
1234
-
1235
-	/**
1236
-	 * @return \OCP\Encryption\Keys\IStorage
1237
-	 */
1238
-	public function getEncryptionKeyStorage() {
1239
-		return $this->query('EncryptionKeyStorage');
1240
-	}
1241
-
1242
-	/**
1243
-	 * The current request object holding all information about the request
1244
-	 * currently being processed is returned from this method.
1245
-	 * In case the current execution was not initiated by a web request null is returned
1246
-	 *
1247
-	 * @return \OCP\IRequest
1248
-	 */
1249
-	public function getRequest() {
1250
-		return $this->query('Request');
1251
-	}
1252
-
1253
-	/**
1254
-	 * Returns the preview manager which can create preview images for a given file
1255
-	 *
1256
-	 * @return \OCP\IPreview
1257
-	 */
1258
-	public function getPreviewManager() {
1259
-		return $this->query('PreviewManager');
1260
-	}
1261
-
1262
-	/**
1263
-	 * Returns the tag manager which can get and set tags for different object types
1264
-	 *
1265
-	 * @see \OCP\ITagManager::load()
1266
-	 * @return \OCP\ITagManager
1267
-	 */
1268
-	public function getTagManager() {
1269
-		return $this->query('TagManager');
1270
-	}
1271
-
1272
-	/**
1273
-	 * Returns the system-tag manager
1274
-	 *
1275
-	 * @return \OCP\SystemTag\ISystemTagManager
1276
-	 *
1277
-	 * @since 9.0.0
1278
-	 */
1279
-	public function getSystemTagManager() {
1280
-		return $this->query('SystemTagManager');
1281
-	}
1282
-
1283
-	/**
1284
-	 * Returns the system-tag object mapper
1285
-	 *
1286
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
1287
-	 *
1288
-	 * @since 9.0.0
1289
-	 */
1290
-	public function getSystemTagObjectMapper() {
1291
-		return $this->query('SystemTagObjectMapper');
1292
-	}
1293
-
1294
-	/**
1295
-	 * Returns the avatar manager, used for avatar functionality
1296
-	 *
1297
-	 * @return \OCP\IAvatarManager
1298
-	 */
1299
-	public function getAvatarManager() {
1300
-		return $this->query('AvatarManager');
1301
-	}
1302
-
1303
-	/**
1304
-	 * Returns the root folder of ownCloud's data directory
1305
-	 *
1306
-	 * @return \OCP\Files\IRootFolder
1307
-	 */
1308
-	public function getRootFolder() {
1309
-		return $this->query('LazyRootFolder');
1310
-	}
1311
-
1312
-	/**
1313
-	 * Returns the root folder of ownCloud's data directory
1314
-	 * This is the lazy variant so this gets only initialized once it
1315
-	 * is actually used.
1316
-	 *
1317
-	 * @return \OCP\Files\IRootFolder
1318
-	 */
1319
-	public function getLazyRootFolder() {
1320
-		return $this->query('LazyRootFolder');
1321
-	}
1322
-
1323
-	/**
1324
-	 * Returns a view to ownCloud's files folder
1325
-	 *
1326
-	 * @param string $userId user ID
1327
-	 * @return \OCP\Files\Folder|null
1328
-	 */
1329
-	public function getUserFolder($userId = null) {
1330
-		if ($userId === null) {
1331
-			$user = $this->getUserSession()->getUser();
1332
-			if (!$user) {
1333
-				return null;
1334
-			}
1335
-			$userId = $user->getUID();
1336
-		}
1337
-		$root = $this->getRootFolder();
1338
-		return $root->getUserFolder($userId);
1339
-	}
1340
-
1341
-	/**
1342
-	 * Returns an app-specific view in ownClouds data directory
1343
-	 *
1344
-	 * @return \OCP\Files\Folder
1345
-	 * @deprecated since 9.2.0 use IAppData
1346
-	 */
1347
-	public function getAppFolder() {
1348
-		$dir = '/' . \OC_App::getCurrentApp();
1349
-		$root = $this->getRootFolder();
1350
-		if (!$root->nodeExists($dir)) {
1351
-			$folder = $root->newFolder($dir);
1352
-		} else {
1353
-			$folder = $root->get($dir);
1354
-		}
1355
-		return $folder;
1356
-	}
1357
-
1358
-	/**
1359
-	 * @return \OC\User\Manager
1360
-	 */
1361
-	public function getUserManager() {
1362
-		return $this->query('UserManager');
1363
-	}
1364
-
1365
-	/**
1366
-	 * @return \OC\Group\Manager
1367
-	 */
1368
-	public function getGroupManager() {
1369
-		return $this->query('GroupManager');
1370
-	}
1371
-
1372
-	/**
1373
-	 * @return \OC\User\Session
1374
-	 */
1375
-	public function getUserSession() {
1376
-		return $this->query('UserSession');
1377
-	}
1378
-
1379
-	/**
1380
-	 * @return \OCP\ISession
1381
-	 */
1382
-	public function getSession() {
1383
-		return $this->query('UserSession')->getSession();
1384
-	}
1385
-
1386
-	/**
1387
-	 * @param \OCP\ISession $session
1388
-	 */
1389
-	public function setSession(\OCP\ISession $session) {
1390
-		$this->query(SessionStorage::class)->setSession($session);
1391
-		$this->query('UserSession')->setSession($session);
1392
-		$this->query(Store::class)->setSession($session);
1393
-	}
1394
-
1395
-	/**
1396
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1397
-	 */
1398
-	public function getTwoFactorAuthManager() {
1399
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1400
-	}
1401
-
1402
-	/**
1403
-	 * @return \OC\NavigationManager
1404
-	 */
1405
-	public function getNavigationManager() {
1406
-		return $this->query('NavigationManager');
1407
-	}
1408
-
1409
-	/**
1410
-	 * @return \OCP\IConfig
1411
-	 */
1412
-	public function getConfig() {
1413
-		return $this->query('AllConfig');
1414
-	}
1415
-
1416
-	/**
1417
-	 * @return \OC\SystemConfig
1418
-	 */
1419
-	public function getSystemConfig() {
1420
-		return $this->query('SystemConfig');
1421
-	}
1422
-
1423
-	/**
1424
-	 * Returns the app config manager
1425
-	 *
1426
-	 * @return \OCP\IAppConfig
1427
-	 */
1428
-	public function getAppConfig() {
1429
-		return $this->query('AppConfig');
1430
-	}
1431
-
1432
-	/**
1433
-	 * @return \OCP\L10N\IFactory
1434
-	 */
1435
-	public function getL10NFactory() {
1436
-		return $this->query('L10NFactory');
1437
-	}
1438
-
1439
-	/**
1440
-	 * get an L10N instance
1441
-	 *
1442
-	 * @param string $app appid
1443
-	 * @param string $lang
1444
-	 * @return IL10N
1445
-	 */
1446
-	public function getL10N($app, $lang = null) {
1447
-		return $this->getL10NFactory()->get($app, $lang);
1448
-	}
1449
-
1450
-	/**
1451
-	 * @return \OCP\IURLGenerator
1452
-	 */
1453
-	public function getURLGenerator() {
1454
-		return $this->query('URLGenerator');
1455
-	}
1456
-
1457
-	/**
1458
-	 * @return AppFetcher
1459
-	 */
1460
-	public function getAppFetcher() {
1461
-		return $this->query(AppFetcher::class);
1462
-	}
1463
-
1464
-	/**
1465
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1466
-	 * getMemCacheFactory() instead.
1467
-	 *
1468
-	 * @return \OCP\ICache
1469
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1470
-	 */
1471
-	public function getCache() {
1472
-		return $this->query('UserCache');
1473
-	}
1474
-
1475
-	/**
1476
-	 * Returns an \OCP\CacheFactory instance
1477
-	 *
1478
-	 * @return \OCP\ICacheFactory
1479
-	 */
1480
-	public function getMemCacheFactory() {
1481
-		return $this->query('MemCacheFactory');
1482
-	}
1483
-
1484
-	/**
1485
-	 * Returns an \OC\RedisFactory instance
1486
-	 *
1487
-	 * @return \OC\RedisFactory
1488
-	 */
1489
-	public function getGetRedisFactory() {
1490
-		return $this->query('RedisFactory');
1491
-	}
1492
-
1493
-
1494
-	/**
1495
-	 * Returns the current session
1496
-	 *
1497
-	 * @return \OCP\IDBConnection
1498
-	 */
1499
-	public function getDatabaseConnection() {
1500
-		return $this->query('DatabaseConnection');
1501
-	}
1502
-
1503
-	/**
1504
-	 * Returns the activity manager
1505
-	 *
1506
-	 * @return \OCP\Activity\IManager
1507
-	 */
1508
-	public function getActivityManager() {
1509
-		return $this->query('ActivityManager');
1510
-	}
1511
-
1512
-	/**
1513
-	 * Returns an job list for controlling background jobs
1514
-	 *
1515
-	 * @return \OCP\BackgroundJob\IJobList
1516
-	 */
1517
-	public function getJobList() {
1518
-		return $this->query('JobList');
1519
-	}
1520
-
1521
-	/**
1522
-	 * Returns a logger instance
1523
-	 *
1524
-	 * @return \OCP\ILogger
1525
-	 */
1526
-	public function getLogger() {
1527
-		return $this->query('Logger');
1528
-	}
1529
-
1530
-	/**
1531
-	 * Returns a router for generating and matching urls
1532
-	 *
1533
-	 * @return \OCP\Route\IRouter
1534
-	 */
1535
-	public function getRouter() {
1536
-		return $this->query('Router');
1537
-	}
1538
-
1539
-	/**
1540
-	 * Returns a search instance
1541
-	 *
1542
-	 * @return \OCP\ISearch
1543
-	 */
1544
-	public function getSearch() {
1545
-		return $this->query('Search');
1546
-	}
1547
-
1548
-	/**
1549
-	 * Returns a SecureRandom instance
1550
-	 *
1551
-	 * @return \OCP\Security\ISecureRandom
1552
-	 */
1553
-	public function getSecureRandom() {
1554
-		return $this->query('SecureRandom');
1555
-	}
1556
-
1557
-	/**
1558
-	 * Returns a Crypto instance
1559
-	 *
1560
-	 * @return \OCP\Security\ICrypto
1561
-	 */
1562
-	public function getCrypto() {
1563
-		return $this->query('Crypto');
1564
-	}
1565
-
1566
-	/**
1567
-	 * Returns a Hasher instance
1568
-	 *
1569
-	 * @return \OCP\Security\IHasher
1570
-	 */
1571
-	public function getHasher() {
1572
-		return $this->query('Hasher');
1573
-	}
1574
-
1575
-	/**
1576
-	 * Returns a CredentialsManager instance
1577
-	 *
1578
-	 * @return \OCP\Security\ICredentialsManager
1579
-	 */
1580
-	public function getCredentialsManager() {
1581
-		return $this->query('CredentialsManager');
1582
-	}
1583
-
1584
-	/**
1585
-	 * Get the certificate manager for the user
1586
-	 *
1587
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1588
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1589
-	 */
1590
-	public function getCertificateManager($userId = '') {
1591
-		if ($userId === '') {
1592
-			$userSession = $this->getUserSession();
1593
-			$user = $userSession->getUser();
1594
-			if (is_null($user)) {
1595
-				return null;
1596
-			}
1597
-			$userId = $user->getUID();
1598
-		}
1599
-		return new CertificateManager(
1600
-			$userId,
1601
-			new View(),
1602
-			$this->getConfig(),
1603
-			$this->getLogger(),
1604
-			$this->getSecureRandom()
1605
-		);
1606
-	}
1607
-
1608
-	/**
1609
-	 * Returns an instance of the HTTP client service
1610
-	 *
1611
-	 * @return \OCP\Http\Client\IClientService
1612
-	 */
1613
-	public function getHTTPClientService() {
1614
-		return $this->query('HttpClientService');
1615
-	}
1616
-
1617
-	/**
1618
-	 * Create a new event source
1619
-	 *
1620
-	 * @return \OCP\IEventSource
1621
-	 */
1622
-	public function createEventSource() {
1623
-		return new \OC_EventSource();
1624
-	}
1625
-
1626
-	/**
1627
-	 * Get the active event logger
1628
-	 *
1629
-	 * The returned logger only logs data when debug mode is enabled
1630
-	 *
1631
-	 * @return \OCP\Diagnostics\IEventLogger
1632
-	 */
1633
-	public function getEventLogger() {
1634
-		return $this->query('EventLogger');
1635
-	}
1636
-
1637
-	/**
1638
-	 * Get the active query logger
1639
-	 *
1640
-	 * The returned logger only logs data when debug mode is enabled
1641
-	 *
1642
-	 * @return \OCP\Diagnostics\IQueryLogger
1643
-	 */
1644
-	public function getQueryLogger() {
1645
-		return $this->query('QueryLogger');
1646
-	}
1647
-
1648
-	/**
1649
-	 * Get the manager for temporary files and folders
1650
-	 *
1651
-	 * @return \OCP\ITempManager
1652
-	 */
1653
-	public function getTempManager() {
1654
-		return $this->query('TempManager');
1655
-	}
1656
-
1657
-	/**
1658
-	 * Get the app manager
1659
-	 *
1660
-	 * @return \OCP\App\IAppManager
1661
-	 */
1662
-	public function getAppManager() {
1663
-		return $this->query('AppManager');
1664
-	}
1665
-
1666
-	/**
1667
-	 * Creates a new mailer
1668
-	 *
1669
-	 * @return \OCP\Mail\IMailer
1670
-	 */
1671
-	public function getMailer() {
1672
-		return $this->query('Mailer');
1673
-	}
1674
-
1675
-	/**
1676
-	 * Get the webroot
1677
-	 *
1678
-	 * @return string
1679
-	 */
1680
-	public function getWebRoot() {
1681
-		return $this->webRoot;
1682
-	}
1683
-
1684
-	/**
1685
-	 * @return \OC\OCSClient
1686
-	 */
1687
-	public function getOcsClient() {
1688
-		return $this->query('OcsClient');
1689
-	}
1690
-
1691
-	/**
1692
-	 * @return \OCP\IDateTimeZone
1693
-	 */
1694
-	public function getDateTimeZone() {
1695
-		return $this->query('DateTimeZone');
1696
-	}
1697
-
1698
-	/**
1699
-	 * @return \OCP\IDateTimeFormatter
1700
-	 */
1701
-	public function getDateTimeFormatter() {
1702
-		return $this->query('DateTimeFormatter');
1703
-	}
1704
-
1705
-	/**
1706
-	 * @return \OCP\Files\Config\IMountProviderCollection
1707
-	 */
1708
-	public function getMountProviderCollection() {
1709
-		return $this->query('MountConfigManager');
1710
-	}
1711
-
1712
-	/**
1713
-	 * Get the IniWrapper
1714
-	 *
1715
-	 * @return IniGetWrapper
1716
-	 */
1717
-	public function getIniWrapper() {
1718
-		return $this->query('IniWrapper');
1719
-	}
1720
-
1721
-	/**
1722
-	 * @return \OCP\Command\IBus
1723
-	 */
1724
-	public function getCommandBus() {
1725
-		return $this->query('AsyncCommandBus');
1726
-	}
1727
-
1728
-	/**
1729
-	 * Get the trusted domain helper
1730
-	 *
1731
-	 * @return TrustedDomainHelper
1732
-	 */
1733
-	public function getTrustedDomainHelper() {
1734
-		return $this->query('TrustedDomainHelper');
1735
-	}
1736
-
1737
-	/**
1738
-	 * Get the locking provider
1739
-	 *
1740
-	 * @return \OCP\Lock\ILockingProvider
1741
-	 * @since 8.1.0
1742
-	 */
1743
-	public function getLockingProvider() {
1744
-		return $this->query('LockingProvider');
1745
-	}
1746
-
1747
-	/**
1748
-	 * @return \OCP\Files\Mount\IMountManager
1749
-	 **/
1750
-	function getMountManager() {
1751
-		return $this->query('MountManager');
1752
-	}
1753
-
1754
-	/** @return \OCP\Files\Config\IUserMountCache */
1755
-	function getUserMountCache() {
1756
-		return $this->query('UserMountCache');
1757
-	}
1758
-
1759
-	/**
1760
-	 * Get the MimeTypeDetector
1761
-	 *
1762
-	 * @return \OCP\Files\IMimeTypeDetector
1763
-	 */
1764
-	public function getMimeTypeDetector() {
1765
-		return $this->query('MimeTypeDetector');
1766
-	}
1767
-
1768
-	/**
1769
-	 * Get the MimeTypeLoader
1770
-	 *
1771
-	 * @return \OCP\Files\IMimeTypeLoader
1772
-	 */
1773
-	public function getMimeTypeLoader() {
1774
-		return $this->query('MimeTypeLoader');
1775
-	}
1776
-
1777
-	/**
1778
-	 * Get the manager of all the capabilities
1779
-	 *
1780
-	 * @return \OC\CapabilitiesManager
1781
-	 */
1782
-	public function getCapabilitiesManager() {
1783
-		return $this->query('CapabilitiesManager');
1784
-	}
1785
-
1786
-	/**
1787
-	 * Get the EventDispatcher
1788
-	 *
1789
-	 * @return EventDispatcherInterface
1790
-	 * @since 8.2.0
1791
-	 */
1792
-	public function getEventDispatcher() {
1793
-		return $this->query('EventDispatcher');
1794
-	}
1795
-
1796
-	/**
1797
-	 * Get the Notification Manager
1798
-	 *
1799
-	 * @return \OCP\Notification\IManager
1800
-	 * @since 8.2.0
1801
-	 */
1802
-	public function getNotificationManager() {
1803
-		return $this->query('NotificationManager');
1804
-	}
1805
-
1806
-	/**
1807
-	 * @return \OCP\Comments\ICommentsManager
1808
-	 */
1809
-	public function getCommentsManager() {
1810
-		return $this->query('CommentsManager');
1811
-	}
1812
-
1813
-	/**
1814
-	 * @return \OCA\Theming\ThemingDefaults
1815
-	 */
1816
-	public function getThemingDefaults() {
1817
-		return $this->query('ThemingDefaults');
1818
-	}
1819
-
1820
-	/**
1821
-	 * @return \OC\IntegrityCheck\Checker
1822
-	 */
1823
-	public function getIntegrityCodeChecker() {
1824
-		return $this->query('IntegrityCodeChecker');
1825
-	}
1826
-
1827
-	/**
1828
-	 * @return \OC\Session\CryptoWrapper
1829
-	 */
1830
-	public function getSessionCryptoWrapper() {
1831
-		return $this->query('CryptoWrapper');
1832
-	}
1833
-
1834
-	/**
1835
-	 * @return CsrfTokenManager
1836
-	 */
1837
-	public function getCsrfTokenManager() {
1838
-		return $this->query('CsrfTokenManager');
1839
-	}
1840
-
1841
-	/**
1842
-	 * @return Throttler
1843
-	 */
1844
-	public function getBruteForceThrottler() {
1845
-		return $this->query('Throttler');
1846
-	}
1847
-
1848
-	/**
1849
-	 * @return IContentSecurityPolicyManager
1850
-	 */
1851
-	public function getContentSecurityPolicyManager() {
1852
-		return $this->query('ContentSecurityPolicyManager');
1853
-	}
1854
-
1855
-	/**
1856
-	 * @return ContentSecurityPolicyNonceManager
1857
-	 */
1858
-	public function getContentSecurityPolicyNonceManager() {
1859
-		return $this->query('ContentSecurityPolicyNonceManager');
1860
-	}
1861
-
1862
-	/**
1863
-	 * Not a public API as of 8.2, wait for 9.0
1864
-	 *
1865
-	 * @return \OCA\Files_External\Service\BackendService
1866
-	 */
1867
-	public function getStoragesBackendService() {
1868
-		return $this->query('OCA\\Files_External\\Service\\BackendService');
1869
-	}
1870
-
1871
-	/**
1872
-	 * Not a public API as of 8.2, wait for 9.0
1873
-	 *
1874
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1875
-	 */
1876
-	public function getGlobalStoragesService() {
1877
-		return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1878
-	}
1879
-
1880
-	/**
1881
-	 * Not a public API as of 8.2, wait for 9.0
1882
-	 *
1883
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1884
-	 */
1885
-	public function getUserGlobalStoragesService() {
1886
-		return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1887
-	}
1888
-
1889
-	/**
1890
-	 * Not a public API as of 8.2, wait for 9.0
1891
-	 *
1892
-	 * @return \OCA\Files_External\Service\UserStoragesService
1893
-	 */
1894
-	public function getUserStoragesService() {
1895
-		return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1896
-	}
1897
-
1898
-	/**
1899
-	 * @return \OCP\Share\IManager
1900
-	 */
1901
-	public function getShareManager() {
1902
-		return $this->query('ShareManager');
1903
-	}
1904
-
1905
-	/**
1906
-	 * @return \OCP\Collaboration\Collaborators\ISearch
1907
-	 */
1908
-	public function getCollaboratorSearch() {
1909
-		return $this->query('CollaboratorSearch');
1910
-	}
1911
-
1912
-	/**
1913
-	 * @return \OCP\Collaboration\AutoComplete\IManager
1914
-	 */
1915
-	public function getAutoCompleteManager(){
1916
-		return $this->query(IManager::class);
1917
-	}
1918
-
1919
-	/**
1920
-	 * Returns the LDAP Provider
1921
-	 *
1922
-	 * @return \OCP\LDAP\ILDAPProvider
1923
-	 */
1924
-	public function getLDAPProvider() {
1925
-		return $this->query('LDAPProvider');
1926
-	}
1927
-
1928
-	/**
1929
-	 * @return \OCP\Settings\IManager
1930
-	 */
1931
-	public function getSettingsManager() {
1932
-		return $this->query('SettingsManager');
1933
-	}
1934
-
1935
-	/**
1936
-	 * @return \OCP\Files\IAppData
1937
-	 */
1938
-	public function getAppDataDir($app) {
1939
-		/** @var \OC\Files\AppData\Factory $factory */
1940
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
1941
-		return $factory->get($app);
1942
-	}
1943
-
1944
-	/**
1945
-	 * @return \OCP\Lockdown\ILockdownManager
1946
-	 */
1947
-	public function getLockdownManager() {
1948
-		return $this->query('LockdownManager');
1949
-	}
1950
-
1951
-	/**
1952
-	 * @return \OCP\Federation\ICloudIdManager
1953
-	 */
1954
-	public function getCloudIdManager() {
1955
-		return $this->query(ICloudIdManager::class);
1956
-	}
1957
-
1958
-	/**
1959
-	 * @return \OCP\Remote\Api\IApiFactory
1960
-	 */
1961
-	public function getRemoteApiFactory() {
1962
-		return $this->query(IApiFactory::class);
1963
-	}
1964
-
1965
-	/**
1966
-	 * @return \OCP\Remote\IInstanceFactory
1967
-	 */
1968
-	public function getRemoteInstanceFactory() {
1969
-		return $this->query(IInstanceFactory::class);
1970
-	}
934
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
935
+            if (isset($prefixes['OCA\\Theming\\'])) {
936
+                $classExists = true;
937
+            } else {
938
+                $classExists = false;
939
+            }
940
+
941
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
942
+                return new ThemingDefaults(
943
+                    $c->getConfig(),
944
+                    $c->getL10N('theming'),
945
+                    $c->getURLGenerator(),
946
+                    $c->getAppDataDir('theming'),
947
+                    $c->getMemCacheFactory(),
948
+                    new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming')),
949
+                    $this->getAppManager()
950
+                );
951
+            }
952
+            return new \OC_Defaults();
953
+        });
954
+        $this->registerService(SCSSCacher::class, function (Server $c) {
955
+            /** @var Factory $cacheFactory */
956
+            $cacheFactory = $c->query(Factory::class);
957
+            return new SCSSCacher(
958
+                $c->getLogger(),
959
+                $c->query(\OC\Files\AppData\Factory::class),
960
+                $c->getURLGenerator(),
961
+                $c->getConfig(),
962
+                $c->getThemingDefaults(),
963
+                \OC::$SERVERROOT,
964
+                $this->getMemCacheFactory()
965
+            );
966
+        });
967
+        $this->registerService(JSCombiner::class, function (Server $c) {
968
+            /** @var Factory $cacheFactory */
969
+            $cacheFactory = $c->query(Factory::class);
970
+            return new JSCombiner(
971
+                $c->getAppDataDir('js'),
972
+                $c->getURLGenerator(),
973
+                $this->getMemCacheFactory(),
974
+                $c->getSystemConfig(),
975
+                $c->getLogger()
976
+            );
977
+        });
978
+        $this->registerService(EventDispatcher::class, function () {
979
+            return new EventDispatcher();
980
+        });
981
+        $this->registerAlias('EventDispatcher', EventDispatcher::class);
982
+        $this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
983
+
984
+        $this->registerService('CryptoWrapper', function (Server $c) {
985
+            // FIXME: Instantiiated here due to cyclic dependency
986
+            $request = new Request(
987
+                [
988
+                    'get' => $_GET,
989
+                    'post' => $_POST,
990
+                    'files' => $_FILES,
991
+                    'server' => $_SERVER,
992
+                    'env' => $_ENV,
993
+                    'cookies' => $_COOKIE,
994
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
995
+                        ? $_SERVER['REQUEST_METHOD']
996
+                        : null,
997
+                ],
998
+                $c->getSecureRandom(),
999
+                $c->getConfig()
1000
+            );
1001
+
1002
+            return new CryptoWrapper(
1003
+                $c->getConfig(),
1004
+                $c->getCrypto(),
1005
+                $c->getSecureRandom(),
1006
+                $request
1007
+            );
1008
+        });
1009
+        $this->registerService('CsrfTokenManager', function (Server $c) {
1010
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1011
+
1012
+            return new CsrfTokenManager(
1013
+                $tokenGenerator,
1014
+                $c->query(SessionStorage::class)
1015
+            );
1016
+        });
1017
+        $this->registerService(SessionStorage::class, function (Server $c) {
1018
+            return new SessionStorage($c->getSession());
1019
+        });
1020
+        $this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1021
+            return new ContentSecurityPolicyManager();
1022
+        });
1023
+        $this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1024
+
1025
+        $this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1026
+            return new ContentSecurityPolicyNonceManager(
1027
+                $c->getCsrfTokenManager(),
1028
+                $c->getRequest()
1029
+            );
1030
+        });
1031
+
1032
+        $this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1033
+            $config = $c->getConfig();
1034
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1035
+            /** @var \OCP\Share\IProviderFactory $factory */
1036
+            $factory = new $factoryClass($this);
1037
+
1038
+            $manager = new \OC\Share20\Manager(
1039
+                $c->getLogger(),
1040
+                $c->getConfig(),
1041
+                $c->getSecureRandom(),
1042
+                $c->getHasher(),
1043
+                $c->getMountManager(),
1044
+                $c->getGroupManager(),
1045
+                $c->getL10N('lib'),
1046
+                $c->getL10NFactory(),
1047
+                $factory,
1048
+                $c->getUserManager(),
1049
+                $c->getLazyRootFolder(),
1050
+                $c->getEventDispatcher(),
1051
+                $c->getMailer(),
1052
+                $c->getURLGenerator(),
1053
+                $c->getThemingDefaults()
1054
+            );
1055
+
1056
+            return $manager;
1057
+        });
1058
+        $this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1059
+
1060
+        $this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1061
+            $instance = new Collaboration\Collaborators\Search($c);
1062
+
1063
+            // register default plugins
1064
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1065
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1066
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1067
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1068
+
1069
+            return $instance;
1070
+        });
1071
+        $this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1072
+
1073
+        $this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1074
+
1075
+        $this->registerService('SettingsManager', function (Server $c) {
1076
+            $manager = new \OC\Settings\Manager(
1077
+                $c->getLogger(),
1078
+                $c->getDatabaseConnection(),
1079
+                $c->getL10N('lib'),
1080
+                $c->getConfig(),
1081
+                $c->getEncryptionManager(),
1082
+                $c->getUserManager(),
1083
+                $c->getLockingProvider(),
1084
+                $c->getRequest(),
1085
+                $c->getURLGenerator(),
1086
+                $c->query(AccountManager::class),
1087
+                $c->getGroupManager(),
1088
+                $c->getL10NFactory(),
1089
+                $c->getAppManager()
1090
+            );
1091
+            return $manager;
1092
+        });
1093
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1094
+            return new \OC\Files\AppData\Factory(
1095
+                $c->getRootFolder(),
1096
+                $c->getSystemConfig()
1097
+            );
1098
+        });
1099
+
1100
+        $this->registerService('LockdownManager', function (Server $c) {
1101
+            return new LockdownManager(function () use ($c) {
1102
+                return $c->getSession();
1103
+            });
1104
+        });
1105
+
1106
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1107
+            return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1108
+        });
1109
+
1110
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
1111
+            return new CloudIdManager();
1112
+        });
1113
+
1114
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1115
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1116
+
1117
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1118
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1119
+
1120
+        $this->registerService(Defaults::class, function (Server $c) {
1121
+            return new Defaults(
1122
+                $c->getThemingDefaults()
1123
+            );
1124
+        });
1125
+        $this->registerAlias('Defaults', \OCP\Defaults::class);
1126
+
1127
+        $this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1128
+            return $c->query(\OCP\IUserSession::class)->getSession();
1129
+        });
1130
+
1131
+        $this->registerService(IShareHelper::class, function (Server $c) {
1132
+            return new ShareHelper(
1133
+                $c->query(\OCP\Share\IManager::class)
1134
+            );
1135
+        });
1136
+
1137
+        $this->registerService(Installer::class, function(Server $c) {
1138
+            return new Installer(
1139
+                $c->getAppFetcher(),
1140
+                $c->getHTTPClientService(),
1141
+                $c->getTempManager(),
1142
+                $c->getLogger(),
1143
+                $c->getConfig()
1144
+            );
1145
+        });
1146
+
1147
+        $this->registerService(IApiFactory::class, function(Server $c) {
1148
+            return new ApiFactory($c->getHTTPClientService());
1149
+        });
1150
+
1151
+        $this->registerService(IInstanceFactory::class, function(Server $c) {
1152
+            $memcacheFactory = $c->getMemCacheFactory();
1153
+            return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1154
+        });
1155
+
1156
+        $this->registerService(IContactsStore::class, function(Server $c) {
1157
+            return new ContactsStore(
1158
+                $c->getContactsManager(),
1159
+                $c->getConfig(),
1160
+                $c->getUserManager(),
1161
+                $c->getGroupManager()
1162
+            );
1163
+        });
1164
+        $this->registerAlias(IContactsStore::class, ContactsStore::class);
1165
+
1166
+        $this->connectDispatcher();
1167
+    }
1168
+
1169
+    /**
1170
+     * @return \OCP\Calendar\IManager
1171
+     */
1172
+    public function getCalendarManager() {
1173
+        return $this->query('CalendarManager');
1174
+    }
1175
+
1176
+    private function connectDispatcher() {
1177
+        $dispatcher = $this->getEventDispatcher();
1178
+
1179
+        // Delete avatar on user deletion
1180
+        $dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1181
+            $logger = $this->getLogger();
1182
+            $manager = $this->getAvatarManager();
1183
+            /** @var IUser $user */
1184
+            $user = $e->getSubject();
1185
+
1186
+            try {
1187
+                $avatar = $manager->getAvatar($user->getUID());
1188
+                $avatar->remove();
1189
+            } catch (NotFoundException $e) {
1190
+                // no avatar to remove
1191
+            } catch (\Exception $e) {
1192
+                // Ignore exceptions
1193
+                $logger->info('Could not cleanup avatar of ' . $user->getUID());
1194
+            }
1195
+        });
1196
+
1197
+        $dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1198
+            $manager = $this->getAvatarManager();
1199
+            /** @var IUser $user */
1200
+            $user = $e->getSubject();
1201
+            $feature = $e->getArgument('feature');
1202
+            $oldValue = $e->getArgument('oldValue');
1203
+            $value = $e->getArgument('value');
1204
+
1205
+            try {
1206
+                $avatar = $manager->getAvatar($user->getUID());
1207
+                $avatar->userChanged($feature, $oldValue, $value);
1208
+            } catch (NotFoundException $e) {
1209
+                // no avatar to remove
1210
+            }
1211
+        });
1212
+    }
1213
+
1214
+    /**
1215
+     * @return \OCP\Contacts\IManager
1216
+     */
1217
+    public function getContactsManager() {
1218
+        return $this->query('ContactsManager');
1219
+    }
1220
+
1221
+    /**
1222
+     * @return \OC\Encryption\Manager
1223
+     */
1224
+    public function getEncryptionManager() {
1225
+        return $this->query('EncryptionManager');
1226
+    }
1227
+
1228
+    /**
1229
+     * @return \OC\Encryption\File
1230
+     */
1231
+    public function getEncryptionFilesHelper() {
1232
+        return $this->query('EncryptionFileHelper');
1233
+    }
1234
+
1235
+    /**
1236
+     * @return \OCP\Encryption\Keys\IStorage
1237
+     */
1238
+    public function getEncryptionKeyStorage() {
1239
+        return $this->query('EncryptionKeyStorage');
1240
+    }
1241
+
1242
+    /**
1243
+     * The current request object holding all information about the request
1244
+     * currently being processed is returned from this method.
1245
+     * In case the current execution was not initiated by a web request null is returned
1246
+     *
1247
+     * @return \OCP\IRequest
1248
+     */
1249
+    public function getRequest() {
1250
+        return $this->query('Request');
1251
+    }
1252
+
1253
+    /**
1254
+     * Returns the preview manager which can create preview images for a given file
1255
+     *
1256
+     * @return \OCP\IPreview
1257
+     */
1258
+    public function getPreviewManager() {
1259
+        return $this->query('PreviewManager');
1260
+    }
1261
+
1262
+    /**
1263
+     * Returns the tag manager which can get and set tags for different object types
1264
+     *
1265
+     * @see \OCP\ITagManager::load()
1266
+     * @return \OCP\ITagManager
1267
+     */
1268
+    public function getTagManager() {
1269
+        return $this->query('TagManager');
1270
+    }
1271
+
1272
+    /**
1273
+     * Returns the system-tag manager
1274
+     *
1275
+     * @return \OCP\SystemTag\ISystemTagManager
1276
+     *
1277
+     * @since 9.0.0
1278
+     */
1279
+    public function getSystemTagManager() {
1280
+        return $this->query('SystemTagManager');
1281
+    }
1282
+
1283
+    /**
1284
+     * Returns the system-tag object mapper
1285
+     *
1286
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
1287
+     *
1288
+     * @since 9.0.0
1289
+     */
1290
+    public function getSystemTagObjectMapper() {
1291
+        return $this->query('SystemTagObjectMapper');
1292
+    }
1293
+
1294
+    /**
1295
+     * Returns the avatar manager, used for avatar functionality
1296
+     *
1297
+     * @return \OCP\IAvatarManager
1298
+     */
1299
+    public function getAvatarManager() {
1300
+        return $this->query('AvatarManager');
1301
+    }
1302
+
1303
+    /**
1304
+     * Returns the root folder of ownCloud's data directory
1305
+     *
1306
+     * @return \OCP\Files\IRootFolder
1307
+     */
1308
+    public function getRootFolder() {
1309
+        return $this->query('LazyRootFolder');
1310
+    }
1311
+
1312
+    /**
1313
+     * Returns the root folder of ownCloud's data directory
1314
+     * This is the lazy variant so this gets only initialized once it
1315
+     * is actually used.
1316
+     *
1317
+     * @return \OCP\Files\IRootFolder
1318
+     */
1319
+    public function getLazyRootFolder() {
1320
+        return $this->query('LazyRootFolder');
1321
+    }
1322
+
1323
+    /**
1324
+     * Returns a view to ownCloud's files folder
1325
+     *
1326
+     * @param string $userId user ID
1327
+     * @return \OCP\Files\Folder|null
1328
+     */
1329
+    public function getUserFolder($userId = null) {
1330
+        if ($userId === null) {
1331
+            $user = $this->getUserSession()->getUser();
1332
+            if (!$user) {
1333
+                return null;
1334
+            }
1335
+            $userId = $user->getUID();
1336
+        }
1337
+        $root = $this->getRootFolder();
1338
+        return $root->getUserFolder($userId);
1339
+    }
1340
+
1341
+    /**
1342
+     * Returns an app-specific view in ownClouds data directory
1343
+     *
1344
+     * @return \OCP\Files\Folder
1345
+     * @deprecated since 9.2.0 use IAppData
1346
+     */
1347
+    public function getAppFolder() {
1348
+        $dir = '/' . \OC_App::getCurrentApp();
1349
+        $root = $this->getRootFolder();
1350
+        if (!$root->nodeExists($dir)) {
1351
+            $folder = $root->newFolder($dir);
1352
+        } else {
1353
+            $folder = $root->get($dir);
1354
+        }
1355
+        return $folder;
1356
+    }
1357
+
1358
+    /**
1359
+     * @return \OC\User\Manager
1360
+     */
1361
+    public function getUserManager() {
1362
+        return $this->query('UserManager');
1363
+    }
1364
+
1365
+    /**
1366
+     * @return \OC\Group\Manager
1367
+     */
1368
+    public function getGroupManager() {
1369
+        return $this->query('GroupManager');
1370
+    }
1371
+
1372
+    /**
1373
+     * @return \OC\User\Session
1374
+     */
1375
+    public function getUserSession() {
1376
+        return $this->query('UserSession');
1377
+    }
1378
+
1379
+    /**
1380
+     * @return \OCP\ISession
1381
+     */
1382
+    public function getSession() {
1383
+        return $this->query('UserSession')->getSession();
1384
+    }
1385
+
1386
+    /**
1387
+     * @param \OCP\ISession $session
1388
+     */
1389
+    public function setSession(\OCP\ISession $session) {
1390
+        $this->query(SessionStorage::class)->setSession($session);
1391
+        $this->query('UserSession')->setSession($session);
1392
+        $this->query(Store::class)->setSession($session);
1393
+    }
1394
+
1395
+    /**
1396
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1397
+     */
1398
+    public function getTwoFactorAuthManager() {
1399
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1400
+    }
1401
+
1402
+    /**
1403
+     * @return \OC\NavigationManager
1404
+     */
1405
+    public function getNavigationManager() {
1406
+        return $this->query('NavigationManager');
1407
+    }
1408
+
1409
+    /**
1410
+     * @return \OCP\IConfig
1411
+     */
1412
+    public function getConfig() {
1413
+        return $this->query('AllConfig');
1414
+    }
1415
+
1416
+    /**
1417
+     * @return \OC\SystemConfig
1418
+     */
1419
+    public function getSystemConfig() {
1420
+        return $this->query('SystemConfig');
1421
+    }
1422
+
1423
+    /**
1424
+     * Returns the app config manager
1425
+     *
1426
+     * @return \OCP\IAppConfig
1427
+     */
1428
+    public function getAppConfig() {
1429
+        return $this->query('AppConfig');
1430
+    }
1431
+
1432
+    /**
1433
+     * @return \OCP\L10N\IFactory
1434
+     */
1435
+    public function getL10NFactory() {
1436
+        return $this->query('L10NFactory');
1437
+    }
1438
+
1439
+    /**
1440
+     * get an L10N instance
1441
+     *
1442
+     * @param string $app appid
1443
+     * @param string $lang
1444
+     * @return IL10N
1445
+     */
1446
+    public function getL10N($app, $lang = null) {
1447
+        return $this->getL10NFactory()->get($app, $lang);
1448
+    }
1449
+
1450
+    /**
1451
+     * @return \OCP\IURLGenerator
1452
+     */
1453
+    public function getURLGenerator() {
1454
+        return $this->query('URLGenerator');
1455
+    }
1456
+
1457
+    /**
1458
+     * @return AppFetcher
1459
+     */
1460
+    public function getAppFetcher() {
1461
+        return $this->query(AppFetcher::class);
1462
+    }
1463
+
1464
+    /**
1465
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1466
+     * getMemCacheFactory() instead.
1467
+     *
1468
+     * @return \OCP\ICache
1469
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1470
+     */
1471
+    public function getCache() {
1472
+        return $this->query('UserCache');
1473
+    }
1474
+
1475
+    /**
1476
+     * Returns an \OCP\CacheFactory instance
1477
+     *
1478
+     * @return \OCP\ICacheFactory
1479
+     */
1480
+    public function getMemCacheFactory() {
1481
+        return $this->query('MemCacheFactory');
1482
+    }
1483
+
1484
+    /**
1485
+     * Returns an \OC\RedisFactory instance
1486
+     *
1487
+     * @return \OC\RedisFactory
1488
+     */
1489
+    public function getGetRedisFactory() {
1490
+        return $this->query('RedisFactory');
1491
+    }
1492
+
1493
+
1494
+    /**
1495
+     * Returns the current session
1496
+     *
1497
+     * @return \OCP\IDBConnection
1498
+     */
1499
+    public function getDatabaseConnection() {
1500
+        return $this->query('DatabaseConnection');
1501
+    }
1502
+
1503
+    /**
1504
+     * Returns the activity manager
1505
+     *
1506
+     * @return \OCP\Activity\IManager
1507
+     */
1508
+    public function getActivityManager() {
1509
+        return $this->query('ActivityManager');
1510
+    }
1511
+
1512
+    /**
1513
+     * Returns an job list for controlling background jobs
1514
+     *
1515
+     * @return \OCP\BackgroundJob\IJobList
1516
+     */
1517
+    public function getJobList() {
1518
+        return $this->query('JobList');
1519
+    }
1520
+
1521
+    /**
1522
+     * Returns a logger instance
1523
+     *
1524
+     * @return \OCP\ILogger
1525
+     */
1526
+    public function getLogger() {
1527
+        return $this->query('Logger');
1528
+    }
1529
+
1530
+    /**
1531
+     * Returns a router for generating and matching urls
1532
+     *
1533
+     * @return \OCP\Route\IRouter
1534
+     */
1535
+    public function getRouter() {
1536
+        return $this->query('Router');
1537
+    }
1538
+
1539
+    /**
1540
+     * Returns a search instance
1541
+     *
1542
+     * @return \OCP\ISearch
1543
+     */
1544
+    public function getSearch() {
1545
+        return $this->query('Search');
1546
+    }
1547
+
1548
+    /**
1549
+     * Returns a SecureRandom instance
1550
+     *
1551
+     * @return \OCP\Security\ISecureRandom
1552
+     */
1553
+    public function getSecureRandom() {
1554
+        return $this->query('SecureRandom');
1555
+    }
1556
+
1557
+    /**
1558
+     * Returns a Crypto instance
1559
+     *
1560
+     * @return \OCP\Security\ICrypto
1561
+     */
1562
+    public function getCrypto() {
1563
+        return $this->query('Crypto');
1564
+    }
1565
+
1566
+    /**
1567
+     * Returns a Hasher instance
1568
+     *
1569
+     * @return \OCP\Security\IHasher
1570
+     */
1571
+    public function getHasher() {
1572
+        return $this->query('Hasher');
1573
+    }
1574
+
1575
+    /**
1576
+     * Returns a CredentialsManager instance
1577
+     *
1578
+     * @return \OCP\Security\ICredentialsManager
1579
+     */
1580
+    public function getCredentialsManager() {
1581
+        return $this->query('CredentialsManager');
1582
+    }
1583
+
1584
+    /**
1585
+     * Get the certificate manager for the user
1586
+     *
1587
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1588
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1589
+     */
1590
+    public function getCertificateManager($userId = '') {
1591
+        if ($userId === '') {
1592
+            $userSession = $this->getUserSession();
1593
+            $user = $userSession->getUser();
1594
+            if (is_null($user)) {
1595
+                return null;
1596
+            }
1597
+            $userId = $user->getUID();
1598
+        }
1599
+        return new CertificateManager(
1600
+            $userId,
1601
+            new View(),
1602
+            $this->getConfig(),
1603
+            $this->getLogger(),
1604
+            $this->getSecureRandom()
1605
+        );
1606
+    }
1607
+
1608
+    /**
1609
+     * Returns an instance of the HTTP client service
1610
+     *
1611
+     * @return \OCP\Http\Client\IClientService
1612
+     */
1613
+    public function getHTTPClientService() {
1614
+        return $this->query('HttpClientService');
1615
+    }
1616
+
1617
+    /**
1618
+     * Create a new event source
1619
+     *
1620
+     * @return \OCP\IEventSource
1621
+     */
1622
+    public function createEventSource() {
1623
+        return new \OC_EventSource();
1624
+    }
1625
+
1626
+    /**
1627
+     * Get the active event logger
1628
+     *
1629
+     * The returned logger only logs data when debug mode is enabled
1630
+     *
1631
+     * @return \OCP\Diagnostics\IEventLogger
1632
+     */
1633
+    public function getEventLogger() {
1634
+        return $this->query('EventLogger');
1635
+    }
1636
+
1637
+    /**
1638
+     * Get the active query logger
1639
+     *
1640
+     * The returned logger only logs data when debug mode is enabled
1641
+     *
1642
+     * @return \OCP\Diagnostics\IQueryLogger
1643
+     */
1644
+    public function getQueryLogger() {
1645
+        return $this->query('QueryLogger');
1646
+    }
1647
+
1648
+    /**
1649
+     * Get the manager for temporary files and folders
1650
+     *
1651
+     * @return \OCP\ITempManager
1652
+     */
1653
+    public function getTempManager() {
1654
+        return $this->query('TempManager');
1655
+    }
1656
+
1657
+    /**
1658
+     * Get the app manager
1659
+     *
1660
+     * @return \OCP\App\IAppManager
1661
+     */
1662
+    public function getAppManager() {
1663
+        return $this->query('AppManager');
1664
+    }
1665
+
1666
+    /**
1667
+     * Creates a new mailer
1668
+     *
1669
+     * @return \OCP\Mail\IMailer
1670
+     */
1671
+    public function getMailer() {
1672
+        return $this->query('Mailer');
1673
+    }
1674
+
1675
+    /**
1676
+     * Get the webroot
1677
+     *
1678
+     * @return string
1679
+     */
1680
+    public function getWebRoot() {
1681
+        return $this->webRoot;
1682
+    }
1683
+
1684
+    /**
1685
+     * @return \OC\OCSClient
1686
+     */
1687
+    public function getOcsClient() {
1688
+        return $this->query('OcsClient');
1689
+    }
1690
+
1691
+    /**
1692
+     * @return \OCP\IDateTimeZone
1693
+     */
1694
+    public function getDateTimeZone() {
1695
+        return $this->query('DateTimeZone');
1696
+    }
1697
+
1698
+    /**
1699
+     * @return \OCP\IDateTimeFormatter
1700
+     */
1701
+    public function getDateTimeFormatter() {
1702
+        return $this->query('DateTimeFormatter');
1703
+    }
1704
+
1705
+    /**
1706
+     * @return \OCP\Files\Config\IMountProviderCollection
1707
+     */
1708
+    public function getMountProviderCollection() {
1709
+        return $this->query('MountConfigManager');
1710
+    }
1711
+
1712
+    /**
1713
+     * Get the IniWrapper
1714
+     *
1715
+     * @return IniGetWrapper
1716
+     */
1717
+    public function getIniWrapper() {
1718
+        return $this->query('IniWrapper');
1719
+    }
1720
+
1721
+    /**
1722
+     * @return \OCP\Command\IBus
1723
+     */
1724
+    public function getCommandBus() {
1725
+        return $this->query('AsyncCommandBus');
1726
+    }
1727
+
1728
+    /**
1729
+     * Get the trusted domain helper
1730
+     *
1731
+     * @return TrustedDomainHelper
1732
+     */
1733
+    public function getTrustedDomainHelper() {
1734
+        return $this->query('TrustedDomainHelper');
1735
+    }
1736
+
1737
+    /**
1738
+     * Get the locking provider
1739
+     *
1740
+     * @return \OCP\Lock\ILockingProvider
1741
+     * @since 8.1.0
1742
+     */
1743
+    public function getLockingProvider() {
1744
+        return $this->query('LockingProvider');
1745
+    }
1746
+
1747
+    /**
1748
+     * @return \OCP\Files\Mount\IMountManager
1749
+     **/
1750
+    function getMountManager() {
1751
+        return $this->query('MountManager');
1752
+    }
1753
+
1754
+    /** @return \OCP\Files\Config\IUserMountCache */
1755
+    function getUserMountCache() {
1756
+        return $this->query('UserMountCache');
1757
+    }
1758
+
1759
+    /**
1760
+     * Get the MimeTypeDetector
1761
+     *
1762
+     * @return \OCP\Files\IMimeTypeDetector
1763
+     */
1764
+    public function getMimeTypeDetector() {
1765
+        return $this->query('MimeTypeDetector');
1766
+    }
1767
+
1768
+    /**
1769
+     * Get the MimeTypeLoader
1770
+     *
1771
+     * @return \OCP\Files\IMimeTypeLoader
1772
+     */
1773
+    public function getMimeTypeLoader() {
1774
+        return $this->query('MimeTypeLoader');
1775
+    }
1776
+
1777
+    /**
1778
+     * Get the manager of all the capabilities
1779
+     *
1780
+     * @return \OC\CapabilitiesManager
1781
+     */
1782
+    public function getCapabilitiesManager() {
1783
+        return $this->query('CapabilitiesManager');
1784
+    }
1785
+
1786
+    /**
1787
+     * Get the EventDispatcher
1788
+     *
1789
+     * @return EventDispatcherInterface
1790
+     * @since 8.2.0
1791
+     */
1792
+    public function getEventDispatcher() {
1793
+        return $this->query('EventDispatcher');
1794
+    }
1795
+
1796
+    /**
1797
+     * Get the Notification Manager
1798
+     *
1799
+     * @return \OCP\Notification\IManager
1800
+     * @since 8.2.0
1801
+     */
1802
+    public function getNotificationManager() {
1803
+        return $this->query('NotificationManager');
1804
+    }
1805
+
1806
+    /**
1807
+     * @return \OCP\Comments\ICommentsManager
1808
+     */
1809
+    public function getCommentsManager() {
1810
+        return $this->query('CommentsManager');
1811
+    }
1812
+
1813
+    /**
1814
+     * @return \OCA\Theming\ThemingDefaults
1815
+     */
1816
+    public function getThemingDefaults() {
1817
+        return $this->query('ThemingDefaults');
1818
+    }
1819
+
1820
+    /**
1821
+     * @return \OC\IntegrityCheck\Checker
1822
+     */
1823
+    public function getIntegrityCodeChecker() {
1824
+        return $this->query('IntegrityCodeChecker');
1825
+    }
1826
+
1827
+    /**
1828
+     * @return \OC\Session\CryptoWrapper
1829
+     */
1830
+    public function getSessionCryptoWrapper() {
1831
+        return $this->query('CryptoWrapper');
1832
+    }
1833
+
1834
+    /**
1835
+     * @return CsrfTokenManager
1836
+     */
1837
+    public function getCsrfTokenManager() {
1838
+        return $this->query('CsrfTokenManager');
1839
+    }
1840
+
1841
+    /**
1842
+     * @return Throttler
1843
+     */
1844
+    public function getBruteForceThrottler() {
1845
+        return $this->query('Throttler');
1846
+    }
1847
+
1848
+    /**
1849
+     * @return IContentSecurityPolicyManager
1850
+     */
1851
+    public function getContentSecurityPolicyManager() {
1852
+        return $this->query('ContentSecurityPolicyManager');
1853
+    }
1854
+
1855
+    /**
1856
+     * @return ContentSecurityPolicyNonceManager
1857
+     */
1858
+    public function getContentSecurityPolicyNonceManager() {
1859
+        return $this->query('ContentSecurityPolicyNonceManager');
1860
+    }
1861
+
1862
+    /**
1863
+     * Not a public API as of 8.2, wait for 9.0
1864
+     *
1865
+     * @return \OCA\Files_External\Service\BackendService
1866
+     */
1867
+    public function getStoragesBackendService() {
1868
+        return $this->query('OCA\\Files_External\\Service\\BackendService');
1869
+    }
1870
+
1871
+    /**
1872
+     * Not a public API as of 8.2, wait for 9.0
1873
+     *
1874
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1875
+     */
1876
+    public function getGlobalStoragesService() {
1877
+        return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1878
+    }
1879
+
1880
+    /**
1881
+     * Not a public API as of 8.2, wait for 9.0
1882
+     *
1883
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1884
+     */
1885
+    public function getUserGlobalStoragesService() {
1886
+        return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1887
+    }
1888
+
1889
+    /**
1890
+     * Not a public API as of 8.2, wait for 9.0
1891
+     *
1892
+     * @return \OCA\Files_External\Service\UserStoragesService
1893
+     */
1894
+    public function getUserStoragesService() {
1895
+        return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1896
+    }
1897
+
1898
+    /**
1899
+     * @return \OCP\Share\IManager
1900
+     */
1901
+    public function getShareManager() {
1902
+        return $this->query('ShareManager');
1903
+    }
1904
+
1905
+    /**
1906
+     * @return \OCP\Collaboration\Collaborators\ISearch
1907
+     */
1908
+    public function getCollaboratorSearch() {
1909
+        return $this->query('CollaboratorSearch');
1910
+    }
1911
+
1912
+    /**
1913
+     * @return \OCP\Collaboration\AutoComplete\IManager
1914
+     */
1915
+    public function getAutoCompleteManager(){
1916
+        return $this->query(IManager::class);
1917
+    }
1918
+
1919
+    /**
1920
+     * Returns the LDAP Provider
1921
+     *
1922
+     * @return \OCP\LDAP\ILDAPProvider
1923
+     */
1924
+    public function getLDAPProvider() {
1925
+        return $this->query('LDAPProvider');
1926
+    }
1927
+
1928
+    /**
1929
+     * @return \OCP\Settings\IManager
1930
+     */
1931
+    public function getSettingsManager() {
1932
+        return $this->query('SettingsManager');
1933
+    }
1934
+
1935
+    /**
1936
+     * @return \OCP\Files\IAppData
1937
+     */
1938
+    public function getAppDataDir($app) {
1939
+        /** @var \OC\Files\AppData\Factory $factory */
1940
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
1941
+        return $factory->get($app);
1942
+    }
1943
+
1944
+    /**
1945
+     * @return \OCP\Lockdown\ILockdownManager
1946
+     */
1947
+    public function getLockdownManager() {
1948
+        return $this->query('LockdownManager');
1949
+    }
1950
+
1951
+    /**
1952
+     * @return \OCP\Federation\ICloudIdManager
1953
+     */
1954
+    public function getCloudIdManager() {
1955
+        return $this->query(ICloudIdManager::class);
1956
+    }
1957
+
1958
+    /**
1959
+     * @return \OCP\Remote\Api\IApiFactory
1960
+     */
1961
+    public function getRemoteApiFactory() {
1962
+        return $this->query(IApiFactory::class);
1963
+    }
1964
+
1965
+    /**
1966
+     * @return \OCP\Remote\IInstanceFactory
1967
+     */
1968
+    public function getRemoteInstanceFactory() {
1969
+        return $this->query(IInstanceFactory::class);
1970
+    }
1971 1971
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Publishing/PublishPlugin.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -134,7 +134,7 @@
 block discarded – undo
134 134
 	 * @param RequestInterface $request
135 135
 	 * @param ResponseInterface $response
136 136
 	 *
137
-	 * @return void|bool
137
+	 * @return null|false
138 138
 	 */
139 139
 	public function httpPost(RequestInterface $request, ResponseInterface $response) {
140 140
 		$path = $request->getPath();
Please login to merge, or discard this patch.
Indentation   +189 added lines, -189 removed lines patch added patch discarded remove patch
@@ -34,194 +34,194 @@
 block discarded – undo
34 34
 use OCP\IConfig;
35 35
 
36 36
 class PublishPlugin extends ServerPlugin {
37
-	const NS_CALENDARSERVER = 'http://calendarserver.org/ns/';
38
-
39
-	/**
40
-	 * Reference to SabreDAV server object.
41
-	 *
42
-	 * @var \Sabre\DAV\Server
43
-	 */
44
-	protected $server;
45
-
46
-	/**
47
-	 * Config instance to get instance secret.
48
-	 *
49
-	 * @var IConfig
50
-	 */
51
-	protected $config;
52
-
53
-	/**
54
-	 * URL Generator for absolute URLs.
55
-	 *
56
-	 * @var IURLGenerator
57
-	 */
58
-	protected $urlGenerator;
59
-
60
-	/**
61
-	 * PublishPlugin constructor.
62
-	 *
63
-	 * @param IConfig $config
64
-	 * @param IURLGenerator $urlGenerator
65
-	 */
66
-	public function __construct(IConfig $config, IURLGenerator $urlGenerator) {
67
-		$this->config = $config;
68
-		$this->urlGenerator = $urlGenerator;
69
-	}
70
-
71
-	/**
72
-	 * This method should return a list of server-features.
73
-	 *
74
-	 * This is for example 'versioning' and is added to the DAV: header
75
-	 * in an OPTIONS response.
76
-	 *
77
-	 * @return string[]
78
-	 */
79
-	public function getFeatures() {
80
-		// May have to be changed to be detected
81
-		return ['oc-calendar-publishing', 'calendarserver-sharing'];
82
-	}
83
-
84
-	/**
85
-	 * Returns a plugin name.
86
-	 *
87
-	 * Using this name other plugins will be able to access other plugins
88
-	 * using Sabre\DAV\Server::getPlugin
89
-	 *
90
-	 * @return string
91
-	 */
92
-	public function getPluginName()	{
93
-		return 'oc-calendar-publishing';
94
-	}
95
-
96
-	/**
97
-	 * This initializes the plugin.
98
-	 *
99
-	 * This function is called by Sabre\DAV\Server, after
100
-	 * addPlugin is called.
101
-	 *
102
-	 * This method should set up the required event subscriptions.
103
-	 *
104
-	 * @param Server $server
105
-	 */
106
-	public function initialize(Server $server) {
107
-		$this->server = $server;
108
-
109
-		$this->server->on('method:POST', [$this, 'httpPost']);
110
-		$this->server->on('propFind',    [$this, 'propFind']);
111
-	}
112
-
113
-	public function propFind(PropFind $propFind, INode $node) {
114
-		if ($node instanceof Calendar) {
115
-			$propFind->handle('{'.self::NS_CALENDARSERVER.'}publish-url', function () use ($node) {
116
-				if ($node->getPublishStatus()) {
117
-					// We return the publish-url only if the calendar is published.
118
-					$token = $node->getPublishStatus();
119
-					$publishUrl = $this->urlGenerator->getAbsoluteURL($this->server->getBaseUri().'public-calendars/').$token;
120
-
121
-					return new Publisher($publishUrl, true);
122
-				}
123
-			});
124
-
125
-			$propFind->handle('{'.self::NS_CALENDARSERVER.'}allowed-sharing-modes', function() use ($node) {
126
-				return new AllowedSharingModes(!$node->isSubscription(), !$node->isSubscription());
127
-			});
128
-		}
129
-	}
130
-
131
-	/**
132
-	 * We intercept this to handle POST requests on calendars.
133
-	 *
134
-	 * @param RequestInterface $request
135
-	 * @param ResponseInterface $response
136
-	 *
137
-	 * @return void|bool
138
-	 */
139
-	public function httpPost(RequestInterface $request, ResponseInterface $response) {
140
-		$path = $request->getPath();
141
-
142
-		// Only handling xml
143
-		$contentType = $request->getHeader('Content-Type');
144
-		if (strpos($contentType, 'application/xml') === false && strpos($contentType, 'text/xml') === false) {
145
-			return;
146
-		}
147
-
148
-		// Making sure the node exists
149
-		try {
150
-			$node = $this->server->tree->getNodeForPath($path);
151
-		} catch (NotFound $e) {
152
-			return;
153
-		}
154
-
155
-		$requestBody = $request->getBodyAsString();
156
-
157
-		// If this request handler could not deal with this POST request, it
158
-		// will return 'null' and other plugins get a chance to handle the
159
-		// request.
160
-		//
161
-		// However, we already requested the full body. This is a problem,
162
-		// because a body can only be read once. This is why we preemptively
163
-		// re-populated the request body with the existing data.
164
-		$request->setBody($requestBody);
165
-
166
-		$this->server->xml->parse($requestBody, $request->getUrl(), $documentType);
167
-
168
-		switch ($documentType) {
169
-
170
-			case '{'.self::NS_CALENDARSERVER.'}publish-calendar' :
171
-
172
-			// We can only deal with IShareableCalendar objects
173
-			if (!$node instanceof Calendar) {
174
-				return;
175
-			}
176
-			$this->server->transactionType = 'post-publish-calendar';
177
-
178
-			// Getting ACL info
179
-			$acl = $this->server->getPlugin('acl');
180
-
181
-			// If there's no ACL support, we allow everything
182
-			if ($acl) {
183
-				$acl->checkPrivileges($path, '{DAV:}write');
184
-			}
185
-
186
-			$node->setPublishStatus(true);
187
-
188
-			// iCloud sends back the 202, so we will too.
189
-			$response->setStatus(202);
190
-
191
-			// Adding this because sending a response body may cause issues,
192
-			// and I wanted some type of indicator the response was handled.
193
-			$response->setHeader('X-Sabre-Status', 'everything-went-well');
194
-
195
-			// Breaking the event chain
196
-			return false;
197
-
198
-			case '{'.self::NS_CALENDARSERVER.'}unpublish-calendar' :
199
-
200
-			// We can only deal with IShareableCalendar objects
201
-			if (!$node instanceof Calendar) {
202
-				return;
203
-			}
204
-			$this->server->transactionType = 'post-unpublish-calendar';
205
-
206
-			// Getting ACL info
207
-			$acl = $this->server->getPlugin('acl');
208
-
209
-			// If there's no ACL support, we allow everything
210
-			if ($acl) {
211
-				$acl->checkPrivileges($path, '{DAV:}write');
212
-			}
213
-
214
-			$node->setPublishStatus(false);
215
-
216
-			$response->setStatus(200);
217
-
218
-			// Adding this because sending a response body may cause issues,
219
-			// and I wanted some type of indicator the response was handled.
220
-			$response->setHeader('X-Sabre-Status', 'everything-went-well');
221
-
222
-			// Breaking the event chain
223
-			return false;
37
+    const NS_CALENDARSERVER = 'http://calendarserver.org/ns/';
38
+
39
+    /**
40
+     * Reference to SabreDAV server object.
41
+     *
42
+     * @var \Sabre\DAV\Server
43
+     */
44
+    protected $server;
45
+
46
+    /**
47
+     * Config instance to get instance secret.
48
+     *
49
+     * @var IConfig
50
+     */
51
+    protected $config;
52
+
53
+    /**
54
+     * URL Generator for absolute URLs.
55
+     *
56
+     * @var IURLGenerator
57
+     */
58
+    protected $urlGenerator;
59
+
60
+    /**
61
+     * PublishPlugin constructor.
62
+     *
63
+     * @param IConfig $config
64
+     * @param IURLGenerator $urlGenerator
65
+     */
66
+    public function __construct(IConfig $config, IURLGenerator $urlGenerator) {
67
+        $this->config = $config;
68
+        $this->urlGenerator = $urlGenerator;
69
+    }
70
+
71
+    /**
72
+     * This method should return a list of server-features.
73
+     *
74
+     * This is for example 'versioning' and is added to the DAV: header
75
+     * in an OPTIONS response.
76
+     *
77
+     * @return string[]
78
+     */
79
+    public function getFeatures() {
80
+        // May have to be changed to be detected
81
+        return ['oc-calendar-publishing', 'calendarserver-sharing'];
82
+    }
83
+
84
+    /**
85
+     * Returns a plugin name.
86
+     *
87
+     * Using this name other plugins will be able to access other plugins
88
+     * using Sabre\DAV\Server::getPlugin
89
+     *
90
+     * @return string
91
+     */
92
+    public function getPluginName()	{
93
+        return 'oc-calendar-publishing';
94
+    }
95
+
96
+    /**
97
+     * This initializes the plugin.
98
+     *
99
+     * This function is called by Sabre\DAV\Server, after
100
+     * addPlugin is called.
101
+     *
102
+     * This method should set up the required event subscriptions.
103
+     *
104
+     * @param Server $server
105
+     */
106
+    public function initialize(Server $server) {
107
+        $this->server = $server;
108
+
109
+        $this->server->on('method:POST', [$this, 'httpPost']);
110
+        $this->server->on('propFind',    [$this, 'propFind']);
111
+    }
112
+
113
+    public function propFind(PropFind $propFind, INode $node) {
114
+        if ($node instanceof Calendar) {
115
+            $propFind->handle('{'.self::NS_CALENDARSERVER.'}publish-url', function () use ($node) {
116
+                if ($node->getPublishStatus()) {
117
+                    // We return the publish-url only if the calendar is published.
118
+                    $token = $node->getPublishStatus();
119
+                    $publishUrl = $this->urlGenerator->getAbsoluteURL($this->server->getBaseUri().'public-calendars/').$token;
120
+
121
+                    return new Publisher($publishUrl, true);
122
+                }
123
+            });
124
+
125
+            $propFind->handle('{'.self::NS_CALENDARSERVER.'}allowed-sharing-modes', function() use ($node) {
126
+                return new AllowedSharingModes(!$node->isSubscription(), !$node->isSubscription());
127
+            });
128
+        }
129
+    }
130
+
131
+    /**
132
+     * We intercept this to handle POST requests on calendars.
133
+     *
134
+     * @param RequestInterface $request
135
+     * @param ResponseInterface $response
136
+     *
137
+     * @return void|bool
138
+     */
139
+    public function httpPost(RequestInterface $request, ResponseInterface $response) {
140
+        $path = $request->getPath();
141
+
142
+        // Only handling xml
143
+        $contentType = $request->getHeader('Content-Type');
144
+        if (strpos($contentType, 'application/xml') === false && strpos($contentType, 'text/xml') === false) {
145
+            return;
146
+        }
147
+
148
+        // Making sure the node exists
149
+        try {
150
+            $node = $this->server->tree->getNodeForPath($path);
151
+        } catch (NotFound $e) {
152
+            return;
153
+        }
154
+
155
+        $requestBody = $request->getBodyAsString();
156
+
157
+        // If this request handler could not deal with this POST request, it
158
+        // will return 'null' and other plugins get a chance to handle the
159
+        // request.
160
+        //
161
+        // However, we already requested the full body. This is a problem,
162
+        // because a body can only be read once. This is why we preemptively
163
+        // re-populated the request body with the existing data.
164
+        $request->setBody($requestBody);
165
+
166
+        $this->server->xml->parse($requestBody, $request->getUrl(), $documentType);
167
+
168
+        switch ($documentType) {
169
+
170
+            case '{'.self::NS_CALENDARSERVER.'}publish-calendar' :
171
+
172
+            // We can only deal with IShareableCalendar objects
173
+            if (!$node instanceof Calendar) {
174
+                return;
175
+            }
176
+            $this->server->transactionType = 'post-publish-calendar';
177
+
178
+            // Getting ACL info
179
+            $acl = $this->server->getPlugin('acl');
180
+
181
+            // If there's no ACL support, we allow everything
182
+            if ($acl) {
183
+                $acl->checkPrivileges($path, '{DAV:}write');
184
+            }
185
+
186
+            $node->setPublishStatus(true);
187
+
188
+            // iCloud sends back the 202, so we will too.
189
+            $response->setStatus(202);
190
+
191
+            // Adding this because sending a response body may cause issues,
192
+            // and I wanted some type of indicator the response was handled.
193
+            $response->setHeader('X-Sabre-Status', 'everything-went-well');
194
+
195
+            // Breaking the event chain
196
+            return false;
197
+
198
+            case '{'.self::NS_CALENDARSERVER.'}unpublish-calendar' :
199
+
200
+            // We can only deal with IShareableCalendar objects
201
+            if (!$node instanceof Calendar) {
202
+                return;
203
+            }
204
+            $this->server->transactionType = 'post-unpublish-calendar';
205
+
206
+            // Getting ACL info
207
+            $acl = $this->server->getPlugin('acl');
208
+
209
+            // If there's no ACL support, we allow everything
210
+            if ($acl) {
211
+                $acl->checkPrivileges($path, '{DAV:}write');
212
+            }
213
+
214
+            $node->setPublishStatus(false);
215
+
216
+            $response->setStatus(200);
217
+
218
+            // Adding this because sending a response body may cause issues,
219
+            // and I wanted some type of indicator the response was handled.
220
+            $response->setHeader('X-Sabre-Status', 'everything-went-well');
221
+
222
+            // Breaking the event chain
223
+            return false;
224 224
 
225
-		}
226
-	}
225
+        }
226
+    }
227 227
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -89,7 +89,7 @@  discard block
 block discarded – undo
89 89
 	 *
90 90
 	 * @return string
91 91
 	 */
92
-	public function getPluginName()	{
92
+	public function getPluginName() {
93 93
 		return 'oc-calendar-publishing';
94 94
 	}
95 95
 
@@ -107,12 +107,12 @@  discard block
 block discarded – undo
107 107
 		$this->server = $server;
108 108
 
109 109
 		$this->server->on('method:POST', [$this, 'httpPost']);
110
-		$this->server->on('propFind',    [$this, 'propFind']);
110
+		$this->server->on('propFind', [$this, 'propFind']);
111 111
 	}
112 112
 
113 113
 	public function propFind(PropFind $propFind, INode $node) {
114 114
 		if ($node instanceof Calendar) {
115
-			$propFind->handle('{'.self::NS_CALENDARSERVER.'}publish-url', function () use ($node) {
115
+			$propFind->handle('{'.self::NS_CALENDARSERVER.'}publish-url', function() use ($node) {
116 116
 				if ($node->getPublishStatus()) {
117 117
 					// We return the publish-url only if the calendar is published.
118 118
 					$token = $node->getPublishStatus();
Please login to merge, or discard this patch.