Completed
Pull Request — master (#3218)
by Vars
46:46 queued 34:29
created
apps/files_sharing/lib/Helper.php 3 patches
Doc Comments   +1 added lines patch added patch discarded remove patch
@@ -303,6 +303,7 @@
 block discarded – undo
303 303
 	 * get default share folder
304 304
 	 *
305 305
 	 * @param \OC\Files\View
306
+	 * @param View $view
306 307
 	 * @return string
307 308
 	 */
308 309
 	public static function getShareFolder($view = null) {
Please login to merge, or discard this patch.
Indentation   +237 added lines, -237 removed lines patch added patch discarded remove patch
@@ -36,242 +36,242 @@
 block discarded – undo
36 36
 
37 37
 class Helper {
38 38
 
39
-	public static function registerHooks() {
40
-		\OCP\Util::connectHook('OC_Filesystem', 'post_rename', '\OCA\Files_Sharing\Updater', 'renameHook');
41
-		\OCP\Util::connectHook('OC_Filesystem', 'post_delete', '\OCA\Files_Sharing\Hooks', 'unshareChildren');
42
-
43
-		\OCP\Util::connectHook('OC_User', 'post_deleteUser', '\OCA\Files_Sharing\Hooks', 'deleteUser');
44
-	}
45
-
46
-	/**
47
-	 * Sets up the filesystem and user for public sharing
48
-	 * @param string $token string share token
49
-	 * @param string $relativePath optional path relative to the share
50
-	 * @param string $password optional password
51
-	 * @return array
52
-	 */
53
-	public static function setupFromToken($token, $relativePath = null, $password = null) {
54
-		\OC_User::setIncognitoMode(true);
55
-
56
-		$shareManager = \OC::$server->getShareManager();
57
-
58
-		try {
59
-			$share = $shareManager->getShareByToken($token);
60
-		} catch (ShareNotFound $e) {
61
-			\OC_Response::setStatus(404);
62
-			\OCP\Util::writeLog('core-preview', 'Passed token parameter is not valid', \OCP\Util::DEBUG);
63
-			exit;
64
-		}
65
-
66
-		\OCP\JSON::checkUserExists($share->getShareOwner());
67
-		\OC_Util::tearDownFS();
68
-		\OC_Util::setupFS($share->getShareOwner());
69
-
70
-
71
-		try {
72
-			$path = Filesystem::getPath($share->getNodeId());
73
-		} catch (NotFoundException $e) {
74
-			\OCP\Util::writeLog('share', 'could not resolve linkItem', \OCP\Util::DEBUG);
75
-			\OC_Response::setStatus(404);
76
-			\OCP\JSON::error(array('success' => false));
77
-			exit();
78
-		}
79
-
80
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK && $share->getPassword() !== null) {
81
-			if (!self::authenticate($share, $password)) {
82
-				\OC_Response::setStatus(403);
83
-				\OCP\JSON::error(array('success' => false));
84
-				exit();
85
-			}
86
-		}
87
-
88
-		$basePath = $path;
89
-
90
-		if ($relativePath !== null && Filesystem::isReadable($basePath . $relativePath)) {
91
-			$path .= Filesystem::normalizePath($relativePath);
92
-		}
93
-
94
-		return array(
95
-			'share' => $share,
96
-			'basePath' => $basePath,
97
-			'realPath' => $path
98
-		);
99
-	}
100
-
101
-	/**
102
-	 * Authenticate link item with the given password
103
-	 * or with the session if no password was given.
104
-	 * @param \OCP\Share\IShare $share
105
-	 * @param string $password optional password
106
-	 *
107
-	 * @return boolean true if authorized, false otherwise
108
-	 */
109
-	public static function authenticate($share, $password = null) {
110
-		$shareManager = \OC::$server->getShareManager();
111
-
112
-		if ($password !== null) {
113
-			if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
114
-				if ($shareManager->checkPassword($share, $password)) {
115
-					\OC::$server->getSession()->set('public_link_authenticated', (string)$share->getId());
116
-					return true;
117
-				}
118
-			}
119
-		} else {
120
-			// not authenticated ?
121
-			if (\OC::$server->getSession()->exists('public_link_authenticated')
122
-				&& \OC::$server->getSession()->get('public_link_authenticated') !== (string)$share->getId()) {
123
-				return true;
124
-			}
125
-		}
126
-		return false;
127
-	}
128
-
129
-	public static function getSharesFromItem($target) {
130
-		$result = array();
131
-		$owner = Filesystem::getOwner($target);
132
-		Filesystem::initMountPoints($owner);
133
-		$info = Filesystem::getFileInfo($target);
134
-		$ownerView = new View('/'.$owner.'/files');
135
-		if ( $owner != User::getUser() ) {
136
-			$path = $ownerView->getPath($info['fileid']);
137
-		} else {
138
-			$path = $target;
139
-		}
140
-
141
-
142
-		$ids = array();
143
-		while ($path !== dirname($path)) {
144
-			$info = $ownerView->getFileInfo($path);
145
-			if ($info instanceof \OC\Files\FileInfo) {
146
-				$ids[] = $info['fileid'];
147
-			} else {
148
-				\OCP\Util::writeLog('sharing', 'No fileinfo available for: ' . $path, \OCP\Util::WARN);
149
-			}
150
-			$path = dirname($path);
151
-		}
152
-
153
-		if (!empty($ids)) {
154
-
155
-			$idList = array_chunk($ids, 99, true);
156
-
157
-			foreach ($idList as $subList) {
158
-				$statement = "SELECT `share_with`, `share_type`, `file_target` FROM `*PREFIX*share` WHERE `file_source` IN (" . implode(',', $subList) . ") AND `share_type` IN (0, 1, 2)";
159
-				$query = \OCP\DB::prepare($statement);
160
-				$r = $query->execute();
161
-				$result = array_merge($result, $r->fetchAll());
162
-			}
163
-		}
164
-
165
-		return $result;
166
-	}
167
-
168
-	/**
169
-	 * get the UID of the owner of the file and the path to the file relative to
170
-	 * owners files folder
171
-	 *
172
-	 * @param $filename
173
-	 * @return array
174
-	 * @throws \OC\User\NoUserException
175
-	 */
176
-	public static function getUidAndFilename($filename) {
177
-		$uid = Filesystem::getOwner($filename);
178
-		$userManager = \OC::$server->getUserManager();
179
-		// if the user with the UID doesn't exists, e.g. because the UID points
180
-		// to a remote user with a federated cloud ID we use the current logged-in
181
-		// user. We need a valid local user to create the share
182
-		if (!$userManager->userExists($uid)) {
183
-			$uid = User::getUser();
184
-		}
185
-		Filesystem::initMountPoints($uid);
186
-		if ( $uid != User::getUser() ) {
187
-			$info = Filesystem::getFileInfo($filename);
188
-			$ownerView = new View('/'.$uid.'/files');
189
-			try {
190
-				$filename = $ownerView->getPath($info['fileid']);
191
-			} catch (NotFoundException $e) {
192
-				$filename = null;
193
-			}
194
-		}
195
-		return [$uid, $filename];
196
-	}
197
-
198
-	/**
199
-	 * Format a path to be relative to the /user/files/ directory
200
-	 * @param string $path the absolute path
201
-	 * @return string e.g. turns '/admin/files/test.txt' into 'test.txt'
202
-	 */
203
-	public static function stripUserFilesPath($path) {
204
-		$trimmed = ltrim($path, '/');
205
-		$split = explode('/', $trimmed);
206
-
207
-		// it is not a file relative to data/user/files
208
-		if (count($split) < 3 || $split[1] !== 'files') {
209
-			return false;
210
-		}
211
-
212
-		$sliced = array_slice($split, 2);
213
-		$relPath = implode('/', $sliced);
214
-
215
-		return $relPath;
216
-	}
217
-
218
-	/**
219
-	 * check if file name already exists and generate unique target
220
-	 *
221
-	 * @param string $path
222
-	 * @param array $excludeList
223
-	 * @param View $view
224
-	 * @return string $path
225
-	 */
226
-	public static function generateUniqueTarget($path, $excludeList, $view) {
227
-		$pathinfo = pathinfo($path);
228
-		$ext = (isset($pathinfo['extension'])) ? '.'.$pathinfo['extension'] : '';
229
-		$name = $pathinfo['filename'];
230
-		$dir = $pathinfo['dirname'];
231
-		$i = 2;
232
-		while ($view->file_exists($path) || in_array($path, $excludeList)) {
233
-			$path = Filesystem::normalizePath($dir . '/' . $name . ' ('.$i.')' . $ext);
234
-			$i++;
235
-		}
236
-
237
-		return $path;
238
-	}
239
-
240
-	/**
241
-	 * get default share folder
242
-	 *
243
-	 * @param \OC\Files\View
244
-	 * @return string
245
-	 */
246
-	public static function getShareFolder($view = null) {
247
-		if ($view === null) {
248
-			$view = Filesystem::getView();
249
-		}
250
-		$shareFolder = \OC::$server->getConfig()->getSystemValue('share_folder', '/');
251
-		$shareFolder = Filesystem::normalizePath($shareFolder);
252
-
253
-		if (!$view->file_exists($shareFolder)) {
254
-			$dir = '';
255
-			$subdirs = explode('/', $shareFolder);
256
-			foreach ($subdirs as $subdir) {
257
-				$dir = $dir . '/' . $subdir;
258
-				if (!$view->is_dir($dir)) {
259
-					$view->mkdir($dir);
260
-				}
261
-			}
262
-		}
263
-
264
-		return $shareFolder;
265
-
266
-	}
267
-
268
-	/**
269
-	 * set default share folder
270
-	 *
271
-	 * @param string $shareFolder
272
-	 */
273
-	public static function setShareFolder($shareFolder) {
274
-		\OC::$server->getConfig()->setSystemValue('share_folder', $shareFolder);
275
-	}
39
+    public static function registerHooks() {
40
+        \OCP\Util::connectHook('OC_Filesystem', 'post_rename', '\OCA\Files_Sharing\Updater', 'renameHook');
41
+        \OCP\Util::connectHook('OC_Filesystem', 'post_delete', '\OCA\Files_Sharing\Hooks', 'unshareChildren');
42
+
43
+        \OCP\Util::connectHook('OC_User', 'post_deleteUser', '\OCA\Files_Sharing\Hooks', 'deleteUser');
44
+    }
45
+
46
+    /**
47
+     * Sets up the filesystem and user for public sharing
48
+     * @param string $token string share token
49
+     * @param string $relativePath optional path relative to the share
50
+     * @param string $password optional password
51
+     * @return array
52
+     */
53
+    public static function setupFromToken($token, $relativePath = null, $password = null) {
54
+        \OC_User::setIncognitoMode(true);
55
+
56
+        $shareManager = \OC::$server->getShareManager();
57
+
58
+        try {
59
+            $share = $shareManager->getShareByToken($token);
60
+        } catch (ShareNotFound $e) {
61
+            \OC_Response::setStatus(404);
62
+            \OCP\Util::writeLog('core-preview', 'Passed token parameter is not valid', \OCP\Util::DEBUG);
63
+            exit;
64
+        }
65
+
66
+        \OCP\JSON::checkUserExists($share->getShareOwner());
67
+        \OC_Util::tearDownFS();
68
+        \OC_Util::setupFS($share->getShareOwner());
69
+
70
+
71
+        try {
72
+            $path = Filesystem::getPath($share->getNodeId());
73
+        } catch (NotFoundException $e) {
74
+            \OCP\Util::writeLog('share', 'could not resolve linkItem', \OCP\Util::DEBUG);
75
+            \OC_Response::setStatus(404);
76
+            \OCP\JSON::error(array('success' => false));
77
+            exit();
78
+        }
79
+
80
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK && $share->getPassword() !== null) {
81
+            if (!self::authenticate($share, $password)) {
82
+                \OC_Response::setStatus(403);
83
+                \OCP\JSON::error(array('success' => false));
84
+                exit();
85
+            }
86
+        }
87
+
88
+        $basePath = $path;
89
+
90
+        if ($relativePath !== null && Filesystem::isReadable($basePath . $relativePath)) {
91
+            $path .= Filesystem::normalizePath($relativePath);
92
+        }
93
+
94
+        return array(
95
+            'share' => $share,
96
+            'basePath' => $basePath,
97
+            'realPath' => $path
98
+        );
99
+    }
100
+
101
+    /**
102
+     * Authenticate link item with the given password
103
+     * or with the session if no password was given.
104
+     * @param \OCP\Share\IShare $share
105
+     * @param string $password optional password
106
+     *
107
+     * @return boolean true if authorized, false otherwise
108
+     */
109
+    public static function authenticate($share, $password = null) {
110
+        $shareManager = \OC::$server->getShareManager();
111
+
112
+        if ($password !== null) {
113
+            if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
114
+                if ($shareManager->checkPassword($share, $password)) {
115
+                    \OC::$server->getSession()->set('public_link_authenticated', (string)$share->getId());
116
+                    return true;
117
+                }
118
+            }
119
+        } else {
120
+            // not authenticated ?
121
+            if (\OC::$server->getSession()->exists('public_link_authenticated')
122
+                && \OC::$server->getSession()->get('public_link_authenticated') !== (string)$share->getId()) {
123
+                return true;
124
+            }
125
+        }
126
+        return false;
127
+    }
128
+
129
+    public static function getSharesFromItem($target) {
130
+        $result = array();
131
+        $owner = Filesystem::getOwner($target);
132
+        Filesystem::initMountPoints($owner);
133
+        $info = Filesystem::getFileInfo($target);
134
+        $ownerView = new View('/'.$owner.'/files');
135
+        if ( $owner != User::getUser() ) {
136
+            $path = $ownerView->getPath($info['fileid']);
137
+        } else {
138
+            $path = $target;
139
+        }
140
+
141
+
142
+        $ids = array();
143
+        while ($path !== dirname($path)) {
144
+            $info = $ownerView->getFileInfo($path);
145
+            if ($info instanceof \OC\Files\FileInfo) {
146
+                $ids[] = $info['fileid'];
147
+            } else {
148
+                \OCP\Util::writeLog('sharing', 'No fileinfo available for: ' . $path, \OCP\Util::WARN);
149
+            }
150
+            $path = dirname($path);
151
+        }
152
+
153
+        if (!empty($ids)) {
154
+
155
+            $idList = array_chunk($ids, 99, true);
156
+
157
+            foreach ($idList as $subList) {
158
+                $statement = "SELECT `share_with`, `share_type`, `file_target` FROM `*PREFIX*share` WHERE `file_source` IN (" . implode(',', $subList) . ") AND `share_type` IN (0, 1, 2)";
159
+                $query = \OCP\DB::prepare($statement);
160
+                $r = $query->execute();
161
+                $result = array_merge($result, $r->fetchAll());
162
+            }
163
+        }
164
+
165
+        return $result;
166
+    }
167
+
168
+    /**
169
+     * get the UID of the owner of the file and the path to the file relative to
170
+     * owners files folder
171
+     *
172
+     * @param $filename
173
+     * @return array
174
+     * @throws \OC\User\NoUserException
175
+     */
176
+    public static function getUidAndFilename($filename) {
177
+        $uid = Filesystem::getOwner($filename);
178
+        $userManager = \OC::$server->getUserManager();
179
+        // if the user with the UID doesn't exists, e.g. because the UID points
180
+        // to a remote user with a federated cloud ID we use the current logged-in
181
+        // user. We need a valid local user to create the share
182
+        if (!$userManager->userExists($uid)) {
183
+            $uid = User::getUser();
184
+        }
185
+        Filesystem::initMountPoints($uid);
186
+        if ( $uid != User::getUser() ) {
187
+            $info = Filesystem::getFileInfo($filename);
188
+            $ownerView = new View('/'.$uid.'/files');
189
+            try {
190
+                $filename = $ownerView->getPath($info['fileid']);
191
+            } catch (NotFoundException $e) {
192
+                $filename = null;
193
+            }
194
+        }
195
+        return [$uid, $filename];
196
+    }
197
+
198
+    /**
199
+     * Format a path to be relative to the /user/files/ directory
200
+     * @param string $path the absolute path
201
+     * @return string e.g. turns '/admin/files/test.txt' into 'test.txt'
202
+     */
203
+    public static function stripUserFilesPath($path) {
204
+        $trimmed = ltrim($path, '/');
205
+        $split = explode('/', $trimmed);
206
+
207
+        // it is not a file relative to data/user/files
208
+        if (count($split) < 3 || $split[1] !== 'files') {
209
+            return false;
210
+        }
211
+
212
+        $sliced = array_slice($split, 2);
213
+        $relPath = implode('/', $sliced);
214
+
215
+        return $relPath;
216
+    }
217
+
218
+    /**
219
+     * check if file name already exists and generate unique target
220
+     *
221
+     * @param string $path
222
+     * @param array $excludeList
223
+     * @param View $view
224
+     * @return string $path
225
+     */
226
+    public static function generateUniqueTarget($path, $excludeList, $view) {
227
+        $pathinfo = pathinfo($path);
228
+        $ext = (isset($pathinfo['extension'])) ? '.'.$pathinfo['extension'] : '';
229
+        $name = $pathinfo['filename'];
230
+        $dir = $pathinfo['dirname'];
231
+        $i = 2;
232
+        while ($view->file_exists($path) || in_array($path, $excludeList)) {
233
+            $path = Filesystem::normalizePath($dir . '/' . $name . ' ('.$i.')' . $ext);
234
+            $i++;
235
+        }
236
+
237
+        return $path;
238
+    }
239
+
240
+    /**
241
+     * get default share folder
242
+     *
243
+     * @param \OC\Files\View
244
+     * @return string
245
+     */
246
+    public static function getShareFolder($view = null) {
247
+        if ($view === null) {
248
+            $view = Filesystem::getView();
249
+        }
250
+        $shareFolder = \OC::$server->getConfig()->getSystemValue('share_folder', '/');
251
+        $shareFolder = Filesystem::normalizePath($shareFolder);
252
+
253
+        if (!$view->file_exists($shareFolder)) {
254
+            $dir = '';
255
+            $subdirs = explode('/', $shareFolder);
256
+            foreach ($subdirs as $subdir) {
257
+                $dir = $dir . '/' . $subdir;
258
+                if (!$view->is_dir($dir)) {
259
+                    $view->mkdir($dir);
260
+                }
261
+            }
262
+        }
263
+
264
+        return $shareFolder;
265
+
266
+    }
267
+
268
+    /**
269
+     * set default share folder
270
+     *
271
+     * @param string $shareFolder
272
+     */
273
+    public static function setShareFolder($shareFolder) {
274
+        \OC::$server->getConfig()->setSystemValue('share_folder', $shareFolder);
275
+    }
276 276
 
277 277
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -87,7 +87,7 @@  discard block
 block discarded – undo
87 87
 
88 88
 		$basePath = $path;
89 89
 
90
-		if ($relativePath !== null && Filesystem::isReadable($basePath . $relativePath)) {
90
+		if ($relativePath !== null && Filesystem::isReadable($basePath.$relativePath)) {
91 91
 			$path .= Filesystem::normalizePath($relativePath);
92 92
 		}
93 93
 
@@ -112,14 +112,14 @@  discard block
 block discarded – undo
112 112
 		if ($password !== null) {
113 113
 			if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
114 114
 				if ($shareManager->checkPassword($share, $password)) {
115
-					\OC::$server->getSession()->set('public_link_authenticated', (string)$share->getId());
115
+					\OC::$server->getSession()->set('public_link_authenticated', (string) $share->getId());
116 116
 					return true;
117 117
 				}
118 118
 			}
119 119
 		} else {
120 120
 			// not authenticated ?
121 121
 			if (\OC::$server->getSession()->exists('public_link_authenticated')
122
-				&& \OC::$server->getSession()->get('public_link_authenticated') !== (string)$share->getId()) {
122
+				&& \OC::$server->getSession()->get('public_link_authenticated') !== (string) $share->getId()) {
123 123
 				return true;
124 124
 			}
125 125
 		}
@@ -132,7 +132,7 @@  discard block
 block discarded – undo
132 132
 		Filesystem::initMountPoints($owner);
133 133
 		$info = Filesystem::getFileInfo($target);
134 134
 		$ownerView = new View('/'.$owner.'/files');
135
-		if ( $owner != User::getUser() ) {
135
+		if ($owner != User::getUser()) {
136 136
 			$path = $ownerView->getPath($info['fileid']);
137 137
 		} else {
138 138
 			$path = $target;
@@ -145,7 +145,7 @@  discard block
 block discarded – undo
145 145
 			if ($info instanceof \OC\Files\FileInfo) {
146 146
 				$ids[] = $info['fileid'];
147 147
 			} else {
148
-				\OCP\Util::writeLog('sharing', 'No fileinfo available for: ' . $path, \OCP\Util::WARN);
148
+				\OCP\Util::writeLog('sharing', 'No fileinfo available for: '.$path, \OCP\Util::WARN);
149 149
 			}
150 150
 			$path = dirname($path);
151 151
 		}
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
 			$idList = array_chunk($ids, 99, true);
156 156
 
157 157
 			foreach ($idList as $subList) {
158
-				$statement = "SELECT `share_with`, `share_type`, `file_target` FROM `*PREFIX*share` WHERE `file_source` IN (" . implode(',', $subList) . ") AND `share_type` IN (0, 1, 2)";
158
+				$statement = "SELECT `share_with`, `share_type`, `file_target` FROM `*PREFIX*share` WHERE `file_source` IN (".implode(',', $subList).") AND `share_type` IN (0, 1, 2)";
159 159
 				$query = \OCP\DB::prepare($statement);
160 160
 				$r = $query->execute();
161 161
 				$result = array_merge($result, $r->fetchAll());
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
 			$uid = User::getUser();
184 184
 		}
185 185
 		Filesystem::initMountPoints($uid);
186
-		if ( $uid != User::getUser() ) {
186
+		if ($uid != User::getUser()) {
187 187
 			$info = Filesystem::getFileInfo($filename);
188 188
 			$ownerView = new View('/'.$uid.'/files');
189 189
 			try {
@@ -230,7 +230,7 @@  discard block
 block discarded – undo
230 230
 		$dir = $pathinfo['dirname'];
231 231
 		$i = 2;
232 232
 		while ($view->file_exists($path) || in_array($path, $excludeList)) {
233
-			$path = Filesystem::normalizePath($dir . '/' . $name . ' ('.$i.')' . $ext);
233
+			$path = Filesystem::normalizePath($dir.'/'.$name.' ('.$i.')'.$ext);
234 234
 			$i++;
235 235
 		}
236 236
 
@@ -254,7 +254,7 @@  discard block
 block discarded – undo
254 254
 			$dir = '';
255 255
 			$subdirs = explode('/', $shareFolder);
256 256
 			foreach ($subdirs as $subdir) {
257
-				$dir = $dir . '/' . $subdir;
257
+				$dir = $dir.'/'.$subdir;
258 258
 				if (!$view->is_dir($dir)) {
259 259
 					$view->mkdir($dir);
260 260
 				}
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.
Indentation   +267 added lines, -267 removed lines patch added patch discarded remove patch
@@ -43,271 +43,271 @@
 block discarded – undo
43 43
 
44 44
 class Migrator {
45 45
 
46
-	/**
47
-	 * @var \Doctrine\DBAL\Connection $connection
48
-	 */
49
-	protected $connection;
50
-
51
-	/**
52
-	 * @var ISecureRandom
53
-	 */
54
-	private $random;
55
-
56
-	/** @var IConfig */
57
-	protected $config;
58
-
59
-	/** @var EventDispatcher  */
60
-	private $dispatcher;
61
-
62
-	/** @var bool */
63
-	private $noEmit = false;
64
-
65
-	/**
66
-	 * @param \Doctrine\DBAL\Connection|Connection $connection
67
-	 * @param ISecureRandom $random
68
-	 * @param IConfig $config
69
-	 * @param EventDispatcher $dispatcher
70
-	 */
71
-	public function __construct(\Doctrine\DBAL\Connection $connection,
72
-								ISecureRandom $random,
73
-								IConfig $config,
74
-								EventDispatcher $dispatcher = null) {
75
-		$this->connection = $connection;
76
-		$this->random = $random;
77
-		$this->config = $config;
78
-		$this->dispatcher = $dispatcher;
79
-	}
80
-
81
-	/**
82
-	 * @param \Doctrine\DBAL\Schema\Schema $targetSchema
83
-	 */
84
-	public function migrate(Schema $targetSchema) {
85
-		$this->noEmit = true;
86
-		$this->applySchema($targetSchema);
87
-	}
88
-
89
-	/**
90
-	 * @param \Doctrine\DBAL\Schema\Schema $targetSchema
91
-	 * @return string
92
-	 */
93
-	public function generateChangeScript(Schema $targetSchema) {
94
-		$schemaDiff = $this->getDiff($targetSchema, $this->connection);
95
-
96
-		$script = '';
97
-		$sqls = $schemaDiff->toSql($this->connection->getDatabasePlatform());
98
-		foreach ($sqls as $sql) {
99
-			$script .= $this->convertStatementToScript($sql);
100
-		}
101
-
102
-		return $script;
103
-	}
104
-
105
-	/**
106
-	 * @param Schema $targetSchema
107
-	 * @throws \OC\DB\MigrationException
108
-	 */
109
-	public function checkMigrate(Schema $targetSchema) {
110
-		$this->noEmit = true;
111
-		/**@var \Doctrine\DBAL\Schema\Table[] $tables */
112
-		$tables = $targetSchema->getTables();
113
-		$filterExpression = $this->getFilterExpression();
114
-		$this->connection->getConfiguration()->
115
-			setFilterSchemaAssetsExpression($filterExpression);
116
-		$existingTables = $this->connection->getSchemaManager()->listTableNames();
117
-
118
-		$step = 0;
119
-		foreach ($tables as $table) {
120
-			if (strpos($table->getName(), '.')) {
121
-				list(, $tableName) = explode('.', $table->getName());
122
-			} else {
123
-				$tableName = $table->getName();
124
-			}
125
-			$this->emitCheckStep($tableName, $step++, count($tables));
126
-			// don't need to check for new tables
127
-			if (array_search($tableName, $existingTables) !== false) {
128
-				$this->checkTableMigrate($table);
129
-			}
130
-		}
131
-	}
132
-
133
-	/**
134
-	 * Create a unique name for the temporary table
135
-	 *
136
-	 * @param string $name
137
-	 * @return string
138
-	 */
139
-	protected function generateTemporaryTableName($name) {
140
-		return $this->config->getSystemValue('dbtableprefix', 'oc_') . $name . '_' . $this->random->generate(13, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
141
-	}
142
-
143
-	/**
144
-	 * Check the migration of a table on a copy so we can detect errors before messing with the real table
145
-	 *
146
-	 * @param \Doctrine\DBAL\Schema\Table $table
147
-	 * @throws \OC\DB\MigrationException
148
-	 */
149
-	protected function checkTableMigrate(Table $table) {
150
-		$name = $table->getName();
151
-		$tmpName = $this->generateTemporaryTableName($name);
152
-
153
-		$this->copyTable($name, $tmpName);
154
-
155
-		//create the migration schema for the temporary table
156
-		$tmpTable = $this->renameTableSchema($table, $tmpName);
157
-		$schemaConfig = new SchemaConfig();
158
-		$schemaConfig->setName($this->connection->getDatabase());
159
-		$schema = new Schema(array($tmpTable), array(), $schemaConfig);
160
-
161
-		try {
162
-			$this->applySchema($schema);
163
-			$this->dropTable($tmpName);
164
-		} catch (DBALException $e) {
165
-			// pgsql needs to commit it's failed transaction before doing anything else
166
-			if ($this->connection->isTransactionActive()) {
167
-				$this->connection->commit();
168
-			}
169
-			$this->dropTable($tmpName);
170
-			throw new MigrationException($table->getName(), $e->getMessage());
171
-		}
172
-	}
173
-
174
-	/**
175
-	 * @param \Doctrine\DBAL\Schema\Table $table
176
-	 * @param string $newName
177
-	 * @return \Doctrine\DBAL\Schema\Table
178
-	 */
179
-	protected function renameTableSchema(Table $table, $newName) {
180
-		/**
181
-		 * @var \Doctrine\DBAL\Schema\Index[] $indexes
182
-		 */
183
-		$indexes = $table->getIndexes();
184
-		$newIndexes = array();
185
-		foreach ($indexes as $index) {
186
-			if ($index->isPrimary()) {
187
-				// do not rename primary key
188
-				$indexName = $index->getName();
189
-			} else {
190
-				// avoid conflicts in index names
191
-				$indexName = $this->config->getSystemValue('dbtableprefix', 'oc_') . $this->random->generate(13, ISecureRandom::CHAR_LOWER);
192
-			}
193
-			$newIndexes[] = new Index($indexName, $index->getColumns(), $index->isUnique(), $index->isPrimary());
194
-		}
195
-
196
-		// foreign keys are not supported so we just set it to an empty array
197
-		return new Table($newName, $table->getColumns(), $newIndexes, array(), 0, $table->getOptions());
198
-	}
199
-
200
-	/**
201
-	 * @param Schema $targetSchema
202
-	 * @param \Doctrine\DBAL\Connection $connection
203
-	 * @return \Doctrine\DBAL\Schema\SchemaDiff
204
-	 * @throws DBALException
205
-	 */
206
-	protected function getDiff(Schema $targetSchema, \Doctrine\DBAL\Connection $connection) {
207
-		// adjust varchar columns with a length higher then getVarcharMaxLength to clob
208
-		foreach ($targetSchema->getTables() as $table) {
209
-			foreach ($table->getColumns() as $column) {
210
-				if ($column->getType() instanceof StringType) {
211
-					if ($column->getLength() > $connection->getDatabasePlatform()->getVarcharMaxLength()) {
212
-						$column->setType(Type::getType('text'));
213
-						$column->setLength(null);
214
-					}
215
-				}
216
-			}
217
-		}
218
-
219
-		$filterExpression = $this->getFilterExpression();
220
-		$this->connection->getConfiguration()->
221
-		setFilterSchemaAssetsExpression($filterExpression);
222
-		$sourceSchema = $connection->getSchemaManager()->createSchema();
223
-
224
-		// remove tables we don't know about
225
-		/** @var $table \Doctrine\DBAL\Schema\Table */
226
-		foreach ($sourceSchema->getTables() as $table) {
227
-			if (!$targetSchema->hasTable($table->getName())) {
228
-				$sourceSchema->dropTable($table->getName());
229
-			}
230
-		}
231
-		// remove sequences we don't know about
232
-		foreach ($sourceSchema->getSequences() as $table) {
233
-			if (!$targetSchema->hasSequence($table->getName())) {
234
-				$sourceSchema->dropSequence($table->getName());
235
-			}
236
-		}
237
-
238
-		$comparator = new Comparator();
239
-		return $comparator->compare($sourceSchema, $targetSchema);
240
-	}
241
-
242
-	/**
243
-	 * @param \Doctrine\DBAL\Schema\Schema $targetSchema
244
-	 * @param \Doctrine\DBAL\Connection $connection
245
-	 */
246
-	protected function applySchema(Schema $targetSchema, \Doctrine\DBAL\Connection $connection = null) {
247
-		if (is_null($connection)) {
248
-			$connection = $this->connection;
249
-		}
250
-
251
-		$schemaDiff = $this->getDiff($targetSchema, $connection);
252
-
253
-		$connection->beginTransaction();
254
-		$sqls = $schemaDiff->toSql($connection->getDatabasePlatform());
255
-		$step = 0;
256
-		foreach ($sqls as $sql) {
257
-			$this->emit($sql, $step++, count($sqls));
258
-			$connection->query($sql);
259
-		}
260
-		$connection->commit();
261
-	}
262
-
263
-	/**
264
-	 * @param string $sourceName
265
-	 * @param string $targetName
266
-	 */
267
-	protected function copyTable($sourceName, $targetName) {
268
-		$quotedSource = $this->connection->quoteIdentifier($sourceName);
269
-		$quotedTarget = $this->connection->quoteIdentifier($targetName);
270
-
271
-		$this->connection->exec('CREATE TABLE ' . $quotedTarget . ' (LIKE ' . $quotedSource . ')');
272
-		$this->connection->exec('INSERT INTO ' . $quotedTarget . ' SELECT * FROM ' . $quotedSource);
273
-	}
274
-
275
-	/**
276
-	 * @param string $name
277
-	 */
278
-	protected function dropTable($name) {
279
-		$this->connection->exec('DROP TABLE ' . $this->connection->quoteIdentifier($name));
280
-	}
281
-
282
-	/**
283
-	 * @param $statement
284
-	 * @return string
285
-	 */
286
-	protected function convertStatementToScript($statement) {
287
-		$script = $statement . ';';
288
-		$script .= PHP_EOL;
289
-		$script .= PHP_EOL;
290
-		return $script;
291
-	}
292
-
293
-	protected function getFilterExpression() {
294
-		return '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
295
-	}
296
-
297
-	protected function emit($sql, $step, $max) {
298
-		if ($this->noEmit) {
299
-			return;
300
-		}
301
-		if(is_null($this->dispatcher)) {
302
-			return;
303
-		}
304
-		$this->dispatcher->dispatch('\OC\DB\Migrator::executeSql', new GenericEvent($sql, [$step+1, $max]));
305
-	}
306
-
307
-	private function emitCheckStep($tableName, $step, $max) {
308
-		if(is_null($this->dispatcher)) {
309
-			return;
310
-		}
311
-		$this->dispatcher->dispatch('\OC\DB\Migrator::checkTable', new GenericEvent($tableName, [$step+1, $max]));
312
-	}
46
+    /**
47
+     * @var \Doctrine\DBAL\Connection $connection
48
+     */
49
+    protected $connection;
50
+
51
+    /**
52
+     * @var ISecureRandom
53
+     */
54
+    private $random;
55
+
56
+    /** @var IConfig */
57
+    protected $config;
58
+
59
+    /** @var EventDispatcher  */
60
+    private $dispatcher;
61
+
62
+    /** @var bool */
63
+    private $noEmit = false;
64
+
65
+    /**
66
+     * @param \Doctrine\DBAL\Connection|Connection $connection
67
+     * @param ISecureRandom $random
68
+     * @param IConfig $config
69
+     * @param EventDispatcher $dispatcher
70
+     */
71
+    public function __construct(\Doctrine\DBAL\Connection $connection,
72
+                                ISecureRandom $random,
73
+                                IConfig $config,
74
+                                EventDispatcher $dispatcher = null) {
75
+        $this->connection = $connection;
76
+        $this->random = $random;
77
+        $this->config = $config;
78
+        $this->dispatcher = $dispatcher;
79
+    }
80
+
81
+    /**
82
+     * @param \Doctrine\DBAL\Schema\Schema $targetSchema
83
+     */
84
+    public function migrate(Schema $targetSchema) {
85
+        $this->noEmit = true;
86
+        $this->applySchema($targetSchema);
87
+    }
88
+
89
+    /**
90
+     * @param \Doctrine\DBAL\Schema\Schema $targetSchema
91
+     * @return string
92
+     */
93
+    public function generateChangeScript(Schema $targetSchema) {
94
+        $schemaDiff = $this->getDiff($targetSchema, $this->connection);
95
+
96
+        $script = '';
97
+        $sqls = $schemaDiff->toSql($this->connection->getDatabasePlatform());
98
+        foreach ($sqls as $sql) {
99
+            $script .= $this->convertStatementToScript($sql);
100
+        }
101
+
102
+        return $script;
103
+    }
104
+
105
+    /**
106
+     * @param Schema $targetSchema
107
+     * @throws \OC\DB\MigrationException
108
+     */
109
+    public function checkMigrate(Schema $targetSchema) {
110
+        $this->noEmit = true;
111
+        /**@var \Doctrine\DBAL\Schema\Table[] $tables */
112
+        $tables = $targetSchema->getTables();
113
+        $filterExpression = $this->getFilterExpression();
114
+        $this->connection->getConfiguration()->
115
+            setFilterSchemaAssetsExpression($filterExpression);
116
+        $existingTables = $this->connection->getSchemaManager()->listTableNames();
117
+
118
+        $step = 0;
119
+        foreach ($tables as $table) {
120
+            if (strpos($table->getName(), '.')) {
121
+                list(, $tableName) = explode('.', $table->getName());
122
+            } else {
123
+                $tableName = $table->getName();
124
+            }
125
+            $this->emitCheckStep($tableName, $step++, count($tables));
126
+            // don't need to check for new tables
127
+            if (array_search($tableName, $existingTables) !== false) {
128
+                $this->checkTableMigrate($table);
129
+            }
130
+        }
131
+    }
132
+
133
+    /**
134
+     * Create a unique name for the temporary table
135
+     *
136
+     * @param string $name
137
+     * @return string
138
+     */
139
+    protected function generateTemporaryTableName($name) {
140
+        return $this->config->getSystemValue('dbtableprefix', 'oc_') . $name . '_' . $this->random->generate(13, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
141
+    }
142
+
143
+    /**
144
+     * Check the migration of a table on a copy so we can detect errors before messing with the real table
145
+     *
146
+     * @param \Doctrine\DBAL\Schema\Table $table
147
+     * @throws \OC\DB\MigrationException
148
+     */
149
+    protected function checkTableMigrate(Table $table) {
150
+        $name = $table->getName();
151
+        $tmpName = $this->generateTemporaryTableName($name);
152
+
153
+        $this->copyTable($name, $tmpName);
154
+
155
+        //create the migration schema for the temporary table
156
+        $tmpTable = $this->renameTableSchema($table, $tmpName);
157
+        $schemaConfig = new SchemaConfig();
158
+        $schemaConfig->setName($this->connection->getDatabase());
159
+        $schema = new Schema(array($tmpTable), array(), $schemaConfig);
160
+
161
+        try {
162
+            $this->applySchema($schema);
163
+            $this->dropTable($tmpName);
164
+        } catch (DBALException $e) {
165
+            // pgsql needs to commit it's failed transaction before doing anything else
166
+            if ($this->connection->isTransactionActive()) {
167
+                $this->connection->commit();
168
+            }
169
+            $this->dropTable($tmpName);
170
+            throw new MigrationException($table->getName(), $e->getMessage());
171
+        }
172
+    }
173
+
174
+    /**
175
+     * @param \Doctrine\DBAL\Schema\Table $table
176
+     * @param string $newName
177
+     * @return \Doctrine\DBAL\Schema\Table
178
+     */
179
+    protected function renameTableSchema(Table $table, $newName) {
180
+        /**
181
+         * @var \Doctrine\DBAL\Schema\Index[] $indexes
182
+         */
183
+        $indexes = $table->getIndexes();
184
+        $newIndexes = array();
185
+        foreach ($indexes as $index) {
186
+            if ($index->isPrimary()) {
187
+                // do not rename primary key
188
+                $indexName = $index->getName();
189
+            } else {
190
+                // avoid conflicts in index names
191
+                $indexName = $this->config->getSystemValue('dbtableprefix', 'oc_') . $this->random->generate(13, ISecureRandom::CHAR_LOWER);
192
+            }
193
+            $newIndexes[] = new Index($indexName, $index->getColumns(), $index->isUnique(), $index->isPrimary());
194
+        }
195
+
196
+        // foreign keys are not supported so we just set it to an empty array
197
+        return new Table($newName, $table->getColumns(), $newIndexes, array(), 0, $table->getOptions());
198
+    }
199
+
200
+    /**
201
+     * @param Schema $targetSchema
202
+     * @param \Doctrine\DBAL\Connection $connection
203
+     * @return \Doctrine\DBAL\Schema\SchemaDiff
204
+     * @throws DBALException
205
+     */
206
+    protected function getDiff(Schema $targetSchema, \Doctrine\DBAL\Connection $connection) {
207
+        // adjust varchar columns with a length higher then getVarcharMaxLength to clob
208
+        foreach ($targetSchema->getTables() as $table) {
209
+            foreach ($table->getColumns() as $column) {
210
+                if ($column->getType() instanceof StringType) {
211
+                    if ($column->getLength() > $connection->getDatabasePlatform()->getVarcharMaxLength()) {
212
+                        $column->setType(Type::getType('text'));
213
+                        $column->setLength(null);
214
+                    }
215
+                }
216
+            }
217
+        }
218
+
219
+        $filterExpression = $this->getFilterExpression();
220
+        $this->connection->getConfiguration()->
221
+        setFilterSchemaAssetsExpression($filterExpression);
222
+        $sourceSchema = $connection->getSchemaManager()->createSchema();
223
+
224
+        // remove tables we don't know about
225
+        /** @var $table \Doctrine\DBAL\Schema\Table */
226
+        foreach ($sourceSchema->getTables() as $table) {
227
+            if (!$targetSchema->hasTable($table->getName())) {
228
+                $sourceSchema->dropTable($table->getName());
229
+            }
230
+        }
231
+        // remove sequences we don't know about
232
+        foreach ($sourceSchema->getSequences() as $table) {
233
+            if (!$targetSchema->hasSequence($table->getName())) {
234
+                $sourceSchema->dropSequence($table->getName());
235
+            }
236
+        }
237
+
238
+        $comparator = new Comparator();
239
+        return $comparator->compare($sourceSchema, $targetSchema);
240
+    }
241
+
242
+    /**
243
+     * @param \Doctrine\DBAL\Schema\Schema $targetSchema
244
+     * @param \Doctrine\DBAL\Connection $connection
245
+     */
246
+    protected function applySchema(Schema $targetSchema, \Doctrine\DBAL\Connection $connection = null) {
247
+        if (is_null($connection)) {
248
+            $connection = $this->connection;
249
+        }
250
+
251
+        $schemaDiff = $this->getDiff($targetSchema, $connection);
252
+
253
+        $connection->beginTransaction();
254
+        $sqls = $schemaDiff->toSql($connection->getDatabasePlatform());
255
+        $step = 0;
256
+        foreach ($sqls as $sql) {
257
+            $this->emit($sql, $step++, count($sqls));
258
+            $connection->query($sql);
259
+        }
260
+        $connection->commit();
261
+    }
262
+
263
+    /**
264
+     * @param string $sourceName
265
+     * @param string $targetName
266
+     */
267
+    protected function copyTable($sourceName, $targetName) {
268
+        $quotedSource = $this->connection->quoteIdentifier($sourceName);
269
+        $quotedTarget = $this->connection->quoteIdentifier($targetName);
270
+
271
+        $this->connection->exec('CREATE TABLE ' . $quotedTarget . ' (LIKE ' . $quotedSource . ')');
272
+        $this->connection->exec('INSERT INTO ' . $quotedTarget . ' SELECT * FROM ' . $quotedSource);
273
+    }
274
+
275
+    /**
276
+     * @param string $name
277
+     */
278
+    protected function dropTable($name) {
279
+        $this->connection->exec('DROP TABLE ' . $this->connection->quoteIdentifier($name));
280
+    }
281
+
282
+    /**
283
+     * @param $statement
284
+     * @return string
285
+     */
286
+    protected function convertStatementToScript($statement) {
287
+        $script = $statement . ';';
288
+        $script .= PHP_EOL;
289
+        $script .= PHP_EOL;
290
+        return $script;
291
+    }
292
+
293
+    protected function getFilterExpression() {
294
+        return '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
295
+    }
296
+
297
+    protected function emit($sql, $step, $max) {
298
+        if ($this->noEmit) {
299
+            return;
300
+        }
301
+        if(is_null($this->dispatcher)) {
302
+            return;
303
+        }
304
+        $this->dispatcher->dispatch('\OC\DB\Migrator::executeSql', new GenericEvent($sql, [$step+1, $max]));
305
+    }
306
+
307
+    private function emitCheckStep($tableName, $step, $max) {
308
+        if(is_null($this->dispatcher)) {
309
+            return;
310
+        }
311
+        $this->dispatcher->dispatch('\OC\DB\Migrator::checkTable', new GenericEvent($tableName, [$step+1, $max]));
312
+    }
313 313
 }
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.
settings/Controller/CheckSetupController.php 3 patches
Doc Comments   +2 added lines, -1 removed lines patch added patch discarded remove patch
@@ -103,6 +103,7 @@  discard block
 block discarded – undo
103 103
 
104 104
 	/**
105 105
 	* Chceks if the ownCloud server can connect to a specific URL using both HTTPS and HTTP
106
+	* @param string $sitename
106 107
 	* @return bool
107 108
 	*/
108 109
 	private function isSiteReachable($sitename) {
@@ -285,7 +286,7 @@  discard block
 block discarded – undo
285 286
 
286 287
 	/**
287 288
 	 * @NoCSRFRequired
288
-	 * @return DataResponse
289
+	 * @return DataDisplayResponse
289 290
 	 */
290 291
 	public function getFailedIntegrityCheckFiles() {
291 292
 		if(!$this->checker->isCodeCheckEnforced()) {
Please login to merge, or discard this patch.
Spacing   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 						'www.google.com',
105 105
 						'www.github.com'];
106 106
 
107
-		foreach($siteArray as $site) {
107
+		foreach ($siteArray as $site) {
108 108
 			if ($this->isSiteReachable($site)) {
109 109
 				return true;
110 110
 			}
@@ -117,8 +117,8 @@  discard block
 block discarded – undo
117 117
 	* @return bool
118 118
 	*/
119 119
 	private function isSiteReachable($sitename) {
120
-		$httpSiteName = 'http://' . $sitename . '/';
121
-		$httpsSiteName = 'https://' . $sitename . '/';
120
+		$httpSiteName = 'http://'.$sitename.'/';
121
+		$httpsSiteName = 'https://'.$sitename.'/';
122 122
 
123 123
 		try {
124 124
 			$client = $this->clientService->newClient();
@@ -145,9 +145,9 @@  discard block
 block discarded – undo
145 145
 	 * @return bool
146 146
 	 */
147 147
 	private function isUrandomAvailable() {
148
-		if(@file_exists('/dev/urandom')) {
148
+		if (@file_exists('/dev/urandom')) {
149 149
 			$file = fopen('/dev/urandom', 'rb');
150
-			if($file) {
150
+			if ($file) {
151 151
 				fclose($file);
152 152
 				return true;
153 153
 			}
@@ -178,40 +178,40 @@  discard block
 block discarded – undo
178 178
 		// Don't run check when:
179 179
 		// 1. Server has `has_internet_connection` set to false
180 180
 		// 2. AppStore AND S2S is disabled
181
-		if(!$this->config->getSystemValue('has_internet_connection', true)) {
181
+		if (!$this->config->getSystemValue('has_internet_connection', true)) {
182 182
 			return '';
183 183
 		}
184
-		if(!$this->config->getSystemValue('appstoreenabled', true)
184
+		if (!$this->config->getSystemValue('appstoreenabled', true)
185 185
 			&& $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'no'
186 186
 			&& $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes') === 'no') {
187 187
 			return '';
188 188
 		}
189 189
 
190 190
 		$versionString = $this->getCurlVersion();
191
-		if(isset($versionString['ssl_version'])) {
191
+		if (isset($versionString['ssl_version'])) {
192 192
 			$versionString = $versionString['ssl_version'];
193 193
 		} else {
194 194
 			return '';
195 195
 		}
196 196
 
197
-		$features = (string)$this->l10n->t('installing and updating apps via the app store or Federated Cloud Sharing');
198
-		if(!$this->config->getSystemValue('appstoreenabled', true)) {
199
-			$features = (string)$this->l10n->t('Federated Cloud Sharing');
197
+		$features = (string) $this->l10n->t('installing and updating apps via the app store or Federated Cloud Sharing');
198
+		if (!$this->config->getSystemValue('appstoreenabled', true)) {
199
+			$features = (string) $this->l10n->t('Federated Cloud Sharing');
200 200
 		}
201 201
 
202 202
 		// Check if at least OpenSSL after 1.01d or 1.0.2b
203
-		if(strpos($versionString, 'OpenSSL/') === 0) {
203
+		if (strpos($versionString, 'OpenSSL/') === 0) {
204 204
 			$majorVersion = substr($versionString, 8, 5);
205 205
 			$patchRelease = substr($versionString, 13, 6);
206 206
 
207
-			if(($majorVersion === '1.0.1' && ord($patchRelease) < ord('d')) ||
207
+			if (($majorVersion === '1.0.1' && ord($patchRelease) < ord('d')) ||
208 208
 				($majorVersion === '1.0.2' && ord($patchRelease) < ord('b'))) {
209 209
 				return (string) $this->l10n->t('cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably.', ['OpenSSL', $versionString, $features]);
210 210
 			}
211 211
 		}
212 212
 
213 213
 		// Check if NSS and perform heuristic check
214
-		if(strpos($versionString, 'NSS/') === 0) {
214
+		if (strpos($versionString, 'NSS/') === 0) {
215 215
 			try {
216 216
 				$firstClient = $this->clientService->newClient();
217 217
 				$firstClient->get('https://www.owncloud.org/');
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
 				$secondClient = $this->clientService->newClient();
220 220
 				$secondClient->get('https://owncloud.org/');
221 221
 			} catch (ClientException $e) {
222
-				if($e->getResponse()->getStatusCode() === 400) {
222
+				if ($e->getResponse()->getStatusCode() === 400) {
223 223
 					return (string) $this->l10n->t('cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably.', ['NSS', $versionString, $features]);
224 224
 				}
225 225
 			}
@@ -300,13 +300,13 @@  discard block
 block discarded – undo
300 300
 	 * @return DataResponse
301 301
 	 */
302 302
 	public function getFailedIntegrityCheckFiles() {
303
-		if(!$this->checker->isCodeCheckEnforced()) {
303
+		if (!$this->checker->isCodeCheckEnforced()) {
304 304
 			return new DataDisplayResponse('Integrity checker has been disabled. Integrity cannot be verified.');
305 305
 		}
306 306
 
307 307
 		$completeResults = $this->checker->getResults();
308 308
 
309
-		if(!empty($completeResults)) {
309
+		if (!empty($completeResults)) {
310 310
 			$formattedTextResponse = 'Technical information
311 311
 =====================
312 312
 The following list covers which files have failed the integrity check. Please read
@@ -316,12 +316,12 @@  discard block
 block discarded – undo
316 316
 Results
317 317
 =======
318 318
 ';
319
-			foreach($completeResults as $context => $contextResult) {
319
+			foreach ($completeResults as $context => $contextResult) {
320 320
 				$formattedTextResponse .= "- $context\n";
321 321
 
322
-				foreach($contextResult as $category => $result) {
322
+				foreach ($contextResult as $category => $result) {
323 323
 					$formattedTextResponse .= "\t- $category\n";
324
-					if($category !== 'EXCEPTION') {
324
+					if ($category !== 'EXCEPTION') {
325 325
 						foreach ($result as $key => $results) {
326 326
 							$formattedTextResponse .= "\t\t- $key\n";
327 327
 						}
@@ -364,27 +364,27 @@  discard block
 block discarded – undo
364 364
 
365 365
 		$isOpcacheProperlySetUp = true;
366 366
 
367
-		if(!$iniWrapper->getBool('opcache.enable')) {
367
+		if (!$iniWrapper->getBool('opcache.enable')) {
368 368
 			$isOpcacheProperlySetUp = false;
369 369
 		}
370 370
 
371
-		if(!$iniWrapper->getBool('opcache.save_comments')) {
371
+		if (!$iniWrapper->getBool('opcache.save_comments')) {
372 372
 			$isOpcacheProperlySetUp = false;
373 373
 		}
374 374
 
375
-		if(!$iniWrapper->getBool('opcache.enable_cli')) {
375
+		if (!$iniWrapper->getBool('opcache.enable_cli')) {
376 376
 			$isOpcacheProperlySetUp = false;
377 377
 		}
378 378
 
379
-		if($iniWrapper->getNumeric('opcache.max_accelerated_files') < 10000) {
379
+		if ($iniWrapper->getNumeric('opcache.max_accelerated_files') < 10000) {
380 380
 			$isOpcacheProperlySetUp = false;
381 381
 		}
382 382
 
383
-		if($iniWrapper->getNumeric('opcache.memory_consumption') < 128) {
383
+		if ($iniWrapper->getNumeric('opcache.memory_consumption') < 128) {
384 384
 			$isOpcacheProperlySetUp = false;
385 385
 		}
386 386
 
387
-		if($iniWrapper->getNumeric('opcache.interned_strings_buffer') < 8) {
387
+		if ($iniWrapper->getNumeric('opcache.interned_strings_buffer') < 8) {
388 388
 			$isOpcacheProperlySetUp = false;
389 389
 		}
390 390
 
Please login to merge, or discard this patch.
Indentation   +372 added lines, -372 removed lines patch added patch discarded remove patch
@@ -46,282 +46,282 @@  discard block
 block discarded – undo
46 46
  * @package OC\Settings\Controller
47 47
  */
48 48
 class CheckSetupController extends Controller {
49
-	/** @var IConfig */
50
-	private $config;
51
-	/** @var IClientService */
52
-	private $clientService;
53
-	/** @var \OC_Util */
54
-	private $util;
55
-	/** @var IURLGenerator */
56
-	private $urlGenerator;
57
-	/** @var IL10N */
58
-	private $l10n;
59
-	/** @var Checker */
60
-	private $checker;
61
-	/** @var ILogger */
62
-	private $logger;
63
-
64
-	/**
65
-	 * @param string $AppName
66
-	 * @param IRequest $request
67
-	 * @param IConfig $config
68
-	 * @param IClientService $clientService
69
-	 * @param IURLGenerator $urlGenerator
70
-	 * @param \OC_Util $util
71
-	 * @param IL10N $l10n
72
-	 * @param Checker $checker
73
-	 * @param ILogger $logger
74
-	 */
75
-	public function __construct($AppName,
76
-								IRequest $request,
77
-								IConfig $config,
78
-								IClientService $clientService,
79
-								IURLGenerator $urlGenerator,
80
-								\OC_Util $util,
81
-								IL10N $l10n,
82
-								Checker $checker,
83
-								ILogger $logger) {
84
-		parent::__construct($AppName, $request);
85
-		$this->config = $config;
86
-		$this->clientService = $clientService;
87
-		$this->util = $util;
88
-		$this->urlGenerator = $urlGenerator;
89
-		$this->l10n = $l10n;
90
-		$this->checker = $checker;
91
-		$this->logger = $logger;
92
-	}
93
-
94
-	/**
95
-	 * Checks if the ownCloud server can connect to the internet using HTTPS and HTTP
96
-	 * @return bool
97
-	 */
98
-	private function isInternetConnectionWorking() {
99
-		if ($this->config->getSystemValue('has_internet_connection', true) === false) {
100
-			return false;
101
-		}
102
-
103
-		$siteArray = ['www.nextcloud.com',
104
-						'www.google.com',
105
-						'www.github.com'];
106
-
107
-		foreach($siteArray as $site) {
108
-			if ($this->isSiteReachable($site)) {
109
-				return true;
110
-			}
111
-		}
112
-		return false;
113
-	}
114
-
115
-	/**
116
-	* Chceks if the ownCloud server can connect to a specific URL using both HTTPS and HTTP
117
-	* @return bool
118
-	*/
119
-	private function isSiteReachable($sitename) {
120
-		$httpSiteName = 'http://' . $sitename . '/';
121
-		$httpsSiteName = 'https://' . $sitename . '/';
122
-
123
-		try {
124
-			$client = $this->clientService->newClient();
125
-			$client->get($httpSiteName);
126
-			$client->get($httpsSiteName);
127
-		} catch (\Exception $e) {
128
-			$this->logger->logException($e, ['app' => 'internet_connection_check']);
129
-			return false;
130
-		}
131
-		return true;
132
-	}
133
-
134
-	/**
135
-	 * Checks whether a local memcache is installed or not
136
-	 * @return bool
137
-	 */
138
-	private function isMemcacheConfigured() {
139
-		return $this->config->getSystemValue('memcache.local', null) !== null;
140
-	}
141
-
142
-	/**
143
-	 * Whether /dev/urandom is available to the PHP controller
144
-	 *
145
-	 * @return bool
146
-	 */
147
-	private function isUrandomAvailable() {
148
-		if(@file_exists('/dev/urandom')) {
149
-			$file = fopen('/dev/urandom', 'rb');
150
-			if($file) {
151
-				fclose($file);
152
-				return true;
153
-			}
154
-		}
155
-
156
-		return false;
157
-	}
158
-
159
-	/**
160
-	 * Public for the sake of unit-testing
161
-	 *
162
-	 * @return array
163
-	 */
164
-	protected function getCurlVersion() {
165
-		return curl_version();
166
-	}
167
-
168
-	/**
169
-	 * Check if the used  SSL lib is outdated. Older OpenSSL and NSS versions do
170
-	 * have multiple bugs which likely lead to problems in combination with
171
-	 * functionality required by ownCloud such as SNI.
172
-	 *
173
-	 * @link https://github.com/owncloud/core/issues/17446#issuecomment-122877546
174
-	 * @link https://bugzilla.redhat.com/show_bug.cgi?id=1241172
175
-	 * @return string
176
-	 */
177
-	private function isUsedTlsLibOutdated() {
178
-		// Don't run check when:
179
-		// 1. Server has `has_internet_connection` set to false
180
-		// 2. AppStore AND S2S is disabled
181
-		if(!$this->config->getSystemValue('has_internet_connection', true)) {
182
-			return '';
183
-		}
184
-		if(!$this->config->getSystemValue('appstoreenabled', true)
185
-			&& $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'no'
186
-			&& $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes') === 'no') {
187
-			return '';
188
-		}
189
-
190
-		$versionString = $this->getCurlVersion();
191
-		if(isset($versionString['ssl_version'])) {
192
-			$versionString = $versionString['ssl_version'];
193
-		} else {
194
-			return '';
195
-		}
196
-
197
-		$features = (string)$this->l10n->t('installing and updating apps via the app store or Federated Cloud Sharing');
198
-		if(!$this->config->getSystemValue('appstoreenabled', true)) {
199
-			$features = (string)$this->l10n->t('Federated Cloud Sharing');
200
-		}
201
-
202
-		// Check if at least OpenSSL after 1.01d or 1.0.2b
203
-		if(strpos($versionString, 'OpenSSL/') === 0) {
204
-			$majorVersion = substr($versionString, 8, 5);
205
-			$patchRelease = substr($versionString, 13, 6);
206
-
207
-			if(($majorVersion === '1.0.1' && ord($patchRelease) < ord('d')) ||
208
-				($majorVersion === '1.0.2' && ord($patchRelease) < ord('b'))) {
209
-				return (string) $this->l10n->t('cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably.', ['OpenSSL', $versionString, $features]);
210
-			}
211
-		}
212
-
213
-		// Check if NSS and perform heuristic check
214
-		if(strpos($versionString, 'NSS/') === 0) {
215
-			try {
216
-				$firstClient = $this->clientService->newClient();
217
-				$firstClient->get('https://www.owncloud.org/');
218
-
219
-				$secondClient = $this->clientService->newClient();
220
-				$secondClient->get('https://owncloud.org/');
221
-			} catch (ClientException $e) {
222
-				if($e->getResponse()->getStatusCode() === 400) {
223
-					return (string) $this->l10n->t('cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably.', ['NSS', $versionString, $features]);
224
-				}
225
-			}
226
-		}
227
-
228
-		return '';
229
-	}
230
-
231
-	/**
232
-	 * Whether the version is outdated
233
-	 *
234
-	 * @return bool
235
-	 */
236
-	protected function isPhpOutdated() {
237
-		if (version_compare(PHP_VERSION, '5.5.0') === -1) {
238
-			return true;
239
-		}
240
-
241
-		return false;
242
-	}
243
-
244
-	/**
245
-	 * Whether the php version is still supported (at time of release)
246
-	 * according to: https://secure.php.net/supported-versions.php
247
-	 *
248
-	 * @return array
249
-	 */
250
-	private function isPhpSupported() {
251
-		return ['eol' => $this->isPhpOutdated(), 'version' => PHP_VERSION];
252
-	}
253
-
254
-	/**
255
-	 * Check if the reverse proxy configuration is working as expected
256
-	 *
257
-	 * @return bool
258
-	 */
259
-	private function forwardedForHeadersWorking() {
260
-		$trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
261
-		$remoteAddress = $this->request->getRemoteAddress();
262
-
263
-		if (is_array($trustedProxies) && in_array($remoteAddress, $trustedProxies)) {
264
-			return false;
265
-		}
266
-
267
-		// either not enabled or working correctly
268
-		return true;
269
-	}
270
-
271
-	/**
272
-	 * Checks if the correct memcache module for PHP is installed. Only
273
-	 * fails if memcached is configured and the working module is not installed.
274
-	 *
275
-	 * @return bool
276
-	 */
277
-	private function isCorrectMemcachedPHPModuleInstalled() {
278
-		if ($this->config->getSystemValue('memcache.distributed', null) !== '\OC\Memcache\Memcached') {
279
-			return true;
280
-		}
281
-
282
-		// there are two different memcached modules for PHP
283
-		// we only support memcached and not memcache
284
-		// https://code.google.com/p/memcached/wiki/PHPClientComparison
285
-		return !(!extension_loaded('memcached') && extension_loaded('memcache'));
286
-	}
287
-
288
-	/**
289
-	 * Checks if set_time_limit is not disabled.
290
-	 *
291
-	 * @return bool
292
-	 */
293
-	private function isSettimelimitAvailable() {
294
-		if (function_exists('set_time_limit')
295
-			&& strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
296
-			return true;
297
-		}
298
-
299
-		return false;
300
-	}
301
-
302
-	/**
303
-	 * @return RedirectResponse
304
-	 */
305
-	public function rescanFailedIntegrityCheck() {
306
-		$this->checker->runInstanceVerification();
307
-		return new RedirectResponse(
308
-			$this->urlGenerator->linkToRoute('settings.AdminSettings.index')
309
-		);
310
-	}
311
-
312
-	/**
313
-	 * @NoCSRFRequired
314
-	 * @return DataResponse
315
-	 */
316
-	public function getFailedIntegrityCheckFiles() {
317
-		if(!$this->checker->isCodeCheckEnforced()) {
318
-			return new DataDisplayResponse('Integrity checker has been disabled. Integrity cannot be verified.');
319
-		}
320
-
321
-		$completeResults = $this->checker->getResults();
322
-
323
-		if(!empty($completeResults)) {
324
-			$formattedTextResponse = 'Technical information
49
+    /** @var IConfig */
50
+    private $config;
51
+    /** @var IClientService */
52
+    private $clientService;
53
+    /** @var \OC_Util */
54
+    private $util;
55
+    /** @var IURLGenerator */
56
+    private $urlGenerator;
57
+    /** @var IL10N */
58
+    private $l10n;
59
+    /** @var Checker */
60
+    private $checker;
61
+    /** @var ILogger */
62
+    private $logger;
63
+
64
+    /**
65
+     * @param string $AppName
66
+     * @param IRequest $request
67
+     * @param IConfig $config
68
+     * @param IClientService $clientService
69
+     * @param IURLGenerator $urlGenerator
70
+     * @param \OC_Util $util
71
+     * @param IL10N $l10n
72
+     * @param Checker $checker
73
+     * @param ILogger $logger
74
+     */
75
+    public function __construct($AppName,
76
+                                IRequest $request,
77
+                                IConfig $config,
78
+                                IClientService $clientService,
79
+                                IURLGenerator $urlGenerator,
80
+                                \OC_Util $util,
81
+                                IL10N $l10n,
82
+                                Checker $checker,
83
+                                ILogger $logger) {
84
+        parent::__construct($AppName, $request);
85
+        $this->config = $config;
86
+        $this->clientService = $clientService;
87
+        $this->util = $util;
88
+        $this->urlGenerator = $urlGenerator;
89
+        $this->l10n = $l10n;
90
+        $this->checker = $checker;
91
+        $this->logger = $logger;
92
+    }
93
+
94
+    /**
95
+     * Checks if the ownCloud server can connect to the internet using HTTPS and HTTP
96
+     * @return bool
97
+     */
98
+    private function isInternetConnectionWorking() {
99
+        if ($this->config->getSystemValue('has_internet_connection', true) === false) {
100
+            return false;
101
+        }
102
+
103
+        $siteArray = ['www.nextcloud.com',
104
+                        'www.google.com',
105
+                        'www.github.com'];
106
+
107
+        foreach($siteArray as $site) {
108
+            if ($this->isSiteReachable($site)) {
109
+                return true;
110
+            }
111
+        }
112
+        return false;
113
+    }
114
+
115
+    /**
116
+     * Chceks if the ownCloud server can connect to a specific URL using both HTTPS and HTTP
117
+     * @return bool
118
+     */
119
+    private function isSiteReachable($sitename) {
120
+        $httpSiteName = 'http://' . $sitename . '/';
121
+        $httpsSiteName = 'https://' . $sitename . '/';
122
+
123
+        try {
124
+            $client = $this->clientService->newClient();
125
+            $client->get($httpSiteName);
126
+            $client->get($httpsSiteName);
127
+        } catch (\Exception $e) {
128
+            $this->logger->logException($e, ['app' => 'internet_connection_check']);
129
+            return false;
130
+        }
131
+        return true;
132
+    }
133
+
134
+    /**
135
+     * Checks whether a local memcache is installed or not
136
+     * @return bool
137
+     */
138
+    private function isMemcacheConfigured() {
139
+        return $this->config->getSystemValue('memcache.local', null) !== null;
140
+    }
141
+
142
+    /**
143
+     * Whether /dev/urandom is available to the PHP controller
144
+     *
145
+     * @return bool
146
+     */
147
+    private function isUrandomAvailable() {
148
+        if(@file_exists('/dev/urandom')) {
149
+            $file = fopen('/dev/urandom', 'rb');
150
+            if($file) {
151
+                fclose($file);
152
+                return true;
153
+            }
154
+        }
155
+
156
+        return false;
157
+    }
158
+
159
+    /**
160
+     * Public for the sake of unit-testing
161
+     *
162
+     * @return array
163
+     */
164
+    protected function getCurlVersion() {
165
+        return curl_version();
166
+    }
167
+
168
+    /**
169
+     * Check if the used  SSL lib is outdated. Older OpenSSL and NSS versions do
170
+     * have multiple bugs which likely lead to problems in combination with
171
+     * functionality required by ownCloud such as SNI.
172
+     *
173
+     * @link https://github.com/owncloud/core/issues/17446#issuecomment-122877546
174
+     * @link https://bugzilla.redhat.com/show_bug.cgi?id=1241172
175
+     * @return string
176
+     */
177
+    private function isUsedTlsLibOutdated() {
178
+        // Don't run check when:
179
+        // 1. Server has `has_internet_connection` set to false
180
+        // 2. AppStore AND S2S is disabled
181
+        if(!$this->config->getSystemValue('has_internet_connection', true)) {
182
+            return '';
183
+        }
184
+        if(!$this->config->getSystemValue('appstoreenabled', true)
185
+            && $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'no'
186
+            && $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes') === 'no') {
187
+            return '';
188
+        }
189
+
190
+        $versionString = $this->getCurlVersion();
191
+        if(isset($versionString['ssl_version'])) {
192
+            $versionString = $versionString['ssl_version'];
193
+        } else {
194
+            return '';
195
+        }
196
+
197
+        $features = (string)$this->l10n->t('installing and updating apps via the app store or Federated Cloud Sharing');
198
+        if(!$this->config->getSystemValue('appstoreenabled', true)) {
199
+            $features = (string)$this->l10n->t('Federated Cloud Sharing');
200
+        }
201
+
202
+        // Check if at least OpenSSL after 1.01d or 1.0.2b
203
+        if(strpos($versionString, 'OpenSSL/') === 0) {
204
+            $majorVersion = substr($versionString, 8, 5);
205
+            $patchRelease = substr($versionString, 13, 6);
206
+
207
+            if(($majorVersion === '1.0.1' && ord($patchRelease) < ord('d')) ||
208
+                ($majorVersion === '1.0.2' && ord($patchRelease) < ord('b'))) {
209
+                return (string) $this->l10n->t('cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably.', ['OpenSSL', $versionString, $features]);
210
+            }
211
+        }
212
+
213
+        // Check if NSS and perform heuristic check
214
+        if(strpos($versionString, 'NSS/') === 0) {
215
+            try {
216
+                $firstClient = $this->clientService->newClient();
217
+                $firstClient->get('https://www.owncloud.org/');
218
+
219
+                $secondClient = $this->clientService->newClient();
220
+                $secondClient->get('https://owncloud.org/');
221
+            } catch (ClientException $e) {
222
+                if($e->getResponse()->getStatusCode() === 400) {
223
+                    return (string) $this->l10n->t('cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably.', ['NSS', $versionString, $features]);
224
+                }
225
+            }
226
+        }
227
+
228
+        return '';
229
+    }
230
+
231
+    /**
232
+     * Whether the version is outdated
233
+     *
234
+     * @return bool
235
+     */
236
+    protected function isPhpOutdated() {
237
+        if (version_compare(PHP_VERSION, '5.5.0') === -1) {
238
+            return true;
239
+        }
240
+
241
+        return false;
242
+    }
243
+
244
+    /**
245
+     * Whether the php version is still supported (at time of release)
246
+     * according to: https://secure.php.net/supported-versions.php
247
+     *
248
+     * @return array
249
+     */
250
+    private function isPhpSupported() {
251
+        return ['eol' => $this->isPhpOutdated(), 'version' => PHP_VERSION];
252
+    }
253
+
254
+    /**
255
+     * Check if the reverse proxy configuration is working as expected
256
+     *
257
+     * @return bool
258
+     */
259
+    private function forwardedForHeadersWorking() {
260
+        $trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
261
+        $remoteAddress = $this->request->getRemoteAddress();
262
+
263
+        if (is_array($trustedProxies) && in_array($remoteAddress, $trustedProxies)) {
264
+            return false;
265
+        }
266
+
267
+        // either not enabled or working correctly
268
+        return true;
269
+    }
270
+
271
+    /**
272
+     * Checks if the correct memcache module for PHP is installed. Only
273
+     * fails if memcached is configured and the working module is not installed.
274
+     *
275
+     * @return bool
276
+     */
277
+    private function isCorrectMemcachedPHPModuleInstalled() {
278
+        if ($this->config->getSystemValue('memcache.distributed', null) !== '\OC\Memcache\Memcached') {
279
+            return true;
280
+        }
281
+
282
+        // there are two different memcached modules for PHP
283
+        // we only support memcached and not memcache
284
+        // https://code.google.com/p/memcached/wiki/PHPClientComparison
285
+        return !(!extension_loaded('memcached') && extension_loaded('memcache'));
286
+    }
287
+
288
+    /**
289
+     * Checks if set_time_limit is not disabled.
290
+     *
291
+     * @return bool
292
+     */
293
+    private function isSettimelimitAvailable() {
294
+        if (function_exists('set_time_limit')
295
+            && strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
296
+            return true;
297
+        }
298
+
299
+        return false;
300
+    }
301
+
302
+    /**
303
+     * @return RedirectResponse
304
+     */
305
+    public function rescanFailedIntegrityCheck() {
306
+        $this->checker->runInstanceVerification();
307
+        return new RedirectResponse(
308
+            $this->urlGenerator->linkToRoute('settings.AdminSettings.index')
309
+        );
310
+    }
311
+
312
+    /**
313
+     * @NoCSRFRequired
314
+     * @return DataResponse
315
+     */
316
+    public function getFailedIntegrityCheckFiles() {
317
+        if(!$this->checker->isCodeCheckEnforced()) {
318
+            return new DataDisplayResponse('Integrity checker has been disabled. Integrity cannot be verified.');
319
+        }
320
+
321
+        $completeResults = $this->checker->getResults();
322
+
323
+        if(!empty($completeResults)) {
324
+            $formattedTextResponse = 'Technical information
325 325
 =====================
326 326
 The following list covers which files have failed the integrity check. Please read
327 327
 the previous linked documentation to learn more about the errors and how to fix
@@ -330,103 +330,103 @@  discard block
 block discarded – undo
330 330
 Results
331 331
 =======
332 332
 ';
333
-			foreach($completeResults as $context => $contextResult) {
334
-				$formattedTextResponse .= "- $context\n";
335
-
336
-				foreach($contextResult as $category => $result) {
337
-					$formattedTextResponse .= "\t- $category\n";
338
-					if($category !== 'EXCEPTION') {
339
-						foreach ($result as $key => $results) {
340
-							$formattedTextResponse .= "\t\t- $key\n";
341
-						}
342
-					} else {
343
-						foreach ($result as $key => $results) {
344
-							$formattedTextResponse .= "\t\t- $results\n";
345
-						}
346
-					}
347
-
348
-				}
349
-			}
350
-
351
-			$formattedTextResponse .= '
333
+            foreach($completeResults as $context => $contextResult) {
334
+                $formattedTextResponse .= "- $context\n";
335
+
336
+                foreach($contextResult as $category => $result) {
337
+                    $formattedTextResponse .= "\t- $category\n";
338
+                    if($category !== 'EXCEPTION') {
339
+                        foreach ($result as $key => $results) {
340
+                            $formattedTextResponse .= "\t\t- $key\n";
341
+                        }
342
+                    } else {
343
+                        foreach ($result as $key => $results) {
344
+                            $formattedTextResponse .= "\t\t- $results\n";
345
+                        }
346
+                    }
347
+
348
+                }
349
+            }
350
+
351
+            $formattedTextResponse .= '
352 352
 Raw output
353 353
 ==========
354 354
 ';
355
-			$formattedTextResponse .= print_r($completeResults, true);
356
-		} else {
357
-			$formattedTextResponse = 'No errors have been found.';
358
-		}
359
-
360
-
361
-		$response = new DataDisplayResponse(
362
-			$formattedTextResponse,
363
-			Http::STATUS_OK,
364
-			[
365
-				'Content-Type' => 'text/plain',
366
-			]
367
-		);
368
-
369
-		return $response;
370
-	}
371
-
372
-	/**
373
-	 * Checks whether a PHP opcache is properly set up
374
-	 * @return bool
375
-	 */
376
-	private function isOpcacheProperlySetup() {
377
-		$iniWrapper = new IniGetWrapper();
378
-
379
-		$isOpcacheProperlySetUp = true;
380
-
381
-		if(!$iniWrapper->getBool('opcache.enable')) {
382
-			$isOpcacheProperlySetUp = false;
383
-		}
384
-
385
-		if(!$iniWrapper->getBool('opcache.save_comments')) {
386
-			$isOpcacheProperlySetUp = false;
387
-		}
388
-
389
-		if(!$iniWrapper->getBool('opcache.enable_cli')) {
390
-			$isOpcacheProperlySetUp = false;
391
-		}
392
-
393
-		if($iniWrapper->getNumeric('opcache.max_accelerated_files') < 10000) {
394
-			$isOpcacheProperlySetUp = false;
395
-		}
396
-
397
-		if($iniWrapper->getNumeric('opcache.memory_consumption') < 128) {
398
-			$isOpcacheProperlySetUp = false;
399
-		}
400
-
401
-		if($iniWrapper->getNumeric('opcache.interned_strings_buffer') < 8) {
402
-			$isOpcacheProperlySetUp = false;
403
-		}
404
-
405
-		return $isOpcacheProperlySetUp;
406
-	}
407
-
408
-	/**
409
-	 * @return DataResponse
410
-	 */
411
-	public function check() {
412
-		return new DataResponse(
413
-			[
414
-				'serverHasInternetConnection' => $this->isInternetConnectionWorking(),
415
-				'isMemcacheConfigured' => $this->isMemcacheConfigured(),
416
-				'memcacheDocs' => $this->urlGenerator->linkToDocs('admin-performance'),
417
-				'isUrandomAvailable' => $this->isUrandomAvailable(),
418
-				'securityDocs' => $this->urlGenerator->linkToDocs('admin-security'),
419
-				'isUsedTlsLibOutdated' => $this->isUsedTlsLibOutdated(),
420
-				'phpSupported' => $this->isPhpSupported(),
421
-				'forwardedForHeadersWorking' => $this->forwardedForHeadersWorking(),
422
-				'reverseProxyDocs' => $this->urlGenerator->linkToDocs('admin-reverse-proxy'),
423
-				'isCorrectMemcachedPHPModuleInstalled' => $this->isCorrectMemcachedPHPModuleInstalled(),
424
-				'hasPassedCodeIntegrityCheck' => $this->checker->hasPassedCheck(),
425
-				'codeIntegrityCheckerDocumentation' => $this->urlGenerator->linkToDocs('admin-code-integrity'),
426
-				'isOpcacheProperlySetup' => $this->isOpcacheProperlySetup(),
427
-				'phpOpcacheDocumentation' => $this->urlGenerator->linkToDocs('admin-php-opcache'),
428
-				'isSettimelimitAvailable' => $this->isSettimelimitAvailable(),
429
-			]
430
-		);
431
-	}
355
+            $formattedTextResponse .= print_r($completeResults, true);
356
+        } else {
357
+            $formattedTextResponse = 'No errors have been found.';
358
+        }
359
+
360
+
361
+        $response = new DataDisplayResponse(
362
+            $formattedTextResponse,
363
+            Http::STATUS_OK,
364
+            [
365
+                'Content-Type' => 'text/plain',
366
+            ]
367
+        );
368
+
369
+        return $response;
370
+    }
371
+
372
+    /**
373
+     * Checks whether a PHP opcache is properly set up
374
+     * @return bool
375
+     */
376
+    private function isOpcacheProperlySetup() {
377
+        $iniWrapper = new IniGetWrapper();
378
+
379
+        $isOpcacheProperlySetUp = true;
380
+
381
+        if(!$iniWrapper->getBool('opcache.enable')) {
382
+            $isOpcacheProperlySetUp = false;
383
+        }
384
+
385
+        if(!$iniWrapper->getBool('opcache.save_comments')) {
386
+            $isOpcacheProperlySetUp = false;
387
+        }
388
+
389
+        if(!$iniWrapper->getBool('opcache.enable_cli')) {
390
+            $isOpcacheProperlySetUp = false;
391
+        }
392
+
393
+        if($iniWrapper->getNumeric('opcache.max_accelerated_files') < 10000) {
394
+            $isOpcacheProperlySetUp = false;
395
+        }
396
+
397
+        if($iniWrapper->getNumeric('opcache.memory_consumption') < 128) {
398
+            $isOpcacheProperlySetUp = false;
399
+        }
400
+
401
+        if($iniWrapper->getNumeric('opcache.interned_strings_buffer') < 8) {
402
+            $isOpcacheProperlySetUp = false;
403
+        }
404
+
405
+        return $isOpcacheProperlySetUp;
406
+    }
407
+
408
+    /**
409
+     * @return DataResponse
410
+     */
411
+    public function check() {
412
+        return new DataResponse(
413
+            [
414
+                'serverHasInternetConnection' => $this->isInternetConnectionWorking(),
415
+                'isMemcacheConfigured' => $this->isMemcacheConfigured(),
416
+                'memcacheDocs' => $this->urlGenerator->linkToDocs('admin-performance'),
417
+                'isUrandomAvailable' => $this->isUrandomAvailable(),
418
+                'securityDocs' => $this->urlGenerator->linkToDocs('admin-security'),
419
+                'isUsedTlsLibOutdated' => $this->isUsedTlsLibOutdated(),
420
+                'phpSupported' => $this->isPhpSupported(),
421
+                'forwardedForHeadersWorking' => $this->forwardedForHeadersWorking(),
422
+                'reverseProxyDocs' => $this->urlGenerator->linkToDocs('admin-reverse-proxy'),
423
+                'isCorrectMemcachedPHPModuleInstalled' => $this->isCorrectMemcachedPHPModuleInstalled(),
424
+                'hasPassedCodeIntegrityCheck' => $this->checker->hasPassedCheck(),
425
+                'codeIntegrityCheckerDocumentation' => $this->urlGenerator->linkToDocs('admin-code-integrity'),
426
+                'isOpcacheProperlySetup' => $this->isOpcacheProperlySetup(),
427
+                'phpOpcacheDocumentation' => $this->urlGenerator->linkToDocs('admin-php-opcache'),
428
+                'isSettimelimitAvailable' => $this->isSettimelimitAvailable(),
429
+            ]
430
+        );
431
+    }
432 432
 }
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   +1318 added lines, -1318 removed lines patch added patch discarded remove patch
@@ -37,1324 +37,1324 @@
 block discarded – undo
37 37
 use OC\ServerNotAvailableException;
38 38
 
39 39
 class Wizard extends LDAPUtility {
40
-	/** @var \OCP\IL10N */
41
-	static protected $l;
42
-	protected $access;
43
-	protected $cr;
44
-	protected $configuration;
45
-	protected $result;
46
-	protected $resultCache = array();
47
-
48
-	const LRESULT_PROCESSED_OK = 2;
49
-	const LRESULT_PROCESSED_INVALID = 3;
50
-	const LRESULT_PROCESSED_SKIP = 4;
51
-
52
-	const LFILTER_LOGIN      = 2;
53
-	const LFILTER_USER_LIST  = 3;
54
-	const LFILTER_GROUP_LIST = 4;
55
-
56
-	const LFILTER_MODE_ASSISTED = 2;
57
-	const LFILTER_MODE_RAW = 1;
58
-
59
-	const LDAP_NW_TIMEOUT = 4;
60
-
61
-	/**
62
-	 * Constructor
63
-	 * @param Configuration $configuration an instance of Configuration
64
-	 * @param ILDAPWrapper $ldap an instance of ILDAPWrapper
65
-	 * @param Access $access
66
-	 */
67
-	public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) {
68
-		parent::__construct($ldap);
69
-		$this->configuration = $configuration;
70
-		if(is_null(Wizard::$l)) {
71
-			Wizard::$l = \OC::$server->getL10N('user_ldap');
72
-		}
73
-		$this->access = $access;
74
-		$this->result = new WizardResult();
75
-	}
76
-
77
-	public function  __destruct() {
78
-		if($this->result->hasChanges()) {
79
-			$this->configuration->saveConfiguration();
80
-		}
81
-	}
82
-
83
-	/**
84
-	 * counts entries in the LDAP directory
85
-	 *
86
-	 * @param string $filter the LDAP search filter
87
-	 * @param string $type a string being either 'users' or 'groups';
88
-	 * @return bool|int
89
-	 * @throws \Exception
90
-	 */
91
-	public function countEntries($filter, $type) {
92
-		$reqs = array('ldapHost', 'ldapPort', 'ldapBase');
93
-		if($type === 'users') {
94
-			$reqs[] = 'ldapUserFilter';
95
-		}
96
-		if(!$this->checkRequirements($reqs)) {
97
-			throw new \Exception('Requirements not met', 400);
98
-		}
99
-
100
-		$attr = array('dn'); // default
101
-		$limit = 1001;
102
-		if($type === 'groups') {
103
-			$result =  $this->access->countGroups($filter, $attr, $limit);
104
-		} else if($type === 'users') {
105
-			$result = $this->access->countUsers($filter, $attr, $limit);
106
-		} else if ($type === 'objects') {
107
-			$result = $this->access->countObjects($limit);
108
-		} else {
109
-			throw new \Exception('internal error: invalid object type', 500);
110
-		}
111
-
112
-		return $result;
113
-	}
114
-
115
-	/**
116
-	 * formats the return value of a count operation to the string to be
117
-	 * inserted.
118
-	 *
119
-	 * @param bool|int $count
120
-	 * @return int|string
121
-	 */
122
-	private function formatCountResult($count) {
123
-		$formatted = ($count !== false) ? $count : 0;
124
-		if($formatted > 1000) {
125
-			$formatted = '> 1000';
126
-		}
127
-		return $formatted;
128
-	}
129
-
130
-	public function countGroups() {
131
-		$filter = $this->configuration->ldapGroupFilter;
132
-
133
-		if(empty($filter)) {
134
-			$output = self::$l->n('%s group found', '%s groups found', 0, array(0));
135
-			$this->result->addChange('ldap_group_count', $output);
136
-			return $this->result;
137
-		}
138
-
139
-		try {
140
-			$groupsTotal = $this->formatCountResult($this->countEntries($filter, 'groups'));
141
-		} catch (\Exception $e) {
142
-			//400 can be ignored, 500 is forwarded
143
-			if($e->getCode() === 500) {
144
-				throw $e;
145
-			}
146
-			return false;
147
-		}
148
-		$output = self::$l->n('%s group found', '%s groups found', $groupsTotal, array($groupsTotal));
149
-		$this->result->addChange('ldap_group_count', $output);
150
-		return $this->result;
151
-	}
152
-
153
-	/**
154
-	 * @return WizardResult
155
-	 * @throws \Exception
156
-	 */
157
-	public function countUsers() {
158
-		$filter = $this->access->getFilterForUserCount();
159
-
160
-		$usersTotal = $this->formatCountResult($this->countEntries($filter, 'users'));
161
-		$output = self::$l->n('%s user found', '%s users found', $usersTotal, array($usersTotal));
162
-		$this->result->addChange('ldap_user_count', $output);
163
-		return $this->result;
164
-	}
165
-
166
-	/**
167
-	 * counts any objects in the currently set base dn
168
-	 *
169
-	 * @return WizardResult
170
-	 * @throws \Exception
171
-	 */
172
-	public function countInBaseDN() {
173
-		// we don't need to provide a filter in this case
174
-		$total = $this->countEntries(null, 'objects');
175
-		if($total === false) {
176
-			throw new \Exception('invalid results received');
177
-		}
178
-		$this->result->addChange('ldap_test_base', $total);
179
-		return $this->result;
180
-	}
181
-
182
-	/**
183
-	 * counts users with a specified attribute
184
-	 * @param string $attr
185
-	 * @param bool $existsCheck
186
-	 * @return int|bool
187
-	 */
188
-	public function countUsersWithAttribute($attr, $existsCheck = false) {
189
-		if(!$this->checkRequirements(array('ldapHost',
190
-										   'ldapPort',
191
-										   'ldapBase',
192
-										   'ldapUserFilter',
193
-										   ))) {
194
-			return  false;
195
-		}
196
-
197
-		$filter = $this->access->combineFilterWithAnd(array(
198
-			$this->configuration->ldapUserFilter,
199
-			$attr . '=*'
200
-		));
201
-
202
-		$limit = ($existsCheck === false) ? null : 1;
203
-
204
-		return $this->access->countUsers($filter, array('dn'), $limit);
205
-	}
206
-
207
-	/**
208
-	 * detects the display name attribute. If a setting is already present that
209
-	 * returns at least one hit, the detection will be canceled.
210
-	 * @return WizardResult|bool
211
-	 * @throws \Exception
212
-	 */
213
-	public function detectUserDisplayNameAttribute() {
214
-		if(!$this->checkRequirements(array('ldapHost',
215
-										'ldapPort',
216
-										'ldapBase',
217
-										'ldapUserFilter',
218
-										))) {
219
-			return  false;
220
-		}
221
-
222
-		$attr = $this->configuration->ldapUserDisplayName;
223
-		if ($attr !== '' && $attr !== 'displayName') {
224
-			// most likely not the default value with upper case N,
225
-			// verify it still produces a result
226
-			$count = intval($this->countUsersWithAttribute($attr, true));
227
-			if($count > 0) {
228
-				//no change, but we sent it back to make sure the user interface
229
-				//is still correct, even if the ajax call was cancelled meanwhile
230
-				$this->result->addChange('ldap_display_name', $attr);
231
-				return $this->result;
232
-			}
233
-		}
234
-
235
-		// first attribute that has at least one result wins
236
-		$displayNameAttrs = array('displayname', 'cn');
237
-		foreach ($displayNameAttrs as $attr) {
238
-			$count = intval($this->countUsersWithAttribute($attr, true));
239
-
240
-			if($count > 0) {
241
-				$this->applyFind('ldap_display_name', $attr);
242
-				return $this->result;
243
-			}
244
-		};
245
-
246
-		throw new \Exception(self::$l->t('Could not detect user display name attribute. Please specify it yourself in advanced ldap settings.'));
247
-	}
248
-
249
-	/**
250
-	 * detects the most often used email attribute for users applying to the
251
-	 * user list filter. If a setting is already present that returns at least
252
-	 * one hit, the detection will be canceled.
253
-	 * @return WizardResult|bool
254
-	 */
255
-	public function detectEmailAttribute() {
256
-		if(!$this->checkRequirements(array('ldapHost',
257
-										   'ldapPort',
258
-										   'ldapBase',
259
-										   'ldapUserFilter',
260
-										   ))) {
261
-			return  false;
262
-		}
263
-
264
-		$attr = $this->configuration->ldapEmailAttribute;
265
-		if ($attr !== '') {
266
-			$count = intval($this->countUsersWithAttribute($attr, true));
267
-			if($count > 0) {
268
-				return false;
269
-			}
270
-			$writeLog = true;
271
-		} else {
272
-			$writeLog = false;
273
-		}
274
-
275
-		$emailAttributes = array('mail', 'mailPrimaryAddress');
276
-		$winner = '';
277
-		$maxUsers = 0;
278
-		foreach($emailAttributes as $attr) {
279
-			$count = $this->countUsersWithAttribute($attr);
280
-			if($count > $maxUsers) {
281
-				$maxUsers = $count;
282
-				$winner = $attr;
283
-			}
284
-		}
285
-
286
-		if($winner !== '') {
287
-			$this->applyFind('ldap_email_attr', $winner);
288
-			if($writeLog) {
289
-				\OCP\Util::writeLog('user_ldap', 'The mail attribute has ' .
290
-					'automatically been reset, because the original value ' .
291
-					'did not return any results.', \OCP\Util::INFO);
292
-			}
293
-		}
294
-
295
-		return $this->result;
296
-	}
297
-
298
-	/**
299
-	 * @return WizardResult
300
-	 * @throws \Exception
301
-	 */
302
-	public function determineAttributes() {
303
-		if(!$this->checkRequirements(array('ldapHost',
304
-										   'ldapPort',
305
-										   'ldapBase',
306
-										   'ldapUserFilter',
307
-										   ))) {
308
-			return  false;
309
-		}
310
-
311
-		$attributes = $this->getUserAttributes();
312
-
313
-		natcasesort($attributes);
314
-		$attributes = array_values($attributes);
315
-
316
-		$this->result->addOptions('ldap_loginfilter_attributes', $attributes);
317
-
318
-		$selected = $this->configuration->ldapLoginFilterAttributes;
319
-		if(is_array($selected) && !empty($selected)) {
320
-			$this->result->addChange('ldap_loginfilter_attributes', $selected);
321
-		}
322
-
323
-		return $this->result;
324
-	}
325
-
326
-	/**
327
-	 * detects the available LDAP attributes
328
-	 * @return array|false The instance's WizardResult instance
329
-	 * @throws \Exception
330
-	 */
331
-	private function getUserAttributes() {
332
-		if(!$this->checkRequirements(array('ldapHost',
333
-										   'ldapPort',
334
-										   'ldapBase',
335
-										   'ldapUserFilter',
336
-										   ))) {
337
-			return  false;
338
-		}
339
-		$cr = $this->getConnection();
340
-		if(!$cr) {
341
-			throw new \Exception('Could not connect to LDAP');
342
-		}
343
-
344
-		$base = $this->configuration->ldapBase[0];
345
-		$filter = $this->configuration->ldapUserFilter;
346
-		$rr = $this->ldap->search($cr, $base, $filter, array(), 1, 1);
347
-		if(!$this->ldap->isResource($rr)) {
348
-			return false;
349
-		}
350
-		$er = $this->ldap->firstEntry($cr, $rr);
351
-		$attributes = $this->ldap->getAttributes($cr, $er);
352
-		$pureAttributes = array();
353
-		for($i = 0; $i < $attributes['count']; $i++) {
354
-			$pureAttributes[] = $attributes[$i];
355
-		}
356
-
357
-		return $pureAttributes;
358
-	}
359
-
360
-	/**
361
-	 * detects the available LDAP groups
362
-	 * @return WizardResult|false the instance's WizardResult instance
363
-	 */
364
-	public function determineGroupsForGroups() {
365
-		return $this->determineGroups('ldap_groupfilter_groups',
366
-									  'ldapGroupFilterGroups',
367
-									  false);
368
-	}
369
-
370
-	/**
371
-	 * detects the available LDAP groups
372
-	 * @return WizardResult|false the instance's WizardResult instance
373
-	 */
374
-	public function determineGroupsForUsers() {
375
-		return $this->determineGroups('ldap_userfilter_groups',
376
-									  'ldapUserFilterGroups');
377
-	}
378
-
379
-	/**
380
-	 * detects the available LDAP groups
381
-	 * @param string $dbKey
382
-	 * @param string $confKey
383
-	 * @param bool $testMemberOf
384
-	 * @return WizardResult|false the instance's WizardResult instance
385
-	 * @throws \Exception
386
-	 */
387
-	private function determineGroups($dbKey, $confKey, $testMemberOf = true) {
388
-		if(!$this->checkRequirements(array('ldapHost',
389
-										   'ldapPort',
390
-										   'ldapBase',
391
-										   ))) {
392
-			return  false;
393
-		}
394
-		$cr = $this->getConnection();
395
-		if(!$cr) {
396
-			throw new \Exception('Could not connect to LDAP');
397
-		}
398
-
399
-		$this->fetchGroups($dbKey, $confKey);
400
-
401
-		if($testMemberOf) {
402
-			$this->configuration->hasMemberOfFilterSupport = $this->testMemberOf();
403
-			$this->result->markChange();
404
-			if(!$this->configuration->hasMemberOfFilterSupport) {
405
-				throw new \Exception('memberOf is not supported by the server');
406
-			}
407
-		}
408
-
409
-		return $this->result;
410
-	}
411
-
412
-	/**
413
-	 * fetches all groups from LDAP and adds them to the result object
414
-	 *
415
-	 * @param string $dbKey
416
-	 * @param string $confKey
417
-	 * @return array $groupEntries
418
-	 * @throws \Exception
419
-	 */
420
-	public function fetchGroups($dbKey, $confKey) {
421
-		$obclasses = array('posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames');
422
-
423
-		$filterParts = array();
424
-		foreach($obclasses as $obclass) {
425
-			$filterParts[] = 'objectclass='.$obclass;
426
-		}
427
-		//we filter for everything
428
-		//- that looks like a group and
429
-		//- has the group display name set
430
-		$filter = $this->access->combineFilterWithOr($filterParts);
431
-		$filter = $this->access->combineFilterWithAnd(array($filter, 'cn=*'));
432
-
433
-		$groupNames = array();
434
-		$groupEntries = array();
435
-		$limit = 400;
436
-		$offset = 0;
437
-		do {
438
-			// we need to request dn additionally here, otherwise memberOf
439
-			// detection will fail later
440
-			$result = $this->access->searchGroups($filter, array('cn', 'dn'), $limit, $offset);
441
-			foreach($result as $item) {
442
-				if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
443
-					// just in case - no issue known
444
-					continue;
445
-				}
446
-				$groupNames[] = $item['cn'][0];
447
-				$groupEntries[] = $item;
448
-			}
449
-			$offset += $limit;
450
-		} while ($this->access->hasMoreResults());
451
-
452
-		if(count($groupNames) > 0) {
453
-			natsort($groupNames);
454
-			$this->result->addOptions($dbKey, array_values($groupNames));
455
-		} else {
456
-			throw new \Exception(self::$l->t('Could not find the desired feature'));
457
-		}
458
-
459
-		$setFeatures = $this->configuration->$confKey;
460
-		if(is_array($setFeatures) && !empty($setFeatures)) {
461
-			//something is already configured? pre-select it.
462
-			$this->result->addChange($dbKey, $setFeatures);
463
-		}
464
-		return $groupEntries;
465
-	}
466
-
467
-	public function determineGroupMemberAssoc() {
468
-		if(!$this->checkRequirements(array('ldapHost',
469
-										   'ldapPort',
470
-										   'ldapGroupFilter',
471
-										   ))) {
472
-			return  false;
473
-		}
474
-		$attribute = $this->detectGroupMemberAssoc();
475
-		if($attribute === false) {
476
-			return false;
477
-		}
478
-		$this->configuration->setConfiguration(array('ldapGroupMemberAssocAttr' => $attribute));
479
-		$this->result->addChange('ldap_group_member_assoc_attribute', $attribute);
480
-
481
-		return $this->result;
482
-	}
483
-
484
-	/**
485
-	 * Detects the available object classes
486
-	 * @return WizardResult|false the instance's WizardResult instance
487
-	 * @throws \Exception
488
-	 */
489
-	public function determineGroupObjectClasses() {
490
-		if(!$this->checkRequirements(array('ldapHost',
491
-										   'ldapPort',
492
-										   'ldapBase',
493
-										   ))) {
494
-			return  false;
495
-		}
496
-		$cr = $this->getConnection();
497
-		if(!$cr) {
498
-			throw new \Exception('Could not connect to LDAP');
499
-		}
500
-
501
-		$obclasses = array('groupOfNames', 'groupOfUniqueNames', 'group', 'posixGroup', '*');
502
-		$this->determineFeature($obclasses,
503
-								'objectclass',
504
-								'ldap_groupfilter_objectclass',
505
-								'ldapGroupFilterObjectclass',
506
-								false);
507
-
508
-		return $this->result;
509
-	}
510
-
511
-	/**
512
-	 * detects the available object classes
513
-	 * @return WizardResult
514
-	 * @throws \Exception
515
-	 */
516
-	public function determineUserObjectClasses() {
517
-		if(!$this->checkRequirements(array('ldapHost',
518
-										   'ldapPort',
519
-										   'ldapBase',
520
-										   ))) {
521
-			return  false;
522
-		}
523
-		$cr = $this->getConnection();
524
-		if(!$cr) {
525
-			throw new \Exception('Could not connect to LDAP');
526
-		}
527
-
528
-		$obclasses = array('inetOrgPerson', 'person', 'organizationalPerson',
529
-						   'user', 'posixAccount', '*');
530
-		$filter = $this->configuration->ldapUserFilter;
531
-		//if filter is empty, it is probably the first time the wizard is called
532
-		//then, apply suggestions.
533
-		$this->determineFeature($obclasses,
534
-								'objectclass',
535
-								'ldap_userfilter_objectclass',
536
-								'ldapUserFilterObjectclass',
537
-								empty($filter));
538
-
539
-		return $this->result;
540
-	}
541
-
542
-	/**
543
-	 * @return WizardResult|false
544
-	 * @throws \Exception
545
-	 */
546
-	public function getGroupFilter() {
547
-		if(!$this->checkRequirements(array('ldapHost',
548
-										   'ldapPort',
549
-										   'ldapBase',
550
-										   ))) {
551
-			return false;
552
-		}
553
-		//make sure the use display name is set
554
-		$displayName = $this->configuration->ldapGroupDisplayName;
555
-		if ($displayName === '') {
556
-			$d = $this->configuration->getDefaults();
557
-			$this->applyFind('ldap_group_display_name',
558
-							 $d['ldap_group_display_name']);
559
-		}
560
-		$filter = $this->composeLdapFilter(self::LFILTER_GROUP_LIST);
561
-
562
-		$this->applyFind('ldap_group_filter', $filter);
563
-		return $this->result;
564
-	}
565
-
566
-	/**
567
-	 * @return WizardResult|false
568
-	 * @throws \Exception
569
-	 */
570
-	public function getUserListFilter() {
571
-		if(!$this->checkRequirements(array('ldapHost',
572
-										   'ldapPort',
573
-										   'ldapBase',
574
-										   ))) {
575
-			return false;
576
-		}
577
-		//make sure the use display name is set
578
-		$displayName = $this->configuration->ldapUserDisplayName;
579
-		if ($displayName === '') {
580
-			$d = $this->configuration->getDefaults();
581
-			$this->applyFind('ldap_display_name', $d['ldap_display_name']);
582
-		}
583
-		$filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
584
-		if(!$filter) {
585
-			throw new \Exception('Cannot create filter');
586
-		}
587
-
588
-		$this->applyFind('ldap_userlist_filter', $filter);
589
-		return $this->result;
590
-	}
591
-
592
-	/**
593
-	 * @return bool|WizardResult
594
-	 * @throws \Exception
595
-	 */
596
-	public function getUserLoginFilter() {
597
-		if(!$this->checkRequirements(array('ldapHost',
598
-										   'ldapPort',
599
-										   'ldapBase',
600
-										   'ldapUserFilter',
601
-										   ))) {
602
-			return false;
603
-		}
604
-
605
-		$filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
606
-		if(!$filter) {
607
-			throw new \Exception('Cannot create filter');
608
-		}
609
-
610
-		$this->applyFind('ldap_login_filter', $filter);
611
-		return $this->result;
612
-	}
613
-
614
-	/**
615
-	 * @return bool|WizardResult
616
-	 * @param string $loginName
617
-	 * @throws \Exception
618
-	 */
619
-	public function testLoginName($loginName) {
620
-		if(!$this->checkRequirements(array('ldapHost',
621
-			'ldapPort',
622
-			'ldapBase',
623
-			'ldapLoginFilter',
624
-		))) {
625
-			return false;
626
-		}
627
-
628
-		$cr = $this->access->connection->getConnectionResource();
629
-		if(!$this->ldap->isResource($cr)) {
630
-			throw new \Exception('connection error');
631
-		}
632
-
633
-		if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
634
-			=== false) {
635
-			throw new \Exception('missing placeholder');
636
-		}
637
-
638
-		$users = $this->access->countUsersByLoginName($loginName);
639
-		if($this->ldap->errno($cr) !== 0) {
640
-			throw new \Exception($this->ldap->error($cr));
641
-		}
642
-		$filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
643
-		$this->result->addChange('ldap_test_loginname', $users);
644
-		$this->result->addChange('ldap_test_effective_filter', $filter);
645
-		return $this->result;
646
-	}
647
-
648
-	/**
649
-	 * Tries to determine the port, requires given Host, User DN and Password
650
-	 * @return WizardResult|false WizardResult on success, false otherwise
651
-	 * @throws \Exception
652
-	 */
653
-	public function guessPortAndTLS() {
654
-		if(!$this->checkRequirements(array('ldapHost',
655
-										   ))) {
656
-			return false;
657
-		}
658
-		$this->checkHost();
659
-		$portSettings = $this->getPortSettingsToTry();
660
-
661
-		if(!is_array($portSettings)) {
662
-			throw new \Exception(print_r($portSettings, true));
663
-		}
664
-
665
-		//proceed from the best configuration and return on first success
666
-		foreach($portSettings as $setting) {
667
-			$p = $setting['port'];
668
-			$t = $setting['tls'];
669
-			\OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, \OCP\Util::DEBUG);
670
-			//connectAndBind may throw Exception, it needs to be catched by the
671
-			//callee of this method
672
-
673
-			try {
674
-				$settingsFound = $this->connectAndBind($p, $t);
675
-			} catch (\Exception $e) {
676
-				// any reply other than -1 (= cannot connect) is already okay,
677
-				// because then we found the server
678
-				// unavailable startTLS returns -11
679
-				if($e->getCode() > 0) {
680
-					$settingsFound = true;
681
-				} else {
682
-					throw $e;
683
-				}
684
-			}
685
-
686
-			if ($settingsFound === true) {
687
-				$config = array(
688
-					'ldapPort' => $p,
689
-					'ldapTLS' => intval($t)
690
-				);
691
-				$this->configuration->setConfiguration($config);
692
-				\OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, \OCP\Util::DEBUG);
693
-				$this->result->addChange('ldap_port', $p);
694
-				return $this->result;
695
-			}
696
-		}
697
-
698
-		//custom port, undetected (we do not brute force)
699
-		return false;
700
-	}
701
-
702
-	/**
703
-	 * tries to determine a base dn from User DN or LDAP Host
704
-	 * @return WizardResult|false WizardResult on success, false otherwise
705
-	 */
706
-	public function guessBaseDN() {
707
-		if(!$this->checkRequirements(array('ldapHost',
708
-										   'ldapPort',
709
-										   ))) {
710
-			return false;
711
-		}
712
-
713
-		//check whether a DN is given in the agent name (99.9% of all cases)
714
-		$base = null;
715
-		$i = stripos($this->configuration->ldapAgentName, 'dc=');
716
-		if($i !== false) {
717
-			$base = substr($this->configuration->ldapAgentName, $i);
718
-			if($this->testBaseDN($base)) {
719
-				$this->applyFind('ldap_base', $base);
720
-				return $this->result;
721
-			}
722
-		}
723
-
724
-		//this did not help :(
725
-		//Let's see whether we can parse the Host URL and convert the domain to
726
-		//a base DN
727
-		$helper = new Helper(\OC::$server->getConfig());
728
-		$domain = $helper->getDomainFromURL($this->configuration->ldapHost);
729
-		if(!$domain) {
730
-			return false;
731
-		}
732
-
733
-		$dparts = explode('.', $domain);
734
-		while(count($dparts) > 0) {
735
-			$base2 = 'dc=' . implode(',dc=', $dparts);
736
-			if ($base !== $base2 && $this->testBaseDN($base2)) {
737
-				$this->applyFind('ldap_base', $base2);
738
-				return $this->result;
739
-			}
740
-			array_shift($dparts);
741
-		}
742
-
743
-		return false;
744
-	}
745
-
746
-	/**
747
-	 * sets the found value for the configuration key in the WizardResult
748
-	 * as well as in the Configuration instance
749
-	 * @param string $key the configuration key
750
-	 * @param string $value the (detected) value
751
-	 *
752
-	 */
753
-	private function applyFind($key, $value) {
754
-		$this->result->addChange($key, $value);
755
-		$this->configuration->setConfiguration(array($key => $value));
756
-	}
757
-
758
-	/**
759
-	 * Checks, whether a port was entered in the Host configuration
760
-	 * field. In this case the port will be stripped off, but also stored as
761
-	 * setting.
762
-	 */
763
-	private function checkHost() {
764
-		$host = $this->configuration->ldapHost;
765
-		$hostInfo = parse_url($host);
766
-
767
-		//removes Port from Host
768
-		if(is_array($hostInfo) && isset($hostInfo['port'])) {
769
-			$port = $hostInfo['port'];
770
-			$host = str_replace(':'.$port, '', $host);
771
-			$this->applyFind('ldap_host', $host);
772
-			$this->applyFind('ldap_port', $port);
773
-		}
774
-	}
775
-
776
-	/**
777
-	 * tries to detect the group member association attribute which is
778
-	 * one of 'uniqueMember', 'memberUid', 'member'
779
-	 * @return string|false, string with the attribute name, false on error
780
-	 * @throws \Exception
781
-	 */
782
-	private function detectGroupMemberAssoc() {
783
-		$possibleAttrs = array('uniqueMember', 'memberUid', 'member');
784
-		$filter = $this->configuration->ldapGroupFilter;
785
-		if(empty($filter)) {
786
-			return false;
787
-		}
788
-		$cr = $this->getConnection();
789
-		if(!$cr) {
790
-			throw new \Exception('Could not connect to LDAP');
791
-		}
792
-		$base = $this->configuration->ldapBase[0];
793
-		$rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
794
-		if(!$this->ldap->isResource($rr)) {
795
-			return false;
796
-		}
797
-		$er = $this->ldap->firstEntry($cr, $rr);
798
-		while(is_resource($er)) {
799
-			$this->ldap->getDN($cr, $er);
800
-			$attrs = $this->ldap->getAttributes($cr, $er);
801
-			$result = array();
802
-			$possibleAttrsCount = count($possibleAttrs);
803
-			for($i = 0; $i < $possibleAttrsCount; $i++) {
804
-				if(isset($attrs[$possibleAttrs[$i]])) {
805
-					$result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
806
-				}
807
-			}
808
-			if(!empty($result)) {
809
-				natsort($result);
810
-				return key($result);
811
-			}
812
-
813
-			$er = $this->ldap->nextEntry($cr, $er);
814
-		}
815
-
816
-		return false;
817
-	}
818
-
819
-	/**
820
-	 * Checks whether for a given BaseDN results will be returned
821
-	 * @param string $base the BaseDN to test
822
-	 * @return bool true on success, false otherwise
823
-	 * @throws \Exception
824
-	 */
825
-	private function testBaseDN($base) {
826
-		$cr = $this->getConnection();
827
-		if(!$cr) {
828
-			throw new \Exception('Could not connect to LDAP');
829
-		}
830
-
831
-		//base is there, let's validate it. If we search for anything, we should
832
-		//get a result set > 0 on a proper base
833
-		$rr = $this->ldap->search($cr, $base, 'objectClass=*', array('dn'), 0, 1);
834
-		if(!$this->ldap->isResource($rr)) {
835
-			$errorNo  = $this->ldap->errno($cr);
836
-			$errorMsg = $this->ldap->error($cr);
837
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base.
838
-							' Error '.$errorNo.': '.$errorMsg, \OCP\Util::INFO);
839
-			return false;
840
-		}
841
-		$entries = $this->ldap->countEntries($cr, $rr);
842
-		return ($entries !== false) && ($entries > 0);
843
-	}
844
-
845
-	/**
846
-	 * Checks whether the server supports memberOf in LDAP Filter.
847
-	 * Note: at least in OpenLDAP, availability of memberOf is dependent on
848
-	 * a configured objectClass. I.e. not necessarily for all available groups
849
-	 * memberOf does work.
850
-	 *
851
-	 * @return bool true if it does, false otherwise
852
-	 * @throws \Exception
853
-	 */
854
-	private function testMemberOf() {
855
-		$cr = $this->getConnection();
856
-		if(!$cr) {
857
-			throw new \Exception('Could not connect to LDAP');
858
-		}
859
-		$result = $this->access->countUsers('memberOf=*', array('memberOf'), 1);
860
-		if(is_int($result) &&  $result > 0) {
861
-			return true;
862
-		}
863
-		return false;
864
-	}
865
-
866
-	/**
867
-	 * creates an LDAP Filter from given configuration
868
-	 * @param integer $filterType int, for which use case the filter shall be created
869
-	 * can be any of self::LFILTER_USER_LIST, self::LFILTER_LOGIN or
870
-	 * self::LFILTER_GROUP_LIST
871
-	 * @return string|false string with the filter on success, false otherwise
872
-	 * @throws \Exception
873
-	 */
874
-	private function composeLdapFilter($filterType) {
875
-		$filter = '';
876
-		$parts = 0;
877
-		switch ($filterType) {
878
-			case self::LFILTER_USER_LIST:
879
-				$objcs = $this->configuration->ldapUserFilterObjectclass;
880
-				//glue objectclasses
881
-				if(is_array($objcs) && count($objcs) > 0) {
882
-					$filter .= '(|';
883
-					foreach($objcs as $objc) {
884
-						$filter .= '(objectclass=' . $objc . ')';
885
-					}
886
-					$filter .= ')';
887
-					$parts++;
888
-				}
889
-				//glue group memberships
890
-				if($this->configuration->hasMemberOfFilterSupport) {
891
-					$cns = $this->configuration->ldapUserFilterGroups;
892
-					if(is_array($cns) && count($cns) > 0) {
893
-						$filter .= '(|';
894
-						$cr = $this->getConnection();
895
-						if(!$cr) {
896
-							throw new \Exception('Could not connect to LDAP');
897
-						}
898
-						$base = $this->configuration->ldapBase[0];
899
-						foreach($cns as $cn) {
900
-							$rr = $this->ldap->search($cr, $base, 'cn=' . $cn, array('dn', 'primaryGroupToken'));
901
-							if(!$this->ldap->isResource($rr)) {
902
-								continue;
903
-							}
904
-							$er = $this->ldap->firstEntry($cr, $rr);
905
-							$attrs = $this->ldap->getAttributes($cr, $er);
906
-							$dn = $this->ldap->getDN($cr, $er);
907
-							if ($dn == false || $dn === '') {
908
-								continue;
909
-							}
910
-							$filterPart = '(memberof=' . $dn . ')';
911
-							if(isset($attrs['primaryGroupToken'])) {
912
-								$pgt = $attrs['primaryGroupToken'][0];
913
-								$primaryFilterPart = '(primaryGroupID=' . $pgt .')';
914
-								$filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
915
-							}
916
-							$filter .= $filterPart;
917
-						}
918
-						$filter .= ')';
919
-					}
920
-					$parts++;
921
-				}
922
-				//wrap parts in AND condition
923
-				if($parts > 1) {
924
-					$filter = '(&' . $filter . ')';
925
-				}
926
-				if ($filter === '') {
927
-					$filter = '(objectclass=*)';
928
-				}
929
-				break;
930
-
931
-			case self::LFILTER_GROUP_LIST:
932
-				$objcs = $this->configuration->ldapGroupFilterObjectclass;
933
-				//glue objectclasses
934
-				if(is_array($objcs) && count($objcs) > 0) {
935
-					$filter .= '(|';
936
-					foreach($objcs as $objc) {
937
-						$filter .= '(objectclass=' . $objc . ')';
938
-					}
939
-					$filter .= ')';
940
-					$parts++;
941
-				}
942
-				//glue group memberships
943
-				$cns = $this->configuration->ldapGroupFilterGroups;
944
-				if(is_array($cns) && count($cns) > 0) {
945
-					$filter .= '(|';
946
-					foreach($cns as $cn) {
947
-						$filter .= '(cn=' . $cn . ')';
948
-					}
949
-					$filter .= ')';
950
-				}
951
-				$parts++;
952
-				//wrap parts in AND condition
953
-				if($parts > 1) {
954
-					$filter = '(&' . $filter . ')';
955
-				}
956
-				break;
957
-
958
-			case self::LFILTER_LOGIN:
959
-				$ulf = $this->configuration->ldapUserFilter;
960
-				$loginpart = '=%uid';
961
-				$filterUsername = '';
962
-				$userAttributes = $this->getUserAttributes();
963
-				$userAttributes = array_change_key_case(array_flip($userAttributes));
964
-				$parts = 0;
965
-
966
-				if($this->configuration->ldapLoginFilterUsername === '1') {
967
-					$attr = '';
968
-					if(isset($userAttributes['uid'])) {
969
-						$attr = 'uid';
970
-					} else if(isset($userAttributes['samaccountname'])) {
971
-						$attr = 'samaccountname';
972
-					} else if(isset($userAttributes['cn'])) {
973
-						//fallback
974
-						$attr = 'cn';
975
-					}
976
-					if ($attr !== '') {
977
-						$filterUsername = '(' . $attr . $loginpart . ')';
978
-						$parts++;
979
-					}
980
-				}
981
-
982
-				$filterEmail = '';
983
-				if($this->configuration->ldapLoginFilterEmail === '1') {
984
-					$filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
985
-					$parts++;
986
-				}
987
-
988
-				$filterAttributes = '';
989
-				$attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
990
-				if(is_array($attrsToFilter) && count($attrsToFilter) > 0) {
991
-					$filterAttributes = '(|';
992
-					foreach($attrsToFilter as $attribute) {
993
-						$filterAttributes .= '(' . $attribute . $loginpart . ')';
994
-					}
995
-					$filterAttributes .= ')';
996
-					$parts++;
997
-				}
998
-
999
-				$filterLogin = '';
1000
-				if($parts > 1) {
1001
-					$filterLogin = '(|';
1002
-				}
1003
-				$filterLogin .= $filterUsername;
1004
-				$filterLogin .= $filterEmail;
1005
-				$filterLogin .= $filterAttributes;
1006
-				if($parts > 1) {
1007
-					$filterLogin .= ')';
1008
-				}
1009
-
1010
-				$filter = '(&'.$ulf.$filterLogin.')';
1011
-				break;
1012
-		}
1013
-
1014
-		\OCP\Util::writeLog('user_ldap', 'Wiz: Final filter '.$filter, \OCP\Util::DEBUG);
1015
-
1016
-		return $filter;
1017
-	}
1018
-
1019
-	/**
1020
-	 * Connects and Binds to an LDAP Server
1021
-	 * @param int $port the port to connect with
1022
-	 * @param bool $tls whether startTLS is to be used
1023
-	 * @param bool $ncc
1024
-	 * @return bool
1025
-	 * @throws \Exception
1026
-	 */
1027
-	private function connectAndBind($port = 389, $tls = false, $ncc = false) {
1028
-		if($ncc) {
1029
-			//No certificate check
1030
-			//FIXME: undo afterwards
1031
-			putenv('LDAPTLS_REQCERT=never');
1032
-		}
1033
-
1034
-		//connect, does not really trigger any server communication
1035
-		\OCP\Util::writeLog('user_ldap', 'Wiz: Checking Host Info ', \OCP\Util::DEBUG);
1036
-		$host = $this->configuration->ldapHost;
1037
-		$hostInfo = parse_url($host);
1038
-		if(!$hostInfo) {
1039
-			throw new \Exception(self::$l->t('Invalid Host'));
1040
-		}
1041
-		\OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', \OCP\Util::DEBUG);
1042
-		$cr = $this->ldap->connect($host, $port);
1043
-		if(!is_resource($cr)) {
1044
-			throw new \Exception(self::$l->t('Invalid Host'));
1045
-		}
1046
-
1047
-		\OCP\Util::writeLog('user_ldap', 'Wiz: Setting LDAP Options ', \OCP\Util::DEBUG);
1048
-		//set LDAP options
1049
-		$this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1050
-		$this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1051
-		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1052
-
1053
-		try {
1054
-			if($tls) {
1055
-				$isTlsWorking = @$this->ldap->startTls($cr);
1056
-				if(!$isTlsWorking) {
1057
-					return false;
1058
-				}
1059
-			}
1060
-
1061
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Attemping to Bind ', \OCP\Util::DEBUG);
1062
-			//interesting part: do the bind!
1063
-			$login = $this->ldap->bind($cr,
1064
-				$this->configuration->ldapAgentName,
1065
-				$this->configuration->ldapAgentPassword
1066
-			);
1067
-			$errNo = $this->ldap->errno($cr);
1068
-			$error = ldap_error($cr);
1069
-			$this->ldap->unbind($cr);
1070
-		} catch(ServerNotAvailableException $e) {
1071
-			return false;
1072
-		}
1073
-
1074
-		if($login === true) {
1075
-			$this->ldap->unbind($cr);
1076
-			if($ncc) {
1077
-				throw new \Exception('Certificate cannot be validated.');
1078
-			}
1079
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . intval($tls), \OCP\Util::DEBUG);
1080
-			return true;
1081
-		}
1082
-
1083
-		if($errNo === -1 || ($errNo === 2 && $ncc)) {
1084
-			//host, port or TLS wrong
1085
-			return false;
1086
-		} else if ($errNo === 2) {
1087
-			return $this->connectAndBind($port, $tls, true);
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 = intval($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
-	}
40
+    /** @var \OCP\IL10N */
41
+    static protected $l;
42
+    protected $access;
43
+    protected $cr;
44
+    protected $configuration;
45
+    protected $result;
46
+    protected $resultCache = array();
47
+
48
+    const LRESULT_PROCESSED_OK = 2;
49
+    const LRESULT_PROCESSED_INVALID = 3;
50
+    const LRESULT_PROCESSED_SKIP = 4;
51
+
52
+    const LFILTER_LOGIN      = 2;
53
+    const LFILTER_USER_LIST  = 3;
54
+    const LFILTER_GROUP_LIST = 4;
55
+
56
+    const LFILTER_MODE_ASSISTED = 2;
57
+    const LFILTER_MODE_RAW = 1;
58
+
59
+    const LDAP_NW_TIMEOUT = 4;
60
+
61
+    /**
62
+     * Constructor
63
+     * @param Configuration $configuration an instance of Configuration
64
+     * @param ILDAPWrapper $ldap an instance of ILDAPWrapper
65
+     * @param Access $access
66
+     */
67
+    public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) {
68
+        parent::__construct($ldap);
69
+        $this->configuration = $configuration;
70
+        if(is_null(Wizard::$l)) {
71
+            Wizard::$l = \OC::$server->getL10N('user_ldap');
72
+        }
73
+        $this->access = $access;
74
+        $this->result = new WizardResult();
75
+    }
76
+
77
+    public function  __destruct() {
78
+        if($this->result->hasChanges()) {
79
+            $this->configuration->saveConfiguration();
80
+        }
81
+    }
82
+
83
+    /**
84
+     * counts entries in the LDAP directory
85
+     *
86
+     * @param string $filter the LDAP search filter
87
+     * @param string $type a string being either 'users' or 'groups';
88
+     * @return bool|int
89
+     * @throws \Exception
90
+     */
91
+    public function countEntries($filter, $type) {
92
+        $reqs = array('ldapHost', 'ldapPort', 'ldapBase');
93
+        if($type === 'users') {
94
+            $reqs[] = 'ldapUserFilter';
95
+        }
96
+        if(!$this->checkRequirements($reqs)) {
97
+            throw new \Exception('Requirements not met', 400);
98
+        }
99
+
100
+        $attr = array('dn'); // default
101
+        $limit = 1001;
102
+        if($type === 'groups') {
103
+            $result =  $this->access->countGroups($filter, $attr, $limit);
104
+        } else if($type === 'users') {
105
+            $result = $this->access->countUsers($filter, $attr, $limit);
106
+        } else if ($type === 'objects') {
107
+            $result = $this->access->countObjects($limit);
108
+        } else {
109
+            throw new \Exception('internal error: invalid object type', 500);
110
+        }
111
+
112
+        return $result;
113
+    }
114
+
115
+    /**
116
+     * formats the return value of a count operation to the string to be
117
+     * inserted.
118
+     *
119
+     * @param bool|int $count
120
+     * @return int|string
121
+     */
122
+    private function formatCountResult($count) {
123
+        $formatted = ($count !== false) ? $count : 0;
124
+        if($formatted > 1000) {
125
+            $formatted = '> 1000';
126
+        }
127
+        return $formatted;
128
+    }
129
+
130
+    public function countGroups() {
131
+        $filter = $this->configuration->ldapGroupFilter;
132
+
133
+        if(empty($filter)) {
134
+            $output = self::$l->n('%s group found', '%s groups found', 0, array(0));
135
+            $this->result->addChange('ldap_group_count', $output);
136
+            return $this->result;
137
+        }
138
+
139
+        try {
140
+            $groupsTotal = $this->formatCountResult($this->countEntries($filter, 'groups'));
141
+        } catch (\Exception $e) {
142
+            //400 can be ignored, 500 is forwarded
143
+            if($e->getCode() === 500) {
144
+                throw $e;
145
+            }
146
+            return false;
147
+        }
148
+        $output = self::$l->n('%s group found', '%s groups found', $groupsTotal, array($groupsTotal));
149
+        $this->result->addChange('ldap_group_count', $output);
150
+        return $this->result;
151
+    }
152
+
153
+    /**
154
+     * @return WizardResult
155
+     * @throws \Exception
156
+     */
157
+    public function countUsers() {
158
+        $filter = $this->access->getFilterForUserCount();
159
+
160
+        $usersTotal = $this->formatCountResult($this->countEntries($filter, 'users'));
161
+        $output = self::$l->n('%s user found', '%s users found', $usersTotal, array($usersTotal));
162
+        $this->result->addChange('ldap_user_count', $output);
163
+        return $this->result;
164
+    }
165
+
166
+    /**
167
+     * counts any objects in the currently set base dn
168
+     *
169
+     * @return WizardResult
170
+     * @throws \Exception
171
+     */
172
+    public function countInBaseDN() {
173
+        // we don't need to provide a filter in this case
174
+        $total = $this->countEntries(null, 'objects');
175
+        if($total === false) {
176
+            throw new \Exception('invalid results received');
177
+        }
178
+        $this->result->addChange('ldap_test_base', $total);
179
+        return $this->result;
180
+    }
181
+
182
+    /**
183
+     * counts users with a specified attribute
184
+     * @param string $attr
185
+     * @param bool $existsCheck
186
+     * @return int|bool
187
+     */
188
+    public function countUsersWithAttribute($attr, $existsCheck = false) {
189
+        if(!$this->checkRequirements(array('ldapHost',
190
+                                            'ldapPort',
191
+                                            'ldapBase',
192
+                                            'ldapUserFilter',
193
+                                            ))) {
194
+            return  false;
195
+        }
196
+
197
+        $filter = $this->access->combineFilterWithAnd(array(
198
+            $this->configuration->ldapUserFilter,
199
+            $attr . '=*'
200
+        ));
201
+
202
+        $limit = ($existsCheck === false) ? null : 1;
203
+
204
+        return $this->access->countUsers($filter, array('dn'), $limit);
205
+    }
206
+
207
+    /**
208
+     * detects the display name attribute. If a setting is already present that
209
+     * returns at least one hit, the detection will be canceled.
210
+     * @return WizardResult|bool
211
+     * @throws \Exception
212
+     */
213
+    public function detectUserDisplayNameAttribute() {
214
+        if(!$this->checkRequirements(array('ldapHost',
215
+                                        'ldapPort',
216
+                                        'ldapBase',
217
+                                        'ldapUserFilter',
218
+                                        ))) {
219
+            return  false;
220
+        }
221
+
222
+        $attr = $this->configuration->ldapUserDisplayName;
223
+        if ($attr !== '' && $attr !== 'displayName') {
224
+            // most likely not the default value with upper case N,
225
+            // verify it still produces a result
226
+            $count = intval($this->countUsersWithAttribute($attr, true));
227
+            if($count > 0) {
228
+                //no change, but we sent it back to make sure the user interface
229
+                //is still correct, even if the ajax call was cancelled meanwhile
230
+                $this->result->addChange('ldap_display_name', $attr);
231
+                return $this->result;
232
+            }
233
+        }
234
+
235
+        // first attribute that has at least one result wins
236
+        $displayNameAttrs = array('displayname', 'cn');
237
+        foreach ($displayNameAttrs as $attr) {
238
+            $count = intval($this->countUsersWithAttribute($attr, true));
239
+
240
+            if($count > 0) {
241
+                $this->applyFind('ldap_display_name', $attr);
242
+                return $this->result;
243
+            }
244
+        };
245
+
246
+        throw new \Exception(self::$l->t('Could not detect user display name attribute. Please specify it yourself in advanced ldap settings.'));
247
+    }
248
+
249
+    /**
250
+     * detects the most often used email attribute for users applying to the
251
+     * user list filter. If a setting is already present that returns at least
252
+     * one hit, the detection will be canceled.
253
+     * @return WizardResult|bool
254
+     */
255
+    public function detectEmailAttribute() {
256
+        if(!$this->checkRequirements(array('ldapHost',
257
+                                            'ldapPort',
258
+                                            'ldapBase',
259
+                                            'ldapUserFilter',
260
+                                            ))) {
261
+            return  false;
262
+        }
263
+
264
+        $attr = $this->configuration->ldapEmailAttribute;
265
+        if ($attr !== '') {
266
+            $count = intval($this->countUsersWithAttribute($attr, true));
267
+            if($count > 0) {
268
+                return false;
269
+            }
270
+            $writeLog = true;
271
+        } else {
272
+            $writeLog = false;
273
+        }
274
+
275
+        $emailAttributes = array('mail', 'mailPrimaryAddress');
276
+        $winner = '';
277
+        $maxUsers = 0;
278
+        foreach($emailAttributes as $attr) {
279
+            $count = $this->countUsersWithAttribute($attr);
280
+            if($count > $maxUsers) {
281
+                $maxUsers = $count;
282
+                $winner = $attr;
283
+            }
284
+        }
285
+
286
+        if($winner !== '') {
287
+            $this->applyFind('ldap_email_attr', $winner);
288
+            if($writeLog) {
289
+                \OCP\Util::writeLog('user_ldap', 'The mail attribute has ' .
290
+                    'automatically been reset, because the original value ' .
291
+                    'did not return any results.', \OCP\Util::INFO);
292
+            }
293
+        }
294
+
295
+        return $this->result;
296
+    }
297
+
298
+    /**
299
+     * @return WizardResult
300
+     * @throws \Exception
301
+     */
302
+    public function determineAttributes() {
303
+        if(!$this->checkRequirements(array('ldapHost',
304
+                                            'ldapPort',
305
+                                            'ldapBase',
306
+                                            'ldapUserFilter',
307
+                                            ))) {
308
+            return  false;
309
+        }
310
+
311
+        $attributes = $this->getUserAttributes();
312
+
313
+        natcasesort($attributes);
314
+        $attributes = array_values($attributes);
315
+
316
+        $this->result->addOptions('ldap_loginfilter_attributes', $attributes);
317
+
318
+        $selected = $this->configuration->ldapLoginFilterAttributes;
319
+        if(is_array($selected) && !empty($selected)) {
320
+            $this->result->addChange('ldap_loginfilter_attributes', $selected);
321
+        }
322
+
323
+        return $this->result;
324
+    }
325
+
326
+    /**
327
+     * detects the available LDAP attributes
328
+     * @return array|false The instance's WizardResult instance
329
+     * @throws \Exception
330
+     */
331
+    private function getUserAttributes() {
332
+        if(!$this->checkRequirements(array('ldapHost',
333
+                                            'ldapPort',
334
+                                            'ldapBase',
335
+                                            'ldapUserFilter',
336
+                                            ))) {
337
+            return  false;
338
+        }
339
+        $cr = $this->getConnection();
340
+        if(!$cr) {
341
+            throw new \Exception('Could not connect to LDAP');
342
+        }
343
+
344
+        $base = $this->configuration->ldapBase[0];
345
+        $filter = $this->configuration->ldapUserFilter;
346
+        $rr = $this->ldap->search($cr, $base, $filter, array(), 1, 1);
347
+        if(!$this->ldap->isResource($rr)) {
348
+            return false;
349
+        }
350
+        $er = $this->ldap->firstEntry($cr, $rr);
351
+        $attributes = $this->ldap->getAttributes($cr, $er);
352
+        $pureAttributes = array();
353
+        for($i = 0; $i < $attributes['count']; $i++) {
354
+            $pureAttributes[] = $attributes[$i];
355
+        }
356
+
357
+        return $pureAttributes;
358
+    }
359
+
360
+    /**
361
+     * detects the available LDAP groups
362
+     * @return WizardResult|false the instance's WizardResult instance
363
+     */
364
+    public function determineGroupsForGroups() {
365
+        return $this->determineGroups('ldap_groupfilter_groups',
366
+                                        'ldapGroupFilterGroups',
367
+                                        false);
368
+    }
369
+
370
+    /**
371
+     * detects the available LDAP groups
372
+     * @return WizardResult|false the instance's WizardResult instance
373
+     */
374
+    public function determineGroupsForUsers() {
375
+        return $this->determineGroups('ldap_userfilter_groups',
376
+                                        'ldapUserFilterGroups');
377
+    }
378
+
379
+    /**
380
+     * detects the available LDAP groups
381
+     * @param string $dbKey
382
+     * @param string $confKey
383
+     * @param bool $testMemberOf
384
+     * @return WizardResult|false the instance's WizardResult instance
385
+     * @throws \Exception
386
+     */
387
+    private function determineGroups($dbKey, $confKey, $testMemberOf = true) {
388
+        if(!$this->checkRequirements(array('ldapHost',
389
+                                            'ldapPort',
390
+                                            'ldapBase',
391
+                                            ))) {
392
+            return  false;
393
+        }
394
+        $cr = $this->getConnection();
395
+        if(!$cr) {
396
+            throw new \Exception('Could not connect to LDAP');
397
+        }
398
+
399
+        $this->fetchGroups($dbKey, $confKey);
400
+
401
+        if($testMemberOf) {
402
+            $this->configuration->hasMemberOfFilterSupport = $this->testMemberOf();
403
+            $this->result->markChange();
404
+            if(!$this->configuration->hasMemberOfFilterSupport) {
405
+                throw new \Exception('memberOf is not supported by the server');
406
+            }
407
+        }
408
+
409
+        return $this->result;
410
+    }
411
+
412
+    /**
413
+     * fetches all groups from LDAP and adds them to the result object
414
+     *
415
+     * @param string $dbKey
416
+     * @param string $confKey
417
+     * @return array $groupEntries
418
+     * @throws \Exception
419
+     */
420
+    public function fetchGroups($dbKey, $confKey) {
421
+        $obclasses = array('posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames');
422
+
423
+        $filterParts = array();
424
+        foreach($obclasses as $obclass) {
425
+            $filterParts[] = 'objectclass='.$obclass;
426
+        }
427
+        //we filter for everything
428
+        //- that looks like a group and
429
+        //- has the group display name set
430
+        $filter = $this->access->combineFilterWithOr($filterParts);
431
+        $filter = $this->access->combineFilterWithAnd(array($filter, 'cn=*'));
432
+
433
+        $groupNames = array();
434
+        $groupEntries = array();
435
+        $limit = 400;
436
+        $offset = 0;
437
+        do {
438
+            // we need to request dn additionally here, otherwise memberOf
439
+            // detection will fail later
440
+            $result = $this->access->searchGroups($filter, array('cn', 'dn'), $limit, $offset);
441
+            foreach($result as $item) {
442
+                if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
443
+                    // just in case - no issue known
444
+                    continue;
445
+                }
446
+                $groupNames[] = $item['cn'][0];
447
+                $groupEntries[] = $item;
448
+            }
449
+            $offset += $limit;
450
+        } while ($this->access->hasMoreResults());
451
+
452
+        if(count($groupNames) > 0) {
453
+            natsort($groupNames);
454
+            $this->result->addOptions($dbKey, array_values($groupNames));
455
+        } else {
456
+            throw new \Exception(self::$l->t('Could not find the desired feature'));
457
+        }
458
+
459
+        $setFeatures = $this->configuration->$confKey;
460
+        if(is_array($setFeatures) && !empty($setFeatures)) {
461
+            //something is already configured? pre-select it.
462
+            $this->result->addChange($dbKey, $setFeatures);
463
+        }
464
+        return $groupEntries;
465
+    }
466
+
467
+    public function determineGroupMemberAssoc() {
468
+        if(!$this->checkRequirements(array('ldapHost',
469
+                                            'ldapPort',
470
+                                            'ldapGroupFilter',
471
+                                            ))) {
472
+            return  false;
473
+        }
474
+        $attribute = $this->detectGroupMemberAssoc();
475
+        if($attribute === false) {
476
+            return false;
477
+        }
478
+        $this->configuration->setConfiguration(array('ldapGroupMemberAssocAttr' => $attribute));
479
+        $this->result->addChange('ldap_group_member_assoc_attribute', $attribute);
480
+
481
+        return $this->result;
482
+    }
483
+
484
+    /**
485
+     * Detects the available object classes
486
+     * @return WizardResult|false the instance's WizardResult instance
487
+     * @throws \Exception
488
+     */
489
+    public function determineGroupObjectClasses() {
490
+        if(!$this->checkRequirements(array('ldapHost',
491
+                                            'ldapPort',
492
+                                            'ldapBase',
493
+                                            ))) {
494
+            return  false;
495
+        }
496
+        $cr = $this->getConnection();
497
+        if(!$cr) {
498
+            throw new \Exception('Could not connect to LDAP');
499
+        }
500
+
501
+        $obclasses = array('groupOfNames', 'groupOfUniqueNames', 'group', 'posixGroup', '*');
502
+        $this->determineFeature($obclasses,
503
+                                'objectclass',
504
+                                'ldap_groupfilter_objectclass',
505
+                                'ldapGroupFilterObjectclass',
506
+                                false);
507
+
508
+        return $this->result;
509
+    }
510
+
511
+    /**
512
+     * detects the available object classes
513
+     * @return WizardResult
514
+     * @throws \Exception
515
+     */
516
+    public function determineUserObjectClasses() {
517
+        if(!$this->checkRequirements(array('ldapHost',
518
+                                            'ldapPort',
519
+                                            'ldapBase',
520
+                                            ))) {
521
+            return  false;
522
+        }
523
+        $cr = $this->getConnection();
524
+        if(!$cr) {
525
+            throw new \Exception('Could not connect to LDAP');
526
+        }
527
+
528
+        $obclasses = array('inetOrgPerson', 'person', 'organizationalPerson',
529
+                            'user', 'posixAccount', '*');
530
+        $filter = $this->configuration->ldapUserFilter;
531
+        //if filter is empty, it is probably the first time the wizard is called
532
+        //then, apply suggestions.
533
+        $this->determineFeature($obclasses,
534
+                                'objectclass',
535
+                                'ldap_userfilter_objectclass',
536
+                                'ldapUserFilterObjectclass',
537
+                                empty($filter));
538
+
539
+        return $this->result;
540
+    }
541
+
542
+    /**
543
+     * @return WizardResult|false
544
+     * @throws \Exception
545
+     */
546
+    public function getGroupFilter() {
547
+        if(!$this->checkRequirements(array('ldapHost',
548
+                                            'ldapPort',
549
+                                            'ldapBase',
550
+                                            ))) {
551
+            return false;
552
+        }
553
+        //make sure the use display name is set
554
+        $displayName = $this->configuration->ldapGroupDisplayName;
555
+        if ($displayName === '') {
556
+            $d = $this->configuration->getDefaults();
557
+            $this->applyFind('ldap_group_display_name',
558
+                                $d['ldap_group_display_name']);
559
+        }
560
+        $filter = $this->composeLdapFilter(self::LFILTER_GROUP_LIST);
561
+
562
+        $this->applyFind('ldap_group_filter', $filter);
563
+        return $this->result;
564
+    }
565
+
566
+    /**
567
+     * @return WizardResult|false
568
+     * @throws \Exception
569
+     */
570
+    public function getUserListFilter() {
571
+        if(!$this->checkRequirements(array('ldapHost',
572
+                                            'ldapPort',
573
+                                            'ldapBase',
574
+                                            ))) {
575
+            return false;
576
+        }
577
+        //make sure the use display name is set
578
+        $displayName = $this->configuration->ldapUserDisplayName;
579
+        if ($displayName === '') {
580
+            $d = $this->configuration->getDefaults();
581
+            $this->applyFind('ldap_display_name', $d['ldap_display_name']);
582
+        }
583
+        $filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
584
+        if(!$filter) {
585
+            throw new \Exception('Cannot create filter');
586
+        }
587
+
588
+        $this->applyFind('ldap_userlist_filter', $filter);
589
+        return $this->result;
590
+    }
591
+
592
+    /**
593
+     * @return bool|WizardResult
594
+     * @throws \Exception
595
+     */
596
+    public function getUserLoginFilter() {
597
+        if(!$this->checkRequirements(array('ldapHost',
598
+                                            'ldapPort',
599
+                                            'ldapBase',
600
+                                            'ldapUserFilter',
601
+                                            ))) {
602
+            return false;
603
+        }
604
+
605
+        $filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
606
+        if(!$filter) {
607
+            throw new \Exception('Cannot create filter');
608
+        }
609
+
610
+        $this->applyFind('ldap_login_filter', $filter);
611
+        return $this->result;
612
+    }
613
+
614
+    /**
615
+     * @return bool|WizardResult
616
+     * @param string $loginName
617
+     * @throws \Exception
618
+     */
619
+    public function testLoginName($loginName) {
620
+        if(!$this->checkRequirements(array('ldapHost',
621
+            'ldapPort',
622
+            'ldapBase',
623
+            'ldapLoginFilter',
624
+        ))) {
625
+            return false;
626
+        }
627
+
628
+        $cr = $this->access->connection->getConnectionResource();
629
+        if(!$this->ldap->isResource($cr)) {
630
+            throw new \Exception('connection error');
631
+        }
632
+
633
+        if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
634
+            === false) {
635
+            throw new \Exception('missing placeholder');
636
+        }
637
+
638
+        $users = $this->access->countUsersByLoginName($loginName);
639
+        if($this->ldap->errno($cr) !== 0) {
640
+            throw new \Exception($this->ldap->error($cr));
641
+        }
642
+        $filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
643
+        $this->result->addChange('ldap_test_loginname', $users);
644
+        $this->result->addChange('ldap_test_effective_filter', $filter);
645
+        return $this->result;
646
+    }
647
+
648
+    /**
649
+     * Tries to determine the port, requires given Host, User DN and Password
650
+     * @return WizardResult|false WizardResult on success, false otherwise
651
+     * @throws \Exception
652
+     */
653
+    public function guessPortAndTLS() {
654
+        if(!$this->checkRequirements(array('ldapHost',
655
+                                            ))) {
656
+            return false;
657
+        }
658
+        $this->checkHost();
659
+        $portSettings = $this->getPortSettingsToTry();
660
+
661
+        if(!is_array($portSettings)) {
662
+            throw new \Exception(print_r($portSettings, true));
663
+        }
664
+
665
+        //proceed from the best configuration and return on first success
666
+        foreach($portSettings as $setting) {
667
+            $p = $setting['port'];
668
+            $t = $setting['tls'];
669
+            \OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, \OCP\Util::DEBUG);
670
+            //connectAndBind may throw Exception, it needs to be catched by the
671
+            //callee of this method
672
+
673
+            try {
674
+                $settingsFound = $this->connectAndBind($p, $t);
675
+            } catch (\Exception $e) {
676
+                // any reply other than -1 (= cannot connect) is already okay,
677
+                // because then we found the server
678
+                // unavailable startTLS returns -11
679
+                if($e->getCode() > 0) {
680
+                    $settingsFound = true;
681
+                } else {
682
+                    throw $e;
683
+                }
684
+            }
685
+
686
+            if ($settingsFound === true) {
687
+                $config = array(
688
+                    'ldapPort' => $p,
689
+                    'ldapTLS' => intval($t)
690
+                );
691
+                $this->configuration->setConfiguration($config);
692
+                \OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, \OCP\Util::DEBUG);
693
+                $this->result->addChange('ldap_port', $p);
694
+                return $this->result;
695
+            }
696
+        }
697
+
698
+        //custom port, undetected (we do not brute force)
699
+        return false;
700
+    }
701
+
702
+    /**
703
+     * tries to determine a base dn from User DN or LDAP Host
704
+     * @return WizardResult|false WizardResult on success, false otherwise
705
+     */
706
+    public function guessBaseDN() {
707
+        if(!$this->checkRequirements(array('ldapHost',
708
+                                            'ldapPort',
709
+                                            ))) {
710
+            return false;
711
+        }
712
+
713
+        //check whether a DN is given in the agent name (99.9% of all cases)
714
+        $base = null;
715
+        $i = stripos($this->configuration->ldapAgentName, 'dc=');
716
+        if($i !== false) {
717
+            $base = substr($this->configuration->ldapAgentName, $i);
718
+            if($this->testBaseDN($base)) {
719
+                $this->applyFind('ldap_base', $base);
720
+                return $this->result;
721
+            }
722
+        }
723
+
724
+        //this did not help :(
725
+        //Let's see whether we can parse the Host URL and convert the domain to
726
+        //a base DN
727
+        $helper = new Helper(\OC::$server->getConfig());
728
+        $domain = $helper->getDomainFromURL($this->configuration->ldapHost);
729
+        if(!$domain) {
730
+            return false;
731
+        }
732
+
733
+        $dparts = explode('.', $domain);
734
+        while(count($dparts) > 0) {
735
+            $base2 = 'dc=' . implode(',dc=', $dparts);
736
+            if ($base !== $base2 && $this->testBaseDN($base2)) {
737
+                $this->applyFind('ldap_base', $base2);
738
+                return $this->result;
739
+            }
740
+            array_shift($dparts);
741
+        }
742
+
743
+        return false;
744
+    }
745
+
746
+    /**
747
+     * sets the found value for the configuration key in the WizardResult
748
+     * as well as in the Configuration instance
749
+     * @param string $key the configuration key
750
+     * @param string $value the (detected) value
751
+     *
752
+     */
753
+    private function applyFind($key, $value) {
754
+        $this->result->addChange($key, $value);
755
+        $this->configuration->setConfiguration(array($key => $value));
756
+    }
757
+
758
+    /**
759
+     * Checks, whether a port was entered in the Host configuration
760
+     * field. In this case the port will be stripped off, but also stored as
761
+     * setting.
762
+     */
763
+    private function checkHost() {
764
+        $host = $this->configuration->ldapHost;
765
+        $hostInfo = parse_url($host);
766
+
767
+        //removes Port from Host
768
+        if(is_array($hostInfo) && isset($hostInfo['port'])) {
769
+            $port = $hostInfo['port'];
770
+            $host = str_replace(':'.$port, '', $host);
771
+            $this->applyFind('ldap_host', $host);
772
+            $this->applyFind('ldap_port', $port);
773
+        }
774
+    }
775
+
776
+    /**
777
+     * tries to detect the group member association attribute which is
778
+     * one of 'uniqueMember', 'memberUid', 'member'
779
+     * @return string|false, string with the attribute name, false on error
780
+     * @throws \Exception
781
+     */
782
+    private function detectGroupMemberAssoc() {
783
+        $possibleAttrs = array('uniqueMember', 'memberUid', 'member');
784
+        $filter = $this->configuration->ldapGroupFilter;
785
+        if(empty($filter)) {
786
+            return false;
787
+        }
788
+        $cr = $this->getConnection();
789
+        if(!$cr) {
790
+            throw new \Exception('Could not connect to LDAP');
791
+        }
792
+        $base = $this->configuration->ldapBase[0];
793
+        $rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
794
+        if(!$this->ldap->isResource($rr)) {
795
+            return false;
796
+        }
797
+        $er = $this->ldap->firstEntry($cr, $rr);
798
+        while(is_resource($er)) {
799
+            $this->ldap->getDN($cr, $er);
800
+            $attrs = $this->ldap->getAttributes($cr, $er);
801
+            $result = array();
802
+            $possibleAttrsCount = count($possibleAttrs);
803
+            for($i = 0; $i < $possibleAttrsCount; $i++) {
804
+                if(isset($attrs[$possibleAttrs[$i]])) {
805
+                    $result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
806
+                }
807
+            }
808
+            if(!empty($result)) {
809
+                natsort($result);
810
+                return key($result);
811
+            }
812
+
813
+            $er = $this->ldap->nextEntry($cr, $er);
814
+        }
815
+
816
+        return false;
817
+    }
818
+
819
+    /**
820
+     * Checks whether for a given BaseDN results will be returned
821
+     * @param string $base the BaseDN to test
822
+     * @return bool true on success, false otherwise
823
+     * @throws \Exception
824
+     */
825
+    private function testBaseDN($base) {
826
+        $cr = $this->getConnection();
827
+        if(!$cr) {
828
+            throw new \Exception('Could not connect to LDAP');
829
+        }
830
+
831
+        //base is there, let's validate it. If we search for anything, we should
832
+        //get a result set > 0 on a proper base
833
+        $rr = $this->ldap->search($cr, $base, 'objectClass=*', array('dn'), 0, 1);
834
+        if(!$this->ldap->isResource($rr)) {
835
+            $errorNo  = $this->ldap->errno($cr);
836
+            $errorMsg = $this->ldap->error($cr);
837
+            \OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base.
838
+                            ' Error '.$errorNo.': '.$errorMsg, \OCP\Util::INFO);
839
+            return false;
840
+        }
841
+        $entries = $this->ldap->countEntries($cr, $rr);
842
+        return ($entries !== false) && ($entries > 0);
843
+    }
844
+
845
+    /**
846
+     * Checks whether the server supports memberOf in LDAP Filter.
847
+     * Note: at least in OpenLDAP, availability of memberOf is dependent on
848
+     * a configured objectClass. I.e. not necessarily for all available groups
849
+     * memberOf does work.
850
+     *
851
+     * @return bool true if it does, false otherwise
852
+     * @throws \Exception
853
+     */
854
+    private function testMemberOf() {
855
+        $cr = $this->getConnection();
856
+        if(!$cr) {
857
+            throw new \Exception('Could not connect to LDAP');
858
+        }
859
+        $result = $this->access->countUsers('memberOf=*', array('memberOf'), 1);
860
+        if(is_int($result) &&  $result > 0) {
861
+            return true;
862
+        }
863
+        return false;
864
+    }
865
+
866
+    /**
867
+     * creates an LDAP Filter from given configuration
868
+     * @param integer $filterType int, for which use case the filter shall be created
869
+     * can be any of self::LFILTER_USER_LIST, self::LFILTER_LOGIN or
870
+     * self::LFILTER_GROUP_LIST
871
+     * @return string|false string with the filter on success, false otherwise
872
+     * @throws \Exception
873
+     */
874
+    private function composeLdapFilter($filterType) {
875
+        $filter = '';
876
+        $parts = 0;
877
+        switch ($filterType) {
878
+            case self::LFILTER_USER_LIST:
879
+                $objcs = $this->configuration->ldapUserFilterObjectclass;
880
+                //glue objectclasses
881
+                if(is_array($objcs) && count($objcs) > 0) {
882
+                    $filter .= '(|';
883
+                    foreach($objcs as $objc) {
884
+                        $filter .= '(objectclass=' . $objc . ')';
885
+                    }
886
+                    $filter .= ')';
887
+                    $parts++;
888
+                }
889
+                //glue group memberships
890
+                if($this->configuration->hasMemberOfFilterSupport) {
891
+                    $cns = $this->configuration->ldapUserFilterGroups;
892
+                    if(is_array($cns) && count($cns) > 0) {
893
+                        $filter .= '(|';
894
+                        $cr = $this->getConnection();
895
+                        if(!$cr) {
896
+                            throw new \Exception('Could not connect to LDAP');
897
+                        }
898
+                        $base = $this->configuration->ldapBase[0];
899
+                        foreach($cns as $cn) {
900
+                            $rr = $this->ldap->search($cr, $base, 'cn=' . $cn, array('dn', 'primaryGroupToken'));
901
+                            if(!$this->ldap->isResource($rr)) {
902
+                                continue;
903
+                            }
904
+                            $er = $this->ldap->firstEntry($cr, $rr);
905
+                            $attrs = $this->ldap->getAttributes($cr, $er);
906
+                            $dn = $this->ldap->getDN($cr, $er);
907
+                            if ($dn == false || $dn === '') {
908
+                                continue;
909
+                            }
910
+                            $filterPart = '(memberof=' . $dn . ')';
911
+                            if(isset($attrs['primaryGroupToken'])) {
912
+                                $pgt = $attrs['primaryGroupToken'][0];
913
+                                $primaryFilterPart = '(primaryGroupID=' . $pgt .')';
914
+                                $filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
915
+                            }
916
+                            $filter .= $filterPart;
917
+                        }
918
+                        $filter .= ')';
919
+                    }
920
+                    $parts++;
921
+                }
922
+                //wrap parts in AND condition
923
+                if($parts > 1) {
924
+                    $filter = '(&' . $filter . ')';
925
+                }
926
+                if ($filter === '') {
927
+                    $filter = '(objectclass=*)';
928
+                }
929
+                break;
930
+
931
+            case self::LFILTER_GROUP_LIST:
932
+                $objcs = $this->configuration->ldapGroupFilterObjectclass;
933
+                //glue objectclasses
934
+                if(is_array($objcs) && count($objcs) > 0) {
935
+                    $filter .= '(|';
936
+                    foreach($objcs as $objc) {
937
+                        $filter .= '(objectclass=' . $objc . ')';
938
+                    }
939
+                    $filter .= ')';
940
+                    $parts++;
941
+                }
942
+                //glue group memberships
943
+                $cns = $this->configuration->ldapGroupFilterGroups;
944
+                if(is_array($cns) && count($cns) > 0) {
945
+                    $filter .= '(|';
946
+                    foreach($cns as $cn) {
947
+                        $filter .= '(cn=' . $cn . ')';
948
+                    }
949
+                    $filter .= ')';
950
+                }
951
+                $parts++;
952
+                //wrap parts in AND condition
953
+                if($parts > 1) {
954
+                    $filter = '(&' . $filter . ')';
955
+                }
956
+                break;
957
+
958
+            case self::LFILTER_LOGIN:
959
+                $ulf = $this->configuration->ldapUserFilter;
960
+                $loginpart = '=%uid';
961
+                $filterUsername = '';
962
+                $userAttributes = $this->getUserAttributes();
963
+                $userAttributes = array_change_key_case(array_flip($userAttributes));
964
+                $parts = 0;
965
+
966
+                if($this->configuration->ldapLoginFilterUsername === '1') {
967
+                    $attr = '';
968
+                    if(isset($userAttributes['uid'])) {
969
+                        $attr = 'uid';
970
+                    } else if(isset($userAttributes['samaccountname'])) {
971
+                        $attr = 'samaccountname';
972
+                    } else if(isset($userAttributes['cn'])) {
973
+                        //fallback
974
+                        $attr = 'cn';
975
+                    }
976
+                    if ($attr !== '') {
977
+                        $filterUsername = '(' . $attr . $loginpart . ')';
978
+                        $parts++;
979
+                    }
980
+                }
981
+
982
+                $filterEmail = '';
983
+                if($this->configuration->ldapLoginFilterEmail === '1') {
984
+                    $filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
985
+                    $parts++;
986
+                }
987
+
988
+                $filterAttributes = '';
989
+                $attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
990
+                if(is_array($attrsToFilter) && count($attrsToFilter) > 0) {
991
+                    $filterAttributes = '(|';
992
+                    foreach($attrsToFilter as $attribute) {
993
+                        $filterAttributes .= '(' . $attribute . $loginpart . ')';
994
+                    }
995
+                    $filterAttributes .= ')';
996
+                    $parts++;
997
+                }
998
+
999
+                $filterLogin = '';
1000
+                if($parts > 1) {
1001
+                    $filterLogin = '(|';
1002
+                }
1003
+                $filterLogin .= $filterUsername;
1004
+                $filterLogin .= $filterEmail;
1005
+                $filterLogin .= $filterAttributes;
1006
+                if($parts > 1) {
1007
+                    $filterLogin .= ')';
1008
+                }
1009
+
1010
+                $filter = '(&'.$ulf.$filterLogin.')';
1011
+                break;
1012
+        }
1013
+
1014
+        \OCP\Util::writeLog('user_ldap', 'Wiz: Final filter '.$filter, \OCP\Util::DEBUG);
1015
+
1016
+        return $filter;
1017
+    }
1018
+
1019
+    /**
1020
+     * Connects and Binds to an LDAP Server
1021
+     * @param int $port the port to connect with
1022
+     * @param bool $tls whether startTLS is to be used
1023
+     * @param bool $ncc
1024
+     * @return bool
1025
+     * @throws \Exception
1026
+     */
1027
+    private function connectAndBind($port = 389, $tls = false, $ncc = false) {
1028
+        if($ncc) {
1029
+            //No certificate check
1030
+            //FIXME: undo afterwards
1031
+            putenv('LDAPTLS_REQCERT=never');
1032
+        }
1033
+
1034
+        //connect, does not really trigger any server communication
1035
+        \OCP\Util::writeLog('user_ldap', 'Wiz: Checking Host Info ', \OCP\Util::DEBUG);
1036
+        $host = $this->configuration->ldapHost;
1037
+        $hostInfo = parse_url($host);
1038
+        if(!$hostInfo) {
1039
+            throw new \Exception(self::$l->t('Invalid Host'));
1040
+        }
1041
+        \OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', \OCP\Util::DEBUG);
1042
+        $cr = $this->ldap->connect($host, $port);
1043
+        if(!is_resource($cr)) {
1044
+            throw new \Exception(self::$l->t('Invalid Host'));
1045
+        }
1046
+
1047
+        \OCP\Util::writeLog('user_ldap', 'Wiz: Setting LDAP Options ', \OCP\Util::DEBUG);
1048
+        //set LDAP options
1049
+        $this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1050
+        $this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1051
+        $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1052
+
1053
+        try {
1054
+            if($tls) {
1055
+                $isTlsWorking = @$this->ldap->startTls($cr);
1056
+                if(!$isTlsWorking) {
1057
+                    return false;
1058
+                }
1059
+            }
1060
+
1061
+            \OCP\Util::writeLog('user_ldap', 'Wiz: Attemping to Bind ', \OCP\Util::DEBUG);
1062
+            //interesting part: do the bind!
1063
+            $login = $this->ldap->bind($cr,
1064
+                $this->configuration->ldapAgentName,
1065
+                $this->configuration->ldapAgentPassword
1066
+            );
1067
+            $errNo = $this->ldap->errno($cr);
1068
+            $error = ldap_error($cr);
1069
+            $this->ldap->unbind($cr);
1070
+        } catch(ServerNotAvailableException $e) {
1071
+            return false;
1072
+        }
1073
+
1074
+        if($login === true) {
1075
+            $this->ldap->unbind($cr);
1076
+            if($ncc) {
1077
+                throw new \Exception('Certificate cannot be validated.');
1078
+            }
1079
+            \OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . intval($tls), \OCP\Util::DEBUG);
1080
+            return true;
1081
+        }
1082
+
1083
+        if($errNo === -1 || ($errNo === 2 && $ncc)) {
1084
+            //host, port or TLS wrong
1085
+            return false;
1086
+        } else if ($errNo === 2) {
1087
+            return $this->connectAndBind($port, $tls, true);
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 = intval($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   +151 added lines, -151 removed lines patch added patch discarded remove patch
@@ -67,7 +67,7 @@  discard block
 block discarded – undo
67 67
 	public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) {
68 68
 		parent::__construct($ldap);
69 69
 		$this->configuration = $configuration;
70
-		if(is_null(Wizard::$l)) {
70
+		if (is_null(Wizard::$l)) {
71 71
 			Wizard::$l = \OC::$server->getL10N('user_ldap');
72 72
 		}
73 73
 		$this->access = $access;
@@ -75,7 +75,7 @@  discard block
 block discarded – undo
75 75
 	}
76 76
 
77 77
 	public function  __destruct() {
78
-		if($this->result->hasChanges()) {
78
+		if ($this->result->hasChanges()) {
79 79
 			$this->configuration->saveConfiguration();
80 80
 		}
81 81
 	}
@@ -90,18 +90,18 @@  discard block
 block discarded – undo
90 90
 	 */
91 91
 	public function countEntries($filter, $type) {
92 92
 		$reqs = array('ldapHost', 'ldapPort', 'ldapBase');
93
-		if($type === 'users') {
93
+		if ($type === 'users') {
94 94
 			$reqs[] = 'ldapUserFilter';
95 95
 		}
96
-		if(!$this->checkRequirements($reqs)) {
96
+		if (!$this->checkRequirements($reqs)) {
97 97
 			throw new \Exception('Requirements not met', 400);
98 98
 		}
99 99
 
100 100
 		$attr = array('dn'); // default
101 101
 		$limit = 1001;
102
-		if($type === 'groups') {
103
-			$result =  $this->access->countGroups($filter, $attr, $limit);
104
-		} else if($type === 'users') {
102
+		if ($type === 'groups') {
103
+			$result = $this->access->countGroups($filter, $attr, $limit);
104
+		} else if ($type === 'users') {
105 105
 			$result = $this->access->countUsers($filter, $attr, $limit);
106 106
 		} else if ($type === 'objects') {
107 107
 			$result = $this->access->countObjects($limit);
@@ -121,7 +121,7 @@  discard block
 block discarded – undo
121 121
 	 */
122 122
 	private function formatCountResult($count) {
123 123
 		$formatted = ($count !== false) ? $count : 0;
124
-		if($formatted > 1000) {
124
+		if ($formatted > 1000) {
125 125
 			$formatted = '> 1000';
126 126
 		}
127 127
 		return $formatted;
@@ -130,7 +130,7 @@  discard block
 block discarded – undo
130 130
 	public function countGroups() {
131 131
 		$filter = $this->configuration->ldapGroupFilter;
132 132
 
133
-		if(empty($filter)) {
133
+		if (empty($filter)) {
134 134
 			$output = self::$l->n('%s group found', '%s groups found', 0, array(0));
135 135
 			$this->result->addChange('ldap_group_count', $output);
136 136
 			return $this->result;
@@ -140,7 +140,7 @@  discard block
 block discarded – undo
140 140
 			$groupsTotal = $this->formatCountResult($this->countEntries($filter, 'groups'));
141 141
 		} catch (\Exception $e) {
142 142
 			//400 can be ignored, 500 is forwarded
143
-			if($e->getCode() === 500) {
143
+			if ($e->getCode() === 500) {
144 144
 				throw $e;
145 145
 			}
146 146
 			return false;
@@ -172,7 +172,7 @@  discard block
 block discarded – undo
172 172
 	public function countInBaseDN() {
173 173
 		// we don't need to provide a filter in this case
174 174
 		$total = $this->countEntries(null, 'objects');
175
-		if($total === false) {
175
+		if ($total === false) {
176 176
 			throw new \Exception('invalid results received');
177 177
 		}
178 178
 		$this->result->addChange('ldap_test_base', $total);
@@ -186,7 +186,7 @@  discard block
 block discarded – undo
186 186
 	 * @return int|bool
187 187
 	 */
188 188
 	public function countUsersWithAttribute($attr, $existsCheck = false) {
189
-		if(!$this->checkRequirements(array('ldapHost',
189
+		if (!$this->checkRequirements(array('ldapHost',
190 190
 										   'ldapPort',
191 191
 										   'ldapBase',
192 192
 										   'ldapUserFilter',
@@ -196,7 +196,7 @@  discard block
 block discarded – undo
196 196
 
197 197
 		$filter = $this->access->combineFilterWithAnd(array(
198 198
 			$this->configuration->ldapUserFilter,
199
-			$attr . '=*'
199
+			$attr.'=*'
200 200
 		));
201 201
 
202 202
 		$limit = ($existsCheck === false) ? null : 1;
@@ -211,7 +211,7 @@  discard block
 block discarded – undo
211 211
 	 * @throws \Exception
212 212
 	 */
213 213
 	public function detectUserDisplayNameAttribute() {
214
-		if(!$this->checkRequirements(array('ldapHost',
214
+		if (!$this->checkRequirements(array('ldapHost',
215 215
 										'ldapPort',
216 216
 										'ldapBase',
217 217
 										'ldapUserFilter',
@@ -224,7 +224,7 @@  discard block
 block discarded – undo
224 224
 			// most likely not the default value with upper case N,
225 225
 			// verify it still produces a result
226 226
 			$count = intval($this->countUsersWithAttribute($attr, true));
227
-			if($count > 0) {
227
+			if ($count > 0) {
228 228
 				//no change, but we sent it back to make sure the user interface
229 229
 				//is still correct, even if the ajax call was cancelled meanwhile
230 230
 				$this->result->addChange('ldap_display_name', $attr);
@@ -237,7 +237,7 @@  discard block
 block discarded – undo
237 237
 		foreach ($displayNameAttrs as $attr) {
238 238
 			$count = intval($this->countUsersWithAttribute($attr, true));
239 239
 
240
-			if($count > 0) {
240
+			if ($count > 0) {
241 241
 				$this->applyFind('ldap_display_name', $attr);
242 242
 				return $this->result;
243 243
 			}
@@ -253,7 +253,7 @@  discard block
 block discarded – undo
253 253
 	 * @return WizardResult|bool
254 254
 	 */
255 255
 	public function detectEmailAttribute() {
256
-		if(!$this->checkRequirements(array('ldapHost',
256
+		if (!$this->checkRequirements(array('ldapHost',
257 257
 										   'ldapPort',
258 258
 										   'ldapBase',
259 259
 										   'ldapUserFilter',
@@ -264,7 +264,7 @@  discard block
 block discarded – undo
264 264
 		$attr = $this->configuration->ldapEmailAttribute;
265 265
 		if ($attr !== '') {
266 266
 			$count = intval($this->countUsersWithAttribute($attr, true));
267
-			if($count > 0) {
267
+			if ($count > 0) {
268 268
 				return false;
269 269
 			}
270 270
 			$writeLog = true;
@@ -275,19 +275,19 @@  discard block
 block discarded – undo
275 275
 		$emailAttributes = array('mail', 'mailPrimaryAddress');
276 276
 		$winner = '';
277 277
 		$maxUsers = 0;
278
-		foreach($emailAttributes as $attr) {
278
+		foreach ($emailAttributes as $attr) {
279 279
 			$count = $this->countUsersWithAttribute($attr);
280
-			if($count > $maxUsers) {
280
+			if ($count > $maxUsers) {
281 281
 				$maxUsers = $count;
282 282
 				$winner = $attr;
283 283
 			}
284 284
 		}
285 285
 
286
-		if($winner !== '') {
286
+		if ($winner !== '') {
287 287
 			$this->applyFind('ldap_email_attr', $winner);
288
-			if($writeLog) {
289
-				\OCP\Util::writeLog('user_ldap', 'The mail attribute has ' .
290
-					'automatically been reset, because the original value ' .
288
+			if ($writeLog) {
289
+				\OCP\Util::writeLog('user_ldap', 'The mail attribute has '.
290
+					'automatically been reset, because the original value '.
291 291
 					'did not return any results.', \OCP\Util::INFO);
292 292
 			}
293 293
 		}
@@ -300,7 +300,7 @@  discard block
 block discarded – undo
300 300
 	 * @throws \Exception
301 301
 	 */
302 302
 	public function determineAttributes() {
303
-		if(!$this->checkRequirements(array('ldapHost',
303
+		if (!$this->checkRequirements(array('ldapHost',
304 304
 										   'ldapPort',
305 305
 										   'ldapBase',
306 306
 										   'ldapUserFilter',
@@ -316,7 +316,7 @@  discard block
 block discarded – undo
316 316
 		$this->result->addOptions('ldap_loginfilter_attributes', $attributes);
317 317
 
318 318
 		$selected = $this->configuration->ldapLoginFilterAttributes;
319
-		if(is_array($selected) && !empty($selected)) {
319
+		if (is_array($selected) && !empty($selected)) {
320 320
 			$this->result->addChange('ldap_loginfilter_attributes', $selected);
321 321
 		}
322 322
 
@@ -329,7 +329,7 @@  discard block
 block discarded – undo
329 329
 	 * @throws \Exception
330 330
 	 */
331 331
 	private function getUserAttributes() {
332
-		if(!$this->checkRequirements(array('ldapHost',
332
+		if (!$this->checkRequirements(array('ldapHost',
333 333
 										   'ldapPort',
334 334
 										   'ldapBase',
335 335
 										   'ldapUserFilter',
@@ -337,20 +337,20 @@  discard block
 block discarded – undo
337 337
 			return  false;
338 338
 		}
339 339
 		$cr = $this->getConnection();
340
-		if(!$cr) {
340
+		if (!$cr) {
341 341
 			throw new \Exception('Could not connect to LDAP');
342 342
 		}
343 343
 
344 344
 		$base = $this->configuration->ldapBase[0];
345 345
 		$filter = $this->configuration->ldapUserFilter;
346 346
 		$rr = $this->ldap->search($cr, $base, $filter, array(), 1, 1);
347
-		if(!$this->ldap->isResource($rr)) {
347
+		if (!$this->ldap->isResource($rr)) {
348 348
 			return false;
349 349
 		}
350 350
 		$er = $this->ldap->firstEntry($cr, $rr);
351 351
 		$attributes = $this->ldap->getAttributes($cr, $er);
352 352
 		$pureAttributes = array();
353
-		for($i = 0; $i < $attributes['count']; $i++) {
353
+		for ($i = 0; $i < $attributes['count']; $i++) {
354 354
 			$pureAttributes[] = $attributes[$i];
355 355
 		}
356 356
 
@@ -385,23 +385,23 @@  discard block
 block discarded – undo
385 385
 	 * @throws \Exception
386 386
 	 */
387 387
 	private function determineGroups($dbKey, $confKey, $testMemberOf = true) {
388
-		if(!$this->checkRequirements(array('ldapHost',
388
+		if (!$this->checkRequirements(array('ldapHost',
389 389
 										   'ldapPort',
390 390
 										   'ldapBase',
391 391
 										   ))) {
392 392
 			return  false;
393 393
 		}
394 394
 		$cr = $this->getConnection();
395
-		if(!$cr) {
395
+		if (!$cr) {
396 396
 			throw new \Exception('Could not connect to LDAP');
397 397
 		}
398 398
 
399 399
 		$this->fetchGroups($dbKey, $confKey);
400 400
 
401
-		if($testMemberOf) {
401
+		if ($testMemberOf) {
402 402
 			$this->configuration->hasMemberOfFilterSupport = $this->testMemberOf();
403 403
 			$this->result->markChange();
404
-			if(!$this->configuration->hasMemberOfFilterSupport) {
404
+			if (!$this->configuration->hasMemberOfFilterSupport) {
405 405
 				throw new \Exception('memberOf is not supported by the server');
406 406
 			}
407 407
 		}
@@ -421,7 +421,7 @@  discard block
 block discarded – undo
421 421
 		$obclasses = array('posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames');
422 422
 
423 423
 		$filterParts = array();
424
-		foreach($obclasses as $obclass) {
424
+		foreach ($obclasses as $obclass) {
425 425
 			$filterParts[] = 'objectclass='.$obclass;
426 426
 		}
427 427
 		//we filter for everything
@@ -438,8 +438,8 @@  discard block
 block discarded – undo
438 438
 			// we need to request dn additionally here, otherwise memberOf
439 439
 			// detection will fail later
440 440
 			$result = $this->access->searchGroups($filter, array('cn', 'dn'), $limit, $offset);
441
-			foreach($result as $item) {
442
-				if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
441
+			foreach ($result as $item) {
442
+				if (!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
443 443
 					// just in case - no issue known
444 444
 					continue;
445 445
 				}
@@ -449,7 +449,7 @@  discard block
 block discarded – undo
449 449
 			$offset += $limit;
450 450
 		} while ($this->access->hasMoreResults());
451 451
 
452
-		if(count($groupNames) > 0) {
452
+		if (count($groupNames) > 0) {
453 453
 			natsort($groupNames);
454 454
 			$this->result->addOptions($dbKey, array_values($groupNames));
455 455
 		} else {
@@ -457,7 +457,7 @@  discard block
 block discarded – undo
457 457
 		}
458 458
 
459 459
 		$setFeatures = $this->configuration->$confKey;
460
-		if(is_array($setFeatures) && !empty($setFeatures)) {
460
+		if (is_array($setFeatures) && !empty($setFeatures)) {
461 461
 			//something is already configured? pre-select it.
462 462
 			$this->result->addChange($dbKey, $setFeatures);
463 463
 		}
@@ -465,14 +465,14 @@  discard block
 block discarded – undo
465 465
 	}
466 466
 
467 467
 	public function determineGroupMemberAssoc() {
468
-		if(!$this->checkRequirements(array('ldapHost',
468
+		if (!$this->checkRequirements(array('ldapHost',
469 469
 										   'ldapPort',
470 470
 										   'ldapGroupFilter',
471 471
 										   ))) {
472 472
 			return  false;
473 473
 		}
474 474
 		$attribute = $this->detectGroupMemberAssoc();
475
-		if($attribute === false) {
475
+		if ($attribute === false) {
476 476
 			return false;
477 477
 		}
478 478
 		$this->configuration->setConfiguration(array('ldapGroupMemberAssocAttr' => $attribute));
@@ -487,14 +487,14 @@  discard block
 block discarded – undo
487 487
 	 * @throws \Exception
488 488
 	 */
489 489
 	public function determineGroupObjectClasses() {
490
-		if(!$this->checkRequirements(array('ldapHost',
490
+		if (!$this->checkRequirements(array('ldapHost',
491 491
 										   'ldapPort',
492 492
 										   'ldapBase',
493 493
 										   ))) {
494 494
 			return  false;
495 495
 		}
496 496
 		$cr = $this->getConnection();
497
-		if(!$cr) {
497
+		if (!$cr) {
498 498
 			throw new \Exception('Could not connect to LDAP');
499 499
 		}
500 500
 
@@ -514,14 +514,14 @@  discard block
 block discarded – undo
514 514
 	 * @throws \Exception
515 515
 	 */
516 516
 	public function determineUserObjectClasses() {
517
-		if(!$this->checkRequirements(array('ldapHost',
517
+		if (!$this->checkRequirements(array('ldapHost',
518 518
 										   'ldapPort',
519 519
 										   'ldapBase',
520 520
 										   ))) {
521 521
 			return  false;
522 522
 		}
523 523
 		$cr = $this->getConnection();
524
-		if(!$cr) {
524
+		if (!$cr) {
525 525
 			throw new \Exception('Could not connect to LDAP');
526 526
 		}
527 527
 
@@ -544,7 +544,7 @@  discard block
 block discarded – undo
544 544
 	 * @throws \Exception
545 545
 	 */
546 546
 	public function getGroupFilter() {
547
-		if(!$this->checkRequirements(array('ldapHost',
547
+		if (!$this->checkRequirements(array('ldapHost',
548 548
 										   'ldapPort',
549 549
 										   'ldapBase',
550 550
 										   ))) {
@@ -568,7 +568,7 @@  discard block
 block discarded – undo
568 568
 	 * @throws \Exception
569 569
 	 */
570 570
 	public function getUserListFilter() {
571
-		if(!$this->checkRequirements(array('ldapHost',
571
+		if (!$this->checkRequirements(array('ldapHost',
572 572
 										   'ldapPort',
573 573
 										   'ldapBase',
574 574
 										   ))) {
@@ -581,7 +581,7 @@  discard block
 block discarded – undo
581 581
 			$this->applyFind('ldap_display_name', $d['ldap_display_name']);
582 582
 		}
583 583
 		$filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
584
-		if(!$filter) {
584
+		if (!$filter) {
585 585
 			throw new \Exception('Cannot create filter');
586 586
 		}
587 587
 
@@ -594,7 +594,7 @@  discard block
 block discarded – undo
594 594
 	 * @throws \Exception
595 595
 	 */
596 596
 	public function getUserLoginFilter() {
597
-		if(!$this->checkRequirements(array('ldapHost',
597
+		if (!$this->checkRequirements(array('ldapHost',
598 598
 										   'ldapPort',
599 599
 										   'ldapBase',
600 600
 										   'ldapUserFilter',
@@ -603,7 +603,7 @@  discard block
 block discarded – undo
603 603
 		}
604 604
 
605 605
 		$filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
606
-		if(!$filter) {
606
+		if (!$filter) {
607 607
 			throw new \Exception('Cannot create filter');
608 608
 		}
609 609
 
@@ -617,7 +617,7 @@  discard block
 block discarded – undo
617 617
 	 * @throws \Exception
618 618
 	 */
619 619
 	public function testLoginName($loginName) {
620
-		if(!$this->checkRequirements(array('ldapHost',
620
+		if (!$this->checkRequirements(array('ldapHost',
621 621
 			'ldapPort',
622 622
 			'ldapBase',
623 623
 			'ldapLoginFilter',
@@ -626,17 +626,17 @@  discard block
 block discarded – undo
626 626
 		}
627 627
 
628 628
 		$cr = $this->access->connection->getConnectionResource();
629
-		if(!$this->ldap->isResource($cr)) {
629
+		if (!$this->ldap->isResource($cr)) {
630 630
 			throw new \Exception('connection error');
631 631
 		}
632 632
 
633
-		if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
633
+		if (mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
634 634
 			=== false) {
635 635
 			throw new \Exception('missing placeholder');
636 636
 		}
637 637
 
638 638
 		$users = $this->access->countUsersByLoginName($loginName);
639
-		if($this->ldap->errno($cr) !== 0) {
639
+		if ($this->ldap->errno($cr) !== 0) {
640 640
 			throw new \Exception($this->ldap->error($cr));
641 641
 		}
642 642
 		$filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
@@ -651,22 +651,22 @@  discard block
 block discarded – undo
651 651
 	 * @throws \Exception
652 652
 	 */
653 653
 	public function guessPortAndTLS() {
654
-		if(!$this->checkRequirements(array('ldapHost',
654
+		if (!$this->checkRequirements(array('ldapHost',
655 655
 										   ))) {
656 656
 			return false;
657 657
 		}
658 658
 		$this->checkHost();
659 659
 		$portSettings = $this->getPortSettingsToTry();
660 660
 
661
-		if(!is_array($portSettings)) {
661
+		if (!is_array($portSettings)) {
662 662
 			throw new \Exception(print_r($portSettings, true));
663 663
 		}
664 664
 
665 665
 		//proceed from the best configuration and return on first success
666
-		foreach($portSettings as $setting) {
666
+		foreach ($portSettings as $setting) {
667 667
 			$p = $setting['port'];
668 668
 			$t = $setting['tls'];
669
-			\OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, \OCP\Util::DEBUG);
669
+			\OCP\Util::writeLog('user_ldap', 'Wiz: trying port '.$p.', TLS '.$t, \OCP\Util::DEBUG);
670 670
 			//connectAndBind may throw Exception, it needs to be catched by the
671 671
 			//callee of this method
672 672
 
@@ -676,7 +676,7 @@  discard block
 block discarded – undo
676 676
 				// any reply other than -1 (= cannot connect) is already okay,
677 677
 				// because then we found the server
678 678
 				// unavailable startTLS returns -11
679
-				if($e->getCode() > 0) {
679
+				if ($e->getCode() > 0) {
680 680
 					$settingsFound = true;
681 681
 				} else {
682 682
 					throw $e;
@@ -689,7 +689,7 @@  discard block
 block discarded – undo
689 689
 					'ldapTLS' => intval($t)
690 690
 				);
691 691
 				$this->configuration->setConfiguration($config);
692
-				\OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, \OCP\Util::DEBUG);
692
+				\OCP\Util::writeLog('user_ldap', 'Wiz: detected Port '.$p, \OCP\Util::DEBUG);
693 693
 				$this->result->addChange('ldap_port', $p);
694 694
 				return $this->result;
695 695
 			}
@@ -704,7 +704,7 @@  discard block
 block discarded – undo
704 704
 	 * @return WizardResult|false WizardResult on success, false otherwise
705 705
 	 */
706 706
 	public function guessBaseDN() {
707
-		if(!$this->checkRequirements(array('ldapHost',
707
+		if (!$this->checkRequirements(array('ldapHost',
708 708
 										   'ldapPort',
709 709
 										   ))) {
710 710
 			return false;
@@ -713,9 +713,9 @@  discard block
 block discarded – undo
713 713
 		//check whether a DN is given in the agent name (99.9% of all cases)
714 714
 		$base = null;
715 715
 		$i = stripos($this->configuration->ldapAgentName, 'dc=');
716
-		if($i !== false) {
716
+		if ($i !== false) {
717 717
 			$base = substr($this->configuration->ldapAgentName, $i);
718
-			if($this->testBaseDN($base)) {
718
+			if ($this->testBaseDN($base)) {
719 719
 				$this->applyFind('ldap_base', $base);
720 720
 				return $this->result;
721 721
 			}
@@ -726,13 +726,13 @@  discard block
 block discarded – undo
726 726
 		//a base DN
727 727
 		$helper = new Helper(\OC::$server->getConfig());
728 728
 		$domain = $helper->getDomainFromURL($this->configuration->ldapHost);
729
-		if(!$domain) {
729
+		if (!$domain) {
730 730
 			return false;
731 731
 		}
732 732
 
733 733
 		$dparts = explode('.', $domain);
734
-		while(count($dparts) > 0) {
735
-			$base2 = 'dc=' . implode(',dc=', $dparts);
734
+		while (count($dparts) > 0) {
735
+			$base2 = 'dc='.implode(',dc=', $dparts);
736 736
 			if ($base !== $base2 && $this->testBaseDN($base2)) {
737 737
 				$this->applyFind('ldap_base', $base2);
738 738
 				return $this->result;
@@ -765,7 +765,7 @@  discard block
 block discarded – undo
765 765
 		$hostInfo = parse_url($host);
766 766
 
767 767
 		//removes Port from Host
768
-		if(is_array($hostInfo) && isset($hostInfo['port'])) {
768
+		if (is_array($hostInfo) && isset($hostInfo['port'])) {
769 769
 			$port = $hostInfo['port'];
770 770
 			$host = str_replace(':'.$port, '', $host);
771 771
 			$this->applyFind('ldap_host', $host);
@@ -782,30 +782,30 @@  discard block
 block discarded – undo
782 782
 	private function detectGroupMemberAssoc() {
783 783
 		$possibleAttrs = array('uniqueMember', 'memberUid', 'member');
784 784
 		$filter = $this->configuration->ldapGroupFilter;
785
-		if(empty($filter)) {
785
+		if (empty($filter)) {
786 786
 			return false;
787 787
 		}
788 788
 		$cr = $this->getConnection();
789
-		if(!$cr) {
789
+		if (!$cr) {
790 790
 			throw new \Exception('Could not connect to LDAP');
791 791
 		}
792 792
 		$base = $this->configuration->ldapBase[0];
793 793
 		$rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
794
-		if(!$this->ldap->isResource($rr)) {
794
+		if (!$this->ldap->isResource($rr)) {
795 795
 			return false;
796 796
 		}
797 797
 		$er = $this->ldap->firstEntry($cr, $rr);
798
-		while(is_resource($er)) {
798
+		while (is_resource($er)) {
799 799
 			$this->ldap->getDN($cr, $er);
800 800
 			$attrs = $this->ldap->getAttributes($cr, $er);
801 801
 			$result = array();
802 802
 			$possibleAttrsCount = count($possibleAttrs);
803
-			for($i = 0; $i < $possibleAttrsCount; $i++) {
804
-				if(isset($attrs[$possibleAttrs[$i]])) {
803
+			for ($i = 0; $i < $possibleAttrsCount; $i++) {
804
+				if (isset($attrs[$possibleAttrs[$i]])) {
805 805
 					$result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
806 806
 				}
807 807
 			}
808
-			if(!empty($result)) {
808
+			if (!empty($result)) {
809 809
 				natsort($result);
810 810
 				return key($result);
811 811
 			}
@@ -824,14 +824,14 @@  discard block
 block discarded – undo
824 824
 	 */
825 825
 	private function testBaseDN($base) {
826 826
 		$cr = $this->getConnection();
827
-		if(!$cr) {
827
+		if (!$cr) {
828 828
 			throw new \Exception('Could not connect to LDAP');
829 829
 		}
830 830
 
831 831
 		//base is there, let's validate it. If we search for anything, we should
832 832
 		//get a result set > 0 on a proper base
833 833
 		$rr = $this->ldap->search($cr, $base, 'objectClass=*', array('dn'), 0, 1);
834
-		if(!$this->ldap->isResource($rr)) {
834
+		if (!$this->ldap->isResource($rr)) {
835 835
 			$errorNo  = $this->ldap->errno($cr);
836 836
 			$errorMsg = $this->ldap->error($cr);
837 837
 			\OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base.
@@ -853,11 +853,11 @@  discard block
 block discarded – undo
853 853
 	 */
854 854
 	private function testMemberOf() {
855 855
 		$cr = $this->getConnection();
856
-		if(!$cr) {
856
+		if (!$cr) {
857 857
 			throw new \Exception('Could not connect to LDAP');
858 858
 		}
859 859
 		$result = $this->access->countUsers('memberOf=*', array('memberOf'), 1);
860
-		if(is_int($result) &&  $result > 0) {
860
+		if (is_int($result) && $result > 0) {
861 861
 			return true;
862 862
 		}
863 863
 		return false;
@@ -878,27 +878,27 @@  discard block
 block discarded – undo
878 878
 			case self::LFILTER_USER_LIST:
879 879
 				$objcs = $this->configuration->ldapUserFilterObjectclass;
880 880
 				//glue objectclasses
881
-				if(is_array($objcs) && count($objcs) > 0) {
881
+				if (is_array($objcs) && count($objcs) > 0) {
882 882
 					$filter .= '(|';
883
-					foreach($objcs as $objc) {
884
-						$filter .= '(objectclass=' . $objc . ')';
883
+					foreach ($objcs as $objc) {
884
+						$filter .= '(objectclass='.$objc.')';
885 885
 					}
886 886
 					$filter .= ')';
887 887
 					$parts++;
888 888
 				}
889 889
 				//glue group memberships
890
-				if($this->configuration->hasMemberOfFilterSupport) {
890
+				if ($this->configuration->hasMemberOfFilterSupport) {
891 891
 					$cns = $this->configuration->ldapUserFilterGroups;
892
-					if(is_array($cns) && count($cns) > 0) {
892
+					if (is_array($cns) && count($cns) > 0) {
893 893
 						$filter .= '(|';
894 894
 						$cr = $this->getConnection();
895
-						if(!$cr) {
895
+						if (!$cr) {
896 896
 							throw new \Exception('Could not connect to LDAP');
897 897
 						}
898 898
 						$base = $this->configuration->ldapBase[0];
899
-						foreach($cns as $cn) {
900
-							$rr = $this->ldap->search($cr, $base, 'cn=' . $cn, array('dn', 'primaryGroupToken'));
901
-							if(!$this->ldap->isResource($rr)) {
899
+						foreach ($cns as $cn) {
900
+							$rr = $this->ldap->search($cr, $base, 'cn='.$cn, array('dn', 'primaryGroupToken'));
901
+							if (!$this->ldap->isResource($rr)) {
902 902
 								continue;
903 903
 							}
904 904
 							$er = $this->ldap->firstEntry($cr, $rr);
@@ -907,11 +907,11 @@  discard block
 block discarded – undo
907 907
 							if ($dn == false || $dn === '') {
908 908
 								continue;
909 909
 							}
910
-							$filterPart = '(memberof=' . $dn . ')';
911
-							if(isset($attrs['primaryGroupToken'])) {
910
+							$filterPart = '(memberof='.$dn.')';
911
+							if (isset($attrs['primaryGroupToken'])) {
912 912
 								$pgt = $attrs['primaryGroupToken'][0];
913
-								$primaryFilterPart = '(primaryGroupID=' . $pgt .')';
914
-								$filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
913
+								$primaryFilterPart = '(primaryGroupID='.$pgt.')';
914
+								$filterPart = '(|'.$filterPart.$primaryFilterPart.')';
915 915
 							}
916 916
 							$filter .= $filterPart;
917 917
 						}
@@ -920,8 +920,8 @@  discard block
 block discarded – undo
920 920
 					$parts++;
921 921
 				}
922 922
 				//wrap parts in AND condition
923
-				if($parts > 1) {
924
-					$filter = '(&' . $filter . ')';
923
+				if ($parts > 1) {
924
+					$filter = '(&'.$filter.')';
925 925
 				}
926 926
 				if ($filter === '') {
927 927
 					$filter = '(objectclass=*)';
@@ -931,27 +931,27 @@  discard block
 block discarded – undo
931 931
 			case self::LFILTER_GROUP_LIST:
932 932
 				$objcs = $this->configuration->ldapGroupFilterObjectclass;
933 933
 				//glue objectclasses
934
-				if(is_array($objcs) && count($objcs) > 0) {
934
+				if (is_array($objcs) && count($objcs) > 0) {
935 935
 					$filter .= '(|';
936
-					foreach($objcs as $objc) {
937
-						$filter .= '(objectclass=' . $objc . ')';
936
+					foreach ($objcs as $objc) {
937
+						$filter .= '(objectclass='.$objc.')';
938 938
 					}
939 939
 					$filter .= ')';
940 940
 					$parts++;
941 941
 				}
942 942
 				//glue group memberships
943 943
 				$cns = $this->configuration->ldapGroupFilterGroups;
944
-				if(is_array($cns) && count($cns) > 0) {
944
+				if (is_array($cns) && count($cns) > 0) {
945 945
 					$filter .= '(|';
946
-					foreach($cns as $cn) {
947
-						$filter .= '(cn=' . $cn . ')';
946
+					foreach ($cns as $cn) {
947
+						$filter .= '(cn='.$cn.')';
948 948
 					}
949 949
 					$filter .= ')';
950 950
 				}
951 951
 				$parts++;
952 952
 				//wrap parts in AND condition
953
-				if($parts > 1) {
954
-					$filter = '(&' . $filter . ')';
953
+				if ($parts > 1) {
954
+					$filter = '(&'.$filter.')';
955 955
 				}
956 956
 				break;
957 957
 
@@ -963,47 +963,47 @@  discard block
 block discarded – undo
963 963
 				$userAttributes = array_change_key_case(array_flip($userAttributes));
964 964
 				$parts = 0;
965 965
 
966
-				if($this->configuration->ldapLoginFilterUsername === '1') {
966
+				if ($this->configuration->ldapLoginFilterUsername === '1') {
967 967
 					$attr = '';
968
-					if(isset($userAttributes['uid'])) {
968
+					if (isset($userAttributes['uid'])) {
969 969
 						$attr = 'uid';
970
-					} else if(isset($userAttributes['samaccountname'])) {
970
+					} else if (isset($userAttributes['samaccountname'])) {
971 971
 						$attr = 'samaccountname';
972
-					} else if(isset($userAttributes['cn'])) {
972
+					} else if (isset($userAttributes['cn'])) {
973 973
 						//fallback
974 974
 						$attr = 'cn';
975 975
 					}
976 976
 					if ($attr !== '') {
977
-						$filterUsername = '(' . $attr . $loginpart . ')';
977
+						$filterUsername = '('.$attr.$loginpart.')';
978 978
 						$parts++;
979 979
 					}
980 980
 				}
981 981
 
982 982
 				$filterEmail = '';
983
-				if($this->configuration->ldapLoginFilterEmail === '1') {
983
+				if ($this->configuration->ldapLoginFilterEmail === '1') {
984 984
 					$filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
985 985
 					$parts++;
986 986
 				}
987 987
 
988 988
 				$filterAttributes = '';
989 989
 				$attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
990
-				if(is_array($attrsToFilter) && count($attrsToFilter) > 0) {
990
+				if (is_array($attrsToFilter) && count($attrsToFilter) > 0) {
991 991
 					$filterAttributes = '(|';
992
-					foreach($attrsToFilter as $attribute) {
993
-						$filterAttributes .= '(' . $attribute . $loginpart . ')';
992
+					foreach ($attrsToFilter as $attribute) {
993
+						$filterAttributes .= '('.$attribute.$loginpart.')';
994 994
 					}
995 995
 					$filterAttributes .= ')';
996 996
 					$parts++;
997 997
 				}
998 998
 
999 999
 				$filterLogin = '';
1000
-				if($parts > 1) {
1000
+				if ($parts > 1) {
1001 1001
 					$filterLogin = '(|';
1002 1002
 				}
1003 1003
 				$filterLogin .= $filterUsername;
1004 1004
 				$filterLogin .= $filterEmail;
1005 1005
 				$filterLogin .= $filterAttributes;
1006
-				if($parts > 1) {
1006
+				if ($parts > 1) {
1007 1007
 					$filterLogin .= ')';
1008 1008
 				}
1009 1009
 
@@ -1025,7 +1025,7 @@  discard block
 block discarded – undo
1025 1025
 	 * @throws \Exception
1026 1026
 	 */
1027 1027
 	private function connectAndBind($port = 389, $tls = false, $ncc = false) {
1028
-		if($ncc) {
1028
+		if ($ncc) {
1029 1029
 			//No certificate check
1030 1030
 			//FIXME: undo afterwards
1031 1031
 			putenv('LDAPTLS_REQCERT=never');
@@ -1035,12 +1035,12 @@  discard block
 block discarded – undo
1035 1035
 		\OCP\Util::writeLog('user_ldap', 'Wiz: Checking Host Info ', \OCP\Util::DEBUG);
1036 1036
 		$host = $this->configuration->ldapHost;
1037 1037
 		$hostInfo = parse_url($host);
1038
-		if(!$hostInfo) {
1038
+		if (!$hostInfo) {
1039 1039
 			throw new \Exception(self::$l->t('Invalid Host'));
1040 1040
 		}
1041 1041
 		\OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', \OCP\Util::DEBUG);
1042 1042
 		$cr = $this->ldap->connect($host, $port);
1043
-		if(!is_resource($cr)) {
1043
+		if (!is_resource($cr)) {
1044 1044
 			throw new \Exception(self::$l->t('Invalid Host'));
1045 1045
 		}
1046 1046
 
@@ -1051,9 +1051,9 @@  discard block
 block discarded – undo
1051 1051
 		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1052 1052
 
1053 1053
 		try {
1054
-			if($tls) {
1054
+			if ($tls) {
1055 1055
 				$isTlsWorking = @$this->ldap->startTls($cr);
1056
-				if(!$isTlsWorking) {
1056
+				if (!$isTlsWorking) {
1057 1057
 					return false;
1058 1058
 				}
1059 1059
 			}
@@ -1067,20 +1067,20 @@  discard block
 block discarded – undo
1067 1067
 			$errNo = $this->ldap->errno($cr);
1068 1068
 			$error = ldap_error($cr);
1069 1069
 			$this->ldap->unbind($cr);
1070
-		} catch(ServerNotAvailableException $e) {
1070
+		} catch (ServerNotAvailableException $e) {
1071 1071
 			return false;
1072 1072
 		}
1073 1073
 
1074
-		if($login === true) {
1074
+		if ($login === true) {
1075 1075
 			$this->ldap->unbind($cr);
1076
-			if($ncc) {
1076
+			if ($ncc) {
1077 1077
 				throw new \Exception('Certificate cannot be validated.');
1078 1078
 			}
1079
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . intval($tls), \OCP\Util::DEBUG);
1079
+			\OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '.$port.' TLS '.intval($tls), \OCP\Util::DEBUG);
1080 1080
 			return true;
1081 1081
 		}
1082 1082
 
1083
-		if($errNo === -1 || ($errNo === 2 && $ncc)) {
1083
+		if ($errNo === -1 || ($errNo === 2 && $ncc)) {
1084 1084
 			//host, port or TLS wrong
1085 1085
 			return false;
1086 1086
 		} else if ($errNo === 2) {
@@ -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
 		}
@@ -1339,14 +1339,14 @@  discard block
 block discarded – undo
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.
lib/private/legacy/db.php 3 patches
Doc Comments   -1 removed lines patch added patch discarded remove patch
@@ -151,7 +151,6 @@
 block discarded – undo
151 151
 	/**
152 152
 	 * saves database schema to xml file
153 153
 	 * @param string $file name of file
154
-	 * @param int $mode
155 154
 	 * @return bool
156 155
 	 *
157 156
 	 * TODO: write more documentation
Please login to merge, or discard this patch.
Indentation   +194 added lines, -194 removed lines patch added patch discarded remove patch
@@ -33,210 +33,210 @@
 block discarded – undo
33 33
  */
34 34
 class OC_DB {
35 35
 
36
-	/**
37
-	 * get MDB2 schema manager
38
-	 *
39
-	 * @return \OC\DB\MDB2SchemaManager
40
-	 */
41
-	private static function getMDB2SchemaManager() {
42
-		return new \OC\DB\MDB2SchemaManager(\OC::$server->getDatabaseConnection());
43
-	}
36
+    /**
37
+     * get MDB2 schema manager
38
+     *
39
+     * @return \OC\DB\MDB2SchemaManager
40
+     */
41
+    private static function getMDB2SchemaManager() {
42
+        return new \OC\DB\MDB2SchemaManager(\OC::$server->getDatabaseConnection());
43
+    }
44 44
 
45
-	/**
46
-	 * Prepare a SQL query
47
-	 * @param string $query Query string
48
-	 * @param int $limit
49
-	 * @param int $offset
50
-	 * @param bool $isManipulation
51
-	 * @throws \OC\DatabaseException
52
-	 * @return OC_DB_StatementWrapper prepared SQL query
53
-	 *
54
-	 * SQL query via Doctrine prepare(), needs to be execute()'d!
55
-	 */
56
-	static public function prepare( $query , $limit = null, $offset = null, $isManipulation = null) {
57
-		$connection = \OC::$server->getDatabaseConnection();
45
+    /**
46
+     * Prepare a SQL query
47
+     * @param string $query Query string
48
+     * @param int $limit
49
+     * @param int $offset
50
+     * @param bool $isManipulation
51
+     * @throws \OC\DatabaseException
52
+     * @return OC_DB_StatementWrapper prepared SQL query
53
+     *
54
+     * SQL query via Doctrine prepare(), needs to be execute()'d!
55
+     */
56
+    static public function prepare( $query , $limit = null, $offset = null, $isManipulation = null) {
57
+        $connection = \OC::$server->getDatabaseConnection();
58 58
 
59
-		if ($isManipulation === null) {
60
-			//try to guess, so we return the number of rows on manipulations
61
-			$isManipulation = self::isManipulation($query);
62
-		}
59
+        if ($isManipulation === null) {
60
+            //try to guess, so we return the number of rows on manipulations
61
+            $isManipulation = self::isManipulation($query);
62
+        }
63 63
 
64
-		// return the result
65
-		try {
66
-			$result =$connection->prepare($query, $limit, $offset);
67
-		} catch (\Doctrine\DBAL\DBALException $e) {
68
-			throw new \OC\DatabaseException($e->getMessage(), $query);
69
-		}
70
-		// differentiate between query and manipulation
71
-		$result = new OC_DB_StatementWrapper($result, $isManipulation);
72
-		return $result;
73
-	}
64
+        // return the result
65
+        try {
66
+            $result =$connection->prepare($query, $limit, $offset);
67
+        } catch (\Doctrine\DBAL\DBALException $e) {
68
+            throw new \OC\DatabaseException($e->getMessage(), $query);
69
+        }
70
+        // differentiate between query and manipulation
71
+        $result = new OC_DB_StatementWrapper($result, $isManipulation);
72
+        return $result;
73
+    }
74 74
 
75
-	/**
76
-	 * tries to guess the type of statement based on the first 10 characters
77
-	 * the current check allows some whitespace but does not work with IF EXISTS or other more complex statements
78
-	 *
79
-	 * @param string $sql
80
-	 * @return bool
81
-	 */
82
-	static public function isManipulation( $sql ) {
83
-		$selectOccurrence = stripos($sql, 'SELECT');
84
-		if ($selectOccurrence !== false && $selectOccurrence < 10) {
85
-			return false;
86
-		}
87
-		$insertOccurrence = stripos($sql, 'INSERT');
88
-		if ($insertOccurrence !== false && $insertOccurrence < 10) {
89
-			return true;
90
-		}
91
-		$updateOccurrence = stripos($sql, 'UPDATE');
92
-		if ($updateOccurrence !== false && $updateOccurrence < 10) {
93
-			return true;
94
-		}
95
-		$deleteOccurrence = stripos($sql, 'DELETE');
96
-		if ($deleteOccurrence !== false && $deleteOccurrence < 10) {
97
-			return true;
98
-		}
99
-		return false;
100
-	}
75
+    /**
76
+     * tries to guess the type of statement based on the first 10 characters
77
+     * the current check allows some whitespace but does not work with IF EXISTS or other more complex statements
78
+     *
79
+     * @param string $sql
80
+     * @return bool
81
+     */
82
+    static public function isManipulation( $sql ) {
83
+        $selectOccurrence = stripos($sql, 'SELECT');
84
+        if ($selectOccurrence !== false && $selectOccurrence < 10) {
85
+            return false;
86
+        }
87
+        $insertOccurrence = stripos($sql, 'INSERT');
88
+        if ($insertOccurrence !== false && $insertOccurrence < 10) {
89
+            return true;
90
+        }
91
+        $updateOccurrence = stripos($sql, 'UPDATE');
92
+        if ($updateOccurrence !== false && $updateOccurrence < 10) {
93
+            return true;
94
+        }
95
+        $deleteOccurrence = stripos($sql, 'DELETE');
96
+        if ($deleteOccurrence !== false && $deleteOccurrence < 10) {
97
+            return true;
98
+        }
99
+        return false;
100
+    }
101 101
 
102
-	/**
103
-	 * execute a prepared statement, on error write log and throw exception
104
-	 * @param mixed $stmt OC_DB_StatementWrapper,
105
-	 *					  an array with 'sql' and optionally 'limit' and 'offset' keys
106
-	 *					.. or a simple sql query string
107
-	 * @param array $parameters
108
-	 * @return OC_DB_StatementWrapper
109
-	 * @throws \OC\DatabaseException
110
-	 */
111
-	static public function executeAudited( $stmt, array $parameters = null) {
112
-		if (is_string($stmt)) {
113
-			// convert to an array with 'sql'
114
-			if (stripos($stmt, 'LIMIT') !== false) { //OFFSET requires LIMIT, so we only need to check for LIMIT
115
-				// TODO try to convert LIMIT OFFSET notation to parameters
116
-				$message = 'LIMIT and OFFSET are forbidden for portability reasons,'
117
-						 . ' pass an array with \'limit\' and \'offset\' instead';
118
-				throw new \OC\DatabaseException($message);
119
-			}
120
-			$stmt = array('sql' => $stmt, 'limit' => null, 'offset' => null);
121
-		}
122
-		if (is_array($stmt)) {
123
-			// convert to prepared statement
124
-			if ( ! array_key_exists('sql', $stmt) ) {
125
-				$message = 'statement array must at least contain key \'sql\'';
126
-				throw new \OC\DatabaseException($message);
127
-			}
128
-			if ( ! array_key_exists('limit', $stmt) ) {
129
-				$stmt['limit'] = null;
130
-			}
131
-			if ( ! array_key_exists('limit', $stmt) ) {
132
-				$stmt['offset'] = null;
133
-			}
134
-			$stmt = self::prepare($stmt['sql'], $stmt['limit'], $stmt['offset']);
135
-		}
136
-		self::raiseExceptionOnError($stmt, 'Could not prepare statement');
137
-		if ($stmt instanceof OC_DB_StatementWrapper) {
138
-			$result = $stmt->execute($parameters);
139
-			self::raiseExceptionOnError($result, 'Could not execute statement');
140
-		} else {
141
-			if (is_object($stmt)) {
142
-				$message = 'Expected a prepared statement or array got ' . get_class($stmt);
143
-			} else {
144
-				$message = 'Expected a prepared statement or array got ' . gettype($stmt);
145
-			}
146
-			throw new \OC\DatabaseException($message);
147
-		}
148
-		return $result;
149
-	}
102
+    /**
103
+     * execute a prepared statement, on error write log and throw exception
104
+     * @param mixed $stmt OC_DB_StatementWrapper,
105
+     *					  an array with 'sql' and optionally 'limit' and 'offset' keys
106
+     *					.. or a simple sql query string
107
+     * @param array $parameters
108
+     * @return OC_DB_StatementWrapper
109
+     * @throws \OC\DatabaseException
110
+     */
111
+    static public function executeAudited( $stmt, array $parameters = null) {
112
+        if (is_string($stmt)) {
113
+            // convert to an array with 'sql'
114
+            if (stripos($stmt, 'LIMIT') !== false) { //OFFSET requires LIMIT, so we only need to check for LIMIT
115
+                // TODO try to convert LIMIT OFFSET notation to parameters
116
+                $message = 'LIMIT and OFFSET are forbidden for portability reasons,'
117
+                            . ' pass an array with \'limit\' and \'offset\' instead';
118
+                throw new \OC\DatabaseException($message);
119
+            }
120
+            $stmt = array('sql' => $stmt, 'limit' => null, 'offset' => null);
121
+        }
122
+        if (is_array($stmt)) {
123
+            // convert to prepared statement
124
+            if ( ! array_key_exists('sql', $stmt) ) {
125
+                $message = 'statement array must at least contain key \'sql\'';
126
+                throw new \OC\DatabaseException($message);
127
+            }
128
+            if ( ! array_key_exists('limit', $stmt) ) {
129
+                $stmt['limit'] = null;
130
+            }
131
+            if ( ! array_key_exists('limit', $stmt) ) {
132
+                $stmt['offset'] = null;
133
+            }
134
+            $stmt = self::prepare($stmt['sql'], $stmt['limit'], $stmt['offset']);
135
+        }
136
+        self::raiseExceptionOnError($stmt, 'Could not prepare statement');
137
+        if ($stmt instanceof OC_DB_StatementWrapper) {
138
+            $result = $stmt->execute($parameters);
139
+            self::raiseExceptionOnError($result, 'Could not execute statement');
140
+        } else {
141
+            if (is_object($stmt)) {
142
+                $message = 'Expected a prepared statement or array got ' . get_class($stmt);
143
+            } else {
144
+                $message = 'Expected a prepared statement or array got ' . gettype($stmt);
145
+            }
146
+            throw new \OC\DatabaseException($message);
147
+        }
148
+        return $result;
149
+    }
150 150
 
151
-	/**
152
-	 * saves database schema to xml file
153
-	 * @param string $file name of file
154
-	 * @param int $mode
155
-	 * @return bool
156
-	 *
157
-	 * TODO: write more documentation
158
-	 */
159
-	public static function getDbStructure($file) {
160
-		$schemaManager = self::getMDB2SchemaManager();
161
-		return $schemaManager->getDbStructure($file);
162
-	}
151
+    /**
152
+     * saves database schema to xml file
153
+     * @param string $file name of file
154
+     * @param int $mode
155
+     * @return bool
156
+     *
157
+     * TODO: write more documentation
158
+     */
159
+    public static function getDbStructure($file) {
160
+        $schemaManager = self::getMDB2SchemaManager();
161
+        return $schemaManager->getDbStructure($file);
162
+    }
163 163
 
164
-	/**
165
-	 * Creates tables from XML file
166
-	 * @param string $file file to read structure from
167
-	 * @return bool
168
-	 *
169
-	 * TODO: write more documentation
170
-	 */
171
-	public static function createDbFromStructure( $file ) {
172
-		$schemaManager = self::getMDB2SchemaManager();
173
-		$result = $schemaManager->createDbFromStructure($file);
174
-		return $result;
175
-	}
164
+    /**
165
+     * Creates tables from XML file
166
+     * @param string $file file to read structure from
167
+     * @return bool
168
+     *
169
+     * TODO: write more documentation
170
+     */
171
+    public static function createDbFromStructure( $file ) {
172
+        $schemaManager = self::getMDB2SchemaManager();
173
+        $result = $schemaManager->createDbFromStructure($file);
174
+        return $result;
175
+    }
176 176
 
177
-	/**
178
-	 * update the database schema
179
-	 * @param string $file file to read structure from
180
-	 * @throws Exception
181
-	 * @return string|boolean
182
-	 */
183
-	public static function updateDbFromStructure($file) {
184
-		$schemaManager = self::getMDB2SchemaManager();
185
-		try {
186
-			$result = $schemaManager->updateDbFromStructure($file);
187
-		} catch (Exception $e) {
188
-			\OCP\Util::writeLog('core', 'Failed to update database structure ('.$e.')', \OCP\Util::FATAL);
189
-			throw $e;
190
-		}
191
-		return $result;
192
-	}
177
+    /**
178
+     * update the database schema
179
+     * @param string $file file to read structure from
180
+     * @throws Exception
181
+     * @return string|boolean
182
+     */
183
+    public static function updateDbFromStructure($file) {
184
+        $schemaManager = self::getMDB2SchemaManager();
185
+        try {
186
+            $result = $schemaManager->updateDbFromStructure($file);
187
+        } catch (Exception $e) {
188
+            \OCP\Util::writeLog('core', 'Failed to update database structure ('.$e.')', \OCP\Util::FATAL);
189
+            throw $e;
190
+        }
191
+        return $result;
192
+    }
193 193
 
194
-	/**
195
-	 * remove all tables defined in a database structure xml file
196
-	 * @param string $file the xml file describing the tables
197
-	 */
198
-	public static function removeDBStructure($file) {
199
-		$schemaManager = self::getMDB2SchemaManager();
200
-		$schemaManager->removeDBStructure($file);
201
-	}
194
+    /**
195
+     * remove all tables defined in a database structure xml file
196
+     * @param string $file the xml file describing the tables
197
+     */
198
+    public static function removeDBStructure($file) {
199
+        $schemaManager = self::getMDB2SchemaManager();
200
+        $schemaManager->removeDBStructure($file);
201
+    }
202 202
 
203
-	/**
204
-	 * check if a result is an error and throws an exception, works with \Doctrine\DBAL\DBALException
205
-	 * @param mixed $result
206
-	 * @param string $message
207
-	 * @return void
208
-	 * @throws \OC\DatabaseException
209
-	 */
210
-	public static function raiseExceptionOnError($result, $message = null) {
211
-		if($result === false) {
212
-			if ($message === null) {
213
-				$message = self::getErrorMessage();
214
-			} else {
215
-				$message .= ', Root cause:' . self::getErrorMessage();
216
-			}
217
-			throw new \OC\DatabaseException($message, \OC::$server->getDatabaseConnection()->errorCode());
218
-		}
219
-	}
203
+    /**
204
+     * check if a result is an error and throws an exception, works with \Doctrine\DBAL\DBALException
205
+     * @param mixed $result
206
+     * @param string $message
207
+     * @return void
208
+     * @throws \OC\DatabaseException
209
+     */
210
+    public static function raiseExceptionOnError($result, $message = null) {
211
+        if($result === false) {
212
+            if ($message === null) {
213
+                $message = self::getErrorMessage();
214
+            } else {
215
+                $message .= ', Root cause:' . self::getErrorMessage();
216
+            }
217
+            throw new \OC\DatabaseException($message, \OC::$server->getDatabaseConnection()->errorCode());
218
+        }
219
+    }
220 220
 
221
-	/**
222
-	 * returns the error code and message as a string for logging
223
-	 * works with DoctrineException
224
-	 * @return string
225
-	 */
226
-	public static function getErrorMessage() {
227
-		$connection = \OC::$server->getDatabaseConnection();
228
-		return $connection->getError();
229
-	}
221
+    /**
222
+     * returns the error code and message as a string for logging
223
+     * works with DoctrineException
224
+     * @return string
225
+     */
226
+    public static function getErrorMessage() {
227
+        $connection = \OC::$server->getDatabaseConnection();
228
+        return $connection->getError();
229
+    }
230 230
 
231
-	/**
232
-	 * Checks if a table exists in the database - the database prefix will be prepended
233
-	 *
234
-	 * @param string $table
235
-	 * @return bool
236
-	 * @throws \OC\DatabaseException
237
-	 */
238
-	public static function tableExists($table) {
239
-		$connection = \OC::$server->getDatabaseConnection();
240
-		return $connection->tableExists($table);
241
-	}
231
+    /**
232
+     * Checks if a table exists in the database - the database prefix will be prepended
233
+     *
234
+     * @param string $table
235
+     * @return bool
236
+     * @throws \OC\DatabaseException
237
+     */
238
+    public static function tableExists($table) {
239
+        $connection = \OC::$server->getDatabaseConnection();
240
+        return $connection->tableExists($table);
241
+    }
242 242
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -53,7 +53,7 @@  discard block
 block discarded – undo
53 53
 	 *
54 54
 	 * SQL query via Doctrine prepare(), needs to be execute()'d!
55 55
 	 */
56
-	static public function prepare( $query , $limit = null, $offset = null, $isManipulation = null) {
56
+	static public function prepare($query, $limit = null, $offset = null, $isManipulation = null) {
57 57
 		$connection = \OC::$server->getDatabaseConnection();
58 58
 
59 59
 		if ($isManipulation === null) {
@@ -63,7 +63,7 @@  discard block
 block discarded – undo
63 63
 
64 64
 		// return the result
65 65
 		try {
66
-			$result =$connection->prepare($query, $limit, $offset);
66
+			$result = $connection->prepare($query, $limit, $offset);
67 67
 		} catch (\Doctrine\DBAL\DBALException $e) {
68 68
 			throw new \OC\DatabaseException($e->getMessage(), $query);
69 69
 		}
@@ -79,7 +79,7 @@  discard block
 block discarded – undo
79 79
 	 * @param string $sql
80 80
 	 * @return bool
81 81
 	 */
82
-	static public function isManipulation( $sql ) {
82
+	static public function isManipulation($sql) {
83 83
 		$selectOccurrence = stripos($sql, 'SELECT');
84 84
 		if ($selectOccurrence !== false && $selectOccurrence < 10) {
85 85
 			return false;
@@ -108,7 +108,7 @@  discard block
 block discarded – undo
108 108
 	 * @return OC_DB_StatementWrapper
109 109
 	 * @throws \OC\DatabaseException
110 110
 	 */
111
-	static public function executeAudited( $stmt, array $parameters = null) {
111
+	static public function executeAudited($stmt, array $parameters = null) {
112 112
 		if (is_string($stmt)) {
113 113
 			// convert to an array with 'sql'
114 114
 			if (stripos($stmt, 'LIMIT') !== false) { //OFFSET requires LIMIT, so we only need to check for LIMIT
@@ -121,14 +121,14 @@  discard block
 block discarded – undo
121 121
 		}
122 122
 		if (is_array($stmt)) {
123 123
 			// convert to prepared statement
124
-			if ( ! array_key_exists('sql', $stmt) ) {
124
+			if (!array_key_exists('sql', $stmt)) {
125 125
 				$message = 'statement array must at least contain key \'sql\'';
126 126
 				throw new \OC\DatabaseException($message);
127 127
 			}
128
-			if ( ! array_key_exists('limit', $stmt) ) {
128
+			if (!array_key_exists('limit', $stmt)) {
129 129
 				$stmt['limit'] = null;
130 130
 			}
131
-			if ( ! array_key_exists('limit', $stmt) ) {
131
+			if (!array_key_exists('limit', $stmt)) {
132 132
 				$stmt['offset'] = null;
133 133
 			}
134 134
 			$stmt = self::prepare($stmt['sql'], $stmt['limit'], $stmt['offset']);
@@ -139,9 +139,9 @@  discard block
 block discarded – undo
139 139
 			self::raiseExceptionOnError($result, 'Could not execute statement');
140 140
 		} else {
141 141
 			if (is_object($stmt)) {
142
-				$message = 'Expected a prepared statement or array got ' . get_class($stmt);
142
+				$message = 'Expected a prepared statement or array got '.get_class($stmt);
143 143
 			} else {
144
-				$message = 'Expected a prepared statement or array got ' . gettype($stmt);
144
+				$message = 'Expected a prepared statement or array got '.gettype($stmt);
145 145
 			}
146 146
 			throw new \OC\DatabaseException($message);
147 147
 		}
@@ -168,7 +168,7 @@  discard block
 block discarded – undo
168 168
 	 *
169 169
 	 * TODO: write more documentation
170 170
 	 */
171
-	public static function createDbFromStructure( $file ) {
171
+	public static function createDbFromStructure($file) {
172 172
 		$schemaManager = self::getMDB2SchemaManager();
173 173
 		$result = $schemaManager->createDbFromStructure($file);
174 174
 		return $result;
@@ -208,11 +208,11 @@  discard block
 block discarded – undo
208 208
 	 * @throws \OC\DatabaseException
209 209
 	 */
210 210
 	public static function raiseExceptionOnError($result, $message = null) {
211
-		if($result === false) {
211
+		if ($result === false) {
212 212
 			if ($message === null) {
213 213
 				$message = self::getErrorMessage();
214 214
 			} else {
215
-				$message .= ', Root cause:' . self::getErrorMessage();
215
+				$message .= ', Root cause:'.self::getErrorMessage();
216 216
 			}
217 217
 			throw new \OC\DatabaseException($message, \OC::$server->getDatabaseConnection()->errorCode());
218 218
 		}
Please login to merge, or discard this patch.
lib/private/User/User.php 3 patches
Doc Comments   +4 added lines patch added patch discarded remove patch
@@ -413,6 +413,10 @@
 block discarded – undo
413 413
 		return $url;
414 414
 	}
415 415
 
416
+	/**
417
+	 * @param string $feature
418
+	 * @param string $value
419
+	 */
416 420
 	public function triggerChange($feature, $value = null) {
417 421
 		if ($this->emitter) {
418 422
 			$this->emitter->emit('\OC\User', 'changeUser', array($this, $feature, $value));
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -83,7 +83,7 @@  discard block
 block discarded – undo
83 83
 		$this->uid = $uid;
84 84
 		$this->backend = $backend;
85 85
 		$this->emitter = $emitter;
86
-		if(is_null($config)) {
86
+		if (is_null($config)) {
87 87
 			$config = \OC::$server->getConfig();
88 88
 		}
89 89
 		$this->config = $config;
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
 	 * @since 9.0.0
159 159
 	 */
160 160
 	public function setEMailAddress($mailAddress) {
161
-		if($mailAddress === '') {
161
+		if ($mailAddress === '') {
162 162
 			$this->config->deleteUserValue($this->uid, 'settings', 'email');
163 163
 		} else {
164 164
 			$this->config->setUserValue($this->uid, 'settings', 'email', $mailAddress);
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
 			}
220 220
 
221 221
 			// Delete the users entry in the storage table
222
-			Storage::remove('home::' . $this->uid);
222
+			Storage::remove('home::'.$this->uid);
223 223
 
224 224
 			\OC::$server->getCommentsManager()->deleteReferencesOfActor('users', $this->uid);
225 225
 			\OC::$server->getCommentsManager()->deleteReadMarksFromUser($this);
@@ -267,9 +267,9 @@  discard block
 block discarded – undo
267 267
 			if ($this->backend->implementsActions(Backend::GET_HOME) and $home = $this->backend->getHome($this->uid)) {
268 268
 				$this->home = $home;
269 269
 			} elseif ($this->config) {
270
-				$this->home = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/' . $this->uid;
270
+				$this->home = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data').'/'.$this->uid;
271 271
 			} else {
272
-				$this->home = \OC::$SERVERROOT . '/data/' . $this->uid;
272
+				$this->home = \OC::$SERVERROOT.'/data/'.$this->uid;
273 273
 			}
274 274
 		}
275 275
 		return $this->home;
@@ -281,7 +281,7 @@  discard block
 block discarded – undo
281 281
 	 * @return string
282 282
 	 */
283 283
 	public function getBackendClassName() {
284
-		if($this->backend instanceof IUserBackend) {
284
+		if ($this->backend instanceof IUserBackend) {
285 285
 			return $this->backend->getBackendName();
286 286
 		}
287 287
 		return get_class($this->backend);
@@ -358,7 +358,7 @@  discard block
 block discarded – undo
358 358
 	 */
359 359
 	public function getQuota() {
360 360
 		$quota = $this->config->getUserValue($this->uid, 'files', 'quota', 'default');
361
-		if($quota === 'default') {
361
+		if ($quota === 'default') {
362 362
 			$quota = $this->config->getAppValue('files', 'default_quota', 'none');
363 363
 		}
364 364
 		return $quota;
@@ -372,7 +372,7 @@  discard block
 block discarded – undo
372 372
 	 * @since 9.0.0
373 373
 	 */
374 374
 	public function setQuota($quota) {
375
-		if($quota !== 'none' and $quota !== 'default') {
375
+		if ($quota !== 'none' and $quota !== 'default') {
376 376
 			$quota = OC_Helper::computerFileSize($quota);
377 377
 			$quota = OC_Helper::humanFileSize($quota);
378 378
 		}
@@ -411,7 +411,7 @@  discard block
 block discarded – undo
411 411
 	public function getCloudId() {
412 412
 		$uid = $this->getUID();
413 413
 		$server = $this->urlGenerator->getAbsoluteURL('/');
414
-		$server =  rtrim( $this->removeProtocolFromUrl($server), '/');
414
+		$server = rtrim($this->removeProtocolFromUrl($server), '/');
415 415
 		return \OC::$server->getCloudIdManager()->getCloudId($uid, $server)->getId();
416 416
 	}
417 417
 
Please login to merge, or discard this patch.
Indentation   +398 added lines, -398 removed lines patch added patch discarded remove patch
@@ -42,402 +42,402 @@
 block discarded – undo
42 42
 use \OCP\IUserBackend;
43 43
 
44 44
 class User implements IUser {
45
-	/** @var string $uid */
46
-	private $uid;
47
-
48
-	/** @var string $displayName */
49
-	private $displayName;
50
-
51
-	/** @var UserInterface $backend */
52
-	private $backend;
53
-
54
-	/** @var bool $enabled */
55
-	private $enabled;
56
-
57
-	/** @var Emitter|Manager $emitter */
58
-	private $emitter;
59
-
60
-	/** @var string $home */
61
-	private $home;
62
-
63
-	/** @var int $lastLogin */
64
-	private $lastLogin;
65
-
66
-	/** @var \OCP\IConfig $config */
67
-	private $config;
68
-
69
-	/** @var IAvatarManager */
70
-	private $avatarManager;
71
-
72
-	/** @var IURLGenerator */
73
-	private $urlGenerator;
74
-
75
-	/**
76
-	 * @param string $uid
77
-	 * @param UserInterface $backend
78
-	 * @param \OC\Hooks\Emitter $emitter
79
-	 * @param IConfig|null $config
80
-	 * @param IURLGenerator $urlGenerator
81
-	 */
82
-	public function __construct($uid, $backend, $emitter = null, IConfig $config = null, $urlGenerator = null) {
83
-		$this->uid = $uid;
84
-		$this->backend = $backend;
85
-		$this->emitter = $emitter;
86
-		if(is_null($config)) {
87
-			$config = \OC::$server->getConfig();
88
-		}
89
-		$this->config = $config;
90
-		$this->urlGenerator = $urlGenerator;
91
-		$enabled = $this->config->getUserValue($uid, 'core', 'enabled', 'true');
92
-		$this->enabled = ($enabled === 'true');
93
-		$this->lastLogin = $this->config->getUserValue($uid, 'login', 'lastLogin', 0);
94
-		if (is_null($this->urlGenerator)) {
95
-			$this->urlGenerator = \OC::$server->getURLGenerator();
96
-		}
97
-	}
98
-
99
-	/**
100
-	 * get the user id
101
-	 *
102
-	 * @return string
103
-	 */
104
-	public function getUID() {
105
-		return $this->uid;
106
-	}
107
-
108
-	/**
109
-	 * get the display name for the user, if no specific display name is set it will fallback to the user id
110
-	 *
111
-	 * @return string
112
-	 */
113
-	public function getDisplayName() {
114
-		if (!isset($this->displayName)) {
115
-			$displayName = '';
116
-			if ($this->backend and $this->backend->implementsActions(Backend::GET_DISPLAYNAME)) {
117
-				// get display name and strip whitespace from the beginning and end of it
118
-				$backendDisplayName = $this->backend->getDisplayName($this->uid);
119
-				if (is_string($backendDisplayName)) {
120
-					$displayName = trim($backendDisplayName);
121
-				}
122
-			}
123
-
124
-			if (!empty($displayName)) {
125
-				$this->displayName = $displayName;
126
-			} else {
127
-				$this->displayName = $this->uid;
128
-			}
129
-		}
130
-		return $this->displayName;
131
-	}
132
-
133
-	/**
134
-	 * set the displayname for the user
135
-	 *
136
-	 * @param string $displayName
137
-	 * @return bool
138
-	 */
139
-	public function setDisplayName($displayName) {
140
-		$displayName = trim($displayName);
141
-		if ($this->backend->implementsActions(Backend::SET_DISPLAYNAME) && !empty($displayName)) {
142
-			$result = $this->backend->setDisplayName($this->uid, $displayName);
143
-			if ($result) {
144
-				$this->displayName = $displayName;
145
-				$this->triggerChange('displayName', $displayName);
146
-			}
147
-			return $result !== false;
148
-		} else {
149
-			return false;
150
-		}
151
-	}
152
-
153
-	/**
154
-	 * set the email address of the user
155
-	 *
156
-	 * @param string|null $mailAddress
157
-	 * @return void
158
-	 * @since 9.0.0
159
-	 */
160
-	public function setEMailAddress($mailAddress) {
161
-		if($mailAddress === '') {
162
-			$this->config->deleteUserValue($this->uid, 'settings', 'email');
163
-		} else {
164
-			$this->config->setUserValue($this->uid, 'settings', 'email', $mailAddress);
165
-		}
166
-		$this->triggerChange('eMailAddress', $mailAddress);
167
-	}
168
-
169
-	/**
170
-	 * returns the timestamp of the user's last login or 0 if the user did never
171
-	 * login
172
-	 *
173
-	 * @return int
174
-	 */
175
-	public function getLastLogin() {
176
-		return $this->lastLogin;
177
-	}
178
-
179
-	/**
180
-	 * updates the timestamp of the most recent login of this user
181
-	 */
182
-	public function updateLastLoginTimestamp() {
183
-		$firstTimeLogin = ($this->lastLogin === 0);
184
-		$this->lastLogin = time();
185
-		$this->config->setUserValue(
186
-			$this->uid, 'login', 'lastLogin', $this->lastLogin);
187
-
188
-		return $firstTimeLogin;
189
-	}
190
-
191
-	/**
192
-	 * Delete the user
193
-	 *
194
-	 * @return bool
195
-	 */
196
-	public function delete() {
197
-		if ($this->emitter) {
198
-			$this->emitter->emit('\OC\User', 'preDelete', array($this));
199
-		}
200
-		// get the home now because it won't return it after user deletion
201
-		$homePath = $this->getHome();
202
-		$result = $this->backend->deleteUser($this->uid);
203
-		if ($result) {
204
-
205
-			// FIXME: Feels like an hack - suggestions?
206
-
207
-			$groupManager = \OC::$server->getGroupManager();
208
-			// We have to delete the user from all groups
209
-			foreach ($groupManager->getUserGroupIds($this) as $groupId) {
210
-				$group = $groupManager->get($groupId);
211
-				if ($group) {
212
-					\OC_Hook::emit("OC_Group", "pre_removeFromGroup", ["run" => true, "uid" => $this->uid, "gid" => $groupId]);
213
-					$group->removeUser($this);
214
-					\OC_Hook::emit("OC_User", "post_removeFromGroup", ["uid" => $this->uid, "gid" => $groupId]);
215
-				}
216
-			}
217
-			// Delete the user's keys in preferences
218
-			\OC::$server->getConfig()->deleteAllUserValues($this->uid);
219
-
220
-			// Delete user files in /data/
221
-			if ($homePath !== false) {
222
-				// FIXME: this operates directly on FS, should use View instead...
223
-				// also this is not testable/mockable...
224
-				\OC_Helper::rmdirr($homePath);
225
-			}
226
-
227
-			// Delete the users entry in the storage table
228
-			Storage::remove('home::' . $this->uid);
229
-
230
-			\OC::$server->getCommentsManager()->deleteReferencesOfActor('users', $this->uid);
231
-			\OC::$server->getCommentsManager()->deleteReadMarksFromUser($this);
232
-
233
-			$notification = \OC::$server->getNotificationManager()->createNotification();
234
-			$notification->setUser($this->uid);
235
-			\OC::$server->getNotificationManager()->markProcessed($notification);
236
-
237
-			if ($this->emitter) {
238
-				$this->emitter->emit('\OC\User', 'postDelete', array($this));
239
-			}
240
-		}
241
-		return !($result === false);
242
-	}
243
-
244
-	/**
245
-	 * Set the password of the user
246
-	 *
247
-	 * @param string $password
248
-	 * @param string $recoveryPassword for the encryption app to reset encryption keys
249
-	 * @return bool
250
-	 */
251
-	public function setPassword($password, $recoveryPassword = null) {
252
-		if ($this->emitter) {
253
-			$this->emitter->emit('\OC\User', 'preSetPassword', array($this, $password, $recoveryPassword));
254
-		}
255
-		if ($this->backend->implementsActions(Backend::SET_PASSWORD)) {
256
-			$result = $this->backend->setPassword($this->uid, $password);
257
-			if ($this->emitter) {
258
-				$this->emitter->emit('\OC\User', 'postSetPassword', array($this, $password, $recoveryPassword));
259
-			}
260
-			return !($result === false);
261
-		} else {
262
-			return false;
263
-		}
264
-	}
265
-
266
-	/**
267
-	 * get the users home folder to mount
268
-	 *
269
-	 * @return string
270
-	 */
271
-	public function getHome() {
272
-		if (!$this->home) {
273
-			if ($this->backend->implementsActions(Backend::GET_HOME) and $home = $this->backend->getHome($this->uid)) {
274
-				$this->home = $home;
275
-			} elseif ($this->config) {
276
-				$this->home = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/' . $this->uid;
277
-			} else {
278
-				$this->home = \OC::$SERVERROOT . '/data/' . $this->uid;
279
-			}
280
-		}
281
-		return $this->home;
282
-	}
283
-
284
-	/**
285
-	 * Get the name of the backend class the user is connected with
286
-	 *
287
-	 * @return string
288
-	 */
289
-	public function getBackendClassName() {
290
-		if($this->backend instanceof IUserBackend) {
291
-			return $this->backend->getBackendName();
292
-		}
293
-		return get_class($this->backend);
294
-	}
295
-
296
-	/**
297
-	 * check if the backend allows the user to change his avatar on Personal page
298
-	 *
299
-	 * @return bool
300
-	 */
301
-	public function canChangeAvatar() {
302
-		if ($this->backend->implementsActions(Backend::PROVIDE_AVATAR)) {
303
-			return $this->backend->canChangeAvatar($this->uid);
304
-		}
305
-		return true;
306
-	}
307
-
308
-	/**
309
-	 * check if the backend supports changing passwords
310
-	 *
311
-	 * @return bool
312
-	 */
313
-	public function canChangePassword() {
314
-		return $this->backend->implementsActions(Backend::SET_PASSWORD);
315
-	}
316
-
317
-	/**
318
-	 * check if the backend supports changing display names
319
-	 *
320
-	 * @return bool
321
-	 */
322
-	public function canChangeDisplayName() {
323
-		if ($this->config->getSystemValue('allow_user_to_change_display_name') === false) {
324
-			return false;
325
-		}
326
-		return $this->backend->implementsActions(Backend::SET_DISPLAYNAME);
327
-	}
328
-
329
-	/**
330
-	 * check if the user is enabled
331
-	 *
332
-	 * @return bool
333
-	 */
334
-	public function isEnabled() {
335
-		return $this->enabled;
336
-	}
337
-
338
-	/**
339
-	 * set the enabled status for the user
340
-	 *
341
-	 * @param bool $enabled
342
-	 */
343
-	public function setEnabled($enabled) {
344
-		$this->enabled = $enabled;
345
-		$enabled = ($enabled) ? 'true' : 'false';
346
-		$this->config->setUserValue($this->uid, 'core', 'enabled', $enabled);
347
-	}
348
-
349
-	/**
350
-	 * get the users email address
351
-	 *
352
-	 * @return string|null
353
-	 * @since 9.0.0
354
-	 */
355
-	public function getEMailAddress() {
356
-		return $this->config->getUserValue($this->uid, 'settings', 'email', null);
357
-	}
358
-
359
-	/**
360
-	 * get the users' quota
361
-	 *
362
-	 * @return string
363
-	 * @since 9.0.0
364
-	 */
365
-	public function getQuota() {
366
-		$quota = $this->config->getUserValue($this->uid, 'files', 'quota', 'default');
367
-		if($quota === 'default') {
368
-			$quota = $this->config->getAppValue('files', 'default_quota', 'none');
369
-		}
370
-		return $quota;
371
-	}
372
-
373
-	/**
374
-	 * set the users' quota
375
-	 *
376
-	 * @param string $quota
377
-	 * @return void
378
-	 * @since 9.0.0
379
-	 */
380
-	public function setQuota($quota) {
381
-		if($quota !== 'none' and $quota !== 'default') {
382
-			$quota = OC_Helper::computerFileSize($quota);
383
-			$quota = OC_Helper::humanFileSize($quota);
384
-		}
385
-		$this->config->setUserValue($this->uid, 'files', 'quota', $quota);
386
-		$this->triggerChange('quota', $quota);
387
-	}
388
-
389
-	/**
390
-	 * get the avatar image if it exists
391
-	 *
392
-	 * @param int $size
393
-	 * @return IImage|null
394
-	 * @since 9.0.0
395
-	 */
396
-	public function getAvatarImage($size) {
397
-		// delay the initialization
398
-		if (is_null($this->avatarManager)) {
399
-			$this->avatarManager = \OC::$server->getAvatarManager();
400
-		}
401
-
402
-		$avatar = $this->avatarManager->getAvatar($this->uid);
403
-		$image = $avatar->get(-1);
404
-		if ($image) {
405
-			return $image;
406
-		}
407
-
408
-		return null;
409
-	}
410
-
411
-	/**
412
-	 * get the federation cloud id
413
-	 *
414
-	 * @return string
415
-	 * @since 9.0.0
416
-	 */
417
-	public function getCloudId() {
418
-		$uid = $this->getUID();
419
-		$server = $this->urlGenerator->getAbsoluteURL('/');
420
-		$server =  rtrim( $this->removeProtocolFromUrl($server), '/');
421
-		return \OC::$server->getCloudIdManager()->getCloudId($uid, $server)->getId();
422
-	}
423
-
424
-	/**
425
-	 * @param string $url
426
-	 * @return string
427
-	 */
428
-	private function removeProtocolFromUrl($url) {
429
-		if (strpos($url, 'https://') === 0) {
430
-			return substr($url, strlen('https://'));
431
-		} else if (strpos($url, 'http://') === 0) {
432
-			return substr($url, strlen('http://'));
433
-		}
434
-
435
-		return $url;
436
-	}
437
-
438
-	public function triggerChange($feature, $value = null) {
439
-		if ($this->emitter) {
440
-			$this->emitter->emit('\OC\User', 'changeUser', array($this, $feature, $value));
441
-		}
442
-	}
45
+    /** @var string $uid */
46
+    private $uid;
47
+
48
+    /** @var string $displayName */
49
+    private $displayName;
50
+
51
+    /** @var UserInterface $backend */
52
+    private $backend;
53
+
54
+    /** @var bool $enabled */
55
+    private $enabled;
56
+
57
+    /** @var Emitter|Manager $emitter */
58
+    private $emitter;
59
+
60
+    /** @var string $home */
61
+    private $home;
62
+
63
+    /** @var int $lastLogin */
64
+    private $lastLogin;
65
+
66
+    /** @var \OCP\IConfig $config */
67
+    private $config;
68
+
69
+    /** @var IAvatarManager */
70
+    private $avatarManager;
71
+
72
+    /** @var IURLGenerator */
73
+    private $urlGenerator;
74
+
75
+    /**
76
+     * @param string $uid
77
+     * @param UserInterface $backend
78
+     * @param \OC\Hooks\Emitter $emitter
79
+     * @param IConfig|null $config
80
+     * @param IURLGenerator $urlGenerator
81
+     */
82
+    public function __construct($uid, $backend, $emitter = null, IConfig $config = null, $urlGenerator = null) {
83
+        $this->uid = $uid;
84
+        $this->backend = $backend;
85
+        $this->emitter = $emitter;
86
+        if(is_null($config)) {
87
+            $config = \OC::$server->getConfig();
88
+        }
89
+        $this->config = $config;
90
+        $this->urlGenerator = $urlGenerator;
91
+        $enabled = $this->config->getUserValue($uid, 'core', 'enabled', 'true');
92
+        $this->enabled = ($enabled === 'true');
93
+        $this->lastLogin = $this->config->getUserValue($uid, 'login', 'lastLogin', 0);
94
+        if (is_null($this->urlGenerator)) {
95
+            $this->urlGenerator = \OC::$server->getURLGenerator();
96
+        }
97
+    }
98
+
99
+    /**
100
+     * get the user id
101
+     *
102
+     * @return string
103
+     */
104
+    public function getUID() {
105
+        return $this->uid;
106
+    }
107
+
108
+    /**
109
+     * get the display name for the user, if no specific display name is set it will fallback to the user id
110
+     *
111
+     * @return string
112
+     */
113
+    public function getDisplayName() {
114
+        if (!isset($this->displayName)) {
115
+            $displayName = '';
116
+            if ($this->backend and $this->backend->implementsActions(Backend::GET_DISPLAYNAME)) {
117
+                // get display name and strip whitespace from the beginning and end of it
118
+                $backendDisplayName = $this->backend->getDisplayName($this->uid);
119
+                if (is_string($backendDisplayName)) {
120
+                    $displayName = trim($backendDisplayName);
121
+                }
122
+            }
123
+
124
+            if (!empty($displayName)) {
125
+                $this->displayName = $displayName;
126
+            } else {
127
+                $this->displayName = $this->uid;
128
+            }
129
+        }
130
+        return $this->displayName;
131
+    }
132
+
133
+    /**
134
+     * set the displayname for the user
135
+     *
136
+     * @param string $displayName
137
+     * @return bool
138
+     */
139
+    public function setDisplayName($displayName) {
140
+        $displayName = trim($displayName);
141
+        if ($this->backend->implementsActions(Backend::SET_DISPLAYNAME) && !empty($displayName)) {
142
+            $result = $this->backend->setDisplayName($this->uid, $displayName);
143
+            if ($result) {
144
+                $this->displayName = $displayName;
145
+                $this->triggerChange('displayName', $displayName);
146
+            }
147
+            return $result !== false;
148
+        } else {
149
+            return false;
150
+        }
151
+    }
152
+
153
+    /**
154
+     * set the email address of the user
155
+     *
156
+     * @param string|null $mailAddress
157
+     * @return void
158
+     * @since 9.0.0
159
+     */
160
+    public function setEMailAddress($mailAddress) {
161
+        if($mailAddress === '') {
162
+            $this->config->deleteUserValue($this->uid, 'settings', 'email');
163
+        } else {
164
+            $this->config->setUserValue($this->uid, 'settings', 'email', $mailAddress);
165
+        }
166
+        $this->triggerChange('eMailAddress', $mailAddress);
167
+    }
168
+
169
+    /**
170
+     * returns the timestamp of the user's last login or 0 if the user did never
171
+     * login
172
+     *
173
+     * @return int
174
+     */
175
+    public function getLastLogin() {
176
+        return $this->lastLogin;
177
+    }
178
+
179
+    /**
180
+     * updates the timestamp of the most recent login of this user
181
+     */
182
+    public function updateLastLoginTimestamp() {
183
+        $firstTimeLogin = ($this->lastLogin === 0);
184
+        $this->lastLogin = time();
185
+        $this->config->setUserValue(
186
+            $this->uid, 'login', 'lastLogin', $this->lastLogin);
187
+
188
+        return $firstTimeLogin;
189
+    }
190
+
191
+    /**
192
+     * Delete the user
193
+     *
194
+     * @return bool
195
+     */
196
+    public function delete() {
197
+        if ($this->emitter) {
198
+            $this->emitter->emit('\OC\User', 'preDelete', array($this));
199
+        }
200
+        // get the home now because it won't return it after user deletion
201
+        $homePath = $this->getHome();
202
+        $result = $this->backend->deleteUser($this->uid);
203
+        if ($result) {
204
+
205
+            // FIXME: Feels like an hack - suggestions?
206
+
207
+            $groupManager = \OC::$server->getGroupManager();
208
+            // We have to delete the user from all groups
209
+            foreach ($groupManager->getUserGroupIds($this) as $groupId) {
210
+                $group = $groupManager->get($groupId);
211
+                if ($group) {
212
+                    \OC_Hook::emit("OC_Group", "pre_removeFromGroup", ["run" => true, "uid" => $this->uid, "gid" => $groupId]);
213
+                    $group->removeUser($this);
214
+                    \OC_Hook::emit("OC_User", "post_removeFromGroup", ["uid" => $this->uid, "gid" => $groupId]);
215
+                }
216
+            }
217
+            // Delete the user's keys in preferences
218
+            \OC::$server->getConfig()->deleteAllUserValues($this->uid);
219
+
220
+            // Delete user files in /data/
221
+            if ($homePath !== false) {
222
+                // FIXME: this operates directly on FS, should use View instead...
223
+                // also this is not testable/mockable...
224
+                \OC_Helper::rmdirr($homePath);
225
+            }
226
+
227
+            // Delete the users entry in the storage table
228
+            Storage::remove('home::' . $this->uid);
229
+
230
+            \OC::$server->getCommentsManager()->deleteReferencesOfActor('users', $this->uid);
231
+            \OC::$server->getCommentsManager()->deleteReadMarksFromUser($this);
232
+
233
+            $notification = \OC::$server->getNotificationManager()->createNotification();
234
+            $notification->setUser($this->uid);
235
+            \OC::$server->getNotificationManager()->markProcessed($notification);
236
+
237
+            if ($this->emitter) {
238
+                $this->emitter->emit('\OC\User', 'postDelete', array($this));
239
+            }
240
+        }
241
+        return !($result === false);
242
+    }
243
+
244
+    /**
245
+     * Set the password of the user
246
+     *
247
+     * @param string $password
248
+     * @param string $recoveryPassword for the encryption app to reset encryption keys
249
+     * @return bool
250
+     */
251
+    public function setPassword($password, $recoveryPassword = null) {
252
+        if ($this->emitter) {
253
+            $this->emitter->emit('\OC\User', 'preSetPassword', array($this, $password, $recoveryPassword));
254
+        }
255
+        if ($this->backend->implementsActions(Backend::SET_PASSWORD)) {
256
+            $result = $this->backend->setPassword($this->uid, $password);
257
+            if ($this->emitter) {
258
+                $this->emitter->emit('\OC\User', 'postSetPassword', array($this, $password, $recoveryPassword));
259
+            }
260
+            return !($result === false);
261
+        } else {
262
+            return false;
263
+        }
264
+    }
265
+
266
+    /**
267
+     * get the users home folder to mount
268
+     *
269
+     * @return string
270
+     */
271
+    public function getHome() {
272
+        if (!$this->home) {
273
+            if ($this->backend->implementsActions(Backend::GET_HOME) and $home = $this->backend->getHome($this->uid)) {
274
+                $this->home = $home;
275
+            } elseif ($this->config) {
276
+                $this->home = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/' . $this->uid;
277
+            } else {
278
+                $this->home = \OC::$SERVERROOT . '/data/' . $this->uid;
279
+            }
280
+        }
281
+        return $this->home;
282
+    }
283
+
284
+    /**
285
+     * Get the name of the backend class the user is connected with
286
+     *
287
+     * @return string
288
+     */
289
+    public function getBackendClassName() {
290
+        if($this->backend instanceof IUserBackend) {
291
+            return $this->backend->getBackendName();
292
+        }
293
+        return get_class($this->backend);
294
+    }
295
+
296
+    /**
297
+     * check if the backend allows the user to change his avatar on Personal page
298
+     *
299
+     * @return bool
300
+     */
301
+    public function canChangeAvatar() {
302
+        if ($this->backend->implementsActions(Backend::PROVIDE_AVATAR)) {
303
+            return $this->backend->canChangeAvatar($this->uid);
304
+        }
305
+        return true;
306
+    }
307
+
308
+    /**
309
+     * check if the backend supports changing passwords
310
+     *
311
+     * @return bool
312
+     */
313
+    public function canChangePassword() {
314
+        return $this->backend->implementsActions(Backend::SET_PASSWORD);
315
+    }
316
+
317
+    /**
318
+     * check if the backend supports changing display names
319
+     *
320
+     * @return bool
321
+     */
322
+    public function canChangeDisplayName() {
323
+        if ($this->config->getSystemValue('allow_user_to_change_display_name') === false) {
324
+            return false;
325
+        }
326
+        return $this->backend->implementsActions(Backend::SET_DISPLAYNAME);
327
+    }
328
+
329
+    /**
330
+     * check if the user is enabled
331
+     *
332
+     * @return bool
333
+     */
334
+    public function isEnabled() {
335
+        return $this->enabled;
336
+    }
337
+
338
+    /**
339
+     * set the enabled status for the user
340
+     *
341
+     * @param bool $enabled
342
+     */
343
+    public function setEnabled($enabled) {
344
+        $this->enabled = $enabled;
345
+        $enabled = ($enabled) ? 'true' : 'false';
346
+        $this->config->setUserValue($this->uid, 'core', 'enabled', $enabled);
347
+    }
348
+
349
+    /**
350
+     * get the users email address
351
+     *
352
+     * @return string|null
353
+     * @since 9.0.0
354
+     */
355
+    public function getEMailAddress() {
356
+        return $this->config->getUserValue($this->uid, 'settings', 'email', null);
357
+    }
358
+
359
+    /**
360
+     * get the users' quota
361
+     *
362
+     * @return string
363
+     * @since 9.0.0
364
+     */
365
+    public function getQuota() {
366
+        $quota = $this->config->getUserValue($this->uid, 'files', 'quota', 'default');
367
+        if($quota === 'default') {
368
+            $quota = $this->config->getAppValue('files', 'default_quota', 'none');
369
+        }
370
+        return $quota;
371
+    }
372
+
373
+    /**
374
+     * set the users' quota
375
+     *
376
+     * @param string $quota
377
+     * @return void
378
+     * @since 9.0.0
379
+     */
380
+    public function setQuota($quota) {
381
+        if($quota !== 'none' and $quota !== 'default') {
382
+            $quota = OC_Helper::computerFileSize($quota);
383
+            $quota = OC_Helper::humanFileSize($quota);
384
+        }
385
+        $this->config->setUserValue($this->uid, 'files', 'quota', $quota);
386
+        $this->triggerChange('quota', $quota);
387
+    }
388
+
389
+    /**
390
+     * get the avatar image if it exists
391
+     *
392
+     * @param int $size
393
+     * @return IImage|null
394
+     * @since 9.0.0
395
+     */
396
+    public function getAvatarImage($size) {
397
+        // delay the initialization
398
+        if (is_null($this->avatarManager)) {
399
+            $this->avatarManager = \OC::$server->getAvatarManager();
400
+        }
401
+
402
+        $avatar = $this->avatarManager->getAvatar($this->uid);
403
+        $image = $avatar->get(-1);
404
+        if ($image) {
405
+            return $image;
406
+        }
407
+
408
+        return null;
409
+    }
410
+
411
+    /**
412
+     * get the federation cloud id
413
+     *
414
+     * @return string
415
+     * @since 9.0.0
416
+     */
417
+    public function getCloudId() {
418
+        $uid = $this->getUID();
419
+        $server = $this->urlGenerator->getAbsoluteURL('/');
420
+        $server =  rtrim( $this->removeProtocolFromUrl($server), '/');
421
+        return \OC::$server->getCloudIdManager()->getCloudId($uid, $server)->getId();
422
+    }
423
+
424
+    /**
425
+     * @param string $url
426
+     * @return string
427
+     */
428
+    private function removeProtocolFromUrl($url) {
429
+        if (strpos($url, 'https://') === 0) {
430
+            return substr($url, strlen('https://'));
431
+        } else if (strpos($url, 'http://') === 0) {
432
+            return substr($url, strlen('http://'));
433
+        }
434
+
435
+        return $url;
436
+    }
437
+
438
+    public function triggerChange($feature, $value = null) {
439
+        if ($this->emitter) {
440
+            $this->emitter->emit('\OC\User', 'changeUser', array($this, $feature, $value));
441
+        }
442
+    }
443 443
 }
Please login to merge, or discard this patch.
lib/private/legacy/files.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -334,7 +334,7 @@
 block discarded – undo
334 334
 	 *
335 335
 	 * @param int $size file size in bytes
336 336
 	 * @param array $files override '.htaccess' and '.user.ini' locations
337
-	 * @return bool false on failure, size on success
337
+	 * @return integer false on failure, size on success
338 338
 	 */
339 339
 	public static function setUploadLimit($size, $files = []) {
340 340
 		//don't allow user to break his config
Please login to merge, or discard this patch.
Spacing   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -115,7 +115,7 @@  discard block
 block discarded – undo
115 115
 			}
116 116
 
117 117
 			if (!is_array($files)) {
118
-				$filename = $dir . '/' . $files;
118
+				$filename = $dir.'/'.$files;
119 119
 				if (!$view->is_dir($filename)) {
120 120
 					self::getSingleFile($view, $dir, $files, is_null($params) ? array() : $params);
121 121
 					return;
@@ -130,9 +130,9 @@  discard block
 block discarded – undo
130 130
 					$name = $basename;
131 131
 				}
132 132
 
133
-				$filename = $dir . '/' . $name;
133
+				$filename = $dir.'/'.$name;
134 134
 			} else {
135
-				$filename = $dir . '/' . $files;
135
+				$filename = $dir.'/'.$files;
136 136
 				$getType = self::ZIP_DIR;
137 137
 				// downloading root ?
138 138
 				if ($files !== '') {
@@ -151,7 +151,7 @@  discard block
 block discarded – undo
151 151
 			ignore_user_abort(true);
152 152
 			if ($getType === self::ZIP_FILES) {
153 153
 				foreach ($files as $file) {
154
-					$file = $dir . '/' . $file;
154
+					$file = $dir.'/'.$file;
155 155
 					if (\OC\Files\Filesystem::is_file($file)) {
156 156
 						$fileSize = \OC\Files\Filesystem::filesize($file);
157 157
 						$fileTime = \OC\Files\Filesystem::filemtime($file);
@@ -163,7 +163,7 @@  discard block
 block discarded – undo
163 163
 					}
164 164
 				}
165 165
 			} elseif ($getType === self::ZIP_DIR) {
166
-				$file = $dir . '/' . $files;
166
+				$file = $dir.'/'.$files;
167 167
 				$streamer->addDirRecursive($file);
168 168
 			}
169 169
 			$streamer->finalize();
@@ -195,7 +195,7 @@  discard block
 block discarded – undo
195 195
 	 * @return array $rangeArray ('from'=>int,'to'=>int), ...
196 196
 	 */
197 197
 	private static function parseHttpRangeHeader($rangeHeaderPos, $fileSize) {
198
-		$rArray=explode(',', $rangeHeaderPos);
198
+		$rArray = explode(',', $rangeHeaderPos);
199 199
 		$minOffset = 0;
200 200
 		$ind = 0;
201 201
 
@@ -207,7 +207,7 @@  discard block
 block discarded – undo
207 207
 				if ($ranges[0] < $minOffset) { // case: bytes=500-700,601-999
208 208
 					$ranges[0] = $minOffset;
209 209
 				}
210
-				if ($ind > 0 && $rangeArray[$ind-1]['to']+1 == $ranges[0]) { // case: bytes=500-600,601-999
210
+				if ($ind > 0 && $rangeArray[$ind - 1]['to'] + 1 == $ranges[0]) { // case: bytes=500-600,601-999
211 211
 					$ind--;
212 212
 					$ranges[0] = $rangeArray[$ind]['from'];
213 213
 				}
@@ -216,9 +216,9 @@  discard block
 block discarded – undo
216 216
 			if (is_numeric($ranges[0]) && is_numeric($ranges[1]) && $ranges[0] < $fileSize && $ranges[0] <= $ranges[1]) {
217 217
 				// case: x-x
218 218
 				if ($ranges[1] >= $fileSize) {
219
-					$ranges[1] = $fileSize-1;
219
+					$ranges[1] = $fileSize - 1;
220 220
 				}
221
-				$rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize );
221
+				$rangeArray[$ind++] = array('from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize);
222 222
 				$minOffset = $ranges[1] + 1;
223 223
 				if ($minOffset >= $fileSize) {
224 224
 					break;
@@ -226,7 +226,7 @@  discard block
 block discarded – undo
226 226
 			}
227 227
 			elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) {
228 228
 				// case: x-
229
-				$rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $fileSize-1, 'size' => $fileSize );
229
+				$rangeArray[$ind++] = array('from' => $ranges[0], 'to' => $fileSize - 1, 'size' => $fileSize);
230 230
 				break;
231 231
 			}
232 232
 			elseif (is_numeric($ranges[1])) {
@@ -234,7 +234,7 @@  discard block
 block discarded – undo
234 234
 				if ($ranges[1] > $fileSize) {
235 235
 					$ranges[1] = $fileSize;
236 236
 				}
237
-				$rangeArray[$ind++] = array( 'from' => $fileSize-$ranges[1], 'to' => $fileSize-1, 'size' => $fileSize );
237
+				$rangeArray[$ind++] = array('from' => $fileSize - $ranges[1], 'to' => $fileSize - 1, 'size' => $fileSize);
238 238
 				break;
239 239
 			}
240 240
 		}
@@ -248,7 +248,7 @@  discard block
 block discarded – undo
248 248
 	 * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
249 249
 	 */
250 250
 	private static function getSingleFile($view, $dir, $name, $params) {
251
-		$filename = $dir . '/' . $name;
251
+		$filename = $dir.'/'.$name;
252 252
 		OC_Util::obEnd();
253 253
 		$view->lockFile($filename, ILockingProvider::LOCK_SHARED);
254 254
 		
@@ -314,17 +314,17 @@  discard block
 block discarded – undo
314 314
 	 */
315 315
 	public static function lockFiles($view, $dir, $files) {
316 316
 		if (!is_array($files)) {
317
-			$file = $dir . '/' . $files;
317
+			$file = $dir.'/'.$files;
318 318
 			$files = [$file];
319 319
 		}
320 320
 		foreach ($files as $file) {
321
-			$file = $dir . '/' . $file;
321
+			$file = $dir.'/'.$file;
322 322
 			$view->lockFile($file, ILockingProvider::LOCK_SHARED);
323 323
 			if ($view->is_dir($file)) {
324 324
 				$contents = $view->getDirectoryContent($file);
325 325
 				$contents = array_map(function($fileInfo) use ($file) {
326 326
 					/** @var \OCP\Files\FileInfo $fileInfo */
327
-					return $file . '/' . $fileInfo->getName();
327
+					return $file.'/'.$fileInfo->getName();
328 328
 				}, $contents);
329 329
 				self::lockFiles($view, $dir, $contents);
330 330
 			}
@@ -353,8 +353,8 @@  discard block
 block discarded – undo
353 353
 
354 354
 		// default locations if not overridden by $files
355 355
 		$files = array_merge([
356
-			'.htaccess' => OC::$SERVERROOT . '/.htaccess',
357
-			'.user.ini' => OC::$SERVERROOT . '/.user.ini'
356
+			'.htaccess' => OC::$SERVERROOT.'/.htaccess',
357
+			'.user.ini' => OC::$SERVERROOT.'/.user.ini'
358 358
 		], $files);
359 359
 
360 360
 		$updateFiles = [
@@ -375,7 +375,7 @@  discard block
 block discarded – undo
375 375
 			$handle = @fopen($filename, 'r+');
376 376
 			if (!$handle) {
377 377
 				\OCP\Util::writeLog('files',
378
-					'Can\'t write upload limit to ' . $filename . '. Please check the file permissions',
378
+					'Can\'t write upload limit to '.$filename.'. Please check the file permissions',
379 379
 					\OCP\Util::WARN);
380 380
 				$success = false;
381 381
 				continue; // try to update as many files as possible
@@ -395,7 +395,7 @@  discard block
 block discarded – undo
395 395
 					$content = $newContent;
396 396
 				}
397 397
 				if ($hasReplaced === 0) {
398
-					$content .= "\n" . $setting;
398
+					$content .= "\n".$setting;
399 399
 				}
400 400
 			}
401 401
 
@@ -426,12 +426,12 @@  discard block
 block discarded – undo
426 426
 		}
427 427
 		if ($getType === self::ZIP_FILES) {
428 428
 			foreach ($files as $file) {
429
-				$file = $dir . '/' . $file;
429
+				$file = $dir.'/'.$file;
430 430
 				$view->unlockFile($file, ILockingProvider::LOCK_SHARED);
431 431
 			}
432 432
 		}
433 433
 		if ($getType === self::ZIP_DIR) {
434
-			$file = $dir . '/' . $files;
434
+			$file = $dir.'/'.$files;
435 435
 			$view->unlockFile($file, ILockingProvider::LOCK_SHARED);
436 436
 		}
437 437
 	}
Please login to merge, or discard this patch.
Braces   +6 added lines, -12 removed lines patch added patch discarded remove patch
@@ -83,13 +83,11 @@  discard block
 block discarded – undo
83 83
 			    if (count($rangeArray) > 1) {
84 84
 				$type = 'multipart/byteranges; boundary='.self::getBoundary();
85 85
 				// no Content-Length header here
86
-			    }
87
-			    else {
86
+			    } else {
88 87
 				header(sprintf('Content-Range: bytes %d-%d/%d', $rangeArray[0]['from'], $rangeArray[0]['to'], $fileSize), true);
89 88
 				OC_Response::setContentLengthHeader($rangeArray[0]['to'] - $rangeArray[0]['from'] + 1);
90 89
 			    }
91
-			}
92
-			else {
90
+			} else {
93 91
 			    OC_Response::setContentLengthHeader($fileSize);
94 92
 			}
95 93
 		}
@@ -223,13 +221,11 @@  discard block
 block discarded – undo
223 221
 				if ($minOffset >= $fileSize) {
224 222
 					break;
225 223
 				}
226
-			}
227
-			elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) {
224
+			} elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) {
228 225
 				// case: x-
229 226
 				$rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $fileSize-1, 'size' => $fileSize );
230 227
 				break;
231
-			}
232
-			elseif (is_numeric($ranges[1])) {
228
+			} elseif (is_numeric($ranges[1])) {
233 229
 				// case: -x
234 230
 				if ($ranges[1] > $fileSize) {
235 231
 					$ranges[1] = $fileSize;
@@ -277,8 +273,7 @@  discard block
 block discarded – undo
277 273
 			try {
278 274
 			    if (count($rangeArray) == 1) {
279 275
 				$view->readfilePart($filename, $rangeArray[0]['from'], $rangeArray[0]['to']);
280
-			    }
281
-			    else {
276
+			    } else {
282 277
 				// check if file is seekable (if not throw UnseekableException)
283 278
 				// we have to check it before body contents
284 279
 				$view->readfilePart($filename, $rangeArray[0]['size'], $rangeArray[0]['size']);
@@ -301,8 +296,7 @@  discard block
 block discarded – undo
301 296
 			    self::sendHeaders($filename, $name, array());
302 297
 			    $view->readfile($filename);
303 298
 			}
304
-		}
305
-		else {
299
+		} else {
306 300
 		    $view->readfile($filename);
307 301
 		}
308 302
 	}
Please login to merge, or discard this patch.
Indentation   +388 added lines, -388 removed lines patch added patch discarded remove patch
@@ -46,396 +46,396 @@
 block discarded – undo
46 46
  *
47 47
  */
48 48
 class OC_Files {
49
-	const FILE = 1;
50
-	const ZIP_FILES = 2;
51
-	const ZIP_DIR = 3;
52
-
53
-	const UPLOAD_MIN_LIMIT_BYTES = 1048576; // 1 MiB
54
-
55
-
56
-	private static $multipartBoundary = '';
57
-
58
-	/**
59
-	 * @return string
60
-	 */
61
-	private static function getBoundary() {
62
-		if (empty(self::$multipartBoundary)) {
63
-			self::$multipartBoundary = md5(mt_rand());
64
-		}
65
-		return self::$multipartBoundary;
66
-	}
67
-
68
-	/**
69
-	 * @param string $filename
70
-	 * @param string $name
71
-	 * @param array $rangeArray ('from'=>int,'to'=>int), ...
72
-	 */
73
-	private static function sendHeaders($filename, $name, array $rangeArray) {
74
-		OC_Response::setContentDispositionHeader($name, 'attachment');
75
-		header('Content-Transfer-Encoding: binary', true);
76
-		OC_Response::disableCaching();
77
-		$fileSize = \OC\Files\Filesystem::filesize($filename);
78
-		$type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
79
-		if ($fileSize > -1) {
80
-			if (!empty($rangeArray)) {
81
-			    header('HTTP/1.1 206 Partial Content', true);
82
-			    header('Accept-Ranges: bytes', true);
83
-			    if (count($rangeArray) > 1) {
84
-				$type = 'multipart/byteranges; boundary='.self::getBoundary();
85
-				// no Content-Length header here
86
-			    }
87
-			    else {
88
-				header(sprintf('Content-Range: bytes %d-%d/%d', $rangeArray[0]['from'], $rangeArray[0]['to'], $fileSize), true);
89
-				OC_Response::setContentLengthHeader($rangeArray[0]['to'] - $rangeArray[0]['from'] + 1);
90
-			    }
91
-			}
92
-			else {
93
-			    OC_Response::setContentLengthHeader($fileSize);
94
-			}
95
-		}
96
-		header('Content-Type: '.$type, true);
97
-	}
98
-
99
-	/**
100
-	 * return the content of a file or return a zip file containing multiple files
101
-	 *
102
-	 * @param string $dir
103
-	 * @param string $files ; separated list of files to download
104
-	 * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
105
-	 */
106
-	public static function get($dir, $files, $params = null) {
107
-
108
-		$view = \OC\Files\Filesystem::getView();
109
-		$getType = self::FILE;
110
-		$filename = $dir;
111
-		try {
112
-
113
-			if (is_array($files) && count($files) === 1) {
114
-				$files = $files[0];
115
-			}
116
-
117
-			if (!is_array($files)) {
118
-				$filename = $dir . '/' . $files;
119
-				if (!$view->is_dir($filename)) {
120
-					self::getSingleFile($view, $dir, $files, is_null($params) ? array() : $params);
121
-					return;
122
-				}
123
-			}
124
-
125
-			$name = 'download';
126
-			if (is_array($files)) {
127
-				$getType = self::ZIP_FILES;
128
-				$basename = basename($dir);
129
-				if ($basename) {
130
-					$name = $basename;
131
-				}
132
-
133
-				$filename = $dir . '/' . $name;
134
-			} else {
135
-				$filename = $dir . '/' . $files;
136
-				$getType = self::ZIP_DIR;
137
-				// downloading root ?
138
-				if ($files !== '') {
139
-					$name = $files;
140
-				}
141
-			}
142
-
143
-			$streamer = new Streamer();
144
-			OC_Util::obEnd();
145
-
146
-			self::lockFiles($view, $dir, $files);
147
-
148
-			$streamer->sendHeaders($name);
149
-			$executionTime = intval(OC::$server->getIniWrapper()->getNumeric('max_execution_time'));
150
-			if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
151
-				@set_time_limit(0);
152
-			}
153
-			ignore_user_abort(true);
154
-			if ($getType === self::ZIP_FILES) {
155
-				foreach ($files as $file) {
156
-					$file = $dir . '/' . $file;
157
-					if (\OC\Files\Filesystem::is_file($file)) {
158
-						$fileSize = \OC\Files\Filesystem::filesize($file);
159
-						$fileTime = \OC\Files\Filesystem::filemtime($file);
160
-						$fh = \OC\Files\Filesystem::fopen($file, 'r');
161
-						$streamer->addFileFromStream($fh, basename($file), $fileSize, $fileTime);
162
-						fclose($fh);
163
-					} elseif (\OC\Files\Filesystem::is_dir($file)) {
164
-						$streamer->addDirRecursive($file);
165
-					}
166
-				}
167
-			} elseif ($getType === self::ZIP_DIR) {
168
-				$file = $dir . '/' . $files;
169
-				$streamer->addDirRecursive($file);
170
-			}
171
-			$streamer->finalize();
172
-			set_time_limit($executionTime);
173
-			self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
174
-		} catch (\OCP\Lock\LockedException $ex) {
175
-			self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
176
-			OC::$server->getLogger()->logException($ex);
177
-			$l = \OC::$server->getL10N('core');
178
-			$hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
179
-			\OC_Template::printErrorPage($l->t('File is currently busy, please try again later'), $hint);
180
-		} catch (\OCP\Files\ForbiddenException $ex) {
181
-			self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
182
-			OC::$server->getLogger()->logException($ex);
183
-			$l = \OC::$server->getL10N('core');
184
-			\OC_Template::printErrorPage($l->t('Can\'t read file'), $ex->getMessage());
185
-		} catch (\Exception $ex) {
186
-			self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
187
-			OC::$server->getLogger()->logException($ex);
188
-			$l = \OC::$server->getL10N('core');
189
-			$hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
190
-			\OC_Template::printErrorPage($l->t('Can\'t read file'), $hint);
191
-		}
192
-	}
193
-
194
-	/**
195
-	 * @param string $rangeHeaderPos
196
-	 * @param int $fileSize
197
-	 * @return array $rangeArray ('from'=>int,'to'=>int), ...
198
-	 */
199
-	private static function parseHttpRangeHeader($rangeHeaderPos, $fileSize) {
200
-		$rArray=explode(',', $rangeHeaderPos);
201
-		$minOffset = 0;
202
-		$ind = 0;
203
-
204
-		$rangeArray = array();
205
-
206
-		foreach ($rArray as $value) {
207
-			$ranges = explode('-', $value);
208
-			if (is_numeric($ranges[0])) {
209
-				if ($ranges[0] < $minOffset) { // case: bytes=500-700,601-999
210
-					$ranges[0] = $minOffset;
211
-				}
212
-				if ($ind > 0 && $rangeArray[$ind-1]['to']+1 == $ranges[0]) { // case: bytes=500-600,601-999
213
-					$ind--;
214
-					$ranges[0] = $rangeArray[$ind]['from'];
215
-				}
216
-			}
217
-
218
-			if (is_numeric($ranges[0]) && is_numeric($ranges[1]) && $ranges[0] < $fileSize && $ranges[0] <= $ranges[1]) {
219
-				// case: x-x
220
-				if ($ranges[1] >= $fileSize) {
221
-					$ranges[1] = $fileSize-1;
222
-				}
223
-				$rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize );
224
-				$minOffset = $ranges[1] + 1;
225
-				if ($minOffset >= $fileSize) {
226
-					break;
227
-				}
228
-			}
229
-			elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) {
230
-				// case: x-
231
-				$rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $fileSize-1, 'size' => $fileSize );
232
-				break;
233
-			}
234
-			elseif (is_numeric($ranges[1])) {
235
-				// case: -x
236
-				if ($ranges[1] > $fileSize) {
237
-					$ranges[1] = $fileSize;
238
-				}
239
-				$rangeArray[$ind++] = array( 'from' => $fileSize-$ranges[1], 'to' => $fileSize-1, 'size' => $fileSize );
240
-				break;
241
-			}
242
-		}
243
-		return $rangeArray;
244
-	}
245
-
246
-	/**
247
-	 * @param View $view
248
-	 * @param string $name
249
-	 * @param string $dir
250
-	 * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
251
-	 */
252
-	private static function getSingleFile($view, $dir, $name, $params) {
253
-		$filename = $dir . '/' . $name;
254
-		OC_Util::obEnd();
255
-		$view->lockFile($filename, ILockingProvider::LOCK_SHARED);
49
+    const FILE = 1;
50
+    const ZIP_FILES = 2;
51
+    const ZIP_DIR = 3;
52
+
53
+    const UPLOAD_MIN_LIMIT_BYTES = 1048576; // 1 MiB
54
+
55
+
56
+    private static $multipartBoundary = '';
57
+
58
+    /**
59
+     * @return string
60
+     */
61
+    private static function getBoundary() {
62
+        if (empty(self::$multipartBoundary)) {
63
+            self::$multipartBoundary = md5(mt_rand());
64
+        }
65
+        return self::$multipartBoundary;
66
+    }
67
+
68
+    /**
69
+     * @param string $filename
70
+     * @param string $name
71
+     * @param array $rangeArray ('from'=>int,'to'=>int), ...
72
+     */
73
+    private static function sendHeaders($filename, $name, array $rangeArray) {
74
+        OC_Response::setContentDispositionHeader($name, 'attachment');
75
+        header('Content-Transfer-Encoding: binary', true);
76
+        OC_Response::disableCaching();
77
+        $fileSize = \OC\Files\Filesystem::filesize($filename);
78
+        $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
79
+        if ($fileSize > -1) {
80
+            if (!empty($rangeArray)) {
81
+                header('HTTP/1.1 206 Partial Content', true);
82
+                header('Accept-Ranges: bytes', true);
83
+                if (count($rangeArray) > 1) {
84
+                $type = 'multipart/byteranges; boundary='.self::getBoundary();
85
+                // no Content-Length header here
86
+                }
87
+                else {
88
+                header(sprintf('Content-Range: bytes %d-%d/%d', $rangeArray[0]['from'], $rangeArray[0]['to'], $fileSize), true);
89
+                OC_Response::setContentLengthHeader($rangeArray[0]['to'] - $rangeArray[0]['from'] + 1);
90
+                }
91
+            }
92
+            else {
93
+                OC_Response::setContentLengthHeader($fileSize);
94
+            }
95
+        }
96
+        header('Content-Type: '.$type, true);
97
+    }
98
+
99
+    /**
100
+     * return the content of a file or return a zip file containing multiple files
101
+     *
102
+     * @param string $dir
103
+     * @param string $files ; separated list of files to download
104
+     * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
105
+     */
106
+    public static function get($dir, $files, $params = null) {
107
+
108
+        $view = \OC\Files\Filesystem::getView();
109
+        $getType = self::FILE;
110
+        $filename = $dir;
111
+        try {
112
+
113
+            if (is_array($files) && count($files) === 1) {
114
+                $files = $files[0];
115
+            }
116
+
117
+            if (!is_array($files)) {
118
+                $filename = $dir . '/' . $files;
119
+                if (!$view->is_dir($filename)) {
120
+                    self::getSingleFile($view, $dir, $files, is_null($params) ? array() : $params);
121
+                    return;
122
+                }
123
+            }
124
+
125
+            $name = 'download';
126
+            if (is_array($files)) {
127
+                $getType = self::ZIP_FILES;
128
+                $basename = basename($dir);
129
+                if ($basename) {
130
+                    $name = $basename;
131
+                }
132
+
133
+                $filename = $dir . '/' . $name;
134
+            } else {
135
+                $filename = $dir . '/' . $files;
136
+                $getType = self::ZIP_DIR;
137
+                // downloading root ?
138
+                if ($files !== '') {
139
+                    $name = $files;
140
+                }
141
+            }
142
+
143
+            $streamer = new Streamer();
144
+            OC_Util::obEnd();
145
+
146
+            self::lockFiles($view, $dir, $files);
147
+
148
+            $streamer->sendHeaders($name);
149
+            $executionTime = intval(OC::$server->getIniWrapper()->getNumeric('max_execution_time'));
150
+            if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
151
+                @set_time_limit(0);
152
+            }
153
+            ignore_user_abort(true);
154
+            if ($getType === self::ZIP_FILES) {
155
+                foreach ($files as $file) {
156
+                    $file = $dir . '/' . $file;
157
+                    if (\OC\Files\Filesystem::is_file($file)) {
158
+                        $fileSize = \OC\Files\Filesystem::filesize($file);
159
+                        $fileTime = \OC\Files\Filesystem::filemtime($file);
160
+                        $fh = \OC\Files\Filesystem::fopen($file, 'r');
161
+                        $streamer->addFileFromStream($fh, basename($file), $fileSize, $fileTime);
162
+                        fclose($fh);
163
+                    } elseif (\OC\Files\Filesystem::is_dir($file)) {
164
+                        $streamer->addDirRecursive($file);
165
+                    }
166
+                }
167
+            } elseif ($getType === self::ZIP_DIR) {
168
+                $file = $dir . '/' . $files;
169
+                $streamer->addDirRecursive($file);
170
+            }
171
+            $streamer->finalize();
172
+            set_time_limit($executionTime);
173
+            self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
174
+        } catch (\OCP\Lock\LockedException $ex) {
175
+            self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
176
+            OC::$server->getLogger()->logException($ex);
177
+            $l = \OC::$server->getL10N('core');
178
+            $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
179
+            \OC_Template::printErrorPage($l->t('File is currently busy, please try again later'), $hint);
180
+        } catch (\OCP\Files\ForbiddenException $ex) {
181
+            self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
182
+            OC::$server->getLogger()->logException($ex);
183
+            $l = \OC::$server->getL10N('core');
184
+            \OC_Template::printErrorPage($l->t('Can\'t read file'), $ex->getMessage());
185
+        } catch (\Exception $ex) {
186
+            self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
187
+            OC::$server->getLogger()->logException($ex);
188
+            $l = \OC::$server->getL10N('core');
189
+            $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
190
+            \OC_Template::printErrorPage($l->t('Can\'t read file'), $hint);
191
+        }
192
+    }
193
+
194
+    /**
195
+     * @param string $rangeHeaderPos
196
+     * @param int $fileSize
197
+     * @return array $rangeArray ('from'=>int,'to'=>int), ...
198
+     */
199
+    private static function parseHttpRangeHeader($rangeHeaderPos, $fileSize) {
200
+        $rArray=explode(',', $rangeHeaderPos);
201
+        $minOffset = 0;
202
+        $ind = 0;
203
+
204
+        $rangeArray = array();
205
+
206
+        foreach ($rArray as $value) {
207
+            $ranges = explode('-', $value);
208
+            if (is_numeric($ranges[0])) {
209
+                if ($ranges[0] < $minOffset) { // case: bytes=500-700,601-999
210
+                    $ranges[0] = $minOffset;
211
+                }
212
+                if ($ind > 0 && $rangeArray[$ind-1]['to']+1 == $ranges[0]) { // case: bytes=500-600,601-999
213
+                    $ind--;
214
+                    $ranges[0] = $rangeArray[$ind]['from'];
215
+                }
216
+            }
217
+
218
+            if (is_numeric($ranges[0]) && is_numeric($ranges[1]) && $ranges[0] < $fileSize && $ranges[0] <= $ranges[1]) {
219
+                // case: x-x
220
+                if ($ranges[1] >= $fileSize) {
221
+                    $ranges[1] = $fileSize-1;
222
+                }
223
+                $rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize );
224
+                $minOffset = $ranges[1] + 1;
225
+                if ($minOffset >= $fileSize) {
226
+                    break;
227
+                }
228
+            }
229
+            elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) {
230
+                // case: x-
231
+                $rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $fileSize-1, 'size' => $fileSize );
232
+                break;
233
+            }
234
+            elseif (is_numeric($ranges[1])) {
235
+                // case: -x
236
+                if ($ranges[1] > $fileSize) {
237
+                    $ranges[1] = $fileSize;
238
+                }
239
+                $rangeArray[$ind++] = array( 'from' => $fileSize-$ranges[1], 'to' => $fileSize-1, 'size' => $fileSize );
240
+                break;
241
+            }
242
+        }
243
+        return $rangeArray;
244
+    }
245
+
246
+    /**
247
+     * @param View $view
248
+     * @param string $name
249
+     * @param string $dir
250
+     * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
251
+     */
252
+    private static function getSingleFile($view, $dir, $name, $params) {
253
+        $filename = $dir . '/' . $name;
254
+        OC_Util::obEnd();
255
+        $view->lockFile($filename, ILockingProvider::LOCK_SHARED);
256 256
 		
257
-		$rangeArray = array();
257
+        $rangeArray = array();
258 258
 
259
-		if (isset($params['range']) && substr($params['range'], 0, 6) === 'bytes=') {
260
-			$rangeArray = self::parseHttpRangeHeader(substr($params['range'], 6), 
261
-								 \OC\Files\Filesystem::filesize($filename));
262
-		}
259
+        if (isset($params['range']) && substr($params['range'], 0, 6) === 'bytes=') {
260
+            $rangeArray = self::parseHttpRangeHeader(substr($params['range'], 6), 
261
+                                    \OC\Files\Filesystem::filesize($filename));
262
+        }
263 263
 		
264
-		if (\OC\Files\Filesystem::isReadable($filename)) {
265
-			self::sendHeaders($filename, $name, $rangeArray);
266
-		} elseif (!\OC\Files\Filesystem::file_exists($filename)) {
267
-			header("HTTP/1.1 404 Not Found");
268
-			$tmpl = new OC_Template('', '404', 'guest');
269
-			$tmpl->printPage();
270
-			exit();
271
-		} else {
272
-			header("HTTP/1.1 403 Forbidden");
273
-			die('403 Forbidden');
274
-		}
275
-		if (isset($params['head']) && $params['head']) {
276
-			return;
277
-		}
278
-		if (!empty($rangeArray)) {
279
-			try {
280
-			    if (count($rangeArray) == 1) {
281
-				$view->readfilePart($filename, $rangeArray[0]['from'], $rangeArray[0]['to']);
282
-			    }
283
-			    else {
284
-				// check if file is seekable (if not throw UnseekableException)
285
-				// we have to check it before body contents
286
-				$view->readfilePart($filename, $rangeArray[0]['size'], $rangeArray[0]['size']);
287
-
288
-				$type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
289
-
290
-				foreach ($rangeArray as $range) {
291
-				    echo "\r\n--".self::getBoundary()."\r\n".
292
-				         "Content-type: ".$type."\r\n".
293
-				         "Content-range: bytes ".$range['from']."-".$range['to']."/".$range['size']."\r\n\r\n";
294
-				    $view->readfilePart($filename, $range['from'], $range['to']);
295
-				}
296
-				echo "\r\n--".self::getBoundary()."--\r\n";
297
-			    }
298
-			} catch (\OCP\Files\UnseekableException $ex) {
299
-			    // file is unseekable
300
-			    header_remove('Accept-Ranges');
301
-			    header_remove('Content-Range');
302
-			    header("HTTP/1.1 200 OK");
303
-			    self::sendHeaders($filename, $name, array());
304
-			    $view->readfile($filename);
305
-			}
306
-		}
307
-		else {
308
-		    $view->readfile($filename);
309
-		}
310
-	}
311
-
312
-	/**
313
-	 * @param View $view
314
-	 * @param string $dir
315
-	 * @param string[]|string $files
316
-	 */
317
-	public static function lockFiles($view, $dir, $files) {
318
-		if (!is_array($files)) {
319
-			$file = $dir . '/' . $files;
320
-			$files = [$file];
321
-		}
322
-		foreach ($files as $file) {
323
-			$file = $dir . '/' . $file;
324
-			$view->lockFile($file, ILockingProvider::LOCK_SHARED);
325
-			if ($view->is_dir($file)) {
326
-				$contents = $view->getDirectoryContent($file);
327
-				$contents = array_map(function($fileInfo) use ($file) {
328
-					/** @var \OCP\Files\FileInfo $fileInfo */
329
-					return $file . '/' . $fileInfo->getName();
330
-				}, $contents);
331
-				self::lockFiles($view, $dir, $contents);
332
-			}
333
-		}
334
-	}
335
-
336
-	/**
337
-	 * set the maximum upload size limit for apache hosts using .htaccess
338
-	 *
339
-	 * @param int $size file size in bytes
340
-	 * @param array $files override '.htaccess' and '.user.ini' locations
341
-	 * @return bool false on failure, size on success
342
-	 */
343
-	public static function setUploadLimit($size, $files = []) {
344
-		//don't allow user to break his config
345
-		$size = intval($size);
346
-		if ($size < self::UPLOAD_MIN_LIMIT_BYTES) {
347
-			return false;
348
-		}
349
-		$size = OC_Helper::phpFileSize($size);
350
-
351
-		$phpValueKeys = array(
352
-			'upload_max_filesize',
353
-			'post_max_size'
354
-		);
355
-
356
-		// default locations if not overridden by $files
357
-		$files = array_merge([
358
-			'.htaccess' => OC::$SERVERROOT . '/.htaccess',
359
-			'.user.ini' => OC::$SERVERROOT . '/.user.ini'
360
-		], $files);
361
-
362
-		$updateFiles = [
363
-			$files['.htaccess'] => [
364
-				'pattern' => '/php_value %1$s (\S)*/',
365
-				'setting' => 'php_value %1$s %2$s'
366
-			],
367
-			$files['.user.ini'] => [
368
-				'pattern' => '/%1$s=(\S)*/',
369
-				'setting' => '%1$s=%2$s'
370
-			]
371
-		];
372
-
373
-		$success = true;
374
-
375
-		foreach ($updateFiles as $filename => $patternMap) {
376
-			// suppress warnings from fopen()
377
-			$handle = @fopen($filename, 'r+');
378
-			if (!$handle) {
379
-				\OCP\Util::writeLog('files',
380
-					'Can\'t write upload limit to ' . $filename . '. Please check the file permissions',
381
-					\OCP\Util::WARN);
382
-				$success = false;
383
-				continue; // try to update as many files as possible
384
-			}
385
-
386
-			$content = '';
387
-			while (!feof($handle)) {
388
-				$content .= fread($handle, 1000);
389
-			}
390
-
391
-			foreach ($phpValueKeys as $key) {
392
-				$pattern = vsprintf($patternMap['pattern'], [$key]);
393
-				$setting = vsprintf($patternMap['setting'], [$key, $size]);
394
-				$hasReplaced = 0;
395
-				$newContent = preg_replace($pattern, $setting, $content, 2, $hasReplaced);
396
-				if ($newContent !== null) {
397
-					$content = $newContent;
398
-				}
399
-				if ($hasReplaced === 0) {
400
-					$content .= "\n" . $setting;
401
-				}
402
-			}
403
-
404
-			// write file back
405
-			ftruncate($handle, 0);
406
-			rewind($handle);
407
-			fwrite($handle, $content);
408
-
409
-			fclose($handle);
410
-		}
411
-
412
-		if ($success) {
413
-			return OC_Helper::computerFileSize($size);
414
-		}
415
-		return false;
416
-	}
417
-
418
-	/**
419
-	 * @param string $dir
420
-	 * @param $files
421
-	 * @param integer $getType
422
-	 * @param View $view
423
-	 * @param string $filename
424
-	 */
425
-	private static function unlockAllTheFiles($dir, $files, $getType, $view, $filename) {
426
-		if ($getType === self::FILE) {
427
-			$view->unlockFile($filename, ILockingProvider::LOCK_SHARED);
428
-		}
429
-		if ($getType === self::ZIP_FILES) {
430
-			foreach ($files as $file) {
431
-				$file = $dir . '/' . $file;
432
-				$view->unlockFile($file, ILockingProvider::LOCK_SHARED);
433
-			}
434
-		}
435
-		if ($getType === self::ZIP_DIR) {
436
-			$file = $dir . '/' . $files;
437
-			$view->unlockFile($file, ILockingProvider::LOCK_SHARED);
438
-		}
439
-	}
264
+        if (\OC\Files\Filesystem::isReadable($filename)) {
265
+            self::sendHeaders($filename, $name, $rangeArray);
266
+        } elseif (!\OC\Files\Filesystem::file_exists($filename)) {
267
+            header("HTTP/1.1 404 Not Found");
268
+            $tmpl = new OC_Template('', '404', 'guest');
269
+            $tmpl->printPage();
270
+            exit();
271
+        } else {
272
+            header("HTTP/1.1 403 Forbidden");
273
+            die('403 Forbidden');
274
+        }
275
+        if (isset($params['head']) && $params['head']) {
276
+            return;
277
+        }
278
+        if (!empty($rangeArray)) {
279
+            try {
280
+                if (count($rangeArray) == 1) {
281
+                $view->readfilePart($filename, $rangeArray[0]['from'], $rangeArray[0]['to']);
282
+                }
283
+                else {
284
+                // check if file is seekable (if not throw UnseekableException)
285
+                // we have to check it before body contents
286
+                $view->readfilePart($filename, $rangeArray[0]['size'], $rangeArray[0]['size']);
287
+
288
+                $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
289
+
290
+                foreach ($rangeArray as $range) {
291
+                    echo "\r\n--".self::getBoundary()."\r\n".
292
+                            "Content-type: ".$type."\r\n".
293
+                            "Content-range: bytes ".$range['from']."-".$range['to']."/".$range['size']."\r\n\r\n";
294
+                    $view->readfilePart($filename, $range['from'], $range['to']);
295
+                }
296
+                echo "\r\n--".self::getBoundary()."--\r\n";
297
+                }
298
+            } catch (\OCP\Files\UnseekableException $ex) {
299
+                // file is unseekable
300
+                header_remove('Accept-Ranges');
301
+                header_remove('Content-Range');
302
+                header("HTTP/1.1 200 OK");
303
+                self::sendHeaders($filename, $name, array());
304
+                $view->readfile($filename);
305
+            }
306
+        }
307
+        else {
308
+            $view->readfile($filename);
309
+        }
310
+    }
311
+
312
+    /**
313
+     * @param View $view
314
+     * @param string $dir
315
+     * @param string[]|string $files
316
+     */
317
+    public static function lockFiles($view, $dir, $files) {
318
+        if (!is_array($files)) {
319
+            $file = $dir . '/' . $files;
320
+            $files = [$file];
321
+        }
322
+        foreach ($files as $file) {
323
+            $file = $dir . '/' . $file;
324
+            $view->lockFile($file, ILockingProvider::LOCK_SHARED);
325
+            if ($view->is_dir($file)) {
326
+                $contents = $view->getDirectoryContent($file);
327
+                $contents = array_map(function($fileInfo) use ($file) {
328
+                    /** @var \OCP\Files\FileInfo $fileInfo */
329
+                    return $file . '/' . $fileInfo->getName();
330
+                }, $contents);
331
+                self::lockFiles($view, $dir, $contents);
332
+            }
333
+        }
334
+    }
335
+
336
+    /**
337
+     * set the maximum upload size limit for apache hosts using .htaccess
338
+     *
339
+     * @param int $size file size in bytes
340
+     * @param array $files override '.htaccess' and '.user.ini' locations
341
+     * @return bool false on failure, size on success
342
+     */
343
+    public static function setUploadLimit($size, $files = []) {
344
+        //don't allow user to break his config
345
+        $size = intval($size);
346
+        if ($size < self::UPLOAD_MIN_LIMIT_BYTES) {
347
+            return false;
348
+        }
349
+        $size = OC_Helper::phpFileSize($size);
350
+
351
+        $phpValueKeys = array(
352
+            'upload_max_filesize',
353
+            'post_max_size'
354
+        );
355
+
356
+        // default locations if not overridden by $files
357
+        $files = array_merge([
358
+            '.htaccess' => OC::$SERVERROOT . '/.htaccess',
359
+            '.user.ini' => OC::$SERVERROOT . '/.user.ini'
360
+        ], $files);
361
+
362
+        $updateFiles = [
363
+            $files['.htaccess'] => [
364
+                'pattern' => '/php_value %1$s (\S)*/',
365
+                'setting' => 'php_value %1$s %2$s'
366
+            ],
367
+            $files['.user.ini'] => [
368
+                'pattern' => '/%1$s=(\S)*/',
369
+                'setting' => '%1$s=%2$s'
370
+            ]
371
+        ];
372
+
373
+        $success = true;
374
+
375
+        foreach ($updateFiles as $filename => $patternMap) {
376
+            // suppress warnings from fopen()
377
+            $handle = @fopen($filename, 'r+');
378
+            if (!$handle) {
379
+                \OCP\Util::writeLog('files',
380
+                    'Can\'t write upload limit to ' . $filename . '. Please check the file permissions',
381
+                    \OCP\Util::WARN);
382
+                $success = false;
383
+                continue; // try to update as many files as possible
384
+            }
385
+
386
+            $content = '';
387
+            while (!feof($handle)) {
388
+                $content .= fread($handle, 1000);
389
+            }
390
+
391
+            foreach ($phpValueKeys as $key) {
392
+                $pattern = vsprintf($patternMap['pattern'], [$key]);
393
+                $setting = vsprintf($patternMap['setting'], [$key, $size]);
394
+                $hasReplaced = 0;
395
+                $newContent = preg_replace($pattern, $setting, $content, 2, $hasReplaced);
396
+                if ($newContent !== null) {
397
+                    $content = $newContent;
398
+                }
399
+                if ($hasReplaced === 0) {
400
+                    $content .= "\n" . $setting;
401
+                }
402
+            }
403
+
404
+            // write file back
405
+            ftruncate($handle, 0);
406
+            rewind($handle);
407
+            fwrite($handle, $content);
408
+
409
+            fclose($handle);
410
+        }
411
+
412
+        if ($success) {
413
+            return OC_Helper::computerFileSize($size);
414
+        }
415
+        return false;
416
+    }
417
+
418
+    /**
419
+     * @param string $dir
420
+     * @param $files
421
+     * @param integer $getType
422
+     * @param View $view
423
+     * @param string $filename
424
+     */
425
+    private static function unlockAllTheFiles($dir, $files, $getType, $view, $filename) {
426
+        if ($getType === self::FILE) {
427
+            $view->unlockFile($filename, ILockingProvider::LOCK_SHARED);
428
+        }
429
+        if ($getType === self::ZIP_FILES) {
430
+            foreach ($files as $file) {
431
+                $file = $dir . '/' . $file;
432
+                $view->unlockFile($file, ILockingProvider::LOCK_SHARED);
433
+            }
434
+        }
435
+        if ($getType === self::ZIP_DIR) {
436
+            $file = $dir . '/' . $files;
437
+            $view->unlockFile($file, ILockingProvider::LOCK_SHARED);
438
+        }
439
+    }
440 440
 
441 441
 }
Please login to merge, or discard this patch.
settings/Controller/CertificateController.php 2 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -72,7 +72,7 @@  discard block
 block discarded – undo
72 72
 	 *
73 73
 	 * @NoAdminRequired
74 74
 	 * @NoSubadminRequired
75
-	 * @return array
75
+	 * @return DataResponse
76 76
 	 */
77 77
 	public function addPersonalRootCertificate() {
78 78
 		return $this->addCertificate($this->userCertificateManager);
@@ -160,7 +160,7 @@  discard block
 block discarded – undo
160 160
 	/**
161 161
 	 * Add a new personal root certificate to the system's trust store
162 162
 	 *
163
-	 * @return array
163
+	 * @return DataResponse
164 164
 	 */
165 165
 	public function addSystemRootCertificate() {
166 166
 		return $this->addCertificate($this->systemCertificateManager);
Please login to merge, or discard this patch.
Indentation   +140 added lines, -140 removed lines patch added patch discarded remove patch
@@ -37,144 +37,144 @@
 block discarded – undo
37 37
  * @package OC\Settings\Controller
38 38
  */
39 39
 class CertificateController extends Controller {
40
-	/** @var ICertificateManager */
41
-	private $userCertificateManager;
42
-	/** @var ICertificateManager  */
43
-	private $systemCertificateManager;
44
-	/** @var IL10N */
45
-	private $l10n;
46
-	/** @var IAppManager */
47
-	private $appManager;
48
-
49
-	/**
50
-	 * @param string $appName
51
-	 * @param IRequest $request
52
-	 * @param ICertificateManager $userCertificateManager
53
-	 * @param ICertificateManager $systemCertificateManager
54
-	 * @param IL10N $l10n
55
-	 * @param IAppManager $appManager
56
-	 */
57
-	public function __construct($appName,
58
-								IRequest $request,
59
-								ICertificateManager $userCertificateManager,
60
-								ICertificateManager $systemCertificateManager,
61
-								IL10N $l10n,
62
-								IAppManager $appManager) {
63
-		parent::__construct($appName, $request);
64
-		$this->userCertificateManager = $userCertificateManager;
65
-		$this->systemCertificateManager = $systemCertificateManager;
66
-		$this->l10n = $l10n;
67
-		$this->appManager = $appManager;
68
-	}
69
-
70
-	/**
71
-	 * Add a new personal root certificate to the users' trust store
72
-	 *
73
-	 * @NoAdminRequired
74
-	 * @NoSubadminRequired
75
-	 * @return array
76
-	 */
77
-	public function addPersonalRootCertificate() {
78
-		return $this->addCertificate($this->userCertificateManager);
79
-	}
80
-
81
-	/**
82
-	 * Add a new root certificate to a trust store
83
-	 *
84
-	 * @param ICertificateManager $certificateManager
85
-	 * @return DataResponse
86
-	 */
87
-	private function addCertificate(ICertificateManager $certificateManager) {
88
-		$headers = [];
89
-
90
-		if ($this->isCertificateImportAllowed() === false) {
91
-			return new DataResponse(['message' => 'Individual certificate management disabled'], Http::STATUS_FORBIDDEN, $headers);
92
-		}
93
-
94
-		$file = $this->request->getUploadedFile('rootcert_import');
95
-		if (empty($file)) {
96
-			return new DataResponse(['message' => 'No file uploaded'], Http::STATUS_UNPROCESSABLE_ENTITY, $headers);
97
-		}
98
-
99
-		try {
100
-			$certificate = $certificateManager->addCertificate(file_get_contents($file['tmp_name']), $file['name']);
101
-			return new DataResponse(
102
-				[
103
-					'name' => $certificate->getName(),
104
-					'commonName' => $certificate->getCommonName(),
105
-					'organization' => $certificate->getOrganization(),
106
-					'validFrom' => $certificate->getIssueDate()->getTimestamp(),
107
-					'validTill' => $certificate->getExpireDate()->getTimestamp(),
108
-					'validFromString' => $this->l10n->l('date', $certificate->getIssueDate()),
109
-					'validTillString' => $this->l10n->l('date', $certificate->getExpireDate()),
110
-					'issuer' => $certificate->getIssuerName(),
111
-					'issuerOrganization' => $certificate->getIssuerOrganization(),
112
-				],
113
-				Http::STATUS_OK,
114
-				$headers
115
-			);
116
-		} catch (\Exception $e) {
117
-			return new DataResponse('An error occurred.', Http::STATUS_UNPROCESSABLE_ENTITY, $headers);
118
-		}
119
-	}
120
-
121
-	/**
122
-	 * Removes a personal root certificate from the users' trust store
123
-	 *
124
-	 * @NoAdminRequired
125
-	 * @NoSubadminRequired
126
-	 * @param string $certificateIdentifier
127
-	 * @return DataResponse
128
-	 */
129
-	public function removePersonalRootCertificate($certificateIdentifier) {
130
-
131
-		if ($this->isCertificateImportAllowed() === false) {
132
-			return new DataResponse('Individual certificate management disabled', Http::STATUS_FORBIDDEN);
133
-		}
134
-
135
-		$this->userCertificateManager->removeCertificate($certificateIdentifier);
136
-		return new DataResponse();
137
-	}
138
-
139
-	/**
140
-	 * check if certificate import is allowed
141
-	 *
142
-	 * @return bool
143
-	 */
144
-	protected function isCertificateImportAllowed() {
145
-		$externalStorageEnabled = $this->appManager->isEnabledForUser('files_external');
146
-		if ($externalStorageEnabled) {
147
-			/** @var \OCA\Files_External\Service\BackendService $backendService */
148
-			$backendService = \OC_Mount_Config::$app->getContainer()->query('\OCA\Files_External\Service\BackendService');
149
-			if ($backendService->isUserMountingAllowed()) {
150
-				return true;
151
-			}
152
-		}
153
-		return false;
154
-	}
155
-
156
-	/**
157
-	 * Add a new personal root certificate to the system's trust store
158
-	 *
159
-	 * @return array
160
-	 */
161
-	public function addSystemRootCertificate() {
162
-		return $this->addCertificate($this->systemCertificateManager);
163
-	}
164
-
165
-	/**
166
-	 * Removes a personal root certificate from the users' trust store
167
-	 *
168
-	 * @param string $certificateIdentifier
169
-	 * @return DataResponse
170
-	 */
171
-	public function removeSystemRootCertificate($certificateIdentifier) {
172
-
173
-		if ($this->isCertificateImportAllowed() === false) {
174
-			return new DataResponse('Individual certificate management disabled', Http::STATUS_FORBIDDEN);
175
-		}
176
-
177
-		$this->systemCertificateManager->removeCertificate($certificateIdentifier);
178
-		return new DataResponse();
179
-	}
40
+    /** @var ICertificateManager */
41
+    private $userCertificateManager;
42
+    /** @var ICertificateManager  */
43
+    private $systemCertificateManager;
44
+    /** @var IL10N */
45
+    private $l10n;
46
+    /** @var IAppManager */
47
+    private $appManager;
48
+
49
+    /**
50
+     * @param string $appName
51
+     * @param IRequest $request
52
+     * @param ICertificateManager $userCertificateManager
53
+     * @param ICertificateManager $systemCertificateManager
54
+     * @param IL10N $l10n
55
+     * @param IAppManager $appManager
56
+     */
57
+    public function __construct($appName,
58
+                                IRequest $request,
59
+                                ICertificateManager $userCertificateManager,
60
+                                ICertificateManager $systemCertificateManager,
61
+                                IL10N $l10n,
62
+                                IAppManager $appManager) {
63
+        parent::__construct($appName, $request);
64
+        $this->userCertificateManager = $userCertificateManager;
65
+        $this->systemCertificateManager = $systemCertificateManager;
66
+        $this->l10n = $l10n;
67
+        $this->appManager = $appManager;
68
+    }
69
+
70
+    /**
71
+     * Add a new personal root certificate to the users' trust store
72
+     *
73
+     * @NoAdminRequired
74
+     * @NoSubadminRequired
75
+     * @return array
76
+     */
77
+    public function addPersonalRootCertificate() {
78
+        return $this->addCertificate($this->userCertificateManager);
79
+    }
80
+
81
+    /**
82
+     * Add a new root certificate to a trust store
83
+     *
84
+     * @param ICertificateManager $certificateManager
85
+     * @return DataResponse
86
+     */
87
+    private function addCertificate(ICertificateManager $certificateManager) {
88
+        $headers = [];
89
+
90
+        if ($this->isCertificateImportAllowed() === false) {
91
+            return new DataResponse(['message' => 'Individual certificate management disabled'], Http::STATUS_FORBIDDEN, $headers);
92
+        }
93
+
94
+        $file = $this->request->getUploadedFile('rootcert_import');
95
+        if (empty($file)) {
96
+            return new DataResponse(['message' => 'No file uploaded'], Http::STATUS_UNPROCESSABLE_ENTITY, $headers);
97
+        }
98
+
99
+        try {
100
+            $certificate = $certificateManager->addCertificate(file_get_contents($file['tmp_name']), $file['name']);
101
+            return new DataResponse(
102
+                [
103
+                    'name' => $certificate->getName(),
104
+                    'commonName' => $certificate->getCommonName(),
105
+                    'organization' => $certificate->getOrganization(),
106
+                    'validFrom' => $certificate->getIssueDate()->getTimestamp(),
107
+                    'validTill' => $certificate->getExpireDate()->getTimestamp(),
108
+                    'validFromString' => $this->l10n->l('date', $certificate->getIssueDate()),
109
+                    'validTillString' => $this->l10n->l('date', $certificate->getExpireDate()),
110
+                    'issuer' => $certificate->getIssuerName(),
111
+                    'issuerOrganization' => $certificate->getIssuerOrganization(),
112
+                ],
113
+                Http::STATUS_OK,
114
+                $headers
115
+            );
116
+        } catch (\Exception $e) {
117
+            return new DataResponse('An error occurred.', Http::STATUS_UNPROCESSABLE_ENTITY, $headers);
118
+        }
119
+    }
120
+
121
+    /**
122
+     * Removes a personal root certificate from the users' trust store
123
+     *
124
+     * @NoAdminRequired
125
+     * @NoSubadminRequired
126
+     * @param string $certificateIdentifier
127
+     * @return DataResponse
128
+     */
129
+    public function removePersonalRootCertificate($certificateIdentifier) {
130
+
131
+        if ($this->isCertificateImportAllowed() === false) {
132
+            return new DataResponse('Individual certificate management disabled', Http::STATUS_FORBIDDEN);
133
+        }
134
+
135
+        $this->userCertificateManager->removeCertificate($certificateIdentifier);
136
+        return new DataResponse();
137
+    }
138
+
139
+    /**
140
+     * check if certificate import is allowed
141
+     *
142
+     * @return bool
143
+     */
144
+    protected function isCertificateImportAllowed() {
145
+        $externalStorageEnabled = $this->appManager->isEnabledForUser('files_external');
146
+        if ($externalStorageEnabled) {
147
+            /** @var \OCA\Files_External\Service\BackendService $backendService */
148
+            $backendService = \OC_Mount_Config::$app->getContainer()->query('\OCA\Files_External\Service\BackendService');
149
+            if ($backendService->isUserMountingAllowed()) {
150
+                return true;
151
+            }
152
+        }
153
+        return false;
154
+    }
155
+
156
+    /**
157
+     * Add a new personal root certificate to the system's trust store
158
+     *
159
+     * @return array
160
+     */
161
+    public function addSystemRootCertificate() {
162
+        return $this->addCertificate($this->systemCertificateManager);
163
+    }
164
+
165
+    /**
166
+     * Removes a personal root certificate from the users' trust store
167
+     *
168
+     * @param string $certificateIdentifier
169
+     * @return DataResponse
170
+     */
171
+    public function removeSystemRootCertificate($certificateIdentifier) {
172
+
173
+        if ($this->isCertificateImportAllowed() === false) {
174
+            return new DataResponse('Individual certificate management disabled', Http::STATUS_FORBIDDEN);
175
+        }
176
+
177
+        $this->systemCertificateManager->removeCertificate($certificateIdentifier);
178
+        return new DataResponse();
179
+    }
180 180
 }
Please login to merge, or discard this patch.
core/Controller/LostController.php 4 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.
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -30,7 +30,6 @@
 block discarded – undo
30 30
 
31 31
 namespace OC\Core\Controller;
32 32
 
33
-use OCA\Encryption\Exceptions\PrivateKeyMissingException;
34 33
 use \OCP\AppFramework\Controller;
35 34
 use \OCP\AppFramework\Http\TemplateResponse;
36 35
 use OCP\AppFramework\Utility\ITimeFactory;
Please login to merge, or discard this patch.
Indentation   +225 added lines, -225 removed lines patch added patch discarded remove patch
@@ -53,256 +53,256 @@
 block discarded – undo
53 53
  */
54 54
 class LostController extends Controller {
55 55
 
56
-	/** @var IURLGenerator */
57
-	protected $urlGenerator;
58
-	/** @var IUserManager */
59
-	protected $userManager;
60
-	/** @var \OC_Defaults */
61
-	protected $defaults;
62
-	/** @var IL10N */
63
-	protected $l10n;
64
-	/** @var string */
65
-	protected $from;
66
-	/** @var IManager */
67
-	protected $encryptionManager;
68
-	/** @var IConfig */
69
-	protected $config;
70
-	/** @var ISecureRandom */
71
-	protected $secureRandom;
72
-	/** @var IMailer */
73
-	protected $mailer;
74
-	/** @var ITimeFactory */
75
-	protected $timeFactory;
76
-	/** @var ICrypto */
77
-	protected $crypto;
56
+    /** @var IURLGenerator */
57
+    protected $urlGenerator;
58
+    /** @var IUserManager */
59
+    protected $userManager;
60
+    /** @var \OC_Defaults */
61
+    protected $defaults;
62
+    /** @var IL10N */
63
+    protected $l10n;
64
+    /** @var string */
65
+    protected $from;
66
+    /** @var IManager */
67
+    protected $encryptionManager;
68
+    /** @var IConfig */
69
+    protected $config;
70
+    /** @var ISecureRandom */
71
+    protected $secureRandom;
72
+    /** @var IMailer */
73
+    protected $mailer;
74
+    /** @var ITimeFactory */
75
+    protected $timeFactory;
76
+    /** @var ICrypto */
77
+    protected $crypto;
78 78
 
79
-	/**
80
-	 * @param string $appName
81
-	 * @param IRequest $request
82
-	 * @param IURLGenerator $urlGenerator
83
-	 * @param IUserManager $userManager
84
-	 * @param \OC_Defaults $defaults
85
-	 * @param IL10N $l10n
86
-	 * @param IConfig $config
87
-	 * @param ISecureRandom $secureRandom
88
-	 * @param string $defaultMailAddress
89
-	 * @param IManager $encryptionManager
90
-	 * @param IMailer $mailer
91
-	 * @param ITimeFactory $timeFactory
92
-	 * @param ICrypto $crypto
93
-	 */
94
-	public function __construct($appName,
95
-								IRequest $request,
96
-								IURLGenerator $urlGenerator,
97
-								IUserManager $userManager,
98
-								\OC_Defaults $defaults,
99
-								IL10N $l10n,
100
-								IConfig $config,
101
-								ISecureRandom $secureRandom,
102
-								$defaultMailAddress,
103
-								IManager $encryptionManager,
104
-								IMailer $mailer,
105
-								ITimeFactory $timeFactory,
106
-								ICrypto $crypto) {
107
-		parent::__construct($appName, $request);
108
-		$this->urlGenerator = $urlGenerator;
109
-		$this->userManager = $userManager;
110
-		$this->defaults = $defaults;
111
-		$this->l10n = $l10n;
112
-		$this->secureRandom = $secureRandom;
113
-		$this->from = $defaultMailAddress;
114
-		$this->encryptionManager = $encryptionManager;
115
-		$this->config = $config;
116
-		$this->mailer = $mailer;
117
-		$this->timeFactory = $timeFactory;
118
-		$this->crypto = $crypto;
119
-	}
79
+    /**
80
+     * @param string $appName
81
+     * @param IRequest $request
82
+     * @param IURLGenerator $urlGenerator
83
+     * @param IUserManager $userManager
84
+     * @param \OC_Defaults $defaults
85
+     * @param IL10N $l10n
86
+     * @param IConfig $config
87
+     * @param ISecureRandom $secureRandom
88
+     * @param string $defaultMailAddress
89
+     * @param IManager $encryptionManager
90
+     * @param IMailer $mailer
91
+     * @param ITimeFactory $timeFactory
92
+     * @param ICrypto $crypto
93
+     */
94
+    public function __construct($appName,
95
+                                IRequest $request,
96
+                                IURLGenerator $urlGenerator,
97
+                                IUserManager $userManager,
98
+                                \OC_Defaults $defaults,
99
+                                IL10N $l10n,
100
+                                IConfig $config,
101
+                                ISecureRandom $secureRandom,
102
+                                $defaultMailAddress,
103
+                                IManager $encryptionManager,
104
+                                IMailer $mailer,
105
+                                ITimeFactory $timeFactory,
106
+                                ICrypto $crypto) {
107
+        parent::__construct($appName, $request);
108
+        $this->urlGenerator = $urlGenerator;
109
+        $this->userManager = $userManager;
110
+        $this->defaults = $defaults;
111
+        $this->l10n = $l10n;
112
+        $this->secureRandom = $secureRandom;
113
+        $this->from = $defaultMailAddress;
114
+        $this->encryptionManager = $encryptionManager;
115
+        $this->config = $config;
116
+        $this->mailer = $mailer;
117
+        $this->timeFactory = $timeFactory;
118
+        $this->crypto = $crypto;
119
+    }
120 120
 
121
-	/**
122
-	 * Someone wants to reset their password:
123
-	 *
124
-	 * @PublicPage
125
-	 * @NoCSRFRequired
126
-	 *
127
-	 * @param string $token
128
-	 * @param string $userId
129
-	 * @return TemplateResponse
130
-	 */
131
-	public function resetform($token, $userId) {
132
-		try {
133
-			$this->checkPasswordResetToken($token, $userId);
134
-		} catch (\Exception $e) {
135
-			return new TemplateResponse(
136
-				'core', 'error', [
137
-					"errors" => array(array("error" => $e->getMessage()))
138
-				],
139
-				'guest'
140
-			);
141
-		}
121
+    /**
122
+     * Someone wants to reset their password:
123
+     *
124
+     * @PublicPage
125
+     * @NoCSRFRequired
126
+     *
127
+     * @param string $token
128
+     * @param string $userId
129
+     * @return TemplateResponse
130
+     */
131
+    public function resetform($token, $userId) {
132
+        try {
133
+            $this->checkPasswordResetToken($token, $userId);
134
+        } catch (\Exception $e) {
135
+            return new TemplateResponse(
136
+                'core', 'error', [
137
+                    "errors" => array(array("error" => $e->getMessage()))
138
+                ],
139
+                'guest'
140
+            );
141
+        }
142 142
 
143
-		return new TemplateResponse(
144
-			'core',
145
-			'lostpassword/resetpassword',
146
-			array(
147
-				'link' => $this->urlGenerator->linkToRouteAbsolute('core.lost.setPassword', array('userId' => $userId, 'token' => $token)),
148
-			),
149
-			'guest'
150
-		);
151
-	}
143
+        return new TemplateResponse(
144
+            'core',
145
+            'lostpassword/resetpassword',
146
+            array(
147
+                'link' => $this->urlGenerator->linkToRouteAbsolute('core.lost.setPassword', array('userId' => $userId, 'token' => $token)),
148
+            ),
149
+            'guest'
150
+        );
151
+    }
152 152
 
153
-	/**
154
-	 * @param string $token
155
-	 * @param string $userId
156
-	 * @throws \Exception
157
-	 */
158
-	protected function checkPasswordResetToken($token, $userId) {
159
-		$user = $this->userManager->get($userId);
160
-		if($user === null) {
161
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
162
-		}
153
+    /**
154
+     * @param string $token
155
+     * @param string $userId
156
+     * @throws \Exception
157
+     */
158
+    protected function checkPasswordResetToken($token, $userId) {
159
+        $user = $this->userManager->get($userId);
160
+        if($user === null) {
161
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
162
+        }
163 163
 
164
-		try {
165
-			$encryptedToken = $this->config->getUserValue($userId, 'core', 'lostpassword', null);
166
-			$mailAddress = !is_null($user->getEMailAddress()) ? $user->getEMailAddress() : '';
167
-			$decryptedToken = $this->crypto->decrypt($encryptedToken, $mailAddress.$this->config->getSystemValue('secret'));
168
-		} catch (\Exception $e) {
169
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
170
-		}
164
+        try {
165
+            $encryptedToken = $this->config->getUserValue($userId, 'core', 'lostpassword', null);
166
+            $mailAddress = !is_null($user->getEMailAddress()) ? $user->getEMailAddress() : '';
167
+            $decryptedToken = $this->crypto->decrypt($encryptedToken, $mailAddress.$this->config->getSystemValue('secret'));
168
+        } catch (\Exception $e) {
169
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
170
+        }
171 171
 
172
-		$splittedToken = explode(':', $decryptedToken);
173
-		if(count($splittedToken) !== 2) {
174
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
175
-		}
172
+        $splittedToken = explode(':', $decryptedToken);
173
+        if(count($splittedToken) !== 2) {
174
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
175
+        }
176 176
 
177
-		if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*12) ||
178
-			$user->getLastLogin() > $splittedToken[0]) {
179
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
180
-		}
177
+        if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*12) ||
178
+            $user->getLastLogin() > $splittedToken[0]) {
179
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
180
+        }
181 181
 
182
-		if (!hash_equals($splittedToken[1], $token)) {
183
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
184
-		}
185
-	}
182
+        if (!hash_equals($splittedToken[1], $token)) {
183
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
184
+        }
185
+    }
186 186
 
187
-	/**
188
-	 * @param $message
189
-	 * @param array $additional
190
-	 * @return array
191
-	 */
192
-	private function error($message, array $additional=array()) {
193
-		return array_merge(array('status' => 'error', 'msg' => $message), $additional);
194
-	}
187
+    /**
188
+     * @param $message
189
+     * @param array $additional
190
+     * @return array
191
+     */
192
+    private function error($message, array $additional=array()) {
193
+        return array_merge(array('status' => 'error', 'msg' => $message), $additional);
194
+    }
195 195
 
196
-	/**
197
-	 * @return array
198
-	 */
199
-	private function success() {
200
-		return array('status'=>'success');
201
-	}
196
+    /**
197
+     * @return array
198
+     */
199
+    private function success() {
200
+        return array('status'=>'success');
201
+    }
202 202
 
203
-	/**
204
-	 * @PublicPage
205
-	 * @BruteForceProtection passwordResetEmail
206
-	 *
207
-	 * @param string $user
208
-	 * @return array
209
-	 */
210
-	public function email($user){
211
-		// FIXME: use HTTP error codes
212
-		try {
213
-			$this->sendEmail($user);
214
-		} catch (\Exception $e){
215
-			return $this->error($e->getMessage());
216
-		}
203
+    /**
204
+     * @PublicPage
205
+     * @BruteForceProtection passwordResetEmail
206
+     *
207
+     * @param string $user
208
+     * @return array
209
+     */
210
+    public function email($user){
211
+        // FIXME: use HTTP error codes
212
+        try {
213
+            $this->sendEmail($user);
214
+        } catch (\Exception $e){
215
+            return $this->error($e->getMessage());
216
+        }
217 217
 
218
-		return $this->success();
219
-	}
218
+        return $this->success();
219
+    }
220 220
 
221
-	/**
222
-	 * @PublicPage
223
-	 * @param string $token
224
-	 * @param string $userId
225
-	 * @param string $password
226
-	 * @param boolean $proceed
227
-	 * @return array
228
-	 */
229
-	public function setPassword($token, $userId, $password, $proceed) {
230
-		if ($this->encryptionManager->isEnabled() && !$proceed) {
231
-			return $this->error('', array('encryption' => true));
232
-		}
221
+    /**
222
+     * @PublicPage
223
+     * @param string $token
224
+     * @param string $userId
225
+     * @param string $password
226
+     * @param boolean $proceed
227
+     * @return array
228
+     */
229
+    public function setPassword($token, $userId, $password, $proceed) {
230
+        if ($this->encryptionManager->isEnabled() && !$proceed) {
231
+            return $this->error('', array('encryption' => true));
232
+        }
233 233
 
234
-		try {
235
-			$this->checkPasswordResetToken($token, $userId);
236
-			$user = $this->userManager->get($userId);
234
+        try {
235
+            $this->checkPasswordResetToken($token, $userId);
236
+            $user = $this->userManager->get($userId);
237 237
 
238
-			\OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'pre_passwordReset', array('uid' => $userId, 'password' => $password));
238
+            \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'pre_passwordReset', array('uid' => $userId, 'password' => $password));
239 239
 
240
-			if (!$user->setPassword($password)) {
241
-				throw new \Exception();
242
-			}
240
+            if (!$user->setPassword($password)) {
241
+                throw new \Exception();
242
+            }
243 243
 
244
-			\OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'post_passwordReset', array('uid' => $userId, 'password' => $password));
244
+            \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'post_passwordReset', array('uid' => $userId, 'password' => $password));
245 245
 
246
-			$this->config->deleteUserValue($userId, 'core', 'lostpassword');
247
-			@\OC_User::unsetMagicInCookie();
248
-		} catch (\Exception $e){
249
-			return $this->error($e->getMessage());
250
-		}
246
+            $this->config->deleteUserValue($userId, 'core', 'lostpassword');
247
+            @\OC_User::unsetMagicInCookie();
248
+        } catch (\Exception $e){
249
+            return $this->error($e->getMessage());
250
+        }
251 251
 
252
-		return $this->success();
253
-	}
252
+        return $this->success();
253
+    }
254 254
 
255
-	/**
256
-	 * @param string $user
257
-	 * @throws \Exception
258
-	 */
259
-	protected function sendEmail($user) {
260
-		if (!$this->userManager->userExists($user)) {
261
-			throw new \Exception($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
262
-		}
255
+    /**
256
+     * @param string $user
257
+     * @throws \Exception
258
+     */
259
+    protected function sendEmail($user) {
260
+        if (!$this->userManager->userExists($user)) {
261
+            throw new \Exception($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
262
+        }
263 263
 
264
-		$userObject = $this->userManager->get($user);
265
-		$email = $userObject->getEMailAddress();
264
+        $userObject = $this->userManager->get($user);
265
+        $email = $userObject->getEMailAddress();
266 266
 
267
-		if (empty($email)) {
268
-			throw new \Exception(
269
-				$this->l10n->t('Could not send reset email because there is no email address for this username. Please contact your administrator.')
270
-			);
271
-		}
267
+        if (empty($email)) {
268
+            throw new \Exception(
269
+                $this->l10n->t('Could not send reset email because there is no email address for this username. Please contact your administrator.')
270
+            );
271
+        }
272 272
 
273
-		// Generate the token. It is stored encrypted in the database with the
274
-		// secret being the users' email address appended with the system secret.
275
-		// This makes the token automatically invalidate once the user changes
276
-		// their email address.
277
-		$token = $this->secureRandom->generate(
278
-			21,
279
-			ISecureRandom::CHAR_DIGITS.
280
-			ISecureRandom::CHAR_LOWER.
281
-			ISecureRandom::CHAR_UPPER
282
-		);
283
-		$tokenValue = $this->timeFactory->getTime() .':'. $token;
284
-		$mailAddress = !is_null($userObject->getEMailAddress()) ? $userObject->getEMailAddress() : '';
285
-		$encryptedValue = $this->crypto->encrypt($tokenValue, $mailAddress.$this->config->getSystemValue('secret'));
286
-		$this->config->setUserValue($user, 'core', 'lostpassword', $encryptedValue);
273
+        // Generate the token. It is stored encrypted in the database with the
274
+        // secret being the users' email address appended with the system secret.
275
+        // This makes the token automatically invalidate once the user changes
276
+        // their email address.
277
+        $token = $this->secureRandom->generate(
278
+            21,
279
+            ISecureRandom::CHAR_DIGITS.
280
+            ISecureRandom::CHAR_LOWER.
281
+            ISecureRandom::CHAR_UPPER
282
+        );
283
+        $tokenValue = $this->timeFactory->getTime() .':'. $token;
284
+        $mailAddress = !is_null($userObject->getEMailAddress()) ? $userObject->getEMailAddress() : '';
285
+        $encryptedValue = $this->crypto->encrypt($tokenValue, $mailAddress.$this->config->getSystemValue('secret'));
286
+        $this->config->setUserValue($user, 'core', 'lostpassword', $encryptedValue);
287 287
 
288
-		$link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user, 'token' => $token));
288
+        $link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user, 'token' => $token));
289 289
 
290
-		$tmpl = new \OC_Template('core', 'lostpassword/email');
291
-		$tmpl->assign('link', $link);
292
-		$msg = $tmpl->fetchPage();
290
+        $tmpl = new \OC_Template('core', 'lostpassword/email');
291
+        $tmpl->assign('link', $link);
292
+        $msg = $tmpl->fetchPage();
293 293
 
294
-		try {
295
-			$message = $this->mailer->createMessage();
296
-			$message->setTo([$email => $user]);
297
-			$message->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
298
-			$message->setPlainBody($msg);
299
-			$message->setFrom([$this->from => $this->defaults->getName()]);
300
-			$this->mailer->send($message);
301
-		} catch (\Exception $e) {
302
-			throw new \Exception($this->l10n->t(
303
-				'Couldn\'t send reset email. Please contact your administrator.'
304
-			));
305
-		}
306
-	}
294
+        try {
295
+            $message = $this->mailer->createMessage();
296
+            $message->setTo([$email => $user]);
297
+            $message->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
298
+            $message->setPlainBody($msg);
299
+            $message->setFrom([$this->from => $this->defaults->getName()]);
300
+            $this->mailer->send($message);
301
+        } catch (\Exception $e) {
302
+            throw new \Exception($this->l10n->t(
303
+                'Couldn\'t send reset email. Please contact your administrator.'
304
+            ));
305
+        }
306
+    }
307 307
 
308 308
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -157,7 +157,7 @@  discard block
 block discarded – undo
157 157
 	 */
158 158
 	protected function checkPasswordResetToken($token, $userId) {
159 159
 		$user = $this->userManager->get($userId);
160
-		if($user === null) {
160
+		if ($user === null) {
161 161
 			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
162 162
 		}
163 163
 
@@ -170,11 +170,11 @@  discard block
 block discarded – undo
170 170
 		}
171 171
 
172 172
 		$splittedToken = explode(':', $decryptedToken);
173
-		if(count($splittedToken) !== 2) {
173
+		if (count($splittedToken) !== 2) {
174 174
 			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
175 175
 		}
176 176
 
177
-		if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*12) ||
177
+		if ($splittedToken[0] < ($this->timeFactory->getTime() - 60 * 60 * 12) ||
178 178
 			$user->getLastLogin() > $splittedToken[0]) {
179 179
 			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
180 180
 		}
@@ -189,7 +189,7 @@  discard block
 block discarded – undo
189 189
 	 * @param array $additional
190 190
 	 * @return array
191 191
 	 */
192
-	private function error($message, array $additional=array()) {
192
+	private function error($message, array $additional = array()) {
193 193
 		return array_merge(array('status' => 'error', 'msg' => $message), $additional);
194 194
 	}
195 195
 
@@ -207,11 +207,11 @@  discard block
 block discarded – undo
207 207
 	 * @param string $user
208 208
 	 * @return array
209 209
 	 */
210
-	public function email($user){
210
+	public function email($user) {
211 211
 		// FIXME: use HTTP error codes
212 212
 		try {
213 213
 			$this->sendEmail($user);
214
-		} catch (\Exception $e){
214
+		} catch (\Exception $e) {
215 215
 			return $this->error($e->getMessage());
216 216
 		}
217 217
 
@@ -245,7 +245,7 @@  discard block
 block discarded – undo
245 245
 
246 246
 			$this->config->deleteUserValue($userId, 'core', 'lostpassword');
247 247
 			@\OC_User::unsetMagicInCookie();
248
-		} catch (\Exception $e){
248
+		} catch (\Exception $e) {
249 249
 			return $this->error($e->getMessage());
250 250
 		}
251 251
 
@@ -280,7 +280,7 @@  discard block
 block discarded – undo
280 280
 			ISecureRandom::CHAR_LOWER.
281 281
 			ISecureRandom::CHAR_UPPER
282 282
 		);
283
-		$tokenValue = $this->timeFactory->getTime() .':'. $token;
283
+		$tokenValue = $this->timeFactory->getTime().':'.$token;
284 284
 		$mailAddress = !is_null($userObject->getEMailAddress()) ? $userObject->getEMailAddress() : '';
285 285
 		$encryptedValue = $this->crypto->encrypt($tokenValue, $mailAddress.$this->config->getSystemValue('secret'));
286 286
 		$this->config->setUserValue($user, 'core', 'lostpassword', $encryptedValue);
Please login to merge, or discard this patch.