Completed
Pull Request — master (#7057)
by Blizzz
13:29
created
apps/user_ldap/lib/Mapping/AbstractMapping.php 2 patches
Indentation   +214 added lines, -214 removed lines patch added patch discarded remove patch
@@ -29,267 +29,267 @@
 block discarded – undo
29 29
 * @package OCA\User_LDAP\Mapping
30 30
 */
31 31
 abstract class AbstractMapping {
32
-	/**
33
-	 * @var \OCP\IDBConnection $dbc
34
-	 */
35
-	protected $dbc;
32
+    /**
33
+     * @var \OCP\IDBConnection $dbc
34
+     */
35
+    protected $dbc;
36 36
 
37
-	/**
38
-	 * returns the DB table name which holds the mappings
39
-	 * @return string
40
-	 */
41
-	abstract protected function getTableName();
37
+    /**
38
+     * returns the DB table name which holds the mappings
39
+     * @return string
40
+     */
41
+    abstract protected function getTableName();
42 42
 
43
-	/**
44
-	 * @param \OCP\IDBConnection $dbc
45
-	 */
46
-	public function __construct(\OCP\IDBConnection $dbc) {
47
-		$this->dbc = $dbc;
48
-	}
43
+    /**
44
+     * @param \OCP\IDBConnection $dbc
45
+     */
46
+    public function __construct(\OCP\IDBConnection $dbc) {
47
+        $this->dbc = $dbc;
48
+    }
49 49
 
50
-	/**
51
-	 * checks whether a provided string represents an existing table col
52
-	 * @param string $col
53
-	 * @return bool
54
-	 */
55
-	public function isColNameValid($col) {
56
-		switch($col) {
57
-			case 'ldap_dn':
58
-			case 'owncloud_name':
59
-			case 'directory_uuid':
60
-				return true;
61
-			default:
62
-				return false;
63
-		}
64
-	}
50
+    /**
51
+     * checks whether a provided string represents an existing table col
52
+     * @param string $col
53
+     * @return bool
54
+     */
55
+    public function isColNameValid($col) {
56
+        switch($col) {
57
+            case 'ldap_dn':
58
+            case 'owncloud_name':
59
+            case 'directory_uuid':
60
+                return true;
61
+            default:
62
+                return false;
63
+        }
64
+    }
65 65
 
66
-	/**
67
-	 * Gets the value of one column based on a provided value of another column
68
-	 * @param string $fetchCol
69
-	 * @param string $compareCol
70
-	 * @param string $search
71
-	 * @throws \Exception
72
-	 * @return string|false
73
-	 */
74
-	protected function getXbyY($fetchCol, $compareCol, $search) {
75
-		if(!$this->isColNameValid($fetchCol)) {
76
-			//this is used internally only, but we don't want to risk
77
-			//having SQL injection at all.
78
-			throw new \Exception('Invalid Column Name');
79
-		}
80
-		$query = $this->dbc->prepare('
66
+    /**
67
+     * Gets the value of one column based on a provided value of another column
68
+     * @param string $fetchCol
69
+     * @param string $compareCol
70
+     * @param string $search
71
+     * @throws \Exception
72
+     * @return string|false
73
+     */
74
+    protected function getXbyY($fetchCol, $compareCol, $search) {
75
+        if(!$this->isColNameValid($fetchCol)) {
76
+            //this is used internally only, but we don't want to risk
77
+            //having SQL injection at all.
78
+            throw new \Exception('Invalid Column Name');
79
+        }
80
+        $query = $this->dbc->prepare('
81 81
 			SELECT `' . $fetchCol . '`
82 82
 			FROM `'. $this->getTableName() .'`
83 83
 			WHERE `' . $compareCol . '` = ?
84 84
 		');
85 85
 
86
-		$res = $query->execute(array($search));
87
-		if($res !== false) {
88
-			return $query->fetchColumn();
89
-		}
86
+        $res = $query->execute(array($search));
87
+        if($res !== false) {
88
+            return $query->fetchColumn();
89
+        }
90 90
 
91
-		return false;
92
-	}
91
+        return false;
92
+    }
93 93
 
94
-	/**
95
-	 * Performs a DELETE or UPDATE query to the database.
96
-	 * @param \Doctrine\DBAL\Driver\Statement $query
97
-	 * @param array $parameters
98
-	 * @return bool true if at least one row was modified, false otherwise
99
-	 */
100
-	protected function modify($query, $parameters) {
101
-		$result = $query->execute($parameters);
102
-		return ($result === true && $query->rowCount() > 0);
103
-	}
94
+    /**
95
+     * Performs a DELETE or UPDATE query to the database.
96
+     * @param \Doctrine\DBAL\Driver\Statement $query
97
+     * @param array $parameters
98
+     * @return bool true if at least one row was modified, false otherwise
99
+     */
100
+    protected function modify($query, $parameters) {
101
+        $result = $query->execute($parameters);
102
+        return ($result === true && $query->rowCount() > 0);
103
+    }
104 104
 
105
-	/**
106
-	 * Gets the LDAP DN based on the provided name.
107
-	 * Replaces Access::ocname2dn
108
-	 * @param string $name
109
-	 * @return string|false
110
-	 */
111
-	public function getDNByName($name) {
112
-		return $this->getXbyY('ldap_dn', 'owncloud_name', $name);
113
-	}
105
+    /**
106
+     * Gets the LDAP DN based on the provided name.
107
+     * Replaces Access::ocname2dn
108
+     * @param string $name
109
+     * @return string|false
110
+     */
111
+    public function getDNByName($name) {
112
+        return $this->getXbyY('ldap_dn', 'owncloud_name', $name);
113
+    }
114 114
 
115
-	/**
116
-	 * Updates the DN based on the given UUID
117
-	 * @param string $fdn
118
-	 * @param string $uuid
119
-	 * @return bool
120
-	 */
121
-	public function setDNbyUUID($fdn, $uuid) {
122
-		$query = $this->dbc->prepare('
115
+    /**
116
+     * Updates the DN based on the given UUID
117
+     * @param string $fdn
118
+     * @param string $uuid
119
+     * @return bool
120
+     */
121
+    public function setDNbyUUID($fdn, $uuid) {
122
+        $query = $this->dbc->prepare('
123 123
 			UPDATE `' . $this->getTableName() . '`
124 124
 			SET `ldap_dn` = ?
125 125
 			WHERE `directory_uuid` = ?
126 126
 		');
127 127
 
128
-		return $this->modify($query, array($fdn, $uuid));
129
-	}
128
+        return $this->modify($query, array($fdn, $uuid));
129
+    }
130 130
 
131
-	/**
132
-	 * Updates the UUID based on the given DN
133
-	 *
134
-	 * required by Migration/UUIDFix
135
-	 *
136
-	 * @param $uuid
137
-	 * @param $fdn
138
-	 * @return bool
139
-	 */
140
-	public function setUUIDbyDN($uuid, $fdn) {
141
-		$query = $this->dbc->prepare('
131
+    /**
132
+     * Updates the UUID based on the given DN
133
+     *
134
+     * required by Migration/UUIDFix
135
+     *
136
+     * @param $uuid
137
+     * @param $fdn
138
+     * @return bool
139
+     */
140
+    public function setUUIDbyDN($uuid, $fdn) {
141
+        $query = $this->dbc->prepare('
142 142
 			UPDATE `' . $this->getTableName() . '`
143 143
 			SET `directory_uuid` = ?
144 144
 			WHERE `ldap_dn` = ?
145 145
 		');
146 146
 
147
-		return $this->modify($query, [$uuid, $fdn]);
148
-	}
147
+        return $this->modify($query, [$uuid, $fdn]);
148
+    }
149 149
 
150
-	/**
151
-	 * Gets the name based on the provided LDAP DN.
152
-	 * @param string $fdn
153
-	 * @return string|false
154
-	 */
155
-	public function getNameByDN($fdn) {
156
-		return $this->getXbyY('owncloud_name', 'ldap_dn', $fdn);
157
-	}
150
+    /**
151
+     * Gets the name based on the provided LDAP DN.
152
+     * @param string $fdn
153
+     * @return string|false
154
+     */
155
+    public function getNameByDN($fdn) {
156
+        return $this->getXbyY('owncloud_name', 'ldap_dn', $fdn);
157
+    }
158 158
 
159
-	/**
160
-	 * Searches mapped names by the giving string in the name column
161
-	 * @param string $search
162
-	 * @param string $prefixMatch
163
-	 * @param string $postfixMatch
164
-	 * @return string[]
165
-	 */
166
-	public function getNamesBySearch($search, $prefixMatch = "", $postfixMatch = "") {
167
-		$query = $this->dbc->prepare('
159
+    /**
160
+     * Searches mapped names by the giving string in the name column
161
+     * @param string $search
162
+     * @param string $prefixMatch
163
+     * @param string $postfixMatch
164
+     * @return string[]
165
+     */
166
+    public function getNamesBySearch($search, $prefixMatch = "", $postfixMatch = "") {
167
+        $query = $this->dbc->prepare('
168 168
 			SELECT `owncloud_name`
169 169
 			FROM `'. $this->getTableName() .'`
170 170
 			WHERE `owncloud_name` LIKE ?
171 171
 		');
172 172
 
173
-		$res = $query->execute(array($prefixMatch.$this->dbc->escapeLikeParameter($search).$postfixMatch));
174
-		$names = array();
175
-		if($res !== false) {
176
-			while($row = $query->fetch()) {
177
-				$names[] = $row['owncloud_name'];
178
-			}
179
-		}
180
-		return $names;
181
-	}
173
+        $res = $query->execute(array($prefixMatch.$this->dbc->escapeLikeParameter($search).$postfixMatch));
174
+        $names = array();
175
+        if($res !== false) {
176
+            while($row = $query->fetch()) {
177
+                $names[] = $row['owncloud_name'];
178
+            }
179
+        }
180
+        return $names;
181
+    }
182 182
 
183
-	/**
184
-	 * Gets the name based on the provided LDAP UUID.
185
-	 * @param string $uuid
186
-	 * @return string|false
187
-	 */
188
-	public function getNameByUUID($uuid) {
189
-		return $this->getXbyY('owncloud_name', 'directory_uuid', $uuid);
190
-	}
183
+    /**
184
+     * Gets the name based on the provided LDAP UUID.
185
+     * @param string $uuid
186
+     * @return string|false
187
+     */
188
+    public function getNameByUUID($uuid) {
189
+        return $this->getXbyY('owncloud_name', 'directory_uuid', $uuid);
190
+    }
191 191
 
192
-	/**
193
-	 * Gets the UUID based on the provided LDAP DN
194
-	 * @param string $dn
195
-	 * @return false|string
196
-	 * @throws \Exception
197
-	 */
198
-	public function getUUIDByDN($dn) {
199
-		return $this->getXbyY('directory_uuid', 'ldap_dn', $dn);
200
-	}
192
+    /**
193
+     * Gets the UUID based on the provided LDAP DN
194
+     * @param string $dn
195
+     * @return false|string
196
+     * @throws \Exception
197
+     */
198
+    public function getUUIDByDN($dn) {
199
+        return $this->getXbyY('directory_uuid', 'ldap_dn', $dn);
200
+    }
201 201
 
202
-	/**
203
-	 * gets a piece of the mapping list
204
-	 * @param int $offset
205
-	 * @param int $limit
206
-	 * @return array
207
-	 */
208
-	public function getList($offset = null, $limit = null) {
209
-		$query = $this->dbc->prepare('
202
+    /**
203
+     * gets a piece of the mapping list
204
+     * @param int $offset
205
+     * @param int $limit
206
+     * @return array
207
+     */
208
+    public function getList($offset = null, $limit = null) {
209
+        $query = $this->dbc->prepare('
210 210
 			SELECT
211 211
 				`ldap_dn` AS `dn`,
212 212
 				`owncloud_name` AS `name`,
213 213
 				`directory_uuid` AS `uuid`
214 214
 			FROM `' . $this->getTableName() . '`',
215
-			$limit,
216
-			$offset
217
-		);
215
+            $limit,
216
+            $offset
217
+        );
218 218
 
219
-		$query->execute();
220
-		return $query->fetchAll();
221
-	}
219
+        $query->execute();
220
+        return $query->fetchAll();
221
+    }
222 222
 
223
-	/**
224
-	 * attempts to map the given entry
225
-	 * @param string $fdn fully distinguished name (from LDAP)
226
-	 * @param string $name
227
-	 * @param string $uuid a unique identifier as used in LDAP
228
-	 * @return bool
229
-	 */
230
-	public function map($fdn, $name, $uuid) {
231
-		if(mb_strlen($fdn) > 255) {
232
-			\OC::$server->getLogger()->error(
233
-				'Cannot map, because the DN exceeds 255 characters: {dn}',
234
-				[
235
-					'app' => 'user_ldap',
236
-					'dn' => $fdn,
237
-				]
238
-			);
239
-			return false;
240
-		}
223
+    /**
224
+     * attempts to map the given entry
225
+     * @param string $fdn fully distinguished name (from LDAP)
226
+     * @param string $name
227
+     * @param string $uuid a unique identifier as used in LDAP
228
+     * @return bool
229
+     */
230
+    public function map($fdn, $name, $uuid) {
231
+        if(mb_strlen($fdn) > 255) {
232
+            \OC::$server->getLogger()->error(
233
+                'Cannot map, because the DN exceeds 255 characters: {dn}',
234
+                [
235
+                    'app' => 'user_ldap',
236
+                    'dn' => $fdn,
237
+                ]
238
+            );
239
+            return false;
240
+        }
241 241
 
242
-		$row = array(
243
-			'ldap_dn'        => $fdn,
244
-			'owncloud_name'  => $name,
245
-			'directory_uuid' => $uuid
246
-		);
242
+        $row = array(
243
+            'ldap_dn'        => $fdn,
244
+            'owncloud_name'  => $name,
245
+            'directory_uuid' => $uuid
246
+        );
247 247
 
248
-		try {
249
-			$result = $this->dbc->insertIfNotExist($this->getTableName(), $row);
250
-			// insertIfNotExist returns values as int
251
-			return (bool)$result;
252
-		} catch (\Exception $e) {
253
-			return false;
254
-		}
255
-	}
248
+        try {
249
+            $result = $this->dbc->insertIfNotExist($this->getTableName(), $row);
250
+            // insertIfNotExist returns values as int
251
+            return (bool)$result;
252
+        } catch (\Exception $e) {
253
+            return false;
254
+        }
255
+    }
256 256
 
257
-	/**
258
-	 * removes a mapping based on the owncloud_name of the entry
259
-	 * @param string $name
260
-	 * @return bool
261
-	 */
262
-	public function unmap($name) {
263
-		$query = $this->dbc->prepare('
257
+    /**
258
+     * removes a mapping based on the owncloud_name of the entry
259
+     * @param string $name
260
+     * @return bool
261
+     */
262
+    public function unmap($name) {
263
+        $query = $this->dbc->prepare('
264 264
 			DELETE FROM `'. $this->getTableName() .'`
265 265
 			WHERE `owncloud_name` = ?');
266 266
 
267
-		return $this->modify($query, array($name));
268
-	}
267
+        return $this->modify($query, array($name));
268
+    }
269 269
 
270
-	/**
271
-	 * Truncate's the mapping table
272
-	 * @return bool
273
-	 */
274
-	public function clear() {
275
-		$sql = $this->dbc
276
-			->getDatabasePlatform()
277
-			->getTruncateTableSQL('`' . $this->getTableName() . '`');
278
-		return $this->dbc->prepare($sql)->execute();
279
-	}
270
+    /**
271
+     * Truncate's the mapping table
272
+     * @return bool
273
+     */
274
+    public function clear() {
275
+        $sql = $this->dbc
276
+            ->getDatabasePlatform()
277
+            ->getTruncateTableSQL('`' . $this->getTableName() . '`');
278
+        return $this->dbc->prepare($sql)->execute();
279
+    }
280 280
 
281
-	/**
282
-	 * returns the number of entries in the mappings table
283
-	 *
284
-	 * @return int
285
-	 */
286
-	public function count() {
287
-		$qb = $this->dbc->getQueryBuilder();
288
-		$query = $qb->select($qb->createFunction('COUNT(`ldap_dn`)'))
289
-			->from($this->getTableName());
290
-		$res = $query->execute();
291
-		$count = $res->fetchColumn();
292
-		$res->closeCursor();
293
-		return (int)$count;
294
-	}
281
+    /**
282
+     * returns the number of entries in the mappings table
283
+     *
284
+     * @return int
285
+     */
286
+    public function count() {
287
+        $qb = $this->dbc->getQueryBuilder();
288
+        $query = $qb->select($qb->createFunction('COUNT(`ldap_dn`)'))
289
+            ->from($this->getTableName());
290
+        $res = $query->execute();
291
+        $count = $res->fetchColumn();
292
+        $res->closeCursor();
293
+        return (int)$count;
294
+    }
295 295
 }
Please login to merge, or discard this patch.
Spacing   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -53,7 +53,7 @@  discard block
 block discarded – undo
53 53
 	 * @return bool
54 54
 	 */
55 55
 	public function isColNameValid($col) {
56
-		switch($col) {
56
+		switch ($col) {
57 57
 			case 'ldap_dn':
58 58
 			case 'owncloud_name':
59 59
 			case 'directory_uuid':
@@ -72,19 +72,19 @@  discard block
 block discarded – undo
72 72
 	 * @return string|false
73 73
 	 */
74 74
 	protected function getXbyY($fetchCol, $compareCol, $search) {
75
-		if(!$this->isColNameValid($fetchCol)) {
75
+		if (!$this->isColNameValid($fetchCol)) {
76 76
 			//this is used internally only, but we don't want to risk
77 77
 			//having SQL injection at all.
78 78
 			throw new \Exception('Invalid Column Name');
79 79
 		}
80 80
 		$query = $this->dbc->prepare('
81
-			SELECT `' . $fetchCol . '`
82
-			FROM `'. $this->getTableName() .'`
83
-			WHERE `' . $compareCol . '` = ?
81
+			SELECT `' . $fetchCol.'`
82
+			FROM `'. $this->getTableName().'`
83
+			WHERE `' . $compareCol.'` = ?
84 84
 		');
85 85
 
86 86
 		$res = $query->execute(array($search));
87
-		if($res !== false) {
87
+		if ($res !== false) {
88 88
 			return $query->fetchColumn();
89 89
 		}
90 90
 
@@ -120,7 +120,7 @@  discard block
 block discarded – undo
120 120
 	 */
121 121
 	public function setDNbyUUID($fdn, $uuid) {
122 122
 		$query = $this->dbc->prepare('
123
-			UPDATE `' . $this->getTableName() . '`
123
+			UPDATE `' . $this->getTableName().'`
124 124
 			SET `ldap_dn` = ?
125 125
 			WHERE `directory_uuid` = ?
126 126
 		');
@@ -139,7 +139,7 @@  discard block
 block discarded – undo
139 139
 	 */
140 140
 	public function setUUIDbyDN($uuid, $fdn) {
141 141
 		$query = $this->dbc->prepare('
142
-			UPDATE `' . $this->getTableName() . '`
142
+			UPDATE `' . $this->getTableName().'`
143 143
 			SET `directory_uuid` = ?
144 144
 			WHERE `ldap_dn` = ?
145 145
 		');
@@ -166,14 +166,14 @@  discard block
 block discarded – undo
166 166
 	public function getNamesBySearch($search, $prefixMatch = "", $postfixMatch = "") {
167 167
 		$query = $this->dbc->prepare('
168 168
 			SELECT `owncloud_name`
169
-			FROM `'. $this->getTableName() .'`
169
+			FROM `'. $this->getTableName().'`
170 170
 			WHERE `owncloud_name` LIKE ?
171 171
 		');
172 172
 
173 173
 		$res = $query->execute(array($prefixMatch.$this->dbc->escapeLikeParameter($search).$postfixMatch));
174 174
 		$names = array();
175
-		if($res !== false) {
176
-			while($row = $query->fetch()) {
175
+		if ($res !== false) {
176
+			while ($row = $query->fetch()) {
177 177
 				$names[] = $row['owncloud_name'];
178 178
 			}
179 179
 		}
@@ -211,7 +211,7 @@  discard block
 block discarded – undo
211 211
 				`ldap_dn` AS `dn`,
212 212
 				`owncloud_name` AS `name`,
213 213
 				`directory_uuid` AS `uuid`
214
-			FROM `' . $this->getTableName() . '`',
214
+			FROM `' . $this->getTableName().'`',
215 215
 			$limit,
216 216
 			$offset
217 217
 		);
@@ -228,7 +228,7 @@  discard block
 block discarded – undo
228 228
 	 * @return bool
229 229
 	 */
230 230
 	public function map($fdn, $name, $uuid) {
231
-		if(mb_strlen($fdn) > 255) {
231
+		if (mb_strlen($fdn) > 255) {
232 232
 			\OC::$server->getLogger()->error(
233 233
 				'Cannot map, because the DN exceeds 255 characters: {dn}',
234 234
 				[
@@ -248,7 +248,7 @@  discard block
 block discarded – undo
248 248
 		try {
249 249
 			$result = $this->dbc->insertIfNotExist($this->getTableName(), $row);
250 250
 			// insertIfNotExist returns values as int
251
-			return (bool)$result;
251
+			return (bool) $result;
252 252
 		} catch (\Exception $e) {
253 253
 			return false;
254 254
 		}
@@ -261,7 +261,7 @@  discard block
 block discarded – undo
261 261
 	 */
262 262
 	public function unmap($name) {
263 263
 		$query = $this->dbc->prepare('
264
-			DELETE FROM `'. $this->getTableName() .'`
264
+			DELETE FROM `'. $this->getTableName().'`
265 265
 			WHERE `owncloud_name` = ?');
266 266
 
267 267
 		return $this->modify($query, array($name));
@@ -274,7 +274,7 @@  discard block
 block discarded – undo
274 274
 	public function clear() {
275 275
 		$sql = $this->dbc
276 276
 			->getDatabasePlatform()
277
-			->getTruncateTableSQL('`' . $this->getTableName() . '`');
277
+			->getTruncateTableSQL('`'.$this->getTableName().'`');
278 278
 		return $this->dbc->prepare($sql)->execute();
279 279
 	}
280 280
 
@@ -290,6 +290,6 @@  discard block
 block discarded – undo
290 290
 		$res = $query->execute();
291 291
 		$count = $res->fetchColumn();
292 292
 		$res->closeCursor();
293
-		return (int)$count;
293
+		return (int) $count;
294 294
 	}
295 295
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Connection.php 2 patches
Indentation   +577 added lines, -577 removed lines patch added patch discarded remove patch
@@ -54,582 +54,582 @@
 block discarded – undo
54 54
  * @property string ldapExpertUUIDGroupAttr
55 55
  */
56 56
 class Connection extends LDAPUtility {
57
-	private $ldapConnectionRes = null;
58
-	private $configPrefix;
59
-	private $configID;
60
-	private $configured = false;
61
-	private $hasPagedResultSupport = true;
62
-	//whether connection should be kept on __destruct
63
-	private $dontDestruct = false;
64
-
65
-	/**
66
-	 * @var bool runtime flag that indicates whether supported primary groups are available
67
-	 */
68
-	public $hasPrimaryGroups = true;
69
-
70
-	/**
71
-	 * @var bool runtime flag that indicates whether supported POSIX gidNumber are available
72
-	 */
73
-	public $hasGidNumber = true;
74
-
75
-	//cache handler
76
-	protected $cache;
77
-
78
-	/** @var Configuration settings handler **/
79
-	protected $configuration;
80
-
81
-	protected $doNotValidate = false;
82
-
83
-	protected $ignoreValidation = false;
84
-
85
-	/**
86
-	 * Constructor
87
-	 * @param ILDAPWrapper $ldap
88
-	 * @param string $configPrefix a string with the prefix for the configkey column (appconfig table)
89
-	 * @param string|null $configID a string with the value for the appid column (appconfig table) or null for on-the-fly connections
90
-	 */
91
-	public function __construct(ILDAPWrapper $ldap, $configPrefix = '', $configID = 'user_ldap') {
92
-		parent::__construct($ldap);
93
-		$this->configPrefix = $configPrefix;
94
-		$this->configID = $configID;
95
-		$this->configuration = new Configuration($configPrefix,
96
-												 !is_null($configID));
97
-		$memcache = \OC::$server->getMemCacheFactory();
98
-		if($memcache->isAvailable()) {
99
-			$this->cache = $memcache->create();
100
-		}
101
-		$helper = new Helper(\OC::$server->getConfig());
102
-		$this->doNotValidate = !in_array($this->configPrefix,
103
-			$helper->getServerConfigurationPrefixes());
104
-		$this->hasPagedResultSupport =
105
-			intval($this->configuration->ldapPagingSize) !== 0
106
-			|| $this->ldap->hasPagedResultSupport();
107
-	}
108
-
109
-	public function __destruct() {
110
-		if(!$this->dontDestruct && $this->ldap->isResource($this->ldapConnectionRes)) {
111
-			@$this->ldap->unbind($this->ldapConnectionRes);
112
-		};
113
-	}
114
-
115
-	/**
116
-	 * defines behaviour when the instance is cloned
117
-	 */
118
-	public function __clone() {
119
-		$this->configuration = new Configuration($this->configPrefix,
120
-												 !is_null($this->configID));
121
-		$this->ldapConnectionRes = null;
122
-		$this->dontDestruct = true;
123
-	}
124
-
125
-	/**
126
-	 * @param string $name
127
-	 * @return bool|mixed
128
-	 */
129
-	public function __get($name) {
130
-		if(!$this->configured) {
131
-			$this->readConfiguration();
132
-		}
133
-
134
-		if($name === 'hasPagedResultSupport') {
135
-			return $this->hasPagedResultSupport;
136
-		}
137
-
138
-		return $this->configuration->$name;
139
-	}
140
-
141
-	/**
142
-	 * @param string $name
143
-	 * @param mixed $value
144
-	 */
145
-	public function __set($name, $value) {
146
-		$this->doNotValidate = false;
147
-		$before = $this->configuration->$name;
148
-		$this->configuration->$name = $value;
149
-		$after = $this->configuration->$name;
150
-		if($before !== $after) {
151
-			if ($this->configID !== '') {
152
-				$this->configuration->saveConfiguration();
153
-			}
154
-			$this->validateConfiguration();
155
-		}
156
-	}
157
-
158
-	/**
159
-	 * sets whether the result of the configuration validation shall
160
-	 * be ignored when establishing the connection. Used by the Wizard
161
-	 * in early configuration state.
162
-	 * @param bool $state
163
-	 */
164
-	public function setIgnoreValidation($state) {
165
-		$this->ignoreValidation = (bool)$state;
166
-	}
167
-
168
-	/**
169
-	 * initializes the LDAP backend
170
-	 * @param bool $force read the config settings no matter what
171
-	 */
172
-	public function init($force = false) {
173
-		$this->readConfiguration($force);
174
-		$this->establishConnection();
175
-	}
176
-
177
-	/**
178
-	 * Returns the LDAP handler
179
-	 */
180
-	public function getConnectionResource() {
181
-		if(!$this->ldapConnectionRes) {
182
-			$this->init();
183
-		} else if(!$this->ldap->isResource($this->ldapConnectionRes)) {
184
-			$this->ldapConnectionRes = null;
185
-			$this->establishConnection();
186
-		}
187
-		if(is_null($this->ldapConnectionRes)) {
188
-			\OCP\Util::writeLog('user_ldap', 'No LDAP Connection to server ' . $this->configuration->ldapHost, \OCP\Util::ERROR);
189
-			throw new ServerNotAvailableException('Connection to LDAP server could not be established');
190
-		}
191
-		return $this->ldapConnectionRes;
192
-	}
193
-
194
-	/**
195
-	 * resets the connection resource
196
-	 */
197
-	public function resetConnectionResource() {
198
-		if(!is_null($this->ldapConnectionRes)) {
199
-			@$this->ldap->unbind($this->ldapConnectionRes);
200
-			$this->ldapConnectionRes = null;
201
-		}
202
-	}
203
-
204
-	/**
205
-	 * @param string|null $key
206
-	 * @return string
207
-	 */
208
-	private function getCacheKey($key) {
209
-		$prefix = 'LDAP-'.$this->configID.'-'.$this->configPrefix.'-';
210
-		if(is_null($key)) {
211
-			return $prefix;
212
-		}
213
-		return $prefix.md5($key);
214
-	}
215
-
216
-	/**
217
-	 * @param string $key
218
-	 * @return mixed|null
219
-	 */
220
-	public function getFromCache($key) {
221
-		if(!$this->configured) {
222
-			$this->readConfiguration();
223
-		}
224
-		if(is_null($this->cache) || !$this->configuration->ldapCacheTTL) {
225
-			return null;
226
-		}
227
-		$key = $this->getCacheKey($key);
228
-
229
-		return json_decode(base64_decode($this->cache->get($key)), true);
230
-	}
231
-
232
-	/**
233
-	 * @param string $key
234
-	 * @param mixed $value
235
-	 *
236
-	 * @return string
237
-	 */
238
-	public function writeToCache($key, $value) {
239
-		if(!$this->configured) {
240
-			$this->readConfiguration();
241
-		}
242
-		if(is_null($this->cache)
243
-			|| !$this->configuration->ldapCacheTTL
244
-			|| !$this->configuration->ldapConfigurationActive) {
245
-			return null;
246
-		}
247
-		$key   = $this->getCacheKey($key);
248
-		$value = base64_encode(json_encode($value));
249
-		$this->cache->set($key, $value, $this->configuration->ldapCacheTTL);
250
-	}
251
-
252
-	public function clearCache() {
253
-		if(!is_null($this->cache)) {
254
-			$this->cache->clear($this->getCacheKey(null));
255
-		}
256
-	}
257
-
258
-	/**
259
-	 * Caches the general LDAP configuration.
260
-	 * @param bool $force optional. true, if the re-read should be forced. defaults
261
-	 * to false.
262
-	 * @return null
263
-	 */
264
-	private function readConfiguration($force = false) {
265
-		if((!$this->configured || $force) && !is_null($this->configID)) {
266
-			$this->configuration->readConfiguration();
267
-			$this->configured = $this->validateConfiguration();
268
-		}
269
-	}
270
-
271
-	/**
272
-	 * set LDAP configuration with values delivered by an array, not read from configuration
273
-	 * @param array $config array that holds the config parameters in an associated array
274
-	 * @param array &$setParameters optional; array where the set fields will be given to
275
-	 * @return boolean true if config validates, false otherwise. Check with $setParameters for detailed success on single parameters
276
-	 */
277
-	public function setConfiguration($config, &$setParameters = null) {
278
-		if(is_null($setParameters)) {
279
-			$setParameters = array();
280
-		}
281
-		$this->doNotValidate = false;
282
-		$this->configuration->setConfiguration($config, $setParameters);
283
-		if(count($setParameters) > 0) {
284
-			$this->configured = $this->validateConfiguration();
285
-		}
286
-
287
-
288
-		return $this->configured;
289
-	}
290
-
291
-	/**
292
-	 * saves the current Configuration in the database and empties the
293
-	 * cache
294
-	 * @return null
295
-	 */
296
-	public function saveConfiguration() {
297
-		$this->configuration->saveConfiguration();
298
-		$this->clearCache();
299
-	}
300
-
301
-	/**
302
-	 * get the current LDAP configuration
303
-	 * @return array
304
-	 */
305
-	public function getConfiguration() {
306
-		$this->readConfiguration();
307
-		$config = $this->configuration->getConfiguration();
308
-		$cta = $this->configuration->getConfigTranslationArray();
309
-		$result = array();
310
-		foreach($cta as $dbkey => $configkey) {
311
-			switch($configkey) {
312
-				case 'homeFolderNamingRule':
313
-					if(strpos($config[$configkey], 'attr:') === 0) {
314
-						$result[$dbkey] = substr($config[$configkey], 5);
315
-					} else {
316
-						$result[$dbkey] = '';
317
-					}
318
-					break;
319
-				case 'ldapBase':
320
-				case 'ldapBaseUsers':
321
-				case 'ldapBaseGroups':
322
-				case 'ldapAttributesForUserSearch':
323
-				case 'ldapAttributesForGroupSearch':
324
-					if(is_array($config[$configkey])) {
325
-						$result[$dbkey] = implode("\n", $config[$configkey]);
326
-						break;
327
-					} //else follows default
328
-				default:
329
-					$result[$dbkey] = $config[$configkey];
330
-			}
331
-		}
332
-		return $result;
333
-	}
334
-
335
-	private function doSoftValidation() {
336
-		//if User or Group Base are not set, take over Base DN setting
337
-		foreach(array('ldapBaseUsers', 'ldapBaseGroups') as $keyBase) {
338
-			$val = $this->configuration->$keyBase;
339
-			if(empty($val)) {
340
-				$this->configuration->$keyBase = $this->configuration->ldapBase;
341
-			}
342
-		}
343
-
344
-		foreach(array('ldapExpertUUIDUserAttr'  => 'ldapUuidUserAttribute',
345
-					  'ldapExpertUUIDGroupAttr' => 'ldapUuidGroupAttribute')
346
-				as $expertSetting => $effectiveSetting) {
347
-			$uuidOverride = $this->configuration->$expertSetting;
348
-			if(!empty($uuidOverride)) {
349
-				$this->configuration->$effectiveSetting = $uuidOverride;
350
-			} else {
351
-				$uuidAttributes = Access::UUID_ATTRIBUTES;
352
-				array_unshift($uuidAttributes, 'auto');
353
-				if(!in_array($this->configuration->$effectiveSetting,
354
-							$uuidAttributes)
355
-					&& (!is_null($this->configID))) {
356
-					$this->configuration->$effectiveSetting = 'auto';
357
-					$this->configuration->saveConfiguration();
358
-					\OCP\Util::writeLog('user_ldap',
359
-										'Illegal value for the '.
360
-										$effectiveSetting.', '.'reset to '.
361
-										'autodetect.', \OCP\Util::INFO);
362
-				}
363
-
364
-			}
365
-		}
366
-
367
-		$backupPort = intval($this->configuration->ldapBackupPort);
368
-		if ($backupPort <= 0) {
369
-			$this->configuration->backupPort = $this->configuration->ldapPort;
370
-		}
371
-
372
-		//make sure empty search attributes are saved as simple, empty array
373
-		$saKeys = array('ldapAttributesForUserSearch',
374
-						'ldapAttributesForGroupSearch');
375
-		foreach($saKeys as $key) {
376
-			$val = $this->configuration->$key;
377
-			if(is_array($val) && count($val) === 1 && empty($val[0])) {
378
-				$this->configuration->$key = array();
379
-			}
380
-		}
381
-
382
-		if((stripos($this->configuration->ldapHost, 'ldaps://') === 0)
383
-			&& $this->configuration->ldapTLS) {
384
-			$this->configuration->ldapTLS = false;
385
-			\OCP\Util::writeLog('user_ldap',
386
-								'LDAPS (already using secure connection) and '.
387
-								'TLS do not work together. Switched off TLS.',
388
-								\OCP\Util::INFO);
389
-		}
390
-	}
391
-
392
-	/**
393
-	 * @return bool
394
-	 */
395
-	private function doCriticalValidation() {
396
-		$configurationOK = true;
397
-		$errorStr = 'Configuration Error (prefix '.
398
-					strval($this->configPrefix).'): ';
399
-
400
-		//options that shall not be empty
401
-		$options = array('ldapHost', 'ldapPort', 'ldapUserDisplayName',
402
-						 'ldapGroupDisplayName', 'ldapLoginFilter');
403
-		foreach($options as $key) {
404
-			$val = $this->configuration->$key;
405
-			if(empty($val)) {
406
-				switch($key) {
407
-					case 'ldapHost':
408
-						$subj = 'LDAP Host';
409
-						break;
410
-					case 'ldapPort':
411
-						$subj = 'LDAP Port';
412
-						break;
413
-					case 'ldapUserDisplayName':
414
-						$subj = 'LDAP User Display Name';
415
-						break;
416
-					case 'ldapGroupDisplayName':
417
-						$subj = 'LDAP Group Display Name';
418
-						break;
419
-					case 'ldapLoginFilter':
420
-						$subj = 'LDAP Login Filter';
421
-						break;
422
-					default:
423
-						$subj = $key;
424
-						break;
425
-				}
426
-				$configurationOK = false;
427
-				\OCP\Util::writeLog('user_ldap',
428
-									$errorStr.'No '.$subj.' given!',
429
-									\OCP\Util::WARN);
430
-			}
431
-		}
432
-
433
-		//combinations
434
-		$agent = $this->configuration->ldapAgentName;
435
-		$pwd = $this->configuration->ldapAgentPassword;
436
-		if (
437
-			($agent === ''  && $pwd !== '')
438
-			|| ($agent !== '' && $pwd === '')
439
-		) {
440
-			\OCP\Util::writeLog('user_ldap',
441
-								$errorStr.'either no password is given for the '.
442
-								'user agent or a password is given, but not an '.
443
-								'LDAP agent.',
444
-				\OCP\Util::WARN);
445
-			$configurationOK = false;
446
-		}
447
-
448
-		$base = $this->configuration->ldapBase;
449
-		$baseUsers = $this->configuration->ldapBaseUsers;
450
-		$baseGroups = $this->configuration->ldapBaseGroups;
451
-
452
-		if(empty($base) && empty($baseUsers) && empty($baseGroups)) {
453
-			\OCP\Util::writeLog('user_ldap',
454
-								$errorStr.'Not a single Base DN given.',
455
-								\OCP\Util::WARN);
456
-			$configurationOK = false;
457
-		}
458
-
459
-		if(mb_strpos($this->configuration->ldapLoginFilter, '%uid', 0, 'UTF-8')
460
-		   === false) {
461
-			\OCP\Util::writeLog('user_ldap',
462
-								$errorStr.'login filter does not contain %uid '.
463
-								'place holder.',
464
-								\OCP\Util::WARN);
465
-			$configurationOK = false;
466
-		}
467
-
468
-		return $configurationOK;
469
-	}
470
-
471
-	/**
472
-	 * Validates the user specified configuration
473
-	 * @return bool true if configuration seems OK, false otherwise
474
-	 */
475
-	private function validateConfiguration() {
476
-
477
-		if($this->doNotValidate) {
478
-			//don't do a validation if it is a new configuration with pure
479
-			//default values. Will be allowed on changes via __set or
480
-			//setConfiguration
481
-			return false;
482
-		}
483
-
484
-		// first step: "soft" checks: settings that are not really
485
-		// necessary, but advisable. If left empty, give an info message
486
-		$this->doSoftValidation();
487
-
488
-		//second step: critical checks. If left empty or filled wrong, mark as
489
-		//not configured and give a warning.
490
-		return $this->doCriticalValidation();
491
-	}
492
-
493
-
494
-	/**
495
-	 * Connects and Binds to LDAP
496
-	 */
497
-	private function establishConnection() {
498
-		if(!$this->configuration->ldapConfigurationActive) {
499
-			return null;
500
-		}
501
-		static $phpLDAPinstalled = true;
502
-		if(!$phpLDAPinstalled) {
503
-			return false;
504
-		}
505
-		if(!$this->ignoreValidation && !$this->configured) {
506
-			\OCP\Util::writeLog('user_ldap',
507
-								'Configuration is invalid, cannot connect',
508
-								\OCP\Util::WARN);
509
-			return false;
510
-		}
511
-		if(!$this->ldapConnectionRes) {
512
-			if(!$this->ldap->areLDAPFunctionsAvailable()) {
513
-				$phpLDAPinstalled = false;
514
-				\OCP\Util::writeLog('user_ldap',
515
-									'function ldap_connect is not available. Make '.
516
-									'sure that the PHP ldap module is installed.',
517
-									\OCP\Util::ERROR);
518
-
519
-				return false;
520
-			}
521
-			if($this->configuration->turnOffCertCheck) {
522
-				if(putenv('LDAPTLS_REQCERT=never')) {
523
-					\OCP\Util::writeLog('user_ldap',
524
-						'Turned off SSL certificate validation successfully.',
525
-						\OCP\Util::DEBUG);
526
-				} else {
527
-					\OCP\Util::writeLog('user_ldap',
528
-										'Could not turn off SSL certificate validation.',
529
-										\OCP\Util::WARN);
530
-				}
531
-			}
532
-
533
-			$isOverrideMainServer = ($this->configuration->ldapOverrideMainServer
534
-				|| $this->getFromCache('overrideMainServer'));
535
-			$isBackupHost = (trim($this->configuration->ldapBackupHost) !== "");
536
-			$bindStatus = false;
537
-			$error = -1;
538
-			try {
539
-				if (!$isOverrideMainServer) {
540
-					$this->doConnect($this->configuration->ldapHost,
541
-						$this->configuration->ldapPort);
542
-					$bindStatus = $this->bind();
543
-					$error = $this->ldap->isResource($this->ldapConnectionRes) ?
544
-						$this->ldap->errno($this->ldapConnectionRes) : -1;
545
-				}
546
-				if($bindStatus === true) {
547
-					return $bindStatus;
548
-				}
549
-			} catch (ServerNotAvailableException $e) {
550
-				if(!$isBackupHost) {
551
-					throw $e;
552
-				}
553
-			}
554
-
555
-			//if LDAP server is not reachable, try the Backup (Replica!) Server
556
-			if($isBackupHost && ($error !== 0 || $isOverrideMainServer)) {
557
-				$this->doConnect($this->configuration->ldapBackupHost,
558
-								 $this->configuration->ldapBackupPort);
559
-				$bindStatus = $this->bind();
560
-				$error = $this->ldap->isResource($this->ldapConnectionRes) ?
561
-					$this->ldap->errno($this->ldapConnectionRes) : -1;
562
-				if($bindStatus && $error === 0 && !$this->getFromCache('overrideMainServer')) {
563
-					//when bind to backup server succeeded and failed to main server,
564
-					//skip contacting him until next cache refresh
565
-					$this->writeToCache('overrideMainServer', true);
566
-				}
567
-			}
568
-
569
-			return $bindStatus;
570
-		}
571
-		return null;
572
-	}
573
-
574
-	/**
575
-	 * @param string $host
576
-	 * @param string $port
577
-	 * @return bool
578
-	 * @throws \OC\ServerNotAvailableException
579
-	 */
580
-	private function doConnect($host, $port) {
581
-		if ($host === '') {
582
-			return false;
583
-		}
584
-
585
-		$this->ldapConnectionRes = $this->ldap->connect($host, $port);
586
-
587
-		if(!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_PROTOCOL_VERSION, 3)) {
588
-			throw new ServerNotAvailableException('Could not set required LDAP Protocol version.');
589
-		}
590
-
591
-		if(!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_REFERRALS, 0)) {
592
-			throw new ServerNotAvailableException('Could not disable LDAP referrals.');
593
-		}
594
-
595
-		if($this->configuration->ldapTLS) {
596
-			if(!$this->ldap->startTls($this->ldapConnectionRes)) {
597
-				throw new ServerNotAvailableException('Start TLS failed, when connecting to LDAP host ' . $host . '.');
598
-			}
599
-		}
600
-
601
-		return true;
602
-	}
603
-
604
-	/**
605
-	 * Binds to LDAP
606
-	 */
607
-	public function bind() {
608
-		if(!$this->configuration->ldapConfigurationActive) {
609
-			return false;
610
-		}
611
-		$cr = $this->getConnectionResource();
612
-		if(!$this->ldap->isResource($cr)) {
613
-			return false;
614
-		}
615
-		$ldapLogin = @$this->ldap->bind($cr,
616
-										$this->configuration->ldapAgentName,
617
-										$this->configuration->ldapAgentPassword);
618
-		if(!$ldapLogin) {
619
-			$errno = $this->ldap->errno($cr);
620
-
621
-			\OCP\Util::writeLog('user_ldap',
622
-				'Bind failed: ' . $errno . ': ' . $this->ldap->error($cr),
623
-				\OCP\Util::WARN);
624
-
625
-			// Set to failure mode, if LDAP error code is not LDAP_SUCCESS or LDAP_INVALID_CREDENTIALS
626
-			if($errno !== 0x00 && $errno !== 0x31) {
627
-				$this->ldapConnectionRes = null;
628
-			}
629
-
630
-			return false;
631
-		}
632
-		return true;
633
-	}
57
+    private $ldapConnectionRes = null;
58
+    private $configPrefix;
59
+    private $configID;
60
+    private $configured = false;
61
+    private $hasPagedResultSupport = true;
62
+    //whether connection should be kept on __destruct
63
+    private $dontDestruct = false;
64
+
65
+    /**
66
+     * @var bool runtime flag that indicates whether supported primary groups are available
67
+     */
68
+    public $hasPrimaryGroups = true;
69
+
70
+    /**
71
+     * @var bool runtime flag that indicates whether supported POSIX gidNumber are available
72
+     */
73
+    public $hasGidNumber = true;
74
+
75
+    //cache handler
76
+    protected $cache;
77
+
78
+    /** @var Configuration settings handler **/
79
+    protected $configuration;
80
+
81
+    protected $doNotValidate = false;
82
+
83
+    protected $ignoreValidation = false;
84
+
85
+    /**
86
+     * Constructor
87
+     * @param ILDAPWrapper $ldap
88
+     * @param string $configPrefix a string with the prefix for the configkey column (appconfig table)
89
+     * @param string|null $configID a string with the value for the appid column (appconfig table) or null for on-the-fly connections
90
+     */
91
+    public function __construct(ILDAPWrapper $ldap, $configPrefix = '', $configID = 'user_ldap') {
92
+        parent::__construct($ldap);
93
+        $this->configPrefix = $configPrefix;
94
+        $this->configID = $configID;
95
+        $this->configuration = new Configuration($configPrefix,
96
+                                                    !is_null($configID));
97
+        $memcache = \OC::$server->getMemCacheFactory();
98
+        if($memcache->isAvailable()) {
99
+            $this->cache = $memcache->create();
100
+        }
101
+        $helper = new Helper(\OC::$server->getConfig());
102
+        $this->doNotValidate = !in_array($this->configPrefix,
103
+            $helper->getServerConfigurationPrefixes());
104
+        $this->hasPagedResultSupport =
105
+            intval($this->configuration->ldapPagingSize) !== 0
106
+            || $this->ldap->hasPagedResultSupport();
107
+    }
108
+
109
+    public function __destruct() {
110
+        if(!$this->dontDestruct && $this->ldap->isResource($this->ldapConnectionRes)) {
111
+            @$this->ldap->unbind($this->ldapConnectionRes);
112
+        };
113
+    }
114
+
115
+    /**
116
+     * defines behaviour when the instance is cloned
117
+     */
118
+    public function __clone() {
119
+        $this->configuration = new Configuration($this->configPrefix,
120
+                                                    !is_null($this->configID));
121
+        $this->ldapConnectionRes = null;
122
+        $this->dontDestruct = true;
123
+    }
124
+
125
+    /**
126
+     * @param string $name
127
+     * @return bool|mixed
128
+     */
129
+    public function __get($name) {
130
+        if(!$this->configured) {
131
+            $this->readConfiguration();
132
+        }
133
+
134
+        if($name === 'hasPagedResultSupport') {
135
+            return $this->hasPagedResultSupport;
136
+        }
137
+
138
+        return $this->configuration->$name;
139
+    }
140
+
141
+    /**
142
+     * @param string $name
143
+     * @param mixed $value
144
+     */
145
+    public function __set($name, $value) {
146
+        $this->doNotValidate = false;
147
+        $before = $this->configuration->$name;
148
+        $this->configuration->$name = $value;
149
+        $after = $this->configuration->$name;
150
+        if($before !== $after) {
151
+            if ($this->configID !== '') {
152
+                $this->configuration->saveConfiguration();
153
+            }
154
+            $this->validateConfiguration();
155
+        }
156
+    }
157
+
158
+    /**
159
+     * sets whether the result of the configuration validation shall
160
+     * be ignored when establishing the connection. Used by the Wizard
161
+     * in early configuration state.
162
+     * @param bool $state
163
+     */
164
+    public function setIgnoreValidation($state) {
165
+        $this->ignoreValidation = (bool)$state;
166
+    }
167
+
168
+    /**
169
+     * initializes the LDAP backend
170
+     * @param bool $force read the config settings no matter what
171
+     */
172
+    public function init($force = false) {
173
+        $this->readConfiguration($force);
174
+        $this->establishConnection();
175
+    }
176
+
177
+    /**
178
+     * Returns the LDAP handler
179
+     */
180
+    public function getConnectionResource() {
181
+        if(!$this->ldapConnectionRes) {
182
+            $this->init();
183
+        } else if(!$this->ldap->isResource($this->ldapConnectionRes)) {
184
+            $this->ldapConnectionRes = null;
185
+            $this->establishConnection();
186
+        }
187
+        if(is_null($this->ldapConnectionRes)) {
188
+            \OCP\Util::writeLog('user_ldap', 'No LDAP Connection to server ' . $this->configuration->ldapHost, \OCP\Util::ERROR);
189
+            throw new ServerNotAvailableException('Connection to LDAP server could not be established');
190
+        }
191
+        return $this->ldapConnectionRes;
192
+    }
193
+
194
+    /**
195
+     * resets the connection resource
196
+     */
197
+    public function resetConnectionResource() {
198
+        if(!is_null($this->ldapConnectionRes)) {
199
+            @$this->ldap->unbind($this->ldapConnectionRes);
200
+            $this->ldapConnectionRes = null;
201
+        }
202
+    }
203
+
204
+    /**
205
+     * @param string|null $key
206
+     * @return string
207
+     */
208
+    private function getCacheKey($key) {
209
+        $prefix = 'LDAP-'.$this->configID.'-'.$this->configPrefix.'-';
210
+        if(is_null($key)) {
211
+            return $prefix;
212
+        }
213
+        return $prefix.md5($key);
214
+    }
215
+
216
+    /**
217
+     * @param string $key
218
+     * @return mixed|null
219
+     */
220
+    public function getFromCache($key) {
221
+        if(!$this->configured) {
222
+            $this->readConfiguration();
223
+        }
224
+        if(is_null($this->cache) || !$this->configuration->ldapCacheTTL) {
225
+            return null;
226
+        }
227
+        $key = $this->getCacheKey($key);
228
+
229
+        return json_decode(base64_decode($this->cache->get($key)), true);
230
+    }
231
+
232
+    /**
233
+     * @param string $key
234
+     * @param mixed $value
235
+     *
236
+     * @return string
237
+     */
238
+    public function writeToCache($key, $value) {
239
+        if(!$this->configured) {
240
+            $this->readConfiguration();
241
+        }
242
+        if(is_null($this->cache)
243
+            || !$this->configuration->ldapCacheTTL
244
+            || !$this->configuration->ldapConfigurationActive) {
245
+            return null;
246
+        }
247
+        $key   = $this->getCacheKey($key);
248
+        $value = base64_encode(json_encode($value));
249
+        $this->cache->set($key, $value, $this->configuration->ldapCacheTTL);
250
+    }
251
+
252
+    public function clearCache() {
253
+        if(!is_null($this->cache)) {
254
+            $this->cache->clear($this->getCacheKey(null));
255
+        }
256
+    }
257
+
258
+    /**
259
+     * Caches the general LDAP configuration.
260
+     * @param bool $force optional. true, if the re-read should be forced. defaults
261
+     * to false.
262
+     * @return null
263
+     */
264
+    private function readConfiguration($force = false) {
265
+        if((!$this->configured || $force) && !is_null($this->configID)) {
266
+            $this->configuration->readConfiguration();
267
+            $this->configured = $this->validateConfiguration();
268
+        }
269
+    }
270
+
271
+    /**
272
+     * set LDAP configuration with values delivered by an array, not read from configuration
273
+     * @param array $config array that holds the config parameters in an associated array
274
+     * @param array &$setParameters optional; array where the set fields will be given to
275
+     * @return boolean true if config validates, false otherwise. Check with $setParameters for detailed success on single parameters
276
+     */
277
+    public function setConfiguration($config, &$setParameters = null) {
278
+        if(is_null($setParameters)) {
279
+            $setParameters = array();
280
+        }
281
+        $this->doNotValidate = false;
282
+        $this->configuration->setConfiguration($config, $setParameters);
283
+        if(count($setParameters) > 0) {
284
+            $this->configured = $this->validateConfiguration();
285
+        }
286
+
287
+
288
+        return $this->configured;
289
+    }
290
+
291
+    /**
292
+     * saves the current Configuration in the database and empties the
293
+     * cache
294
+     * @return null
295
+     */
296
+    public function saveConfiguration() {
297
+        $this->configuration->saveConfiguration();
298
+        $this->clearCache();
299
+    }
300
+
301
+    /**
302
+     * get the current LDAP configuration
303
+     * @return array
304
+     */
305
+    public function getConfiguration() {
306
+        $this->readConfiguration();
307
+        $config = $this->configuration->getConfiguration();
308
+        $cta = $this->configuration->getConfigTranslationArray();
309
+        $result = array();
310
+        foreach($cta as $dbkey => $configkey) {
311
+            switch($configkey) {
312
+                case 'homeFolderNamingRule':
313
+                    if(strpos($config[$configkey], 'attr:') === 0) {
314
+                        $result[$dbkey] = substr($config[$configkey], 5);
315
+                    } else {
316
+                        $result[$dbkey] = '';
317
+                    }
318
+                    break;
319
+                case 'ldapBase':
320
+                case 'ldapBaseUsers':
321
+                case 'ldapBaseGroups':
322
+                case 'ldapAttributesForUserSearch':
323
+                case 'ldapAttributesForGroupSearch':
324
+                    if(is_array($config[$configkey])) {
325
+                        $result[$dbkey] = implode("\n", $config[$configkey]);
326
+                        break;
327
+                    } //else follows default
328
+                default:
329
+                    $result[$dbkey] = $config[$configkey];
330
+            }
331
+        }
332
+        return $result;
333
+    }
334
+
335
+    private function doSoftValidation() {
336
+        //if User or Group Base are not set, take over Base DN setting
337
+        foreach(array('ldapBaseUsers', 'ldapBaseGroups') as $keyBase) {
338
+            $val = $this->configuration->$keyBase;
339
+            if(empty($val)) {
340
+                $this->configuration->$keyBase = $this->configuration->ldapBase;
341
+            }
342
+        }
343
+
344
+        foreach(array('ldapExpertUUIDUserAttr'  => 'ldapUuidUserAttribute',
345
+                        'ldapExpertUUIDGroupAttr' => 'ldapUuidGroupAttribute')
346
+                as $expertSetting => $effectiveSetting) {
347
+            $uuidOverride = $this->configuration->$expertSetting;
348
+            if(!empty($uuidOverride)) {
349
+                $this->configuration->$effectiveSetting = $uuidOverride;
350
+            } else {
351
+                $uuidAttributes = Access::UUID_ATTRIBUTES;
352
+                array_unshift($uuidAttributes, 'auto');
353
+                if(!in_array($this->configuration->$effectiveSetting,
354
+                            $uuidAttributes)
355
+                    && (!is_null($this->configID))) {
356
+                    $this->configuration->$effectiveSetting = 'auto';
357
+                    $this->configuration->saveConfiguration();
358
+                    \OCP\Util::writeLog('user_ldap',
359
+                                        'Illegal value for the '.
360
+                                        $effectiveSetting.', '.'reset to '.
361
+                                        'autodetect.', \OCP\Util::INFO);
362
+                }
363
+
364
+            }
365
+        }
366
+
367
+        $backupPort = intval($this->configuration->ldapBackupPort);
368
+        if ($backupPort <= 0) {
369
+            $this->configuration->backupPort = $this->configuration->ldapPort;
370
+        }
371
+
372
+        //make sure empty search attributes are saved as simple, empty array
373
+        $saKeys = array('ldapAttributesForUserSearch',
374
+                        'ldapAttributesForGroupSearch');
375
+        foreach($saKeys as $key) {
376
+            $val = $this->configuration->$key;
377
+            if(is_array($val) && count($val) === 1 && empty($val[0])) {
378
+                $this->configuration->$key = array();
379
+            }
380
+        }
381
+
382
+        if((stripos($this->configuration->ldapHost, 'ldaps://') === 0)
383
+            && $this->configuration->ldapTLS) {
384
+            $this->configuration->ldapTLS = false;
385
+            \OCP\Util::writeLog('user_ldap',
386
+                                'LDAPS (already using secure connection) and '.
387
+                                'TLS do not work together. Switched off TLS.',
388
+                                \OCP\Util::INFO);
389
+        }
390
+    }
391
+
392
+    /**
393
+     * @return bool
394
+     */
395
+    private function doCriticalValidation() {
396
+        $configurationOK = true;
397
+        $errorStr = 'Configuration Error (prefix '.
398
+                    strval($this->configPrefix).'): ';
399
+
400
+        //options that shall not be empty
401
+        $options = array('ldapHost', 'ldapPort', 'ldapUserDisplayName',
402
+                            'ldapGroupDisplayName', 'ldapLoginFilter');
403
+        foreach($options as $key) {
404
+            $val = $this->configuration->$key;
405
+            if(empty($val)) {
406
+                switch($key) {
407
+                    case 'ldapHost':
408
+                        $subj = 'LDAP Host';
409
+                        break;
410
+                    case 'ldapPort':
411
+                        $subj = 'LDAP Port';
412
+                        break;
413
+                    case 'ldapUserDisplayName':
414
+                        $subj = 'LDAP User Display Name';
415
+                        break;
416
+                    case 'ldapGroupDisplayName':
417
+                        $subj = 'LDAP Group Display Name';
418
+                        break;
419
+                    case 'ldapLoginFilter':
420
+                        $subj = 'LDAP Login Filter';
421
+                        break;
422
+                    default:
423
+                        $subj = $key;
424
+                        break;
425
+                }
426
+                $configurationOK = false;
427
+                \OCP\Util::writeLog('user_ldap',
428
+                                    $errorStr.'No '.$subj.' given!',
429
+                                    \OCP\Util::WARN);
430
+            }
431
+        }
432
+
433
+        //combinations
434
+        $agent = $this->configuration->ldapAgentName;
435
+        $pwd = $this->configuration->ldapAgentPassword;
436
+        if (
437
+            ($agent === ''  && $pwd !== '')
438
+            || ($agent !== '' && $pwd === '')
439
+        ) {
440
+            \OCP\Util::writeLog('user_ldap',
441
+                                $errorStr.'either no password is given for the '.
442
+                                'user agent or a password is given, but not an '.
443
+                                'LDAP agent.',
444
+                \OCP\Util::WARN);
445
+            $configurationOK = false;
446
+        }
447
+
448
+        $base = $this->configuration->ldapBase;
449
+        $baseUsers = $this->configuration->ldapBaseUsers;
450
+        $baseGroups = $this->configuration->ldapBaseGroups;
451
+
452
+        if(empty($base) && empty($baseUsers) && empty($baseGroups)) {
453
+            \OCP\Util::writeLog('user_ldap',
454
+                                $errorStr.'Not a single Base DN given.',
455
+                                \OCP\Util::WARN);
456
+            $configurationOK = false;
457
+        }
458
+
459
+        if(mb_strpos($this->configuration->ldapLoginFilter, '%uid', 0, 'UTF-8')
460
+            === false) {
461
+            \OCP\Util::writeLog('user_ldap',
462
+                                $errorStr.'login filter does not contain %uid '.
463
+                                'place holder.',
464
+                                \OCP\Util::WARN);
465
+            $configurationOK = false;
466
+        }
467
+
468
+        return $configurationOK;
469
+    }
470
+
471
+    /**
472
+     * Validates the user specified configuration
473
+     * @return bool true if configuration seems OK, false otherwise
474
+     */
475
+    private function validateConfiguration() {
476
+
477
+        if($this->doNotValidate) {
478
+            //don't do a validation if it is a new configuration with pure
479
+            //default values. Will be allowed on changes via __set or
480
+            //setConfiguration
481
+            return false;
482
+        }
483
+
484
+        // first step: "soft" checks: settings that are not really
485
+        // necessary, but advisable. If left empty, give an info message
486
+        $this->doSoftValidation();
487
+
488
+        //second step: critical checks. If left empty or filled wrong, mark as
489
+        //not configured and give a warning.
490
+        return $this->doCriticalValidation();
491
+    }
492
+
493
+
494
+    /**
495
+     * Connects and Binds to LDAP
496
+     */
497
+    private function establishConnection() {
498
+        if(!$this->configuration->ldapConfigurationActive) {
499
+            return null;
500
+        }
501
+        static $phpLDAPinstalled = true;
502
+        if(!$phpLDAPinstalled) {
503
+            return false;
504
+        }
505
+        if(!$this->ignoreValidation && !$this->configured) {
506
+            \OCP\Util::writeLog('user_ldap',
507
+                                'Configuration is invalid, cannot connect',
508
+                                \OCP\Util::WARN);
509
+            return false;
510
+        }
511
+        if(!$this->ldapConnectionRes) {
512
+            if(!$this->ldap->areLDAPFunctionsAvailable()) {
513
+                $phpLDAPinstalled = false;
514
+                \OCP\Util::writeLog('user_ldap',
515
+                                    'function ldap_connect is not available. Make '.
516
+                                    'sure that the PHP ldap module is installed.',
517
+                                    \OCP\Util::ERROR);
518
+
519
+                return false;
520
+            }
521
+            if($this->configuration->turnOffCertCheck) {
522
+                if(putenv('LDAPTLS_REQCERT=never')) {
523
+                    \OCP\Util::writeLog('user_ldap',
524
+                        'Turned off SSL certificate validation successfully.',
525
+                        \OCP\Util::DEBUG);
526
+                } else {
527
+                    \OCP\Util::writeLog('user_ldap',
528
+                                        'Could not turn off SSL certificate validation.',
529
+                                        \OCP\Util::WARN);
530
+                }
531
+            }
532
+
533
+            $isOverrideMainServer = ($this->configuration->ldapOverrideMainServer
534
+                || $this->getFromCache('overrideMainServer'));
535
+            $isBackupHost = (trim($this->configuration->ldapBackupHost) !== "");
536
+            $bindStatus = false;
537
+            $error = -1;
538
+            try {
539
+                if (!$isOverrideMainServer) {
540
+                    $this->doConnect($this->configuration->ldapHost,
541
+                        $this->configuration->ldapPort);
542
+                    $bindStatus = $this->bind();
543
+                    $error = $this->ldap->isResource($this->ldapConnectionRes) ?
544
+                        $this->ldap->errno($this->ldapConnectionRes) : -1;
545
+                }
546
+                if($bindStatus === true) {
547
+                    return $bindStatus;
548
+                }
549
+            } catch (ServerNotAvailableException $e) {
550
+                if(!$isBackupHost) {
551
+                    throw $e;
552
+                }
553
+            }
554
+
555
+            //if LDAP server is not reachable, try the Backup (Replica!) Server
556
+            if($isBackupHost && ($error !== 0 || $isOverrideMainServer)) {
557
+                $this->doConnect($this->configuration->ldapBackupHost,
558
+                                    $this->configuration->ldapBackupPort);
559
+                $bindStatus = $this->bind();
560
+                $error = $this->ldap->isResource($this->ldapConnectionRes) ?
561
+                    $this->ldap->errno($this->ldapConnectionRes) : -1;
562
+                if($bindStatus && $error === 0 && !$this->getFromCache('overrideMainServer')) {
563
+                    //when bind to backup server succeeded and failed to main server,
564
+                    //skip contacting him until next cache refresh
565
+                    $this->writeToCache('overrideMainServer', true);
566
+                }
567
+            }
568
+
569
+            return $bindStatus;
570
+        }
571
+        return null;
572
+    }
573
+
574
+    /**
575
+     * @param string $host
576
+     * @param string $port
577
+     * @return bool
578
+     * @throws \OC\ServerNotAvailableException
579
+     */
580
+    private function doConnect($host, $port) {
581
+        if ($host === '') {
582
+            return false;
583
+        }
584
+
585
+        $this->ldapConnectionRes = $this->ldap->connect($host, $port);
586
+
587
+        if(!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_PROTOCOL_VERSION, 3)) {
588
+            throw new ServerNotAvailableException('Could not set required LDAP Protocol version.');
589
+        }
590
+
591
+        if(!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_REFERRALS, 0)) {
592
+            throw new ServerNotAvailableException('Could not disable LDAP referrals.');
593
+        }
594
+
595
+        if($this->configuration->ldapTLS) {
596
+            if(!$this->ldap->startTls($this->ldapConnectionRes)) {
597
+                throw new ServerNotAvailableException('Start TLS failed, when connecting to LDAP host ' . $host . '.');
598
+            }
599
+        }
600
+
601
+        return true;
602
+    }
603
+
604
+    /**
605
+     * Binds to LDAP
606
+     */
607
+    public function bind() {
608
+        if(!$this->configuration->ldapConfigurationActive) {
609
+            return false;
610
+        }
611
+        $cr = $this->getConnectionResource();
612
+        if(!$this->ldap->isResource($cr)) {
613
+            return false;
614
+        }
615
+        $ldapLogin = @$this->ldap->bind($cr,
616
+                                        $this->configuration->ldapAgentName,
617
+                                        $this->configuration->ldapAgentPassword);
618
+        if(!$ldapLogin) {
619
+            $errno = $this->ldap->errno($cr);
620
+
621
+            \OCP\Util::writeLog('user_ldap',
622
+                'Bind failed: ' . $errno . ': ' . $this->ldap->error($cr),
623
+                \OCP\Util::WARN);
624
+
625
+            // Set to failure mode, if LDAP error code is not LDAP_SUCCESS or LDAP_INVALID_CREDENTIALS
626
+            if($errno !== 0x00 && $errno !== 0x31) {
627
+                $this->ldapConnectionRes = null;
628
+            }
629
+
630
+            return false;
631
+        }
632
+        return true;
633
+    }
634 634
 
635 635
 }
Please login to merge, or discard this patch.
Spacing   +60 added lines, -60 removed lines patch added patch discarded remove patch
@@ -95,7 +95,7 @@  discard block
 block discarded – undo
95 95
 		$this->configuration = new Configuration($configPrefix,
96 96
 												 !is_null($configID));
97 97
 		$memcache = \OC::$server->getMemCacheFactory();
98
-		if($memcache->isAvailable()) {
98
+		if ($memcache->isAvailable()) {
99 99
 			$this->cache = $memcache->create();
100 100
 		}
101 101
 		$helper = new Helper(\OC::$server->getConfig());
@@ -107,7 +107,7 @@  discard block
 block discarded – undo
107 107
 	}
108 108
 
109 109
 	public function __destruct() {
110
-		if(!$this->dontDestruct && $this->ldap->isResource($this->ldapConnectionRes)) {
110
+		if (!$this->dontDestruct && $this->ldap->isResource($this->ldapConnectionRes)) {
111 111
 			@$this->ldap->unbind($this->ldapConnectionRes);
112 112
 		};
113 113
 	}
@@ -127,11 +127,11 @@  discard block
 block discarded – undo
127 127
 	 * @return bool|mixed
128 128
 	 */
129 129
 	public function __get($name) {
130
-		if(!$this->configured) {
130
+		if (!$this->configured) {
131 131
 			$this->readConfiguration();
132 132
 		}
133 133
 
134
-		if($name === 'hasPagedResultSupport') {
134
+		if ($name === 'hasPagedResultSupport') {
135 135
 			return $this->hasPagedResultSupport;
136 136
 		}
137 137
 
@@ -147,7 +147,7 @@  discard block
 block discarded – undo
147 147
 		$before = $this->configuration->$name;
148 148
 		$this->configuration->$name = $value;
149 149
 		$after = $this->configuration->$name;
150
-		if($before !== $after) {
150
+		if ($before !== $after) {
151 151
 			if ($this->configID !== '') {
152 152
 				$this->configuration->saveConfiguration();
153 153
 			}
@@ -162,7 +162,7 @@  discard block
 block discarded – undo
162 162
 	 * @param bool $state
163 163
 	 */
164 164
 	public function setIgnoreValidation($state) {
165
-		$this->ignoreValidation = (bool)$state;
165
+		$this->ignoreValidation = (bool) $state;
166 166
 	}
167 167
 
168 168
 	/**
@@ -178,14 +178,14 @@  discard block
 block discarded – undo
178 178
 	 * Returns the LDAP handler
179 179
 	 */
180 180
 	public function getConnectionResource() {
181
-		if(!$this->ldapConnectionRes) {
181
+		if (!$this->ldapConnectionRes) {
182 182
 			$this->init();
183
-		} else if(!$this->ldap->isResource($this->ldapConnectionRes)) {
183
+		} else if (!$this->ldap->isResource($this->ldapConnectionRes)) {
184 184
 			$this->ldapConnectionRes = null;
185 185
 			$this->establishConnection();
186 186
 		}
187
-		if(is_null($this->ldapConnectionRes)) {
188
-			\OCP\Util::writeLog('user_ldap', 'No LDAP Connection to server ' . $this->configuration->ldapHost, \OCP\Util::ERROR);
187
+		if (is_null($this->ldapConnectionRes)) {
188
+			\OCP\Util::writeLog('user_ldap', 'No LDAP Connection to server '.$this->configuration->ldapHost, \OCP\Util::ERROR);
189 189
 			throw new ServerNotAvailableException('Connection to LDAP server could not be established');
190 190
 		}
191 191
 		return $this->ldapConnectionRes;
@@ -195,7 +195,7 @@  discard block
 block discarded – undo
195 195
 	 * resets the connection resource
196 196
 	 */
197 197
 	public function resetConnectionResource() {
198
-		if(!is_null($this->ldapConnectionRes)) {
198
+		if (!is_null($this->ldapConnectionRes)) {
199 199
 			@$this->ldap->unbind($this->ldapConnectionRes);
200 200
 			$this->ldapConnectionRes = null;
201 201
 		}
@@ -207,7 +207,7 @@  discard block
 block discarded – undo
207 207
 	 */
208 208
 	private function getCacheKey($key) {
209 209
 		$prefix = 'LDAP-'.$this->configID.'-'.$this->configPrefix.'-';
210
-		if(is_null($key)) {
210
+		if (is_null($key)) {
211 211
 			return $prefix;
212 212
 		}
213 213
 		return $prefix.md5($key);
@@ -218,10 +218,10 @@  discard block
 block discarded – undo
218 218
 	 * @return mixed|null
219 219
 	 */
220 220
 	public function getFromCache($key) {
221
-		if(!$this->configured) {
221
+		if (!$this->configured) {
222 222
 			$this->readConfiguration();
223 223
 		}
224
-		if(is_null($this->cache) || !$this->configuration->ldapCacheTTL) {
224
+		if (is_null($this->cache) || !$this->configuration->ldapCacheTTL) {
225 225
 			return null;
226 226
 		}
227 227
 		$key = $this->getCacheKey($key);
@@ -236,10 +236,10 @@  discard block
 block discarded – undo
236 236
 	 * @return string
237 237
 	 */
238 238
 	public function writeToCache($key, $value) {
239
-		if(!$this->configured) {
239
+		if (!$this->configured) {
240 240
 			$this->readConfiguration();
241 241
 		}
242
-		if(is_null($this->cache)
242
+		if (is_null($this->cache)
243 243
 			|| !$this->configuration->ldapCacheTTL
244 244
 			|| !$this->configuration->ldapConfigurationActive) {
245 245
 			return null;
@@ -250,7 +250,7 @@  discard block
 block discarded – undo
250 250
 	}
251 251
 
252 252
 	public function clearCache() {
253
-		if(!is_null($this->cache)) {
253
+		if (!is_null($this->cache)) {
254 254
 			$this->cache->clear($this->getCacheKey(null));
255 255
 		}
256 256
 	}
@@ -262,7 +262,7 @@  discard block
 block discarded – undo
262 262
 	 * @return null
263 263
 	 */
264 264
 	private function readConfiguration($force = false) {
265
-		if((!$this->configured || $force) && !is_null($this->configID)) {
265
+		if ((!$this->configured || $force) && !is_null($this->configID)) {
266 266
 			$this->configuration->readConfiguration();
267 267
 			$this->configured = $this->validateConfiguration();
268 268
 		}
@@ -275,12 +275,12 @@  discard block
 block discarded – undo
275 275
 	 * @return boolean true if config validates, false otherwise. Check with $setParameters for detailed success on single parameters
276 276
 	 */
277 277
 	public function setConfiguration($config, &$setParameters = null) {
278
-		if(is_null($setParameters)) {
278
+		if (is_null($setParameters)) {
279 279
 			$setParameters = array();
280 280
 		}
281 281
 		$this->doNotValidate = false;
282 282
 		$this->configuration->setConfiguration($config, $setParameters);
283
-		if(count($setParameters) > 0) {
283
+		if (count($setParameters) > 0) {
284 284
 			$this->configured = $this->validateConfiguration();
285 285
 		}
286 286
 
@@ -307,10 +307,10 @@  discard block
 block discarded – undo
307 307
 		$config = $this->configuration->getConfiguration();
308 308
 		$cta = $this->configuration->getConfigTranslationArray();
309 309
 		$result = array();
310
-		foreach($cta as $dbkey => $configkey) {
311
-			switch($configkey) {
310
+		foreach ($cta as $dbkey => $configkey) {
311
+			switch ($configkey) {
312 312
 				case 'homeFolderNamingRule':
313
-					if(strpos($config[$configkey], 'attr:') === 0) {
313
+					if (strpos($config[$configkey], 'attr:') === 0) {
314 314
 						$result[$dbkey] = substr($config[$configkey], 5);
315 315
 					} else {
316 316
 						$result[$dbkey] = '';
@@ -321,7 +321,7 @@  discard block
 block discarded – undo
321 321
 				case 'ldapBaseGroups':
322 322
 				case 'ldapAttributesForUserSearch':
323 323
 				case 'ldapAttributesForGroupSearch':
324
-					if(is_array($config[$configkey])) {
324
+					if (is_array($config[$configkey])) {
325 325
 						$result[$dbkey] = implode("\n", $config[$configkey]);
326 326
 						break;
327 327
 					} //else follows default
@@ -334,23 +334,23 @@  discard block
 block discarded – undo
334 334
 
335 335
 	private function doSoftValidation() {
336 336
 		//if User or Group Base are not set, take over Base DN setting
337
-		foreach(array('ldapBaseUsers', 'ldapBaseGroups') as $keyBase) {
337
+		foreach (array('ldapBaseUsers', 'ldapBaseGroups') as $keyBase) {
338 338
 			$val = $this->configuration->$keyBase;
339
-			if(empty($val)) {
339
+			if (empty($val)) {
340 340
 				$this->configuration->$keyBase = $this->configuration->ldapBase;
341 341
 			}
342 342
 		}
343 343
 
344
-		foreach(array('ldapExpertUUIDUserAttr'  => 'ldapUuidUserAttribute',
344
+		foreach (array('ldapExpertUUIDUserAttr'  => 'ldapUuidUserAttribute',
345 345
 					  'ldapExpertUUIDGroupAttr' => 'ldapUuidGroupAttribute')
346 346
 				as $expertSetting => $effectiveSetting) {
347 347
 			$uuidOverride = $this->configuration->$expertSetting;
348
-			if(!empty($uuidOverride)) {
348
+			if (!empty($uuidOverride)) {
349 349
 				$this->configuration->$effectiveSetting = $uuidOverride;
350 350
 			} else {
351 351
 				$uuidAttributes = Access::UUID_ATTRIBUTES;
352 352
 				array_unshift($uuidAttributes, 'auto');
353
-				if(!in_array($this->configuration->$effectiveSetting,
353
+				if (!in_array($this->configuration->$effectiveSetting,
354 354
 							$uuidAttributes)
355 355
 					&& (!is_null($this->configID))) {
356 356
 					$this->configuration->$effectiveSetting = 'auto';
@@ -372,14 +372,14 @@  discard block
 block discarded – undo
372 372
 		//make sure empty search attributes are saved as simple, empty array
373 373
 		$saKeys = array('ldapAttributesForUserSearch',
374 374
 						'ldapAttributesForGroupSearch');
375
-		foreach($saKeys as $key) {
375
+		foreach ($saKeys as $key) {
376 376
 			$val = $this->configuration->$key;
377
-			if(is_array($val) && count($val) === 1 && empty($val[0])) {
377
+			if (is_array($val) && count($val) === 1 && empty($val[0])) {
378 378
 				$this->configuration->$key = array();
379 379
 			}
380 380
 		}
381 381
 
382
-		if((stripos($this->configuration->ldapHost, 'ldaps://') === 0)
382
+		if ((stripos($this->configuration->ldapHost, 'ldaps://') === 0)
383 383
 			&& $this->configuration->ldapTLS) {
384 384
 			$this->configuration->ldapTLS = false;
385 385
 			\OCP\Util::writeLog('user_ldap',
@@ -400,10 +400,10 @@  discard block
 block discarded – undo
400 400
 		//options that shall not be empty
401 401
 		$options = array('ldapHost', 'ldapPort', 'ldapUserDisplayName',
402 402
 						 'ldapGroupDisplayName', 'ldapLoginFilter');
403
-		foreach($options as $key) {
403
+		foreach ($options as $key) {
404 404
 			$val = $this->configuration->$key;
405
-			if(empty($val)) {
406
-				switch($key) {
405
+			if (empty($val)) {
406
+				switch ($key) {
407 407
 					case 'ldapHost':
408 408
 						$subj = 'LDAP Host';
409 409
 						break;
@@ -434,7 +434,7 @@  discard block
 block discarded – undo
434 434
 		$agent = $this->configuration->ldapAgentName;
435 435
 		$pwd = $this->configuration->ldapAgentPassword;
436 436
 		if (
437
-			($agent === ''  && $pwd !== '')
437
+			($agent === '' && $pwd !== '')
438 438
 			|| ($agent !== '' && $pwd === '')
439 439
 		) {
440 440
 			\OCP\Util::writeLog('user_ldap',
@@ -449,14 +449,14 @@  discard block
 block discarded – undo
449 449
 		$baseUsers = $this->configuration->ldapBaseUsers;
450 450
 		$baseGroups = $this->configuration->ldapBaseGroups;
451 451
 
452
-		if(empty($base) && empty($baseUsers) && empty($baseGroups)) {
452
+		if (empty($base) && empty($baseUsers) && empty($baseGroups)) {
453 453
 			\OCP\Util::writeLog('user_ldap',
454 454
 								$errorStr.'Not a single Base DN given.',
455 455
 								\OCP\Util::WARN);
456 456
 			$configurationOK = false;
457 457
 		}
458 458
 
459
-		if(mb_strpos($this->configuration->ldapLoginFilter, '%uid', 0, 'UTF-8')
459
+		if (mb_strpos($this->configuration->ldapLoginFilter, '%uid', 0, 'UTF-8')
460 460
 		   === false) {
461 461
 			\OCP\Util::writeLog('user_ldap',
462 462
 								$errorStr.'login filter does not contain %uid '.
@@ -474,7 +474,7 @@  discard block
 block discarded – undo
474 474
 	 */
475 475
 	private function validateConfiguration() {
476 476
 
477
-		if($this->doNotValidate) {
477
+		if ($this->doNotValidate) {
478 478
 			//don't do a validation if it is a new configuration with pure
479 479
 			//default values. Will be allowed on changes via __set or
480 480
 			//setConfiguration
@@ -495,21 +495,21 @@  discard block
 block discarded – undo
495 495
 	 * Connects and Binds to LDAP
496 496
 	 */
497 497
 	private function establishConnection() {
498
-		if(!$this->configuration->ldapConfigurationActive) {
498
+		if (!$this->configuration->ldapConfigurationActive) {
499 499
 			return null;
500 500
 		}
501 501
 		static $phpLDAPinstalled = true;
502
-		if(!$phpLDAPinstalled) {
502
+		if (!$phpLDAPinstalled) {
503 503
 			return false;
504 504
 		}
505
-		if(!$this->ignoreValidation && !$this->configured) {
505
+		if (!$this->ignoreValidation && !$this->configured) {
506 506
 			\OCP\Util::writeLog('user_ldap',
507 507
 								'Configuration is invalid, cannot connect',
508 508
 								\OCP\Util::WARN);
509 509
 			return false;
510 510
 		}
511
-		if(!$this->ldapConnectionRes) {
512
-			if(!$this->ldap->areLDAPFunctionsAvailable()) {
511
+		if (!$this->ldapConnectionRes) {
512
+			if (!$this->ldap->areLDAPFunctionsAvailable()) {
513 513
 				$phpLDAPinstalled = false;
514 514
 				\OCP\Util::writeLog('user_ldap',
515 515
 									'function ldap_connect is not available. Make '.
@@ -518,8 +518,8 @@  discard block
 block discarded – undo
518 518
 
519 519
 				return false;
520 520
 			}
521
-			if($this->configuration->turnOffCertCheck) {
522
-				if(putenv('LDAPTLS_REQCERT=never')) {
521
+			if ($this->configuration->turnOffCertCheck) {
522
+				if (putenv('LDAPTLS_REQCERT=never')) {
523 523
 					\OCP\Util::writeLog('user_ldap',
524 524
 						'Turned off SSL certificate validation successfully.',
525 525
 						\OCP\Util::DEBUG);
@@ -543,23 +543,23 @@  discard block
 block discarded – undo
543 543
 					$error = $this->ldap->isResource($this->ldapConnectionRes) ?
544 544
 						$this->ldap->errno($this->ldapConnectionRes) : -1;
545 545
 				}
546
-				if($bindStatus === true) {
546
+				if ($bindStatus === true) {
547 547
 					return $bindStatus;
548 548
 				}
549 549
 			} catch (ServerNotAvailableException $e) {
550
-				if(!$isBackupHost) {
550
+				if (!$isBackupHost) {
551 551
 					throw $e;
552 552
 				}
553 553
 			}
554 554
 
555 555
 			//if LDAP server is not reachable, try the Backup (Replica!) Server
556
-			if($isBackupHost && ($error !== 0 || $isOverrideMainServer)) {
556
+			if ($isBackupHost && ($error !== 0 || $isOverrideMainServer)) {
557 557
 				$this->doConnect($this->configuration->ldapBackupHost,
558 558
 								 $this->configuration->ldapBackupPort);
559 559
 				$bindStatus = $this->bind();
560 560
 				$error = $this->ldap->isResource($this->ldapConnectionRes) ?
561 561
 					$this->ldap->errno($this->ldapConnectionRes) : -1;
562
-				if($bindStatus && $error === 0 && !$this->getFromCache('overrideMainServer')) {
562
+				if ($bindStatus && $error === 0 && !$this->getFromCache('overrideMainServer')) {
563 563
 					//when bind to backup server succeeded and failed to main server,
564 564
 					//skip contacting him until next cache refresh
565 565
 					$this->writeToCache('overrideMainServer', true);
@@ -584,17 +584,17 @@  discard block
 block discarded – undo
584 584
 
585 585
 		$this->ldapConnectionRes = $this->ldap->connect($host, $port);
586 586
 
587
-		if(!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_PROTOCOL_VERSION, 3)) {
587
+		if (!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_PROTOCOL_VERSION, 3)) {
588 588
 			throw new ServerNotAvailableException('Could not set required LDAP Protocol version.');
589 589
 		}
590 590
 
591
-		if(!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_REFERRALS, 0)) {
591
+		if (!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_REFERRALS, 0)) {
592 592
 			throw new ServerNotAvailableException('Could not disable LDAP referrals.');
593 593
 		}
594 594
 
595
-		if($this->configuration->ldapTLS) {
596
-			if(!$this->ldap->startTls($this->ldapConnectionRes)) {
597
-				throw new ServerNotAvailableException('Start TLS failed, when connecting to LDAP host ' . $host . '.');
595
+		if ($this->configuration->ldapTLS) {
596
+			if (!$this->ldap->startTls($this->ldapConnectionRes)) {
597
+				throw new ServerNotAvailableException('Start TLS failed, when connecting to LDAP host '.$host.'.');
598 598
 			}
599 599
 		}
600 600
 
@@ -605,25 +605,25 @@  discard block
 block discarded – undo
605 605
 	 * Binds to LDAP
606 606
 	 */
607 607
 	public function bind() {
608
-		if(!$this->configuration->ldapConfigurationActive) {
608
+		if (!$this->configuration->ldapConfigurationActive) {
609 609
 			return false;
610 610
 		}
611 611
 		$cr = $this->getConnectionResource();
612
-		if(!$this->ldap->isResource($cr)) {
612
+		if (!$this->ldap->isResource($cr)) {
613 613
 			return false;
614 614
 		}
615 615
 		$ldapLogin = @$this->ldap->bind($cr,
616 616
 										$this->configuration->ldapAgentName,
617 617
 										$this->configuration->ldapAgentPassword);
618
-		if(!$ldapLogin) {
618
+		if (!$ldapLogin) {
619 619
 			$errno = $this->ldap->errno($cr);
620 620
 
621 621
 			\OCP\Util::writeLog('user_ldap',
622
-				'Bind failed: ' . $errno . ': ' . $this->ldap->error($cr),
622
+				'Bind failed: '.$errno.': '.$this->ldap->error($cr),
623 623
 				\OCP\Util::WARN);
624 624
 
625 625
 			// Set to failure mode, if LDAP error code is not LDAP_SUCCESS or LDAP_INVALID_CREDENTIALS
626
-			if($errno !== 0x00 && $errno !== 0x31) {
626
+			if ($errno !== 0x00 && $errno !== 0x31) {
627 627
 				$this->ldapConnectionRes = null;
628 628
 			}
629 629
 
Please login to merge, or discard this patch.