Completed
Push — stable13 ( 4021ba...4b997b )
by
unknown
20:00 queued 09:44
created
lib/private/Template/Base.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -103,7 +103,7 @@
 block discarded – undo
103 103
 	/**
104 104
 	 * Appends a variable
105 105
 	 * @param string $key key
106
-	 * @param mixed $value value
106
+	 * @param string $value value
107 107
 	 * @return boolean|null
108 108
 	 *
109 109
 	 * This function assigns a variable in an array context. If the key already
Please login to merge, or discard this patch.
Braces   +2 added lines, -4 removed lines patch added patch discarded remove patch
@@ -114,8 +114,7 @@  discard block
 block discarded – undo
114 114
 	public function append( $key, $value ) {
115 115
 		if( array_key_exists( $key, $this->vars )) {
116 116
 			$this->vars[$key][] = $value;
117
-		}
118
-		else{
117
+		} else{
119 118
 			$this->vars[$key] = array( $value );
120 119
 		}
121 120
 	}
@@ -130,8 +129,7 @@  discard block
 block discarded – undo
130 129
 		$data = $this->fetchPage();
131 130
 		if( $data === false ) {
132 131
 			return false;
133
-		}
134
-		else{
132
+		} else{
135 133
 			print $data;
136 134
 			return true;
137 135
 		}
Please login to merge, or discard this patch.
Indentation   +153 added lines, -153 removed lines patch added patch discarded remove patch
@@ -31,158 +31,158 @@
 block discarded – undo
31 31
 use OCP\Defaults;
32 32
 
33 33
 class Base {
34
-	private $template; // The template
35
-	private $vars; // Vars
36
-
37
-	/** @var \OCP\IL10N */
38
-	private $l10n;
39
-
40
-	/** @var Defaults */
41
-	private $theme;
42
-
43
-	/**
44
-	 * @param string $template
45
-	 * @param string $requestToken
46
-	 * @param \OCP\IL10N $l10n
47
-	 * @param Defaults $theme
48
-	 */
49
-	public function __construct($template, $requestToken, $l10n, $theme ) {
50
-		$this->vars = array();
51
-		$this->vars['requesttoken'] = $requestToken;
52
-		$this->l10n = $l10n;
53
-		$this->template = $template;
54
-		$this->theme = $theme;
55
-	}
56
-
57
-	/**
58
-	 * @param string $serverRoot
59
-	 * @param string|false $app_dir
60
-	 * @param string $theme
61
-	 * @param string $app
62
-	 * @return string[]
63
-	 */
64
-	protected function getAppTemplateDirs($theme, $app, $serverRoot, $app_dir) {
65
-		// Check if the app is in the app folder or in the root
66
-		if( file_exists($app_dir.'/templates/' )) {
67
-			return [
68
-				$serverRoot.'/themes/'.$theme.'/apps/'.$app.'/templates/',
69
-				$app_dir.'/templates/',
70
-			];
71
-		}
72
-		return [
73
-			$serverRoot.'/themes/'.$theme.'/'.$app.'/templates/',
74
-			$serverRoot.'/'.$app.'/templates/',
75
-		];
76
-	}
77
-
78
-	/**
79
-	 * @param string $serverRoot
80
-	 * @param string $theme
81
-	 * @return string[]
82
-	 */
83
-	protected function getCoreTemplateDirs($theme, $serverRoot) {
84
-		return [
85
-			$serverRoot.'/themes/'.$theme.'/core/templates/',
86
-			$serverRoot.'/core/templates/',
87
-		];
88
-	}
89
-
90
-	/**
91
-	 * Assign variables
92
-	 * @param string $key key
93
-	 * @param array|bool|integer|string $value value
94
-	 * @return bool
95
-	 *
96
-	 * This function assigns a variable. It can be accessed via $_[$key] in
97
-	 * the template.
98
-	 *
99
-	 * If the key existed before, it will be overwritten
100
-	 */
101
-	public function assign( $key, $value) {
102
-		$this->vars[$key] = $value;
103
-		return true;
104
-	}
105
-
106
-	/**
107
-	 * Appends a variable
108
-	 * @param string $key key
109
-	 * @param mixed $value value
110
-	 * @return boolean|null
111
-	 *
112
-	 * This function assigns a variable in an array context. If the key already
113
-	 * exists, the value will be appended. It can be accessed via
114
-	 * $_[$key][$position] in the template.
115
-	 */
116
-	public function append( $key, $value ) {
117
-		if( array_key_exists( $key, $this->vars )) {
118
-			$this->vars[$key][] = $value;
119
-		}
120
-		else{
121
-			$this->vars[$key] = array( $value );
122
-		}
123
-	}
124
-
125
-	/**
126
-	 * Prints the proceeded template
127
-	 * @return bool
128
-	 *
129
-	 * This function proceeds the template and prints its output.
130
-	 */
131
-	public function printPage() {
132
-		$data = $this->fetchPage();
133
-		if( $data === false ) {
134
-			return false;
135
-		}
136
-		else{
137
-			print $data;
138
-			return true;
139
-		}
140
-	}
141
-
142
-	/**
143
-	 * Process the template
144
-	 *
145
-	 * @param array|null $additionalParams
146
-	 * @return string This function processes the template.
147
-	 *
148
-	 * This function processes the template.
149
-	 */
150
-	public function fetchPage($additionalParams = null) {
151
-		return $this->load($this->template, $additionalParams);
152
-	}
153
-
154
-	/**
155
-	 * doing the actual work
156
-	 *
157
-	 * @param string $file
158
-	 * @param array|null $additionalParams
159
-	 * @return string content
160
-	 *
161
-	 * Includes the template file, fetches its output
162
-	 */
163
-	protected function load($file, $additionalParams = null) {
164
-		// Register the variables
165
-		$_ = $this->vars;
166
-		$l = $this->l10n;
167
-		$theme = $this->theme;
168
-
169
-		if( !is_null($additionalParams)) {
170
-			$_ = array_merge( $additionalParams, $this->vars );
171
-		}
172
-
173
-		// Include
174
-		ob_start();
175
-		try {
176
-			include $file;
177
-			$data = ob_get_contents();
178
-		} catch (\Exception $e) {
179
-			@ob_end_clean();
180
-			throw $e;
181
-		}
182
-		@ob_end_clean();
183
-
184
-		// Return data
185
-		return $data;
186
-	}
34
+    private $template; // The template
35
+    private $vars; // Vars
36
+
37
+    /** @var \OCP\IL10N */
38
+    private $l10n;
39
+
40
+    /** @var Defaults */
41
+    private $theme;
42
+
43
+    /**
44
+     * @param string $template
45
+     * @param string $requestToken
46
+     * @param \OCP\IL10N $l10n
47
+     * @param Defaults $theme
48
+     */
49
+    public function __construct($template, $requestToken, $l10n, $theme ) {
50
+        $this->vars = array();
51
+        $this->vars['requesttoken'] = $requestToken;
52
+        $this->l10n = $l10n;
53
+        $this->template = $template;
54
+        $this->theme = $theme;
55
+    }
56
+
57
+    /**
58
+     * @param string $serverRoot
59
+     * @param string|false $app_dir
60
+     * @param string $theme
61
+     * @param string $app
62
+     * @return string[]
63
+     */
64
+    protected function getAppTemplateDirs($theme, $app, $serverRoot, $app_dir) {
65
+        // Check if the app is in the app folder or in the root
66
+        if( file_exists($app_dir.'/templates/' )) {
67
+            return [
68
+                $serverRoot.'/themes/'.$theme.'/apps/'.$app.'/templates/',
69
+                $app_dir.'/templates/',
70
+            ];
71
+        }
72
+        return [
73
+            $serverRoot.'/themes/'.$theme.'/'.$app.'/templates/',
74
+            $serverRoot.'/'.$app.'/templates/',
75
+        ];
76
+    }
77
+
78
+    /**
79
+     * @param string $serverRoot
80
+     * @param string $theme
81
+     * @return string[]
82
+     */
83
+    protected function getCoreTemplateDirs($theme, $serverRoot) {
84
+        return [
85
+            $serverRoot.'/themes/'.$theme.'/core/templates/',
86
+            $serverRoot.'/core/templates/',
87
+        ];
88
+    }
89
+
90
+    /**
91
+     * Assign variables
92
+     * @param string $key key
93
+     * @param array|bool|integer|string $value value
94
+     * @return bool
95
+     *
96
+     * This function assigns a variable. It can be accessed via $_[$key] in
97
+     * the template.
98
+     *
99
+     * If the key existed before, it will be overwritten
100
+     */
101
+    public function assign( $key, $value) {
102
+        $this->vars[$key] = $value;
103
+        return true;
104
+    }
105
+
106
+    /**
107
+     * Appends a variable
108
+     * @param string $key key
109
+     * @param mixed $value value
110
+     * @return boolean|null
111
+     *
112
+     * This function assigns a variable in an array context. If the key already
113
+     * exists, the value will be appended. It can be accessed via
114
+     * $_[$key][$position] in the template.
115
+     */
116
+    public function append( $key, $value ) {
117
+        if( array_key_exists( $key, $this->vars )) {
118
+            $this->vars[$key][] = $value;
119
+        }
120
+        else{
121
+            $this->vars[$key] = array( $value );
122
+        }
123
+    }
124
+
125
+    /**
126
+     * Prints the proceeded template
127
+     * @return bool
128
+     *
129
+     * This function proceeds the template and prints its output.
130
+     */
131
+    public function printPage() {
132
+        $data = $this->fetchPage();
133
+        if( $data === false ) {
134
+            return false;
135
+        }
136
+        else{
137
+            print $data;
138
+            return true;
139
+        }
140
+    }
141
+
142
+    /**
143
+     * Process the template
144
+     *
145
+     * @param array|null $additionalParams
146
+     * @return string This function processes the template.
147
+     *
148
+     * This function processes the template.
149
+     */
150
+    public function fetchPage($additionalParams = null) {
151
+        return $this->load($this->template, $additionalParams);
152
+    }
153
+
154
+    /**
155
+     * doing the actual work
156
+     *
157
+     * @param string $file
158
+     * @param array|null $additionalParams
159
+     * @return string content
160
+     *
161
+     * Includes the template file, fetches its output
162
+     */
163
+    protected function load($file, $additionalParams = null) {
164
+        // Register the variables
165
+        $_ = $this->vars;
166
+        $l = $this->l10n;
167
+        $theme = $this->theme;
168
+
169
+        if( !is_null($additionalParams)) {
170
+            $_ = array_merge( $additionalParams, $this->vars );
171
+        }
172
+
173
+        // Include
174
+        ob_start();
175
+        try {
176
+            include $file;
177
+            $data = ob_get_contents();
178
+        } catch (\Exception $e) {
179
+            @ob_end_clean();
180
+            throw $e;
181
+        }
182
+        @ob_end_clean();
183
+
184
+        // Return data
185
+        return $data;
186
+    }
187 187
 
188 188
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -46,7 +46,7 @@  discard block
 block discarded – undo
46 46
 	 * @param \OCP\IL10N $l10n
47 47
 	 * @param Defaults $theme
48 48
 	 */
49
-	public function __construct($template, $requestToken, $l10n, $theme ) {
49
+	public function __construct($template, $requestToken, $l10n, $theme) {
50 50
 		$this->vars = array();
51 51
 		$this->vars['requesttoken'] = $requestToken;
52 52
 		$this->l10n = $l10n;
@@ -63,7 +63,7 @@  discard block
 block discarded – undo
63 63
 	 */
64 64
 	protected function getAppTemplateDirs($theme, $app, $serverRoot, $app_dir) {
65 65
 		// Check if the app is in the app folder or in the root
66
-		if( file_exists($app_dir.'/templates/' )) {
66
+		if (file_exists($app_dir.'/templates/')) {
67 67
 			return [
68 68
 				$serverRoot.'/themes/'.$theme.'/apps/'.$app.'/templates/',
69 69
 				$app_dir.'/templates/',
@@ -98,7 +98,7 @@  discard block
 block discarded – undo
98 98
 	 *
99 99
 	 * If the key existed before, it will be overwritten
100 100
 	 */
101
-	public function assign( $key, $value) {
101
+	public function assign($key, $value) {
102 102
 		$this->vars[$key] = $value;
103 103
 		return true;
104 104
 	}
@@ -113,12 +113,12 @@  discard block
 block discarded – undo
113 113
 	 * exists, the value will be appended. It can be accessed via
114 114
 	 * $_[$key][$position] in the template.
115 115
 	 */
116
-	public function append( $key, $value ) {
117
-		if( array_key_exists( $key, $this->vars )) {
116
+	public function append($key, $value) {
117
+		if (array_key_exists($key, $this->vars)) {
118 118
 			$this->vars[$key][] = $value;
119 119
 		}
120
-		else{
121
-			$this->vars[$key] = array( $value );
120
+		else {
121
+			$this->vars[$key] = array($value);
122 122
 		}
123 123
 	}
124 124
 
@@ -130,10 +130,10 @@  discard block
 block discarded – undo
130 130
 	 */
131 131
 	public function printPage() {
132 132
 		$data = $this->fetchPage();
133
-		if( $data === false ) {
133
+		if ($data === false) {
134 134
 			return false;
135 135
 		}
136
-		else{
136
+		else {
137 137
 			print $data;
138 138
 			return true;
139 139
 		}
@@ -166,8 +166,8 @@  discard block
 block discarded – undo
166 166
 		$l = $this->l10n;
167 167
 		$theme = $this->theme;
168 168
 
169
-		if( !is_null($additionalParams)) {
170
-			$_ = array_merge( $additionalParams, $this->vars );
169
+		if (!is_null($additionalParams)) {
170
+			$_ = array_merge($additionalParams, $this->vars);
171 171
 		}
172 172
 
173 173
 		// Include
Please login to merge, or discard this patch.
lib/public/Migration/IOutput.php 2 patches
Doc Comments   +5 added lines, -1 removed lines patch added patch discarded remove patch
@@ -32,18 +32,21 @@  discard block
 block discarded – undo
32 32
 	/**
33 33
 	 * @param string $message
34 34
 	 * @since 9.1.0
35
+	 * @return void
35 36
 	 */
36 37
 	public function info($message);
37 38
 
38 39
 	/**
39 40
 	 * @param string $message
40 41
 	 * @since 9.1.0
42
+	 * @return void
41 43
 	 */
42 44
 	public function warning($message);
43 45
 
44 46
 	/**
45 47
 	 * @param int $max
46 48
 	 * @since 9.1.0
49
+	 * @return void
47 50
 	 */
48 51
 	public function startProgress($max = 0);
49 52
 
@@ -51,12 +54,13 @@  discard block
 block discarded – undo
51 54
 	 * @param int $step
52 55
 	 * @param string $description
53 56
 	 * @since 9.1.0
57
+	 * @return void
54 58
 	 */
55 59
 	public function advance($step = 1, $description = '');
56 60
 
57 61
 	/**
58
-	 * @param int $max
59 62
 	 * @since 9.1.0
63
+	 * @return void
60 64
 	 */
61 65
 	public function finishProgress();
62 66
 
Please login to merge, or discard this patch.
Indentation   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -30,35 +30,35 @@
 block discarded – undo
30 30
  */
31 31
 interface IOutput {
32 32
 
33
-	/**
34
-	 * @param string $message
35
-	 * @since 9.1.0
36
-	 */
37
-	public function info($message);
33
+    /**
34
+     * @param string $message
35
+     * @since 9.1.0
36
+     */
37
+    public function info($message);
38 38
 
39
-	/**
40
-	 * @param string $message
41
-	 * @since 9.1.0
42
-	 */
43
-	public function warning($message);
39
+    /**
40
+     * @param string $message
41
+     * @since 9.1.0
42
+     */
43
+    public function warning($message);
44 44
 
45
-	/**
46
-	 * @param int $max
47
-	 * @since 9.1.0
48
-	 */
49
-	public function startProgress($max = 0);
45
+    /**
46
+     * @param int $max
47
+     * @since 9.1.0
48
+     */
49
+    public function startProgress($max = 0);
50 50
 
51
-	/**
52
-	 * @param int $step
53
-	 * @param string $description
54
-	 * @since 9.1.0
55
-	 */
56
-	public function advance($step = 1, $description = '');
51
+    /**
52
+     * @param int $step
53
+     * @param string $description
54
+     * @since 9.1.0
55
+     */
56
+    public function advance($step = 1, $description = '');
57 57
 
58
-	/**
59
-	 * @param int $max
60
-	 * @since 9.1.0
61
-	 */
62
-	public function finishProgress();
58
+    /**
59
+     * @param int $max
60
+     * @since 9.1.0
61
+     */
62
+    public function finishProgress();
63 63
 
64 64
 }
Please login to merge, or discard this patch.
lib/public/SystemTag/ISystemTagManager.php 2 patches
Doc Comments   +7 added lines, -4 removed lines patch added patch discarded remove patch
@@ -102,17 +102,19 @@  discard block
 block discarded – undo
102 102
 	 * with the same attributes
103 103
 	 *
104 104
 	 * @since 9.0.0
105
+	 * @return void
105 106
 	 */
106 107
 	public function updateTag($tagId, $newName, $userVisible, $userAssignable);
107 108
 
108 109
 	/**
109 110
 	 * Delete the given tags from the database and all their relationships.
110 111
 	 *
111
-	 * @param string|array $tagIds array of tag ids
112
+	 * @param string $tagIds array of tag ids
112 113
 	 *
113 114
 	 * @throws \OCP\SystemTag\TagNotFoundException if at least one tag did not exist
114 115
 	 *
115 116
 	 * @since 9.0.0
117
+	 * @return void
116 118
 	 */
117 119
 	public function deleteTags($tagIds);
118 120
 
@@ -123,7 +125,7 @@  discard block
 block discarded – undo
123 125
 	 * @param ISystemTag $tag tag to check permission for
124 126
 	 * @param IUser $user user to check permission for
125 127
 	 *
126
-	 * @return true if the user is allowed to assign/unassign the tag, false otherwise
128
+	 * @return boolean if the user is allowed to assign/unassign the tag, false otherwise
127 129
 	 *
128 130
 	 * @since 9.1.0
129 131
 	 */
@@ -133,9 +135,9 @@  discard block
 block discarded – undo
133 135
 	 * Checks whether the given user is allowed to see the tag with the given id.
134 136
 	 *
135 137
 	 * @param ISystemTag $tag tag to check permission for
136
-	 * @param IUser $user user to check permission for
138
+	 * @param IUser $userId user to check permission for
137 139
 	 *
138
-	 * @return true if the user can see the tag, false otherwise
140
+	 * @return boolean if the user can see the tag, false otherwise
139 141
 	 *
140 142
 	 * @since 9.1.0
141 143
 	 */
@@ -148,6 +150,7 @@  discard block
 block discarded – undo
148 150
 	 * @param string[] $groupIds group ids of groups that can assign/unassign the tag
149 151
 	 *
150 152
 	 * @since 9.1.0
153
+	 * @return void
151 154
 	 */
152 155
 	public function setTagGroups(ISystemTag $tag, $groupIds);
153 156
 
Please login to merge, or discard this patch.
Indentation   +120 added lines, -120 removed lines patch added patch discarded remove patch
@@ -33,133 +33,133 @@
 block discarded – undo
33 33
  */
34 34
 interface ISystemTagManager {
35 35
 
36
-	/**
37
-	 * Returns the tag objects matching the given tag ids.
38
-	 *
39
-	 * @param array|string $tagIds id or array of unique ids of the tag to retrieve
40
-	 *
41
-	 * @return \OCP\SystemTag\ISystemTag[] array of system tags with tag id as key
42
-	 *
43
-	 * @throws \InvalidArgumentException if at least one given tag ids is invalid (string instead of integer, etc.)
44
-	 * @throws \OCP\SystemTag\TagNotFoundException if at least one given tag ids did no exist
45
-	 * 			The message contains a json_encoded array of the ids that could not be found
46
-	 *
47
-	 * @since 9.0.0
48
-	 */
49
-	public function getTagsByIds($tagIds);
36
+    /**
37
+     * Returns the tag objects matching the given tag ids.
38
+     *
39
+     * @param array|string $tagIds id or array of unique ids of the tag to retrieve
40
+     *
41
+     * @return \OCP\SystemTag\ISystemTag[] array of system tags with tag id as key
42
+     *
43
+     * @throws \InvalidArgumentException if at least one given tag ids is invalid (string instead of integer, etc.)
44
+     * @throws \OCP\SystemTag\TagNotFoundException if at least one given tag ids did no exist
45
+     * 			The message contains a json_encoded array of the ids that could not be found
46
+     *
47
+     * @since 9.0.0
48
+     */
49
+    public function getTagsByIds($tagIds);
50 50
 
51
-	/**
52
-	 * Returns the tag object matching the given attributes.
53
-	 *
54
-	 * @param string $tagName tag name
55
-	 * @param bool $userVisible whether the tag is visible by users
56
-	 * @param bool $userAssignable whether the tag is assignable by users
57
-	 *
58
-	 * @return \OCP\SystemTag\ISystemTag system tag
59
-	 *
60
-	 * @throws \OCP\SystemTag\TagNotFoundException if tag does not exist
61
-	 *
62
-	 * @since 9.0.0
63
-	 */
64
-	public function getTag($tagName, $userVisible, $userAssignable);
51
+    /**
52
+     * Returns the tag object matching the given attributes.
53
+     *
54
+     * @param string $tagName tag name
55
+     * @param bool $userVisible whether the tag is visible by users
56
+     * @param bool $userAssignable whether the tag is assignable by users
57
+     *
58
+     * @return \OCP\SystemTag\ISystemTag system tag
59
+     *
60
+     * @throws \OCP\SystemTag\TagNotFoundException if tag does not exist
61
+     *
62
+     * @since 9.0.0
63
+     */
64
+    public function getTag($tagName, $userVisible, $userAssignable);
65 65
 
66
-	/**
67
-	 * Creates the tag object using the given attributes.
68
-	 *
69
-	 * @param string $tagName tag name
70
-	 * @param bool $userVisible whether the tag is visible by users
71
-	 * @param bool $userAssignable whether the tag is assignable by users
72
-	 *
73
-	 * @return \OCP\SystemTag\ISystemTag system tag
74
-	 *
75
-	 * @throws \OCP\SystemTag\TagAlreadyExistsException if tag already exists
76
-	 *
77
-	 * @since 9.0.0
78
-	 */
79
-	public function createTag($tagName, $userVisible, $userAssignable);
66
+    /**
67
+     * Creates the tag object using the given attributes.
68
+     *
69
+     * @param string $tagName tag name
70
+     * @param bool $userVisible whether the tag is visible by users
71
+     * @param bool $userAssignable whether the tag is assignable by users
72
+     *
73
+     * @return \OCP\SystemTag\ISystemTag system tag
74
+     *
75
+     * @throws \OCP\SystemTag\TagAlreadyExistsException if tag already exists
76
+     *
77
+     * @since 9.0.0
78
+     */
79
+    public function createTag($tagName, $userVisible, $userAssignable);
80 80
 
81
-	/**
82
-	 * Returns all known tags, optionally filtered by visibility.
83
-	 *
84
-	 * @param bool|null $visibilityFilter filter by visibility if non-null
85
-	 * @param string $nameSearchPattern optional search pattern for the tag name
86
-	 *
87
-	 * @return \OCP\SystemTag\ISystemTag[] array of system tags or empty array if none found
88
-	 *
89
-	 * @since 9.0.0
90
-	 */
91
-	public function getAllTags($visibilityFilter = null, $nameSearchPattern = null);
81
+    /**
82
+     * Returns all known tags, optionally filtered by visibility.
83
+     *
84
+     * @param bool|null $visibilityFilter filter by visibility if non-null
85
+     * @param string $nameSearchPattern optional search pattern for the tag name
86
+     *
87
+     * @return \OCP\SystemTag\ISystemTag[] array of system tags or empty array if none found
88
+     *
89
+     * @since 9.0.0
90
+     */
91
+    public function getAllTags($visibilityFilter = null, $nameSearchPattern = null);
92 92
 
93
-	/**
94
-	 * Updates the given tag
95
-	 *
96
-	 * @param string $tagId tag id
97
-	 * @param string $newName the new tag name
98
-	 * @param bool $userVisible whether the tag is visible by users
99
-	 * @param bool $userAssignable whether the tag is assignable by users
100
-	 *
101
-	 * @throws \OCP\SystemTag\TagNotFoundException if tag with the given id does not exist
102
-	 * @throws \OCP\SystemTag\TagAlreadyExistsException if there is already another tag
103
-	 * with the same attributes
104
-	 *
105
-	 * @since 9.0.0
106
-	 */
107
-	public function updateTag($tagId, $newName, $userVisible, $userAssignable);
93
+    /**
94
+     * Updates the given tag
95
+     *
96
+     * @param string $tagId tag id
97
+     * @param string $newName the new tag name
98
+     * @param bool $userVisible whether the tag is visible by users
99
+     * @param bool $userAssignable whether the tag is assignable by users
100
+     *
101
+     * @throws \OCP\SystemTag\TagNotFoundException if tag with the given id does not exist
102
+     * @throws \OCP\SystemTag\TagAlreadyExistsException if there is already another tag
103
+     * with the same attributes
104
+     *
105
+     * @since 9.0.0
106
+     */
107
+    public function updateTag($tagId, $newName, $userVisible, $userAssignable);
108 108
 
109
-	/**
110
-	 * Delete the given tags from the database and all their relationships.
111
-	 *
112
-	 * @param string|array $tagIds array of tag ids
113
-	 *
114
-	 * @throws \OCP\SystemTag\TagNotFoundException if at least one tag did not exist
115
-	 *
116
-	 * @since 9.0.0
117
-	 */
118
-	public function deleteTags($tagIds);
109
+    /**
110
+     * Delete the given tags from the database and all their relationships.
111
+     *
112
+     * @param string|array $tagIds array of tag ids
113
+     *
114
+     * @throws \OCP\SystemTag\TagNotFoundException if at least one tag did not exist
115
+     *
116
+     * @since 9.0.0
117
+     */
118
+    public function deleteTags($tagIds);
119 119
 
120
-	/**
121
-	 * Checks whether the given user is allowed to assign/unassign the tag with the
122
-	 * given id.
123
-	 *
124
-	 * @param ISystemTag $tag tag to check permission for
125
-	 * @param IUser $user user to check permission for
126
-	 *
127
-	 * @return true if the user is allowed to assign/unassign the tag, false otherwise
128
-	 *
129
-	 * @since 9.1.0
130
-	 */
131
-	public function canUserAssignTag(ISystemTag $tag, IUser $user);
120
+    /**
121
+     * Checks whether the given user is allowed to assign/unassign the tag with the
122
+     * given id.
123
+     *
124
+     * @param ISystemTag $tag tag to check permission for
125
+     * @param IUser $user user to check permission for
126
+     *
127
+     * @return true if the user is allowed to assign/unassign the tag, false otherwise
128
+     *
129
+     * @since 9.1.0
130
+     */
131
+    public function canUserAssignTag(ISystemTag $tag, IUser $user);
132 132
 
133
-	/**
134
-	 * Checks whether the given user is allowed to see the tag with the given id.
135
-	 *
136
-	 * @param ISystemTag $tag tag to check permission for
137
-	 * @param IUser $user user to check permission for
138
-	 *
139
-	 * @return true if the user can see the tag, false otherwise
140
-	 *
141
-	 * @since 9.1.0
142
-	 */
143
-	public function canUserSeeTag(ISystemTag $tag, IUser $userId);
133
+    /**
134
+     * Checks whether the given user is allowed to see the tag with the given id.
135
+     *
136
+     * @param ISystemTag $tag tag to check permission for
137
+     * @param IUser $user user to check permission for
138
+     *
139
+     * @return true if the user can see the tag, false otherwise
140
+     *
141
+     * @since 9.1.0
142
+     */
143
+    public function canUserSeeTag(ISystemTag $tag, IUser $userId);
144 144
 
145
-	/**
146
-	 * Set groups that can assign a given tag.
147
-	 *
148
-	 * @param ISystemTag $tag tag for group assignment
149
-	 * @param string[] $groupIds group ids of groups that can assign/unassign the tag
150
-	 *
151
-	 * @since 9.1.0
152
-	 */
153
-	public function setTagGroups(ISystemTag $tag, $groupIds);
145
+    /**
146
+     * Set groups that can assign a given tag.
147
+     *
148
+     * @param ISystemTag $tag tag for group assignment
149
+     * @param string[] $groupIds group ids of groups that can assign/unassign the tag
150
+     *
151
+     * @since 9.1.0
152
+     */
153
+    public function setTagGroups(ISystemTag $tag, $groupIds);
154 154
 
155
-	/**
156
-	 * Get groups that can assign a given tag.
157
-	 *
158
-	 * @param ISystemTag $tag tag for group assignment
159
-	 *
160
-	 * @return string[] group ids of groups that can assign/unassign the tag
161
-	 *
162
-	 * @since 9.1.0
163
-	 */
164
-	public function getTagGroups(ISystemTag $tag);
155
+    /**
156
+     * Get groups that can assign a given tag.
157
+     *
158
+     * @param ISystemTag $tag tag for group assignment
159
+     *
160
+     * @return string[] group ids of groups that can assign/unassign the tag
161
+     *
162
+     * @since 9.1.0
163
+     */
164
+    public function getTagGroups(ISystemTag $tag);
165 165
 }
Please login to merge, or discard this patch.
lib/private/Files/View.php 3 patches
Doc Comments   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -200,7 +200,7 @@  discard block
 block discarded – undo
200 200
 	 * and does not take the chroot into account )
201 201
 	 *
202 202
 	 * @param string $path
203
-	 * @return \OCP\Files\Mount\IMountPoint
203
+	 * @return Mount\MountPoint|null
204 204
 	 */
205 205
 	public function getMount($path) {
206 206
 		return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
@@ -963,7 +963,7 @@  discard block
 block discarded – undo
963 963
 
964 964
 	/**
965 965
 	 * @param string $path
966
-	 * @return bool|string
966
+	 * @return string|false
967 967
 	 * @throws \OCP\Files\InvalidPathException
968 968
 	 */
969 969
 	public function toTmpFile($path) {
@@ -1078,7 +1078,7 @@  discard block
 block discarded – undo
1078 1078
 	 * @param string $path
1079 1079
 	 * @param array $hooks (optional)
1080 1080
 	 * @param mixed $extraParam (optional)
1081
-	 * @return mixed
1081
+	 * @return string
1082 1082
 	 * @throws \Exception
1083 1083
 	 *
1084 1084
 	 * This method takes requests for basic filesystem functions (e.g. reading & writing
@@ -2086,7 +2086,7 @@  discard block
 block discarded – undo
2086 2086
 
2087 2087
 	/**
2088 2088
 	 * @param string $filename
2089
-	 * @return array
2089
+	 * @return string[]
2090 2090
 	 * @throws \OC\User\NoUserException
2091 2091
 	 * @throws NotFoundException
2092 2092
 	 */
Please login to merge, or discard this patch.
Indentation   +2086 added lines, -2086 removed lines patch added patch discarded remove patch
@@ -80,2090 +80,2090 @@
 block discarded – undo
80 80
  * \OC\Files\Storage\Storage object
81 81
  */
82 82
 class View {
83
-	/** @var string */
84
-	private $fakeRoot = '';
85
-
86
-	/**
87
-	 * @var \OCP\Lock\ILockingProvider
88
-	 */
89
-	protected $lockingProvider;
90
-
91
-	private $lockingEnabled;
92
-
93
-	private $updaterEnabled = true;
94
-
95
-	/** @var \OC\User\Manager */
96
-	private $userManager;
97
-
98
-	/** @var \OCP\ILogger */
99
-	private $logger;
100
-
101
-	/**
102
-	 * @param string $root
103
-	 * @throws \Exception If $root contains an invalid path
104
-	 */
105
-	public function __construct($root = '') {
106
-		if (is_null($root)) {
107
-			throw new \InvalidArgumentException('Root can\'t be null');
108
-		}
109
-		if (!Filesystem::isValidPath($root)) {
110
-			throw new \Exception();
111
-		}
112
-
113
-		$this->fakeRoot = $root;
114
-		$this->lockingProvider = \OC::$server->getLockingProvider();
115
-		$this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
116
-		$this->userManager = \OC::$server->getUserManager();
117
-		$this->logger = \OC::$server->getLogger();
118
-	}
119
-
120
-	public function getAbsolutePath($path = '/') {
121
-		if ($path === null) {
122
-			return null;
123
-		}
124
-		$this->assertPathLength($path);
125
-		if ($path === '') {
126
-			$path = '/';
127
-		}
128
-		if ($path[0] !== '/') {
129
-			$path = '/' . $path;
130
-		}
131
-		return $this->fakeRoot . $path;
132
-	}
133
-
134
-	/**
135
-	 * change the root to a fake root
136
-	 *
137
-	 * @param string $fakeRoot
138
-	 * @return boolean|null
139
-	 */
140
-	public function chroot($fakeRoot) {
141
-		if (!$fakeRoot == '') {
142
-			if ($fakeRoot[0] !== '/') {
143
-				$fakeRoot = '/' . $fakeRoot;
144
-			}
145
-		}
146
-		$this->fakeRoot = $fakeRoot;
147
-	}
148
-
149
-	/**
150
-	 * get the fake root
151
-	 *
152
-	 * @return string
153
-	 */
154
-	public function getRoot() {
155
-		return $this->fakeRoot;
156
-	}
157
-
158
-	/**
159
-	 * get path relative to the root of the view
160
-	 *
161
-	 * @param string $path
162
-	 * @return string
163
-	 */
164
-	public function getRelativePath($path) {
165
-		$this->assertPathLength($path);
166
-		if ($this->fakeRoot == '') {
167
-			return $path;
168
-		}
169
-
170
-		if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
171
-			return '/';
172
-		}
173
-
174
-		// missing slashes can cause wrong matches!
175
-		$root = rtrim($this->fakeRoot, '/') . '/';
176
-
177
-		if (strpos($path, $root) !== 0) {
178
-			return null;
179
-		} else {
180
-			$path = substr($path, strlen($this->fakeRoot));
181
-			if (strlen($path) === 0) {
182
-				return '/';
183
-			} else {
184
-				return $path;
185
-			}
186
-		}
187
-	}
188
-
189
-	/**
190
-	 * get the mountpoint of the storage object for a path
191
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
192
-	 * returned mountpoint is relative to the absolute root of the filesystem
193
-	 * and does not take the chroot into account )
194
-	 *
195
-	 * @param string $path
196
-	 * @return string
197
-	 */
198
-	public function getMountPoint($path) {
199
-		return Filesystem::getMountPoint($this->getAbsolutePath($path));
200
-	}
201
-
202
-	/**
203
-	 * get the mountpoint of the storage object for a path
204
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
205
-	 * returned mountpoint is relative to the absolute root of the filesystem
206
-	 * and does not take the chroot into account )
207
-	 *
208
-	 * @param string $path
209
-	 * @return \OCP\Files\Mount\IMountPoint
210
-	 */
211
-	public function getMount($path) {
212
-		return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
213
-	}
214
-
215
-	/**
216
-	 * resolve a path to a storage and internal path
217
-	 *
218
-	 * @param string $path
219
-	 * @return array an array consisting of the storage and the internal path
220
-	 */
221
-	public function resolvePath($path) {
222
-		$a = $this->getAbsolutePath($path);
223
-		$p = Filesystem::normalizePath($a);
224
-		return Filesystem::resolvePath($p);
225
-	}
226
-
227
-	/**
228
-	 * return the path to a local version of the file
229
-	 * we need this because we can't know if a file is stored local or not from
230
-	 * outside the filestorage and for some purposes a local file is needed
231
-	 *
232
-	 * @param string $path
233
-	 * @return string
234
-	 */
235
-	public function getLocalFile($path) {
236
-		$parent = substr($path, 0, strrpos($path, '/'));
237
-		$path = $this->getAbsolutePath($path);
238
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
239
-		if (Filesystem::isValidPath($parent) and $storage) {
240
-			return $storage->getLocalFile($internalPath);
241
-		} else {
242
-			return null;
243
-		}
244
-	}
245
-
246
-	/**
247
-	 * @param string $path
248
-	 * @return string
249
-	 */
250
-	public function getLocalFolder($path) {
251
-		$parent = substr($path, 0, strrpos($path, '/'));
252
-		$path = $this->getAbsolutePath($path);
253
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
254
-		if (Filesystem::isValidPath($parent) and $storage) {
255
-			return $storage->getLocalFolder($internalPath);
256
-		} else {
257
-			return null;
258
-		}
259
-	}
260
-
261
-	/**
262
-	 * the following functions operate with arguments and return values identical
263
-	 * to those of their PHP built-in equivalents. Mostly they are merely wrappers
264
-	 * for \OC\Files\Storage\Storage via basicOperation().
265
-	 */
266
-	public function mkdir($path) {
267
-		return $this->basicOperation('mkdir', $path, array('create', 'write'));
268
-	}
269
-
270
-	/**
271
-	 * remove mount point
272
-	 *
273
-	 * @param \OC\Files\Mount\MoveableMount $mount
274
-	 * @param string $path relative to data/
275
-	 * @return boolean
276
-	 */
277
-	protected function removeMount($mount, $path) {
278
-		if ($mount instanceof MoveableMount) {
279
-			// cut of /user/files to get the relative path to data/user/files
280
-			$pathParts = explode('/', $path, 4);
281
-			$relPath = '/' . $pathParts[3];
282
-			$this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
283
-			\OC_Hook::emit(
284
-				Filesystem::CLASSNAME, "umount",
285
-				array(Filesystem::signal_param_path => $relPath)
286
-			);
287
-			$this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
288
-			$result = $mount->removeMount();
289
-			$this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
290
-			if ($result) {
291
-				\OC_Hook::emit(
292
-					Filesystem::CLASSNAME, "post_umount",
293
-					array(Filesystem::signal_param_path => $relPath)
294
-				);
295
-			}
296
-			$this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
297
-			return $result;
298
-		} else {
299
-			// do not allow deleting the storage's root / the mount point
300
-			// because for some storages it might delete the whole contents
301
-			// but isn't supposed to work that way
302
-			return false;
303
-		}
304
-	}
305
-
306
-	public function disableCacheUpdate() {
307
-		$this->updaterEnabled = false;
308
-	}
309
-
310
-	public function enableCacheUpdate() {
311
-		$this->updaterEnabled = true;
312
-	}
313
-
314
-	protected function writeUpdate(Storage $storage, $internalPath, $time = null) {
315
-		if ($this->updaterEnabled) {
316
-			if (is_null($time)) {
317
-				$time = time();
318
-			}
319
-			$storage->getUpdater()->update($internalPath, $time);
320
-		}
321
-	}
322
-
323
-	protected function removeUpdate(Storage $storage, $internalPath) {
324
-		if ($this->updaterEnabled) {
325
-			$storage->getUpdater()->remove($internalPath);
326
-		}
327
-	}
328
-
329
-	protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, $sourceInternalPath, $targetInternalPath) {
330
-		if ($this->updaterEnabled) {
331
-			$targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
332
-		}
333
-	}
334
-
335
-	/**
336
-	 * @param string $path
337
-	 * @return bool|mixed
338
-	 */
339
-	public function rmdir($path) {
340
-		$absolutePath = $this->getAbsolutePath($path);
341
-		$mount = Filesystem::getMountManager()->find($absolutePath);
342
-		if ($mount->getInternalPath($absolutePath) === '') {
343
-			return $this->removeMount($mount, $absolutePath);
344
-		}
345
-		if ($this->is_dir($path)) {
346
-			$result = $this->basicOperation('rmdir', $path, array('delete'));
347
-		} else {
348
-			$result = false;
349
-		}
350
-
351
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
352
-			$storage = $mount->getStorage();
353
-			$internalPath = $mount->getInternalPath($absolutePath);
354
-			$storage->getUpdater()->remove($internalPath);
355
-		}
356
-		return $result;
357
-	}
358
-
359
-	/**
360
-	 * @param string $path
361
-	 * @return resource
362
-	 */
363
-	public function opendir($path) {
364
-		return $this->basicOperation('opendir', $path, array('read'));
365
-	}
366
-
367
-	/**
368
-	 * @param string $path
369
-	 * @return bool|mixed
370
-	 */
371
-	public function is_dir($path) {
372
-		if ($path == '/') {
373
-			return true;
374
-		}
375
-		return $this->basicOperation('is_dir', $path);
376
-	}
377
-
378
-	/**
379
-	 * @param string $path
380
-	 * @return bool|mixed
381
-	 */
382
-	public function is_file($path) {
383
-		if ($path == '/') {
384
-			return false;
385
-		}
386
-		return $this->basicOperation('is_file', $path);
387
-	}
388
-
389
-	/**
390
-	 * @param string $path
391
-	 * @return mixed
392
-	 */
393
-	public function stat($path) {
394
-		return $this->basicOperation('stat', $path);
395
-	}
396
-
397
-	/**
398
-	 * @param string $path
399
-	 * @return mixed
400
-	 */
401
-	public function filetype($path) {
402
-		return $this->basicOperation('filetype', $path);
403
-	}
404
-
405
-	/**
406
-	 * @param string $path
407
-	 * @return mixed
408
-	 */
409
-	public function filesize($path) {
410
-		return $this->basicOperation('filesize', $path);
411
-	}
412
-
413
-	/**
414
-	 * @param string $path
415
-	 * @return bool|mixed
416
-	 * @throws \OCP\Files\InvalidPathException
417
-	 */
418
-	public function readfile($path) {
419
-		$this->assertPathLength($path);
420
-		@ob_end_clean();
421
-		$handle = $this->fopen($path, 'rb');
422
-		if ($handle) {
423
-			$chunkSize = 8192; // 8 kB chunks
424
-			while (!feof($handle)) {
425
-				echo fread($handle, $chunkSize);
426
-				flush();
427
-			}
428
-			fclose($handle);
429
-			$size = $this->filesize($path);
430
-			return $size;
431
-		}
432
-		return false;
433
-	}
434
-
435
-	/**
436
-	 * @param string $path
437
-	 * @param int $from
438
-	 * @param int $to
439
-	 * @return bool|mixed
440
-	 * @throws \OCP\Files\InvalidPathException
441
-	 * @throws \OCP\Files\UnseekableException
442
-	 */
443
-	public function readfilePart($path, $from, $to) {
444
-		$this->assertPathLength($path);
445
-		@ob_end_clean();
446
-		$handle = $this->fopen($path, 'rb');
447
-		if ($handle) {
448
-			$chunkSize = 8192; // 8 kB chunks
449
-			$startReading = true;
450
-
451
-			if ($from !== 0 && $from !== '0' && fseek($handle, $from) !== 0) {
452
-				// forward file handle via chunked fread because fseek seem to have failed
453
-
454
-				$end = $from + 1;
455
-				while (!feof($handle) && ftell($handle) < $end) {
456
-					$len = $from - ftell($handle);
457
-					if ($len > $chunkSize) {
458
-						$len = $chunkSize;
459
-					}
460
-					$result = fread($handle, $len);
461
-
462
-					if ($result === false) {
463
-						$startReading = false;
464
-						break;
465
-					}
466
-				}
467
-			}
468
-
469
-			if ($startReading) {
470
-				$end = $to + 1;
471
-				while (!feof($handle) && ftell($handle) < $end) {
472
-					$len = $end - ftell($handle);
473
-					if ($len > $chunkSize) {
474
-						$len = $chunkSize;
475
-					}
476
-					echo fread($handle, $len);
477
-					flush();
478
-				}
479
-				$size = ftell($handle) - $from;
480
-				return $size;
481
-			}
482
-
483
-			throw new \OCP\Files\UnseekableException('fseek error');
484
-		}
485
-		return false;
486
-	}
487
-
488
-	/**
489
-	 * @param string $path
490
-	 * @return mixed
491
-	 */
492
-	public function isCreatable($path) {
493
-		return $this->basicOperation('isCreatable', $path);
494
-	}
495
-
496
-	/**
497
-	 * @param string $path
498
-	 * @return mixed
499
-	 */
500
-	public function isReadable($path) {
501
-		return $this->basicOperation('isReadable', $path);
502
-	}
503
-
504
-	/**
505
-	 * @param string $path
506
-	 * @return mixed
507
-	 */
508
-	public function isUpdatable($path) {
509
-		return $this->basicOperation('isUpdatable', $path);
510
-	}
511
-
512
-	/**
513
-	 * @param string $path
514
-	 * @return bool|mixed
515
-	 */
516
-	public function isDeletable($path) {
517
-		$absolutePath = $this->getAbsolutePath($path);
518
-		$mount = Filesystem::getMountManager()->find($absolutePath);
519
-		if ($mount->getInternalPath($absolutePath) === '') {
520
-			return $mount instanceof MoveableMount;
521
-		}
522
-		return $this->basicOperation('isDeletable', $path);
523
-	}
524
-
525
-	/**
526
-	 * @param string $path
527
-	 * @return mixed
528
-	 */
529
-	public function isSharable($path) {
530
-		return $this->basicOperation('isSharable', $path);
531
-	}
532
-
533
-	/**
534
-	 * @param string $path
535
-	 * @return bool|mixed
536
-	 */
537
-	public function file_exists($path) {
538
-		if ($path == '/') {
539
-			return true;
540
-		}
541
-		return $this->basicOperation('file_exists', $path);
542
-	}
543
-
544
-	/**
545
-	 * @param string $path
546
-	 * @return mixed
547
-	 */
548
-	public function filemtime($path) {
549
-		return $this->basicOperation('filemtime', $path);
550
-	}
551
-
552
-	/**
553
-	 * @param string $path
554
-	 * @param int|string $mtime
555
-	 * @return bool
556
-	 */
557
-	public function touch($path, $mtime = null) {
558
-		if (!is_null($mtime) and !is_numeric($mtime)) {
559
-			$mtime = strtotime($mtime);
560
-		}
561
-
562
-		$hooks = array('touch');
563
-
564
-		if (!$this->file_exists($path)) {
565
-			$hooks[] = 'create';
566
-			$hooks[] = 'write';
567
-		}
568
-		$result = $this->basicOperation('touch', $path, $hooks, $mtime);
569
-		if (!$result) {
570
-			// If create file fails because of permissions on external storage like SMB folders,
571
-			// check file exists and return false if not.
572
-			if (!$this->file_exists($path)) {
573
-				return false;
574
-			}
575
-			if (is_null($mtime)) {
576
-				$mtime = time();
577
-			}
578
-			//if native touch fails, we emulate it by changing the mtime in the cache
579
-			$this->putFileInfo($path, array('mtime' => floor($mtime)));
580
-		}
581
-		return true;
582
-	}
583
-
584
-	/**
585
-	 * @param string $path
586
-	 * @return mixed
587
-	 */
588
-	public function file_get_contents($path) {
589
-		return $this->basicOperation('file_get_contents', $path, array('read'));
590
-	}
591
-
592
-	/**
593
-	 * @param bool $exists
594
-	 * @param string $path
595
-	 * @param bool $run
596
-	 */
597
-	protected function emit_file_hooks_pre($exists, $path, &$run) {
598
-		if (!$exists) {
599
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, array(
600
-				Filesystem::signal_param_path => $this->getHookPath($path),
601
-				Filesystem::signal_param_run => &$run,
602
-			));
603
-		} else {
604
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, array(
605
-				Filesystem::signal_param_path => $this->getHookPath($path),
606
-				Filesystem::signal_param_run => &$run,
607
-			));
608
-		}
609
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, array(
610
-			Filesystem::signal_param_path => $this->getHookPath($path),
611
-			Filesystem::signal_param_run => &$run,
612
-		));
613
-	}
614
-
615
-	/**
616
-	 * @param bool $exists
617
-	 * @param string $path
618
-	 */
619
-	protected function emit_file_hooks_post($exists, $path) {
620
-		if (!$exists) {
621
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, array(
622
-				Filesystem::signal_param_path => $this->getHookPath($path),
623
-			));
624
-		} else {
625
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, array(
626
-				Filesystem::signal_param_path => $this->getHookPath($path),
627
-			));
628
-		}
629
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, array(
630
-			Filesystem::signal_param_path => $this->getHookPath($path),
631
-		));
632
-	}
633
-
634
-	/**
635
-	 * @param string $path
636
-	 * @param mixed $data
637
-	 * @return bool|mixed
638
-	 * @throws \Exception
639
-	 */
640
-	public function file_put_contents($path, $data) {
641
-		if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
642
-			$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
643
-			if (Filesystem::isValidPath($path)
644
-				and !Filesystem::isFileBlacklisted($path)
645
-			) {
646
-				$path = $this->getRelativePath($absolutePath);
647
-
648
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
649
-
650
-				$exists = $this->file_exists($path);
651
-				$run = true;
652
-				if ($this->shouldEmitHooks($path)) {
653
-					$this->emit_file_hooks_pre($exists, $path, $run);
654
-				}
655
-				if (!$run) {
656
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
657
-					return false;
658
-				}
659
-
660
-				$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
661
-
662
-				/** @var \OC\Files\Storage\Storage $storage */
663
-				list($storage, $internalPath) = $this->resolvePath($path);
664
-				$target = $storage->fopen($internalPath, 'w');
665
-				if ($target) {
666
-					list (, $result) = \OC_Helper::streamCopy($data, $target);
667
-					fclose($target);
668
-					fclose($data);
669
-
670
-					$this->writeUpdate($storage, $internalPath);
671
-
672
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
673
-
674
-					if ($this->shouldEmitHooks($path) && $result !== false) {
675
-						$this->emit_file_hooks_post($exists, $path);
676
-					}
677
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
678
-					return $result;
679
-				} else {
680
-					$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
681
-					return false;
682
-				}
683
-			} else {
684
-				return false;
685
-			}
686
-		} else {
687
-			$hooks = ($this->file_exists($path)) ? array('update', 'write') : array('create', 'write');
688
-			return $this->basicOperation('file_put_contents', $path, $hooks, $data);
689
-		}
690
-	}
691
-
692
-	/**
693
-	 * @param string $path
694
-	 * @return bool|mixed
695
-	 */
696
-	public function unlink($path) {
697
-		if ($path === '' || $path === '/') {
698
-			// do not allow deleting the root
699
-			return false;
700
-		}
701
-		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
702
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
703
-		$mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
704
-		if ($mount and $mount->getInternalPath($absolutePath) === '') {
705
-			return $this->removeMount($mount, $absolutePath);
706
-		}
707
-		if ($this->is_dir($path)) {
708
-			$result = $this->basicOperation('rmdir', $path, ['delete']);
709
-		} else {
710
-			$result = $this->basicOperation('unlink', $path, ['delete']);
711
-		}
712
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
713
-			$storage = $mount->getStorage();
714
-			$internalPath = $mount->getInternalPath($absolutePath);
715
-			$storage->getUpdater()->remove($internalPath);
716
-			return true;
717
-		} else {
718
-			return $result;
719
-		}
720
-	}
721
-
722
-	/**
723
-	 * @param string $directory
724
-	 * @return bool|mixed
725
-	 */
726
-	public function deleteAll($directory) {
727
-		return $this->rmdir($directory);
728
-	}
729
-
730
-	/**
731
-	 * Rename/move a file or folder from the source path to target path.
732
-	 *
733
-	 * @param string $path1 source path
734
-	 * @param string $path2 target path
735
-	 *
736
-	 * @return bool|mixed
737
-	 */
738
-	public function rename($path1, $path2) {
739
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
740
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
741
-		$result = false;
742
-		if (
743
-			Filesystem::isValidPath($path2)
744
-			and Filesystem::isValidPath($path1)
745
-			and !Filesystem::isFileBlacklisted($path2)
746
-		) {
747
-			$path1 = $this->getRelativePath($absolutePath1);
748
-			$path2 = $this->getRelativePath($absolutePath2);
749
-			$exists = $this->file_exists($path2);
750
-
751
-			if ($path1 == null or $path2 == null) {
752
-				return false;
753
-			}
754
-
755
-			$this->lockFile($path1, ILockingProvider::LOCK_SHARED, true);
756
-			try {
757
-				$this->lockFile($path2, ILockingProvider::LOCK_SHARED, true);
758
-
759
-				$run = true;
760
-				if ($this->shouldEmitHooks($path1) && (Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2))) {
761
-					// if it was a rename from a part file to a regular file it was a write and not a rename operation
762
-					$this->emit_file_hooks_pre($exists, $path2, $run);
763
-				} elseif ($this->shouldEmitHooks($path1)) {
764
-					\OC_Hook::emit(
765
-						Filesystem::CLASSNAME, Filesystem::signal_rename,
766
-						array(
767
-							Filesystem::signal_param_oldpath => $this->getHookPath($path1),
768
-							Filesystem::signal_param_newpath => $this->getHookPath($path2),
769
-							Filesystem::signal_param_run => &$run
770
-						)
771
-					);
772
-				}
773
-				if ($run) {
774
-					$this->verifyPath(dirname($path2), basename($path2));
775
-
776
-					$manager = Filesystem::getMountManager();
777
-					$mount1 = $this->getMount($path1);
778
-					$mount2 = $this->getMount($path2);
779
-					$storage1 = $mount1->getStorage();
780
-					$storage2 = $mount2->getStorage();
781
-					$internalPath1 = $mount1->getInternalPath($absolutePath1);
782
-					$internalPath2 = $mount2->getInternalPath($absolutePath2);
783
-
784
-					$this->changeLock($path1, ILockingProvider::LOCK_EXCLUSIVE, true);
785
-					try {
786
-						$this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE, true);
787
-
788
-						if ($internalPath1 === '') {
789
-							if ($mount1 instanceof MoveableMount) {
790
-								if ($this->isTargetAllowed($absolutePath2)) {
791
-									/**
792
-									 * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
793
-									 */
794
-									$sourceMountPoint = $mount1->getMountPoint();
795
-									$result = $mount1->moveMount($absolutePath2);
796
-									$manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
797
-								} else {
798
-									$result = false;
799
-								}
800
-							} else {
801
-								$result = false;
802
-							}
803
-							// moving a file/folder within the same mount point
804
-						} elseif ($storage1 === $storage2) {
805
-							if ($storage1) {
806
-								$result = $storage1->rename($internalPath1, $internalPath2);
807
-							} else {
808
-								$result = false;
809
-							}
810
-							// moving a file/folder between storages (from $storage1 to $storage2)
811
-						} else {
812
-							$result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
813
-						}
814
-
815
-						if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
816
-							// if it was a rename from a part file to a regular file it was a write and not a rename operation
817
-							$this->writeUpdate($storage2, $internalPath2);
818
-						} else if ($result) {
819
-							if ($internalPath1 !== '') { // don't do a cache update for moved mounts
820
-								$this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
821
-							}
822
-						}
823
-					} catch(\Exception $e) {
824
-						throw $e;
825
-					} finally {
826
-						$this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
827
-						$this->changeLock($path2, ILockingProvider::LOCK_SHARED, true);
828
-					}
829
-
830
-					if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
831
-						if ($this->shouldEmitHooks()) {
832
-							$this->emit_file_hooks_post($exists, $path2);
833
-						}
834
-					} elseif ($result) {
835
-						if ($this->shouldEmitHooks($path1) and $this->shouldEmitHooks($path2)) {
836
-							\OC_Hook::emit(
837
-								Filesystem::CLASSNAME,
838
-								Filesystem::signal_post_rename,
839
-								array(
840
-									Filesystem::signal_param_oldpath => $this->getHookPath($path1),
841
-									Filesystem::signal_param_newpath => $this->getHookPath($path2)
842
-								)
843
-							);
844
-						}
845
-					}
846
-				}
847
-			} catch(\Exception $e) {
848
-				throw $e;
849
-			} finally {
850
-				$this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
851
-				$this->unlockFile($path2, ILockingProvider::LOCK_SHARED, true);
852
-			}
853
-		}
854
-		return $result;
855
-	}
856
-
857
-	/**
858
-	 * Copy a file/folder from the source path to target path
859
-	 *
860
-	 * @param string $path1 source path
861
-	 * @param string $path2 target path
862
-	 * @param bool $preserveMtime whether to preserve mtime on the copy
863
-	 *
864
-	 * @return bool|mixed
865
-	 */
866
-	public function copy($path1, $path2, $preserveMtime = false) {
867
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
868
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
869
-		$result = false;
870
-		if (
871
-			Filesystem::isValidPath($path2)
872
-			and Filesystem::isValidPath($path1)
873
-			and !Filesystem::isFileBlacklisted($path2)
874
-		) {
875
-			$path1 = $this->getRelativePath($absolutePath1);
876
-			$path2 = $this->getRelativePath($absolutePath2);
877
-
878
-			if ($path1 == null or $path2 == null) {
879
-				return false;
880
-			}
881
-			$run = true;
882
-
883
-			$this->lockFile($path2, ILockingProvider::LOCK_SHARED);
884
-			$this->lockFile($path1, ILockingProvider::LOCK_SHARED);
885
-			$lockTypePath1 = ILockingProvider::LOCK_SHARED;
886
-			$lockTypePath2 = ILockingProvider::LOCK_SHARED;
887
-
888
-			try {
889
-
890
-				$exists = $this->file_exists($path2);
891
-				if ($this->shouldEmitHooks()) {
892
-					\OC_Hook::emit(
893
-						Filesystem::CLASSNAME,
894
-						Filesystem::signal_copy,
895
-						array(
896
-							Filesystem::signal_param_oldpath => $this->getHookPath($path1),
897
-							Filesystem::signal_param_newpath => $this->getHookPath($path2),
898
-							Filesystem::signal_param_run => &$run
899
-						)
900
-					);
901
-					$this->emit_file_hooks_pre($exists, $path2, $run);
902
-				}
903
-				if ($run) {
904
-					$mount1 = $this->getMount($path1);
905
-					$mount2 = $this->getMount($path2);
906
-					$storage1 = $mount1->getStorage();
907
-					$internalPath1 = $mount1->getInternalPath($absolutePath1);
908
-					$storage2 = $mount2->getStorage();
909
-					$internalPath2 = $mount2->getInternalPath($absolutePath2);
910
-
911
-					$this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE);
912
-					$lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
913
-
914
-					if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
915
-						if ($storage1) {
916
-							$result = $storage1->copy($internalPath1, $internalPath2);
917
-						} else {
918
-							$result = false;
919
-						}
920
-					} else {
921
-						$result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
922
-					}
923
-
924
-					$this->writeUpdate($storage2, $internalPath2);
925
-
926
-					$this->changeLock($path2, ILockingProvider::LOCK_SHARED);
927
-					$lockTypePath2 = ILockingProvider::LOCK_SHARED;
928
-
929
-					if ($this->shouldEmitHooks() && $result !== false) {
930
-						\OC_Hook::emit(
931
-							Filesystem::CLASSNAME,
932
-							Filesystem::signal_post_copy,
933
-							array(
934
-								Filesystem::signal_param_oldpath => $this->getHookPath($path1),
935
-								Filesystem::signal_param_newpath => $this->getHookPath($path2)
936
-							)
937
-						);
938
-						$this->emit_file_hooks_post($exists, $path2);
939
-					}
940
-
941
-				}
942
-			} catch (\Exception $e) {
943
-				$this->unlockFile($path2, $lockTypePath2);
944
-				$this->unlockFile($path1, $lockTypePath1);
945
-				throw $e;
946
-			}
947
-
948
-			$this->unlockFile($path2, $lockTypePath2);
949
-			$this->unlockFile($path1, $lockTypePath1);
950
-
951
-		}
952
-		return $result;
953
-	}
954
-
955
-	/**
956
-	 * @param string $path
957
-	 * @param string $mode 'r' or 'w'
958
-	 * @return resource
959
-	 */
960
-	public function fopen($path, $mode) {
961
-		$mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
962
-		$hooks = array();
963
-		switch ($mode) {
964
-			case 'r':
965
-				$hooks[] = 'read';
966
-				break;
967
-			case 'r+':
968
-			case 'w+':
969
-			case 'x+':
970
-			case 'a+':
971
-				$hooks[] = 'read';
972
-				$hooks[] = 'write';
973
-				break;
974
-			case 'w':
975
-			case 'x':
976
-			case 'a':
977
-				$hooks[] = 'write';
978
-				break;
979
-			default:
980
-				\OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, \OCP\Util::ERROR);
981
-		}
982
-
983
-		if ($mode !== 'r' && $mode !== 'w') {
984
-			\OC::$server->getLogger()->info('Trying to open a file with a mode other than "r" or "w" can cause severe performance issues with some backends');
985
-		}
986
-
987
-		return $this->basicOperation('fopen', $path, $hooks, $mode);
988
-	}
989
-
990
-	/**
991
-	 * @param string $path
992
-	 * @return bool|string
993
-	 * @throws \OCP\Files\InvalidPathException
994
-	 */
995
-	public function toTmpFile($path) {
996
-		$this->assertPathLength($path);
997
-		if (Filesystem::isValidPath($path)) {
998
-			$source = $this->fopen($path, 'r');
999
-			if ($source) {
1000
-				$extension = pathinfo($path, PATHINFO_EXTENSION);
1001
-				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
1002
-				file_put_contents($tmpFile, $source);
1003
-				return $tmpFile;
1004
-			} else {
1005
-				return false;
1006
-			}
1007
-		} else {
1008
-			return false;
1009
-		}
1010
-	}
1011
-
1012
-	/**
1013
-	 * @param string $tmpFile
1014
-	 * @param string $path
1015
-	 * @return bool|mixed
1016
-	 * @throws \OCP\Files\InvalidPathException
1017
-	 */
1018
-	public function fromTmpFile($tmpFile, $path) {
1019
-		$this->assertPathLength($path);
1020
-		if (Filesystem::isValidPath($path)) {
1021
-
1022
-			// Get directory that the file is going into
1023
-			$filePath = dirname($path);
1024
-
1025
-			// Create the directories if any
1026
-			if (!$this->file_exists($filePath)) {
1027
-				$result = $this->createParentDirectories($filePath);
1028
-				if ($result === false) {
1029
-					return false;
1030
-				}
1031
-			}
1032
-
1033
-			$source = fopen($tmpFile, 'r');
1034
-			if ($source) {
1035
-				$result = $this->file_put_contents($path, $source);
1036
-				// $this->file_put_contents() might have already closed
1037
-				// the resource, so we check it, before trying to close it
1038
-				// to avoid messages in the error log.
1039
-				if (is_resource($source)) {
1040
-					fclose($source);
1041
-				}
1042
-				unlink($tmpFile);
1043
-				return $result;
1044
-			} else {
1045
-				return false;
1046
-			}
1047
-		} else {
1048
-			return false;
1049
-		}
1050
-	}
1051
-
1052
-
1053
-	/**
1054
-	 * @param string $path
1055
-	 * @return mixed
1056
-	 * @throws \OCP\Files\InvalidPathException
1057
-	 */
1058
-	public function getMimeType($path) {
1059
-		$this->assertPathLength($path);
1060
-		return $this->basicOperation('getMimeType', $path);
1061
-	}
1062
-
1063
-	/**
1064
-	 * @param string $type
1065
-	 * @param string $path
1066
-	 * @param bool $raw
1067
-	 * @return bool|null|string
1068
-	 */
1069
-	public function hash($type, $path, $raw = false) {
1070
-		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1071
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1072
-		if (Filesystem::isValidPath($path)) {
1073
-			$path = $this->getRelativePath($absolutePath);
1074
-			if ($path == null) {
1075
-				return false;
1076
-			}
1077
-			if ($this->shouldEmitHooks($path)) {
1078
-				\OC_Hook::emit(
1079
-					Filesystem::CLASSNAME,
1080
-					Filesystem::signal_read,
1081
-					array(Filesystem::signal_param_path => $this->getHookPath($path))
1082
-				);
1083
-			}
1084
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1085
-			if ($storage) {
1086
-				$result = $storage->hash($type, $internalPath, $raw);
1087
-				return $result;
1088
-			}
1089
-		}
1090
-		return null;
1091
-	}
1092
-
1093
-	/**
1094
-	 * @param string $path
1095
-	 * @return mixed
1096
-	 * @throws \OCP\Files\InvalidPathException
1097
-	 */
1098
-	public function free_space($path = '/') {
1099
-		$this->assertPathLength($path);
1100
-		$result = $this->basicOperation('free_space', $path);
1101
-		if ($result === null) {
1102
-			throw new InvalidPathException();
1103
-		}
1104
-		return $result;
1105
-	}
1106
-
1107
-	/**
1108
-	 * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1109
-	 *
1110
-	 * @param string $operation
1111
-	 * @param string $path
1112
-	 * @param array $hooks (optional)
1113
-	 * @param mixed $extraParam (optional)
1114
-	 * @return mixed
1115
-	 * @throws \Exception
1116
-	 *
1117
-	 * This method takes requests for basic filesystem functions (e.g. reading & writing
1118
-	 * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1119
-	 * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1120
-	 */
1121
-	private function basicOperation($operation, $path, $hooks = [], $extraParam = null) {
1122
-		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1123
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1124
-		if (Filesystem::isValidPath($path)
1125
-			and !Filesystem::isFileBlacklisted($path)
1126
-		) {
1127
-			$path = $this->getRelativePath($absolutePath);
1128
-			if ($path == null) {
1129
-				return false;
1130
-			}
1131
-
1132
-			if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1133
-				// always a shared lock during pre-hooks so the hook can read the file
1134
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
1135
-			}
1136
-
1137
-			$run = $this->runHooks($hooks, $path);
1138
-			/** @var \OC\Files\Storage\Storage $storage */
1139
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1140
-			if ($run and $storage) {
1141
-				if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1142
-					try {
1143
-						$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1144
-					} catch (LockedException $e) {
1145
-						// release the shared lock we acquired before quiting
1146
-						$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1147
-						throw $e;
1148
-					}
1149
-				}
1150
-				try {
1151
-					if (!is_null($extraParam)) {
1152
-						$result = $storage->$operation($internalPath, $extraParam);
1153
-					} else {
1154
-						$result = $storage->$operation($internalPath);
1155
-					}
1156
-				} catch (\Exception $e) {
1157
-					if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1158
-						$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1159
-					} else if (in_array('read', $hooks)) {
1160
-						$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1161
-					}
1162
-					throw $e;
1163
-				}
1164
-
1165
-				if ($result && in_array('delete', $hooks) and $result) {
1166
-					$this->removeUpdate($storage, $internalPath);
1167
-				}
1168
-				if ($result && in_array('write', $hooks) and $operation !== 'fopen') {
1169
-					$this->writeUpdate($storage, $internalPath);
1170
-				}
1171
-				if ($result && in_array('touch', $hooks)) {
1172
-					$this->writeUpdate($storage, $internalPath, $extraParam);
1173
-				}
1174
-
1175
-				if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1176
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
1177
-				}
1178
-
1179
-				$unlockLater = false;
1180
-				if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1181
-					$unlockLater = true;
1182
-					// make sure our unlocking callback will still be called if connection is aborted
1183
-					ignore_user_abort(true);
1184
-					$result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1185
-						if (in_array('write', $hooks)) {
1186
-							$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1187
-						} else if (in_array('read', $hooks)) {
1188
-							$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1189
-						}
1190
-					});
1191
-				}
1192
-
1193
-				if ($this->shouldEmitHooks($path) && $result !== false) {
1194
-					if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1195
-						$this->runHooks($hooks, $path, true);
1196
-					}
1197
-				}
1198
-
1199
-				if (!$unlockLater
1200
-					&& (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1201
-				) {
1202
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1203
-				}
1204
-				return $result;
1205
-			} else {
1206
-				$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1207
-			}
1208
-		}
1209
-		return null;
1210
-	}
1211
-
1212
-	/**
1213
-	 * get the path relative to the default root for hook usage
1214
-	 *
1215
-	 * @param string $path
1216
-	 * @return string
1217
-	 */
1218
-	private function getHookPath($path) {
1219
-		if (!Filesystem::getView()) {
1220
-			return $path;
1221
-		}
1222
-		return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
1223
-	}
1224
-
1225
-	private function shouldEmitHooks($path = '') {
1226
-		if ($path && Cache\Scanner::isPartialFile($path)) {
1227
-			return false;
1228
-		}
1229
-		if (!Filesystem::$loaded) {
1230
-			return false;
1231
-		}
1232
-		$defaultRoot = Filesystem::getRoot();
1233
-		if ($defaultRoot === null) {
1234
-			return false;
1235
-		}
1236
-		if ($this->fakeRoot === $defaultRoot) {
1237
-			return true;
1238
-		}
1239
-		$fullPath = $this->getAbsolutePath($path);
1240
-
1241
-		if ($fullPath === $defaultRoot) {
1242
-			return true;
1243
-		}
1244
-
1245
-		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1246
-	}
1247
-
1248
-	/**
1249
-	 * @param string[] $hooks
1250
-	 * @param string $path
1251
-	 * @param bool $post
1252
-	 * @return bool
1253
-	 */
1254
-	private function runHooks($hooks, $path, $post = false) {
1255
-		$relativePath = $path;
1256
-		$path = $this->getHookPath($path);
1257
-		$prefix = ($post) ? 'post_' : '';
1258
-		$run = true;
1259
-		if ($this->shouldEmitHooks($relativePath)) {
1260
-			foreach ($hooks as $hook) {
1261
-				if ($hook != 'read') {
1262
-					\OC_Hook::emit(
1263
-						Filesystem::CLASSNAME,
1264
-						$prefix . $hook,
1265
-						array(
1266
-							Filesystem::signal_param_run => &$run,
1267
-							Filesystem::signal_param_path => $path
1268
-						)
1269
-					);
1270
-				} elseif (!$post) {
1271
-					\OC_Hook::emit(
1272
-						Filesystem::CLASSNAME,
1273
-						$prefix . $hook,
1274
-						array(
1275
-							Filesystem::signal_param_path => $path
1276
-						)
1277
-					);
1278
-				}
1279
-			}
1280
-		}
1281
-		return $run;
1282
-	}
1283
-
1284
-	/**
1285
-	 * check if a file or folder has been updated since $time
1286
-	 *
1287
-	 * @param string $path
1288
-	 * @param int $time
1289
-	 * @return bool
1290
-	 */
1291
-	public function hasUpdated($path, $time) {
1292
-		return $this->basicOperation('hasUpdated', $path, array(), $time);
1293
-	}
1294
-
1295
-	/**
1296
-	 * @param string $ownerId
1297
-	 * @return \OC\User\User
1298
-	 */
1299
-	private function getUserObjectForOwner($ownerId) {
1300
-		$owner = $this->userManager->get($ownerId);
1301
-		if ($owner instanceof IUser) {
1302
-			return $owner;
1303
-		} else {
1304
-			return new User($ownerId, null);
1305
-		}
1306
-	}
1307
-
1308
-	/**
1309
-	 * Get file info from cache
1310
-	 *
1311
-	 * If the file is not in cached it will be scanned
1312
-	 * If the file has changed on storage the cache will be updated
1313
-	 *
1314
-	 * @param \OC\Files\Storage\Storage $storage
1315
-	 * @param string $internalPath
1316
-	 * @param string $relativePath
1317
-	 * @return ICacheEntry|bool
1318
-	 */
1319
-	private function getCacheEntry($storage, $internalPath, $relativePath) {
1320
-		$cache = $storage->getCache($internalPath);
1321
-		$data = $cache->get($internalPath);
1322
-		$watcher = $storage->getWatcher($internalPath);
1323
-
1324
-		try {
1325
-			// if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1326
-			if (!$data || $data['size'] === -1) {
1327
-				if (!$storage->file_exists($internalPath)) {
1328
-					return false;
1329
-				}
1330
-				// don't need to get a lock here since the scanner does it's own locking
1331
-				$scanner = $storage->getScanner($internalPath);
1332
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1333
-				$data = $cache->get($internalPath);
1334
-			} else if (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1335
-				$this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1336
-				$watcher->update($internalPath, $data);
1337
-				$storage->getPropagator()->propagateChange($internalPath, time());
1338
-				$data = $cache->get($internalPath);
1339
-				$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1340
-			}
1341
-		} catch (LockedException $e) {
1342
-			// if the file is locked we just use the old cache info
1343
-		}
1344
-
1345
-		return $data;
1346
-	}
1347
-
1348
-	/**
1349
-	 * get the filesystem info
1350
-	 *
1351
-	 * @param string $path
1352
-	 * @param boolean|string $includeMountPoints true to add mountpoint sizes,
1353
-	 * 'ext' to add only ext storage mount point sizes. Defaults to true.
1354
-	 * defaults to true
1355
-	 * @return \OC\Files\FileInfo|false False if file does not exist
1356
-	 */
1357
-	public function getFileInfo($path, $includeMountPoints = true) {
1358
-		$this->assertPathLength($path);
1359
-		if (!Filesystem::isValidPath($path)) {
1360
-			return false;
1361
-		}
1362
-		if (Cache\Scanner::isPartialFile($path)) {
1363
-			return $this->getPartFileInfo($path);
1364
-		}
1365
-		$relativePath = $path;
1366
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1367
-
1368
-		$mount = Filesystem::getMountManager()->find($path);
1369
-		if (!$mount) {
1370
-			return false;
1371
-		}
1372
-		$storage = $mount->getStorage();
1373
-		$internalPath = $mount->getInternalPath($path);
1374
-		if ($storage) {
1375
-			$data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1376
-
1377
-			if (!$data instanceof ICacheEntry) {
1378
-				return false;
1379
-			}
1380
-
1381
-			if ($mount instanceof MoveableMount && $internalPath === '') {
1382
-				$data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1383
-			}
1384
-
1385
-			$owner = $this->getUserObjectForOwner($storage->getOwner($internalPath));
1386
-			$info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1387
-
1388
-			if ($data and isset($data['fileid'])) {
1389
-				if ($includeMountPoints and $data['mimetype'] === 'httpd/unix-directory') {
1390
-					//add the sizes of other mount points to the folder
1391
-					$extOnly = ($includeMountPoints === 'ext');
1392
-					$mounts = Filesystem::getMountManager()->findIn($path);
1393
-					$info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1394
-						$subStorage = $mount->getStorage();
1395
-						return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1396
-					}));
1397
-				}
1398
-			}
1399
-
1400
-			return $info;
1401
-		}
1402
-
1403
-		return false;
1404
-	}
1405
-
1406
-	/**
1407
-	 * get the content of a directory
1408
-	 *
1409
-	 * @param string $directory path under datadirectory
1410
-	 * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1411
-	 * @return FileInfo[]
1412
-	 */
1413
-	public function getDirectoryContent($directory, $mimetype_filter = '') {
1414
-		$this->assertPathLength($directory);
1415
-		if (!Filesystem::isValidPath($directory)) {
1416
-			return [];
1417
-		}
1418
-		$path = $this->getAbsolutePath($directory);
1419
-		$path = Filesystem::normalizePath($path);
1420
-		$mount = $this->getMount($directory);
1421
-		if (!$mount) {
1422
-			return [];
1423
-		}
1424
-		$storage = $mount->getStorage();
1425
-		$internalPath = $mount->getInternalPath($path);
1426
-		if ($storage) {
1427
-			$cache = $storage->getCache($internalPath);
1428
-			$user = \OC_User::getUser();
1429
-
1430
-			$data = $this->getCacheEntry($storage, $internalPath, $directory);
1431
-
1432
-			if (!$data instanceof ICacheEntry || !isset($data['fileid']) || !($data->getPermissions() && Constants::PERMISSION_READ)) {
1433
-				return [];
1434
-			}
1435
-
1436
-			$folderId = $data['fileid'];
1437
-			$contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1438
-
1439
-			$sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1440
-
1441
-			$fileNames = array_map(function(ICacheEntry $content) {
1442
-				return $content->getName();
1443
-			}, $contents);
1444
-			/**
1445
-			 * @var \OC\Files\FileInfo[] $fileInfos
1446
-			 */
1447
-			$fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1448
-				if ($sharingDisabled) {
1449
-					$content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1450
-				}
1451
-				$owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1452
-				return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1453
-			}, $contents);
1454
-			$files = array_combine($fileNames, $fileInfos);
1455
-
1456
-			//add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1457
-			$mounts = Filesystem::getMountManager()->findIn($path);
1458
-			$dirLength = strlen($path);
1459
-			foreach ($mounts as $mount) {
1460
-				$mountPoint = $mount->getMountPoint();
1461
-				$subStorage = $mount->getStorage();
1462
-				if ($subStorage) {
1463
-					$subCache = $subStorage->getCache('');
1464
-
1465
-					$rootEntry = $subCache->get('');
1466
-					if (!$rootEntry) {
1467
-						$subScanner = $subStorage->getScanner('');
1468
-						try {
1469
-							$subScanner->scanFile('');
1470
-						} catch (\OCP\Files\StorageNotAvailableException $e) {
1471
-							continue;
1472
-						} catch (\OCP\Files\StorageInvalidException $e) {
1473
-							continue;
1474
-						} catch (\Exception $e) {
1475
-							// sometimes when the storage is not available it can be any exception
1476
-							\OCP\Util::writeLog(
1477
-								'core',
1478
-								'Exception while scanning storage "' . $subStorage->getId() . '": ' .
1479
-								get_class($e) . ': ' . $e->getMessage(),
1480
-								\OCP\Util::ERROR
1481
-							);
1482
-							continue;
1483
-						}
1484
-						$rootEntry = $subCache->get('');
1485
-					}
1486
-
1487
-					if ($rootEntry && ($rootEntry->getPermissions() && Constants::PERMISSION_READ)) {
1488
-						$relativePath = trim(substr($mountPoint, $dirLength), '/');
1489
-						if ($pos = strpos($relativePath, '/')) {
1490
-							//mountpoint inside subfolder add size to the correct folder
1491
-							$entryName = substr($relativePath, 0, $pos);
1492
-							foreach ($files as &$entry) {
1493
-								if ($entry->getName() === $entryName) {
1494
-									$entry->addSubEntry($rootEntry, $mountPoint);
1495
-								}
1496
-							}
1497
-						} else { //mountpoint in this folder, add an entry for it
1498
-							$rootEntry['name'] = $relativePath;
1499
-							$rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1500
-							$permissions = $rootEntry['permissions'];
1501
-							// do not allow renaming/deleting the mount point if they are not shared files/folders
1502
-							// for shared files/folders we use the permissions given by the owner
1503
-							if ($mount instanceof MoveableMount) {
1504
-								$rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1505
-							} else {
1506
-								$rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1507
-							}
1508
-
1509
-							$rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1510
-
1511
-							// if sharing was disabled for the user we remove the share permissions
1512
-							if (\OCP\Util::isSharingDisabledForUser()) {
1513
-								$rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1514
-							}
1515
-
1516
-							$owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1517
-							$files[$rootEntry->getName()] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1518
-						}
1519
-					}
1520
-				}
1521
-			}
1522
-
1523
-			if ($mimetype_filter) {
1524
-				$files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1525
-					if (strpos($mimetype_filter, '/')) {
1526
-						return $file->getMimetype() === $mimetype_filter;
1527
-					} else {
1528
-						return $file->getMimePart() === $mimetype_filter;
1529
-					}
1530
-				});
1531
-			}
1532
-
1533
-			return array_values($files);
1534
-		} else {
1535
-			return [];
1536
-		}
1537
-	}
1538
-
1539
-	/**
1540
-	 * change file metadata
1541
-	 *
1542
-	 * @param string $path
1543
-	 * @param array|\OCP\Files\FileInfo $data
1544
-	 * @return int
1545
-	 *
1546
-	 * returns the fileid of the updated file
1547
-	 */
1548
-	public function putFileInfo($path, $data) {
1549
-		$this->assertPathLength($path);
1550
-		if ($data instanceof FileInfo) {
1551
-			$data = $data->getData();
1552
-		}
1553
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1554
-		/**
1555
-		 * @var \OC\Files\Storage\Storage $storage
1556
-		 * @var string $internalPath
1557
-		 */
1558
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
1559
-		if ($storage) {
1560
-			$cache = $storage->getCache($path);
1561
-
1562
-			if (!$cache->inCache($internalPath)) {
1563
-				$scanner = $storage->getScanner($internalPath);
1564
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1565
-			}
1566
-
1567
-			return $cache->put($internalPath, $data);
1568
-		} else {
1569
-			return -1;
1570
-		}
1571
-	}
1572
-
1573
-	/**
1574
-	 * search for files with the name matching $query
1575
-	 *
1576
-	 * @param string $query
1577
-	 * @return FileInfo[]
1578
-	 */
1579
-	public function search($query) {
1580
-		return $this->searchCommon('search', array('%' . $query . '%'));
1581
-	}
1582
-
1583
-	/**
1584
-	 * search for files with the name matching $query
1585
-	 *
1586
-	 * @param string $query
1587
-	 * @return FileInfo[]
1588
-	 */
1589
-	public function searchRaw($query) {
1590
-		return $this->searchCommon('search', array($query));
1591
-	}
1592
-
1593
-	/**
1594
-	 * search for files by mimetype
1595
-	 *
1596
-	 * @param string $mimetype
1597
-	 * @return FileInfo[]
1598
-	 */
1599
-	public function searchByMime($mimetype) {
1600
-		return $this->searchCommon('searchByMime', array($mimetype));
1601
-	}
1602
-
1603
-	/**
1604
-	 * search for files by tag
1605
-	 *
1606
-	 * @param string|int $tag name or tag id
1607
-	 * @param string $userId owner of the tags
1608
-	 * @return FileInfo[]
1609
-	 */
1610
-	public function searchByTag($tag, $userId) {
1611
-		return $this->searchCommon('searchByTag', array($tag, $userId));
1612
-	}
1613
-
1614
-	/**
1615
-	 * @param string $method cache method
1616
-	 * @param array $args
1617
-	 * @return FileInfo[]
1618
-	 */
1619
-	private function searchCommon($method, $args) {
1620
-		$files = array();
1621
-		$rootLength = strlen($this->fakeRoot);
1622
-
1623
-		$mount = $this->getMount('');
1624
-		$mountPoint = $mount->getMountPoint();
1625
-		$storage = $mount->getStorage();
1626
-		if ($storage) {
1627
-			$cache = $storage->getCache('');
1628
-
1629
-			$results = call_user_func_array(array($cache, $method), $args);
1630
-			foreach ($results as $result) {
1631
-				if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1632
-					$internalPath = $result['path'];
1633
-					$path = $mountPoint . $result['path'];
1634
-					$result['path'] = substr($mountPoint . $result['path'], $rootLength);
1635
-					$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1636
-					$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1637
-				}
1638
-			}
1639
-
1640
-			$mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1641
-			foreach ($mounts as $mount) {
1642
-				$mountPoint = $mount->getMountPoint();
1643
-				$storage = $mount->getStorage();
1644
-				if ($storage) {
1645
-					$cache = $storage->getCache('');
1646
-
1647
-					$relativeMountPoint = substr($mountPoint, $rootLength);
1648
-					$results = call_user_func_array(array($cache, $method), $args);
1649
-					if ($results) {
1650
-						foreach ($results as $result) {
1651
-							$internalPath = $result['path'];
1652
-							$result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1653
-							$path = rtrim($mountPoint . $internalPath, '/');
1654
-							$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1655
-							$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1656
-						}
1657
-					}
1658
-				}
1659
-			}
1660
-		}
1661
-		return $files;
1662
-	}
1663
-
1664
-	/**
1665
-	 * Get the owner for a file or folder
1666
-	 *
1667
-	 * @param string $path
1668
-	 * @return string the user id of the owner
1669
-	 * @throws NotFoundException
1670
-	 */
1671
-	public function getOwner($path) {
1672
-		$info = $this->getFileInfo($path);
1673
-		if (!$info) {
1674
-			throw new NotFoundException($path . ' not found while trying to get owner');
1675
-		}
1676
-		return $info->getOwner()->getUID();
1677
-	}
1678
-
1679
-	/**
1680
-	 * get the ETag for a file or folder
1681
-	 *
1682
-	 * @param string $path
1683
-	 * @return string
1684
-	 */
1685
-	public function getETag($path) {
1686
-		/**
1687
-		 * @var Storage\Storage $storage
1688
-		 * @var string $internalPath
1689
-		 */
1690
-		list($storage, $internalPath) = $this->resolvePath($path);
1691
-		if ($storage) {
1692
-			return $storage->getETag($internalPath);
1693
-		} else {
1694
-			return null;
1695
-		}
1696
-	}
1697
-
1698
-	/**
1699
-	 * Get the path of a file by id, relative to the view
1700
-	 *
1701
-	 * Note that the resulting path is not guarantied to be unique for the id, multiple paths can point to the same file
1702
-	 *
1703
-	 * @param int $id
1704
-	 * @throws NotFoundException
1705
-	 * @return string
1706
-	 */
1707
-	public function getPath($id) {
1708
-		$id = (int)$id;
1709
-		$manager = Filesystem::getMountManager();
1710
-		$mounts = $manager->findIn($this->fakeRoot);
1711
-		$mounts[] = $manager->find($this->fakeRoot);
1712
-		// reverse the array so we start with the storage this view is in
1713
-		// which is the most likely to contain the file we're looking for
1714
-		$mounts = array_reverse($mounts);
1715
-		foreach ($mounts as $mount) {
1716
-			/**
1717
-			 * @var \OC\Files\Mount\MountPoint $mount
1718
-			 */
1719
-			if ($mount->getStorage()) {
1720
-				$cache = $mount->getStorage()->getCache();
1721
-				$internalPath = $cache->getPathById($id);
1722
-				if (is_string($internalPath)) {
1723
-					$fullPath = $mount->getMountPoint() . $internalPath;
1724
-					if (!is_null($path = $this->getRelativePath($fullPath))) {
1725
-						return $path;
1726
-					}
1727
-				}
1728
-			}
1729
-		}
1730
-		throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1731
-	}
1732
-
1733
-	/**
1734
-	 * @param string $path
1735
-	 * @throws InvalidPathException
1736
-	 */
1737
-	private function assertPathLength($path) {
1738
-		$maxLen = min(PHP_MAXPATHLEN, 4000);
1739
-		// Check for the string length - performed using isset() instead of strlen()
1740
-		// because isset() is about 5x-40x faster.
1741
-		if (isset($path[$maxLen])) {
1742
-			$pathLen = strlen($path);
1743
-			throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1744
-		}
1745
-	}
1746
-
1747
-	/**
1748
-	 * check if it is allowed to move a mount point to a given target.
1749
-	 * It is not allowed to move a mount point into a different mount point or
1750
-	 * into an already shared folder
1751
-	 *
1752
-	 * @param string $target path
1753
-	 * @return boolean
1754
-	 */
1755
-	private function isTargetAllowed($target) {
1756
-
1757
-		list($targetStorage, $targetInternalPath) = \OC\Files\Filesystem::resolvePath($target);
1758
-		if (!$targetStorage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
1759
-			\OCP\Util::writeLog('files',
1760
-				'It is not allowed to move one mount point into another one',
1761
-				\OCP\Util::DEBUG);
1762
-			return false;
1763
-		}
1764
-
1765
-		// note: cannot use the view because the target is already locked
1766
-		$fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1767
-		if ($fileId === -1) {
1768
-			// target might not exist, need to check parent instead
1769
-			$fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1770
-		}
1771
-
1772
-		// check if any of the parents were shared by the current owner (include collections)
1773
-		$shares = \OCP\Share::getItemShared(
1774
-			'folder',
1775
-			$fileId,
1776
-			\OCP\Share::FORMAT_NONE,
1777
-			null,
1778
-			true
1779
-		);
1780
-
1781
-		if (count($shares) > 0) {
1782
-			\OCP\Util::writeLog('files',
1783
-				'It is not allowed to move one mount point into a shared folder',
1784
-				\OCP\Util::DEBUG);
1785
-			return false;
1786
-		}
1787
-
1788
-		return true;
1789
-	}
1790
-
1791
-	/**
1792
-	 * Get a fileinfo object for files that are ignored in the cache (part files)
1793
-	 *
1794
-	 * @param string $path
1795
-	 * @return \OCP\Files\FileInfo
1796
-	 */
1797
-	private function getPartFileInfo($path) {
1798
-		$mount = $this->getMount($path);
1799
-		$storage = $mount->getStorage();
1800
-		$internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1801
-		$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1802
-		return new FileInfo(
1803
-			$this->getAbsolutePath($path),
1804
-			$storage,
1805
-			$internalPath,
1806
-			[
1807
-				'fileid' => null,
1808
-				'mimetype' => $storage->getMimeType($internalPath),
1809
-				'name' => basename($path),
1810
-				'etag' => null,
1811
-				'size' => $storage->filesize($internalPath),
1812
-				'mtime' => $storage->filemtime($internalPath),
1813
-				'encrypted' => false,
1814
-				'permissions' => \OCP\Constants::PERMISSION_ALL
1815
-			],
1816
-			$mount,
1817
-			$owner
1818
-		);
1819
-	}
1820
-
1821
-	/**
1822
-	 * @param string $path
1823
-	 * @param string $fileName
1824
-	 * @throws InvalidPathException
1825
-	 */
1826
-	public function verifyPath($path, $fileName) {
1827
-		try {
1828
-			/** @type \OCP\Files\Storage $storage */
1829
-			list($storage, $internalPath) = $this->resolvePath($path);
1830
-			$storage->verifyPath($internalPath, $fileName);
1831
-		} catch (ReservedWordException $ex) {
1832
-			$l = \OC::$server->getL10N('lib');
1833
-			throw new InvalidPathException($l->t('File name is a reserved word'));
1834
-		} catch (InvalidCharacterInPathException $ex) {
1835
-			$l = \OC::$server->getL10N('lib');
1836
-			throw new InvalidPathException($l->t('File name contains at least one invalid character'));
1837
-		} catch (FileNameTooLongException $ex) {
1838
-			$l = \OC::$server->getL10N('lib');
1839
-			throw new InvalidPathException($l->t('File name is too long'));
1840
-		} catch (InvalidDirectoryException $ex) {
1841
-			$l = \OC::$server->getL10N('lib');
1842
-			throw new InvalidPathException($l->t('Dot files are not allowed'));
1843
-		} catch (EmptyFileNameException $ex) {
1844
-			$l = \OC::$server->getL10N('lib');
1845
-			throw new InvalidPathException($l->t('Empty filename is not allowed'));
1846
-		}
1847
-	}
1848
-
1849
-	/**
1850
-	 * get all parent folders of $path
1851
-	 *
1852
-	 * @param string $path
1853
-	 * @return string[]
1854
-	 */
1855
-	private function getParents($path) {
1856
-		$path = trim($path, '/');
1857
-		if (!$path) {
1858
-			return [];
1859
-		}
1860
-
1861
-		$parts = explode('/', $path);
1862
-
1863
-		// remove the single file
1864
-		array_pop($parts);
1865
-		$result = array('/');
1866
-		$resultPath = '';
1867
-		foreach ($parts as $part) {
1868
-			if ($part) {
1869
-				$resultPath .= '/' . $part;
1870
-				$result[] = $resultPath;
1871
-			}
1872
-		}
1873
-		return $result;
1874
-	}
1875
-
1876
-	/**
1877
-	 * Returns the mount point for which to lock
1878
-	 *
1879
-	 * @param string $absolutePath absolute path
1880
-	 * @param bool $useParentMount true to return parent mount instead of whatever
1881
-	 * is mounted directly on the given path, false otherwise
1882
-	 * @return \OC\Files\Mount\MountPoint mount point for which to apply locks
1883
-	 */
1884
-	private function getMountForLock($absolutePath, $useParentMount = false) {
1885
-		$results = [];
1886
-		$mount = Filesystem::getMountManager()->find($absolutePath);
1887
-		if (!$mount) {
1888
-			return $results;
1889
-		}
1890
-
1891
-		if ($useParentMount) {
1892
-			// find out if something is mounted directly on the path
1893
-			$internalPath = $mount->getInternalPath($absolutePath);
1894
-			if ($internalPath === '') {
1895
-				// resolve the parent mount instead
1896
-				$mount = Filesystem::getMountManager()->find(dirname($absolutePath));
1897
-			}
1898
-		}
1899
-
1900
-		return $mount;
1901
-	}
1902
-
1903
-	/**
1904
-	 * Lock the given path
1905
-	 *
1906
-	 * @param string $path the path of the file to lock, relative to the view
1907
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1908
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1909
-	 *
1910
-	 * @return bool False if the path is excluded from locking, true otherwise
1911
-	 * @throws \OCP\Lock\LockedException if the path is already locked
1912
-	 */
1913
-	private function lockPath($path, $type, $lockMountPoint = false) {
1914
-		$absolutePath = $this->getAbsolutePath($path);
1915
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1916
-		if (!$this->shouldLockFile($absolutePath)) {
1917
-			return false;
1918
-		}
1919
-
1920
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1921
-		if ($mount) {
1922
-			try {
1923
-				$storage = $mount->getStorage();
1924
-				if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1925
-					$storage->acquireLock(
1926
-						$mount->getInternalPath($absolutePath),
1927
-						$type,
1928
-						$this->lockingProvider
1929
-					);
1930
-				}
1931
-			} catch (\OCP\Lock\LockedException $e) {
1932
-				// rethrow with the a human-readable path
1933
-				throw new \OCP\Lock\LockedException(
1934
-					$this->getPathRelativeToFiles($absolutePath),
1935
-					$e
1936
-				);
1937
-			}
1938
-		}
1939
-
1940
-		return true;
1941
-	}
1942
-
1943
-	/**
1944
-	 * Change the lock type
1945
-	 *
1946
-	 * @param string $path the path of the file to lock, relative to the view
1947
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1948
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1949
-	 *
1950
-	 * @return bool False if the path is excluded from locking, true otherwise
1951
-	 * @throws \OCP\Lock\LockedException if the path is already locked
1952
-	 */
1953
-	public function changeLock($path, $type, $lockMountPoint = false) {
1954
-		$path = Filesystem::normalizePath($path);
1955
-		$absolutePath = $this->getAbsolutePath($path);
1956
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1957
-		if (!$this->shouldLockFile($absolutePath)) {
1958
-			return false;
1959
-		}
1960
-
1961
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1962
-		if ($mount) {
1963
-			try {
1964
-				$storage = $mount->getStorage();
1965
-				if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1966
-					$storage->changeLock(
1967
-						$mount->getInternalPath($absolutePath),
1968
-						$type,
1969
-						$this->lockingProvider
1970
-					);
1971
-				}
1972
-			} catch (\OCP\Lock\LockedException $e) {
1973
-				try {
1974
-					// rethrow with the a human-readable path
1975
-					throw new \OCP\Lock\LockedException(
1976
-						$this->getPathRelativeToFiles($absolutePath),
1977
-						$e
1978
-					);
1979
-				} catch (\InvalidArgumentException $e) {
1980
-					throw new \OCP\Lock\LockedException(
1981
-						$absolutePath,
1982
-						$e
1983
-					);
1984
-				}
1985
-			}
1986
-		}
1987
-
1988
-		return true;
1989
-	}
1990
-
1991
-	/**
1992
-	 * Unlock the given path
1993
-	 *
1994
-	 * @param string $path the path of the file to unlock, relative to the view
1995
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1996
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1997
-	 *
1998
-	 * @return bool False if the path is excluded from locking, true otherwise
1999
-	 */
2000
-	private function unlockPath($path, $type, $lockMountPoint = false) {
2001
-		$absolutePath = $this->getAbsolutePath($path);
2002
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2003
-		if (!$this->shouldLockFile($absolutePath)) {
2004
-			return false;
2005
-		}
2006
-
2007
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2008
-		if ($mount) {
2009
-			$storage = $mount->getStorage();
2010
-			if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2011
-				$storage->releaseLock(
2012
-					$mount->getInternalPath($absolutePath),
2013
-					$type,
2014
-					$this->lockingProvider
2015
-				);
2016
-			}
2017
-		}
2018
-
2019
-		return true;
2020
-	}
2021
-
2022
-	/**
2023
-	 * Lock a path and all its parents up to the root of the view
2024
-	 *
2025
-	 * @param string $path the path of the file to lock relative to the view
2026
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2027
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2028
-	 *
2029
-	 * @return bool False if the path is excluded from locking, true otherwise
2030
-	 */
2031
-	public function lockFile($path, $type, $lockMountPoint = false) {
2032
-		$absolutePath = $this->getAbsolutePath($path);
2033
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2034
-		if (!$this->shouldLockFile($absolutePath)) {
2035
-			return false;
2036
-		}
2037
-
2038
-		$this->lockPath($path, $type, $lockMountPoint);
2039
-
2040
-		$parents = $this->getParents($path);
2041
-		foreach ($parents as $parent) {
2042
-			$this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2043
-		}
2044
-
2045
-		return true;
2046
-	}
2047
-
2048
-	/**
2049
-	 * Unlock a path and all its parents up to the root of the view
2050
-	 *
2051
-	 * @param string $path the path of the file to lock relative to the view
2052
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2053
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2054
-	 *
2055
-	 * @return bool False if the path is excluded from locking, true otherwise
2056
-	 */
2057
-	public function unlockFile($path, $type, $lockMountPoint = false) {
2058
-		$absolutePath = $this->getAbsolutePath($path);
2059
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2060
-		if (!$this->shouldLockFile($absolutePath)) {
2061
-			return false;
2062
-		}
2063
-
2064
-		$this->unlockPath($path, $type, $lockMountPoint);
2065
-
2066
-		$parents = $this->getParents($path);
2067
-		foreach ($parents as $parent) {
2068
-			$this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2069
-		}
2070
-
2071
-		return true;
2072
-	}
2073
-
2074
-	/**
2075
-	 * Only lock files in data/user/files/
2076
-	 *
2077
-	 * @param string $path Absolute path to the file/folder we try to (un)lock
2078
-	 * @return bool
2079
-	 */
2080
-	protected function shouldLockFile($path) {
2081
-		$path = Filesystem::normalizePath($path);
2082
-
2083
-		$pathSegments = explode('/', $path);
2084
-		if (isset($pathSegments[2])) {
2085
-			// E.g.: /username/files/path-to-file
2086
-			return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2087
-		}
2088
-
2089
-		return strpos($path, '/appdata_') !== 0;
2090
-	}
2091
-
2092
-	/**
2093
-	 * Shortens the given absolute path to be relative to
2094
-	 * "$user/files".
2095
-	 *
2096
-	 * @param string $absolutePath absolute path which is under "files"
2097
-	 *
2098
-	 * @return string path relative to "files" with trimmed slashes or null
2099
-	 * if the path was NOT relative to files
2100
-	 *
2101
-	 * @throws \InvalidArgumentException if the given path was not under "files"
2102
-	 * @since 8.1.0
2103
-	 */
2104
-	public function getPathRelativeToFiles($absolutePath) {
2105
-		$path = Filesystem::normalizePath($absolutePath);
2106
-		$parts = explode('/', trim($path, '/'), 3);
2107
-		// "$user", "files", "path/to/dir"
2108
-		if (!isset($parts[1]) || $parts[1] !== 'files') {
2109
-			$this->logger->error(
2110
-				'$absolutePath must be relative to "files", value is "%s"',
2111
-				[
2112
-					$absolutePath
2113
-				]
2114
-			);
2115
-			throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2116
-		}
2117
-		if (isset($parts[2])) {
2118
-			return $parts[2];
2119
-		}
2120
-		return '';
2121
-	}
2122
-
2123
-	/**
2124
-	 * @param string $filename
2125
-	 * @return array
2126
-	 * @throws \OC\User\NoUserException
2127
-	 * @throws NotFoundException
2128
-	 */
2129
-	public function getUidAndFilename($filename) {
2130
-		$info = $this->getFileInfo($filename);
2131
-		if (!$info instanceof \OCP\Files\FileInfo) {
2132
-			throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2133
-		}
2134
-		$uid = $info->getOwner()->getUID();
2135
-		if ($uid != \OCP\User::getUser()) {
2136
-			Filesystem::initMountPoints($uid);
2137
-			$ownerView = new View('/' . $uid . '/files');
2138
-			try {
2139
-				$filename = $ownerView->getPath($info['fileid']);
2140
-			} catch (NotFoundException $e) {
2141
-				throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2142
-			}
2143
-		}
2144
-		return [$uid, $filename];
2145
-	}
2146
-
2147
-	/**
2148
-	 * Creates parent non-existing folders
2149
-	 *
2150
-	 * @param string $filePath
2151
-	 * @return bool
2152
-	 */
2153
-	private function createParentDirectories($filePath) {
2154
-		$directoryParts = explode('/', $filePath);
2155
-		$directoryParts = array_filter($directoryParts);
2156
-		foreach ($directoryParts as $key => $part) {
2157
-			$currentPathElements = array_slice($directoryParts, 0, $key);
2158
-			$currentPath = '/' . implode('/', $currentPathElements);
2159
-			if ($this->is_file($currentPath)) {
2160
-				return false;
2161
-			}
2162
-			if (!$this->file_exists($currentPath)) {
2163
-				$this->mkdir($currentPath);
2164
-			}
2165
-		}
2166
-
2167
-		return true;
2168
-	}
83
+    /** @var string */
84
+    private $fakeRoot = '';
85
+
86
+    /**
87
+     * @var \OCP\Lock\ILockingProvider
88
+     */
89
+    protected $lockingProvider;
90
+
91
+    private $lockingEnabled;
92
+
93
+    private $updaterEnabled = true;
94
+
95
+    /** @var \OC\User\Manager */
96
+    private $userManager;
97
+
98
+    /** @var \OCP\ILogger */
99
+    private $logger;
100
+
101
+    /**
102
+     * @param string $root
103
+     * @throws \Exception If $root contains an invalid path
104
+     */
105
+    public function __construct($root = '') {
106
+        if (is_null($root)) {
107
+            throw new \InvalidArgumentException('Root can\'t be null');
108
+        }
109
+        if (!Filesystem::isValidPath($root)) {
110
+            throw new \Exception();
111
+        }
112
+
113
+        $this->fakeRoot = $root;
114
+        $this->lockingProvider = \OC::$server->getLockingProvider();
115
+        $this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
116
+        $this->userManager = \OC::$server->getUserManager();
117
+        $this->logger = \OC::$server->getLogger();
118
+    }
119
+
120
+    public function getAbsolutePath($path = '/') {
121
+        if ($path === null) {
122
+            return null;
123
+        }
124
+        $this->assertPathLength($path);
125
+        if ($path === '') {
126
+            $path = '/';
127
+        }
128
+        if ($path[0] !== '/') {
129
+            $path = '/' . $path;
130
+        }
131
+        return $this->fakeRoot . $path;
132
+    }
133
+
134
+    /**
135
+     * change the root to a fake root
136
+     *
137
+     * @param string $fakeRoot
138
+     * @return boolean|null
139
+     */
140
+    public function chroot($fakeRoot) {
141
+        if (!$fakeRoot == '') {
142
+            if ($fakeRoot[0] !== '/') {
143
+                $fakeRoot = '/' . $fakeRoot;
144
+            }
145
+        }
146
+        $this->fakeRoot = $fakeRoot;
147
+    }
148
+
149
+    /**
150
+     * get the fake root
151
+     *
152
+     * @return string
153
+     */
154
+    public function getRoot() {
155
+        return $this->fakeRoot;
156
+    }
157
+
158
+    /**
159
+     * get path relative to the root of the view
160
+     *
161
+     * @param string $path
162
+     * @return string
163
+     */
164
+    public function getRelativePath($path) {
165
+        $this->assertPathLength($path);
166
+        if ($this->fakeRoot == '') {
167
+            return $path;
168
+        }
169
+
170
+        if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
171
+            return '/';
172
+        }
173
+
174
+        // missing slashes can cause wrong matches!
175
+        $root = rtrim($this->fakeRoot, '/') . '/';
176
+
177
+        if (strpos($path, $root) !== 0) {
178
+            return null;
179
+        } else {
180
+            $path = substr($path, strlen($this->fakeRoot));
181
+            if (strlen($path) === 0) {
182
+                return '/';
183
+            } else {
184
+                return $path;
185
+            }
186
+        }
187
+    }
188
+
189
+    /**
190
+     * get the mountpoint of the storage object for a path
191
+     * ( note: because a storage is not always mounted inside the fakeroot, the
192
+     * returned mountpoint is relative to the absolute root of the filesystem
193
+     * and does not take the chroot into account )
194
+     *
195
+     * @param string $path
196
+     * @return string
197
+     */
198
+    public function getMountPoint($path) {
199
+        return Filesystem::getMountPoint($this->getAbsolutePath($path));
200
+    }
201
+
202
+    /**
203
+     * get the mountpoint of the storage object for a path
204
+     * ( note: because a storage is not always mounted inside the fakeroot, the
205
+     * returned mountpoint is relative to the absolute root of the filesystem
206
+     * and does not take the chroot into account )
207
+     *
208
+     * @param string $path
209
+     * @return \OCP\Files\Mount\IMountPoint
210
+     */
211
+    public function getMount($path) {
212
+        return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
213
+    }
214
+
215
+    /**
216
+     * resolve a path to a storage and internal path
217
+     *
218
+     * @param string $path
219
+     * @return array an array consisting of the storage and the internal path
220
+     */
221
+    public function resolvePath($path) {
222
+        $a = $this->getAbsolutePath($path);
223
+        $p = Filesystem::normalizePath($a);
224
+        return Filesystem::resolvePath($p);
225
+    }
226
+
227
+    /**
228
+     * return the path to a local version of the file
229
+     * we need this because we can't know if a file is stored local or not from
230
+     * outside the filestorage and for some purposes a local file is needed
231
+     *
232
+     * @param string $path
233
+     * @return string
234
+     */
235
+    public function getLocalFile($path) {
236
+        $parent = substr($path, 0, strrpos($path, '/'));
237
+        $path = $this->getAbsolutePath($path);
238
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
239
+        if (Filesystem::isValidPath($parent) and $storage) {
240
+            return $storage->getLocalFile($internalPath);
241
+        } else {
242
+            return null;
243
+        }
244
+    }
245
+
246
+    /**
247
+     * @param string $path
248
+     * @return string
249
+     */
250
+    public function getLocalFolder($path) {
251
+        $parent = substr($path, 0, strrpos($path, '/'));
252
+        $path = $this->getAbsolutePath($path);
253
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
254
+        if (Filesystem::isValidPath($parent) and $storage) {
255
+            return $storage->getLocalFolder($internalPath);
256
+        } else {
257
+            return null;
258
+        }
259
+    }
260
+
261
+    /**
262
+     * the following functions operate with arguments and return values identical
263
+     * to those of their PHP built-in equivalents. Mostly they are merely wrappers
264
+     * for \OC\Files\Storage\Storage via basicOperation().
265
+     */
266
+    public function mkdir($path) {
267
+        return $this->basicOperation('mkdir', $path, array('create', 'write'));
268
+    }
269
+
270
+    /**
271
+     * remove mount point
272
+     *
273
+     * @param \OC\Files\Mount\MoveableMount $mount
274
+     * @param string $path relative to data/
275
+     * @return boolean
276
+     */
277
+    protected function removeMount($mount, $path) {
278
+        if ($mount instanceof MoveableMount) {
279
+            // cut of /user/files to get the relative path to data/user/files
280
+            $pathParts = explode('/', $path, 4);
281
+            $relPath = '/' . $pathParts[3];
282
+            $this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
283
+            \OC_Hook::emit(
284
+                Filesystem::CLASSNAME, "umount",
285
+                array(Filesystem::signal_param_path => $relPath)
286
+            );
287
+            $this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
288
+            $result = $mount->removeMount();
289
+            $this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
290
+            if ($result) {
291
+                \OC_Hook::emit(
292
+                    Filesystem::CLASSNAME, "post_umount",
293
+                    array(Filesystem::signal_param_path => $relPath)
294
+                );
295
+            }
296
+            $this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
297
+            return $result;
298
+        } else {
299
+            // do not allow deleting the storage's root / the mount point
300
+            // because for some storages it might delete the whole contents
301
+            // but isn't supposed to work that way
302
+            return false;
303
+        }
304
+    }
305
+
306
+    public function disableCacheUpdate() {
307
+        $this->updaterEnabled = false;
308
+    }
309
+
310
+    public function enableCacheUpdate() {
311
+        $this->updaterEnabled = true;
312
+    }
313
+
314
+    protected function writeUpdate(Storage $storage, $internalPath, $time = null) {
315
+        if ($this->updaterEnabled) {
316
+            if (is_null($time)) {
317
+                $time = time();
318
+            }
319
+            $storage->getUpdater()->update($internalPath, $time);
320
+        }
321
+    }
322
+
323
+    protected function removeUpdate(Storage $storage, $internalPath) {
324
+        if ($this->updaterEnabled) {
325
+            $storage->getUpdater()->remove($internalPath);
326
+        }
327
+    }
328
+
329
+    protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, $sourceInternalPath, $targetInternalPath) {
330
+        if ($this->updaterEnabled) {
331
+            $targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
332
+        }
333
+    }
334
+
335
+    /**
336
+     * @param string $path
337
+     * @return bool|mixed
338
+     */
339
+    public function rmdir($path) {
340
+        $absolutePath = $this->getAbsolutePath($path);
341
+        $mount = Filesystem::getMountManager()->find($absolutePath);
342
+        if ($mount->getInternalPath($absolutePath) === '') {
343
+            return $this->removeMount($mount, $absolutePath);
344
+        }
345
+        if ($this->is_dir($path)) {
346
+            $result = $this->basicOperation('rmdir', $path, array('delete'));
347
+        } else {
348
+            $result = false;
349
+        }
350
+
351
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
352
+            $storage = $mount->getStorage();
353
+            $internalPath = $mount->getInternalPath($absolutePath);
354
+            $storage->getUpdater()->remove($internalPath);
355
+        }
356
+        return $result;
357
+    }
358
+
359
+    /**
360
+     * @param string $path
361
+     * @return resource
362
+     */
363
+    public function opendir($path) {
364
+        return $this->basicOperation('opendir', $path, array('read'));
365
+    }
366
+
367
+    /**
368
+     * @param string $path
369
+     * @return bool|mixed
370
+     */
371
+    public function is_dir($path) {
372
+        if ($path == '/') {
373
+            return true;
374
+        }
375
+        return $this->basicOperation('is_dir', $path);
376
+    }
377
+
378
+    /**
379
+     * @param string $path
380
+     * @return bool|mixed
381
+     */
382
+    public function is_file($path) {
383
+        if ($path == '/') {
384
+            return false;
385
+        }
386
+        return $this->basicOperation('is_file', $path);
387
+    }
388
+
389
+    /**
390
+     * @param string $path
391
+     * @return mixed
392
+     */
393
+    public function stat($path) {
394
+        return $this->basicOperation('stat', $path);
395
+    }
396
+
397
+    /**
398
+     * @param string $path
399
+     * @return mixed
400
+     */
401
+    public function filetype($path) {
402
+        return $this->basicOperation('filetype', $path);
403
+    }
404
+
405
+    /**
406
+     * @param string $path
407
+     * @return mixed
408
+     */
409
+    public function filesize($path) {
410
+        return $this->basicOperation('filesize', $path);
411
+    }
412
+
413
+    /**
414
+     * @param string $path
415
+     * @return bool|mixed
416
+     * @throws \OCP\Files\InvalidPathException
417
+     */
418
+    public function readfile($path) {
419
+        $this->assertPathLength($path);
420
+        @ob_end_clean();
421
+        $handle = $this->fopen($path, 'rb');
422
+        if ($handle) {
423
+            $chunkSize = 8192; // 8 kB chunks
424
+            while (!feof($handle)) {
425
+                echo fread($handle, $chunkSize);
426
+                flush();
427
+            }
428
+            fclose($handle);
429
+            $size = $this->filesize($path);
430
+            return $size;
431
+        }
432
+        return false;
433
+    }
434
+
435
+    /**
436
+     * @param string $path
437
+     * @param int $from
438
+     * @param int $to
439
+     * @return bool|mixed
440
+     * @throws \OCP\Files\InvalidPathException
441
+     * @throws \OCP\Files\UnseekableException
442
+     */
443
+    public function readfilePart($path, $from, $to) {
444
+        $this->assertPathLength($path);
445
+        @ob_end_clean();
446
+        $handle = $this->fopen($path, 'rb');
447
+        if ($handle) {
448
+            $chunkSize = 8192; // 8 kB chunks
449
+            $startReading = true;
450
+
451
+            if ($from !== 0 && $from !== '0' && fseek($handle, $from) !== 0) {
452
+                // forward file handle via chunked fread because fseek seem to have failed
453
+
454
+                $end = $from + 1;
455
+                while (!feof($handle) && ftell($handle) < $end) {
456
+                    $len = $from - ftell($handle);
457
+                    if ($len > $chunkSize) {
458
+                        $len = $chunkSize;
459
+                    }
460
+                    $result = fread($handle, $len);
461
+
462
+                    if ($result === false) {
463
+                        $startReading = false;
464
+                        break;
465
+                    }
466
+                }
467
+            }
468
+
469
+            if ($startReading) {
470
+                $end = $to + 1;
471
+                while (!feof($handle) && ftell($handle) < $end) {
472
+                    $len = $end - ftell($handle);
473
+                    if ($len > $chunkSize) {
474
+                        $len = $chunkSize;
475
+                    }
476
+                    echo fread($handle, $len);
477
+                    flush();
478
+                }
479
+                $size = ftell($handle) - $from;
480
+                return $size;
481
+            }
482
+
483
+            throw new \OCP\Files\UnseekableException('fseek error');
484
+        }
485
+        return false;
486
+    }
487
+
488
+    /**
489
+     * @param string $path
490
+     * @return mixed
491
+     */
492
+    public function isCreatable($path) {
493
+        return $this->basicOperation('isCreatable', $path);
494
+    }
495
+
496
+    /**
497
+     * @param string $path
498
+     * @return mixed
499
+     */
500
+    public function isReadable($path) {
501
+        return $this->basicOperation('isReadable', $path);
502
+    }
503
+
504
+    /**
505
+     * @param string $path
506
+     * @return mixed
507
+     */
508
+    public function isUpdatable($path) {
509
+        return $this->basicOperation('isUpdatable', $path);
510
+    }
511
+
512
+    /**
513
+     * @param string $path
514
+     * @return bool|mixed
515
+     */
516
+    public function isDeletable($path) {
517
+        $absolutePath = $this->getAbsolutePath($path);
518
+        $mount = Filesystem::getMountManager()->find($absolutePath);
519
+        if ($mount->getInternalPath($absolutePath) === '') {
520
+            return $mount instanceof MoveableMount;
521
+        }
522
+        return $this->basicOperation('isDeletable', $path);
523
+    }
524
+
525
+    /**
526
+     * @param string $path
527
+     * @return mixed
528
+     */
529
+    public function isSharable($path) {
530
+        return $this->basicOperation('isSharable', $path);
531
+    }
532
+
533
+    /**
534
+     * @param string $path
535
+     * @return bool|mixed
536
+     */
537
+    public function file_exists($path) {
538
+        if ($path == '/') {
539
+            return true;
540
+        }
541
+        return $this->basicOperation('file_exists', $path);
542
+    }
543
+
544
+    /**
545
+     * @param string $path
546
+     * @return mixed
547
+     */
548
+    public function filemtime($path) {
549
+        return $this->basicOperation('filemtime', $path);
550
+    }
551
+
552
+    /**
553
+     * @param string $path
554
+     * @param int|string $mtime
555
+     * @return bool
556
+     */
557
+    public function touch($path, $mtime = null) {
558
+        if (!is_null($mtime) and !is_numeric($mtime)) {
559
+            $mtime = strtotime($mtime);
560
+        }
561
+
562
+        $hooks = array('touch');
563
+
564
+        if (!$this->file_exists($path)) {
565
+            $hooks[] = 'create';
566
+            $hooks[] = 'write';
567
+        }
568
+        $result = $this->basicOperation('touch', $path, $hooks, $mtime);
569
+        if (!$result) {
570
+            // If create file fails because of permissions on external storage like SMB folders,
571
+            // check file exists and return false if not.
572
+            if (!$this->file_exists($path)) {
573
+                return false;
574
+            }
575
+            if (is_null($mtime)) {
576
+                $mtime = time();
577
+            }
578
+            //if native touch fails, we emulate it by changing the mtime in the cache
579
+            $this->putFileInfo($path, array('mtime' => floor($mtime)));
580
+        }
581
+        return true;
582
+    }
583
+
584
+    /**
585
+     * @param string $path
586
+     * @return mixed
587
+     */
588
+    public function file_get_contents($path) {
589
+        return $this->basicOperation('file_get_contents', $path, array('read'));
590
+    }
591
+
592
+    /**
593
+     * @param bool $exists
594
+     * @param string $path
595
+     * @param bool $run
596
+     */
597
+    protected function emit_file_hooks_pre($exists, $path, &$run) {
598
+        if (!$exists) {
599
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, array(
600
+                Filesystem::signal_param_path => $this->getHookPath($path),
601
+                Filesystem::signal_param_run => &$run,
602
+            ));
603
+        } else {
604
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, array(
605
+                Filesystem::signal_param_path => $this->getHookPath($path),
606
+                Filesystem::signal_param_run => &$run,
607
+            ));
608
+        }
609
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, array(
610
+            Filesystem::signal_param_path => $this->getHookPath($path),
611
+            Filesystem::signal_param_run => &$run,
612
+        ));
613
+    }
614
+
615
+    /**
616
+     * @param bool $exists
617
+     * @param string $path
618
+     */
619
+    protected function emit_file_hooks_post($exists, $path) {
620
+        if (!$exists) {
621
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, array(
622
+                Filesystem::signal_param_path => $this->getHookPath($path),
623
+            ));
624
+        } else {
625
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, array(
626
+                Filesystem::signal_param_path => $this->getHookPath($path),
627
+            ));
628
+        }
629
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, array(
630
+            Filesystem::signal_param_path => $this->getHookPath($path),
631
+        ));
632
+    }
633
+
634
+    /**
635
+     * @param string $path
636
+     * @param mixed $data
637
+     * @return bool|mixed
638
+     * @throws \Exception
639
+     */
640
+    public function file_put_contents($path, $data) {
641
+        if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
642
+            $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
643
+            if (Filesystem::isValidPath($path)
644
+                and !Filesystem::isFileBlacklisted($path)
645
+            ) {
646
+                $path = $this->getRelativePath($absolutePath);
647
+
648
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
649
+
650
+                $exists = $this->file_exists($path);
651
+                $run = true;
652
+                if ($this->shouldEmitHooks($path)) {
653
+                    $this->emit_file_hooks_pre($exists, $path, $run);
654
+                }
655
+                if (!$run) {
656
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
657
+                    return false;
658
+                }
659
+
660
+                $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
661
+
662
+                /** @var \OC\Files\Storage\Storage $storage */
663
+                list($storage, $internalPath) = $this->resolvePath($path);
664
+                $target = $storage->fopen($internalPath, 'w');
665
+                if ($target) {
666
+                    list (, $result) = \OC_Helper::streamCopy($data, $target);
667
+                    fclose($target);
668
+                    fclose($data);
669
+
670
+                    $this->writeUpdate($storage, $internalPath);
671
+
672
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
673
+
674
+                    if ($this->shouldEmitHooks($path) && $result !== false) {
675
+                        $this->emit_file_hooks_post($exists, $path);
676
+                    }
677
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
678
+                    return $result;
679
+                } else {
680
+                    $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
681
+                    return false;
682
+                }
683
+            } else {
684
+                return false;
685
+            }
686
+        } else {
687
+            $hooks = ($this->file_exists($path)) ? array('update', 'write') : array('create', 'write');
688
+            return $this->basicOperation('file_put_contents', $path, $hooks, $data);
689
+        }
690
+    }
691
+
692
+    /**
693
+     * @param string $path
694
+     * @return bool|mixed
695
+     */
696
+    public function unlink($path) {
697
+        if ($path === '' || $path === '/') {
698
+            // do not allow deleting the root
699
+            return false;
700
+        }
701
+        $postFix = (substr($path, -1, 1) === '/') ? '/' : '';
702
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
703
+        $mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
704
+        if ($mount and $mount->getInternalPath($absolutePath) === '') {
705
+            return $this->removeMount($mount, $absolutePath);
706
+        }
707
+        if ($this->is_dir($path)) {
708
+            $result = $this->basicOperation('rmdir', $path, ['delete']);
709
+        } else {
710
+            $result = $this->basicOperation('unlink', $path, ['delete']);
711
+        }
712
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
713
+            $storage = $mount->getStorage();
714
+            $internalPath = $mount->getInternalPath($absolutePath);
715
+            $storage->getUpdater()->remove($internalPath);
716
+            return true;
717
+        } else {
718
+            return $result;
719
+        }
720
+    }
721
+
722
+    /**
723
+     * @param string $directory
724
+     * @return bool|mixed
725
+     */
726
+    public function deleteAll($directory) {
727
+        return $this->rmdir($directory);
728
+    }
729
+
730
+    /**
731
+     * Rename/move a file or folder from the source path to target path.
732
+     *
733
+     * @param string $path1 source path
734
+     * @param string $path2 target path
735
+     *
736
+     * @return bool|mixed
737
+     */
738
+    public function rename($path1, $path2) {
739
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
740
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
741
+        $result = false;
742
+        if (
743
+            Filesystem::isValidPath($path2)
744
+            and Filesystem::isValidPath($path1)
745
+            and !Filesystem::isFileBlacklisted($path2)
746
+        ) {
747
+            $path1 = $this->getRelativePath($absolutePath1);
748
+            $path2 = $this->getRelativePath($absolutePath2);
749
+            $exists = $this->file_exists($path2);
750
+
751
+            if ($path1 == null or $path2 == null) {
752
+                return false;
753
+            }
754
+
755
+            $this->lockFile($path1, ILockingProvider::LOCK_SHARED, true);
756
+            try {
757
+                $this->lockFile($path2, ILockingProvider::LOCK_SHARED, true);
758
+
759
+                $run = true;
760
+                if ($this->shouldEmitHooks($path1) && (Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2))) {
761
+                    // if it was a rename from a part file to a regular file it was a write and not a rename operation
762
+                    $this->emit_file_hooks_pre($exists, $path2, $run);
763
+                } elseif ($this->shouldEmitHooks($path1)) {
764
+                    \OC_Hook::emit(
765
+                        Filesystem::CLASSNAME, Filesystem::signal_rename,
766
+                        array(
767
+                            Filesystem::signal_param_oldpath => $this->getHookPath($path1),
768
+                            Filesystem::signal_param_newpath => $this->getHookPath($path2),
769
+                            Filesystem::signal_param_run => &$run
770
+                        )
771
+                    );
772
+                }
773
+                if ($run) {
774
+                    $this->verifyPath(dirname($path2), basename($path2));
775
+
776
+                    $manager = Filesystem::getMountManager();
777
+                    $mount1 = $this->getMount($path1);
778
+                    $mount2 = $this->getMount($path2);
779
+                    $storage1 = $mount1->getStorage();
780
+                    $storage2 = $mount2->getStorage();
781
+                    $internalPath1 = $mount1->getInternalPath($absolutePath1);
782
+                    $internalPath2 = $mount2->getInternalPath($absolutePath2);
783
+
784
+                    $this->changeLock($path1, ILockingProvider::LOCK_EXCLUSIVE, true);
785
+                    try {
786
+                        $this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE, true);
787
+
788
+                        if ($internalPath1 === '') {
789
+                            if ($mount1 instanceof MoveableMount) {
790
+                                if ($this->isTargetAllowed($absolutePath2)) {
791
+                                    /**
792
+                                     * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
793
+                                     */
794
+                                    $sourceMountPoint = $mount1->getMountPoint();
795
+                                    $result = $mount1->moveMount($absolutePath2);
796
+                                    $manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
797
+                                } else {
798
+                                    $result = false;
799
+                                }
800
+                            } else {
801
+                                $result = false;
802
+                            }
803
+                            // moving a file/folder within the same mount point
804
+                        } elseif ($storage1 === $storage2) {
805
+                            if ($storage1) {
806
+                                $result = $storage1->rename($internalPath1, $internalPath2);
807
+                            } else {
808
+                                $result = false;
809
+                            }
810
+                            // moving a file/folder between storages (from $storage1 to $storage2)
811
+                        } else {
812
+                            $result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
813
+                        }
814
+
815
+                        if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
816
+                            // if it was a rename from a part file to a regular file it was a write and not a rename operation
817
+                            $this->writeUpdate($storage2, $internalPath2);
818
+                        } else if ($result) {
819
+                            if ($internalPath1 !== '') { // don't do a cache update for moved mounts
820
+                                $this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
821
+                            }
822
+                        }
823
+                    } catch(\Exception $e) {
824
+                        throw $e;
825
+                    } finally {
826
+                        $this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
827
+                        $this->changeLock($path2, ILockingProvider::LOCK_SHARED, true);
828
+                    }
829
+
830
+                    if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
831
+                        if ($this->shouldEmitHooks()) {
832
+                            $this->emit_file_hooks_post($exists, $path2);
833
+                        }
834
+                    } elseif ($result) {
835
+                        if ($this->shouldEmitHooks($path1) and $this->shouldEmitHooks($path2)) {
836
+                            \OC_Hook::emit(
837
+                                Filesystem::CLASSNAME,
838
+                                Filesystem::signal_post_rename,
839
+                                array(
840
+                                    Filesystem::signal_param_oldpath => $this->getHookPath($path1),
841
+                                    Filesystem::signal_param_newpath => $this->getHookPath($path2)
842
+                                )
843
+                            );
844
+                        }
845
+                    }
846
+                }
847
+            } catch(\Exception $e) {
848
+                throw $e;
849
+            } finally {
850
+                $this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
851
+                $this->unlockFile($path2, ILockingProvider::LOCK_SHARED, true);
852
+            }
853
+        }
854
+        return $result;
855
+    }
856
+
857
+    /**
858
+     * Copy a file/folder from the source path to target path
859
+     *
860
+     * @param string $path1 source path
861
+     * @param string $path2 target path
862
+     * @param bool $preserveMtime whether to preserve mtime on the copy
863
+     *
864
+     * @return bool|mixed
865
+     */
866
+    public function copy($path1, $path2, $preserveMtime = false) {
867
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
868
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
869
+        $result = false;
870
+        if (
871
+            Filesystem::isValidPath($path2)
872
+            and Filesystem::isValidPath($path1)
873
+            and !Filesystem::isFileBlacklisted($path2)
874
+        ) {
875
+            $path1 = $this->getRelativePath($absolutePath1);
876
+            $path2 = $this->getRelativePath($absolutePath2);
877
+
878
+            if ($path1 == null or $path2 == null) {
879
+                return false;
880
+            }
881
+            $run = true;
882
+
883
+            $this->lockFile($path2, ILockingProvider::LOCK_SHARED);
884
+            $this->lockFile($path1, ILockingProvider::LOCK_SHARED);
885
+            $lockTypePath1 = ILockingProvider::LOCK_SHARED;
886
+            $lockTypePath2 = ILockingProvider::LOCK_SHARED;
887
+
888
+            try {
889
+
890
+                $exists = $this->file_exists($path2);
891
+                if ($this->shouldEmitHooks()) {
892
+                    \OC_Hook::emit(
893
+                        Filesystem::CLASSNAME,
894
+                        Filesystem::signal_copy,
895
+                        array(
896
+                            Filesystem::signal_param_oldpath => $this->getHookPath($path1),
897
+                            Filesystem::signal_param_newpath => $this->getHookPath($path2),
898
+                            Filesystem::signal_param_run => &$run
899
+                        )
900
+                    );
901
+                    $this->emit_file_hooks_pre($exists, $path2, $run);
902
+                }
903
+                if ($run) {
904
+                    $mount1 = $this->getMount($path1);
905
+                    $mount2 = $this->getMount($path2);
906
+                    $storage1 = $mount1->getStorage();
907
+                    $internalPath1 = $mount1->getInternalPath($absolutePath1);
908
+                    $storage2 = $mount2->getStorage();
909
+                    $internalPath2 = $mount2->getInternalPath($absolutePath2);
910
+
911
+                    $this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE);
912
+                    $lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
913
+
914
+                    if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
915
+                        if ($storage1) {
916
+                            $result = $storage1->copy($internalPath1, $internalPath2);
917
+                        } else {
918
+                            $result = false;
919
+                        }
920
+                    } else {
921
+                        $result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
922
+                    }
923
+
924
+                    $this->writeUpdate($storage2, $internalPath2);
925
+
926
+                    $this->changeLock($path2, ILockingProvider::LOCK_SHARED);
927
+                    $lockTypePath2 = ILockingProvider::LOCK_SHARED;
928
+
929
+                    if ($this->shouldEmitHooks() && $result !== false) {
930
+                        \OC_Hook::emit(
931
+                            Filesystem::CLASSNAME,
932
+                            Filesystem::signal_post_copy,
933
+                            array(
934
+                                Filesystem::signal_param_oldpath => $this->getHookPath($path1),
935
+                                Filesystem::signal_param_newpath => $this->getHookPath($path2)
936
+                            )
937
+                        );
938
+                        $this->emit_file_hooks_post($exists, $path2);
939
+                    }
940
+
941
+                }
942
+            } catch (\Exception $e) {
943
+                $this->unlockFile($path2, $lockTypePath2);
944
+                $this->unlockFile($path1, $lockTypePath1);
945
+                throw $e;
946
+            }
947
+
948
+            $this->unlockFile($path2, $lockTypePath2);
949
+            $this->unlockFile($path1, $lockTypePath1);
950
+
951
+        }
952
+        return $result;
953
+    }
954
+
955
+    /**
956
+     * @param string $path
957
+     * @param string $mode 'r' or 'w'
958
+     * @return resource
959
+     */
960
+    public function fopen($path, $mode) {
961
+        $mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
962
+        $hooks = array();
963
+        switch ($mode) {
964
+            case 'r':
965
+                $hooks[] = 'read';
966
+                break;
967
+            case 'r+':
968
+            case 'w+':
969
+            case 'x+':
970
+            case 'a+':
971
+                $hooks[] = 'read';
972
+                $hooks[] = 'write';
973
+                break;
974
+            case 'w':
975
+            case 'x':
976
+            case 'a':
977
+                $hooks[] = 'write';
978
+                break;
979
+            default:
980
+                \OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, \OCP\Util::ERROR);
981
+        }
982
+
983
+        if ($mode !== 'r' && $mode !== 'w') {
984
+            \OC::$server->getLogger()->info('Trying to open a file with a mode other than "r" or "w" can cause severe performance issues with some backends');
985
+        }
986
+
987
+        return $this->basicOperation('fopen', $path, $hooks, $mode);
988
+    }
989
+
990
+    /**
991
+     * @param string $path
992
+     * @return bool|string
993
+     * @throws \OCP\Files\InvalidPathException
994
+     */
995
+    public function toTmpFile($path) {
996
+        $this->assertPathLength($path);
997
+        if (Filesystem::isValidPath($path)) {
998
+            $source = $this->fopen($path, 'r');
999
+            if ($source) {
1000
+                $extension = pathinfo($path, PATHINFO_EXTENSION);
1001
+                $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
1002
+                file_put_contents($tmpFile, $source);
1003
+                return $tmpFile;
1004
+            } else {
1005
+                return false;
1006
+            }
1007
+        } else {
1008
+            return false;
1009
+        }
1010
+    }
1011
+
1012
+    /**
1013
+     * @param string $tmpFile
1014
+     * @param string $path
1015
+     * @return bool|mixed
1016
+     * @throws \OCP\Files\InvalidPathException
1017
+     */
1018
+    public function fromTmpFile($tmpFile, $path) {
1019
+        $this->assertPathLength($path);
1020
+        if (Filesystem::isValidPath($path)) {
1021
+
1022
+            // Get directory that the file is going into
1023
+            $filePath = dirname($path);
1024
+
1025
+            // Create the directories if any
1026
+            if (!$this->file_exists($filePath)) {
1027
+                $result = $this->createParentDirectories($filePath);
1028
+                if ($result === false) {
1029
+                    return false;
1030
+                }
1031
+            }
1032
+
1033
+            $source = fopen($tmpFile, 'r');
1034
+            if ($source) {
1035
+                $result = $this->file_put_contents($path, $source);
1036
+                // $this->file_put_contents() might have already closed
1037
+                // the resource, so we check it, before trying to close it
1038
+                // to avoid messages in the error log.
1039
+                if (is_resource($source)) {
1040
+                    fclose($source);
1041
+                }
1042
+                unlink($tmpFile);
1043
+                return $result;
1044
+            } else {
1045
+                return false;
1046
+            }
1047
+        } else {
1048
+            return false;
1049
+        }
1050
+    }
1051
+
1052
+
1053
+    /**
1054
+     * @param string $path
1055
+     * @return mixed
1056
+     * @throws \OCP\Files\InvalidPathException
1057
+     */
1058
+    public function getMimeType($path) {
1059
+        $this->assertPathLength($path);
1060
+        return $this->basicOperation('getMimeType', $path);
1061
+    }
1062
+
1063
+    /**
1064
+     * @param string $type
1065
+     * @param string $path
1066
+     * @param bool $raw
1067
+     * @return bool|null|string
1068
+     */
1069
+    public function hash($type, $path, $raw = false) {
1070
+        $postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1071
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1072
+        if (Filesystem::isValidPath($path)) {
1073
+            $path = $this->getRelativePath($absolutePath);
1074
+            if ($path == null) {
1075
+                return false;
1076
+            }
1077
+            if ($this->shouldEmitHooks($path)) {
1078
+                \OC_Hook::emit(
1079
+                    Filesystem::CLASSNAME,
1080
+                    Filesystem::signal_read,
1081
+                    array(Filesystem::signal_param_path => $this->getHookPath($path))
1082
+                );
1083
+            }
1084
+            list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1085
+            if ($storage) {
1086
+                $result = $storage->hash($type, $internalPath, $raw);
1087
+                return $result;
1088
+            }
1089
+        }
1090
+        return null;
1091
+    }
1092
+
1093
+    /**
1094
+     * @param string $path
1095
+     * @return mixed
1096
+     * @throws \OCP\Files\InvalidPathException
1097
+     */
1098
+    public function free_space($path = '/') {
1099
+        $this->assertPathLength($path);
1100
+        $result = $this->basicOperation('free_space', $path);
1101
+        if ($result === null) {
1102
+            throw new InvalidPathException();
1103
+        }
1104
+        return $result;
1105
+    }
1106
+
1107
+    /**
1108
+     * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1109
+     *
1110
+     * @param string $operation
1111
+     * @param string $path
1112
+     * @param array $hooks (optional)
1113
+     * @param mixed $extraParam (optional)
1114
+     * @return mixed
1115
+     * @throws \Exception
1116
+     *
1117
+     * This method takes requests for basic filesystem functions (e.g. reading & writing
1118
+     * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1119
+     * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1120
+     */
1121
+    private function basicOperation($operation, $path, $hooks = [], $extraParam = null) {
1122
+        $postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1123
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1124
+        if (Filesystem::isValidPath($path)
1125
+            and !Filesystem::isFileBlacklisted($path)
1126
+        ) {
1127
+            $path = $this->getRelativePath($absolutePath);
1128
+            if ($path == null) {
1129
+                return false;
1130
+            }
1131
+
1132
+            if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1133
+                // always a shared lock during pre-hooks so the hook can read the file
1134
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
1135
+            }
1136
+
1137
+            $run = $this->runHooks($hooks, $path);
1138
+            /** @var \OC\Files\Storage\Storage $storage */
1139
+            list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1140
+            if ($run and $storage) {
1141
+                if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1142
+                    try {
1143
+                        $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1144
+                    } catch (LockedException $e) {
1145
+                        // release the shared lock we acquired before quiting
1146
+                        $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1147
+                        throw $e;
1148
+                    }
1149
+                }
1150
+                try {
1151
+                    if (!is_null($extraParam)) {
1152
+                        $result = $storage->$operation($internalPath, $extraParam);
1153
+                    } else {
1154
+                        $result = $storage->$operation($internalPath);
1155
+                    }
1156
+                } catch (\Exception $e) {
1157
+                    if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1158
+                        $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1159
+                    } else if (in_array('read', $hooks)) {
1160
+                        $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1161
+                    }
1162
+                    throw $e;
1163
+                }
1164
+
1165
+                if ($result && in_array('delete', $hooks) and $result) {
1166
+                    $this->removeUpdate($storage, $internalPath);
1167
+                }
1168
+                if ($result && in_array('write', $hooks) and $operation !== 'fopen') {
1169
+                    $this->writeUpdate($storage, $internalPath);
1170
+                }
1171
+                if ($result && in_array('touch', $hooks)) {
1172
+                    $this->writeUpdate($storage, $internalPath, $extraParam);
1173
+                }
1174
+
1175
+                if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1176
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
1177
+                }
1178
+
1179
+                $unlockLater = false;
1180
+                if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1181
+                    $unlockLater = true;
1182
+                    // make sure our unlocking callback will still be called if connection is aborted
1183
+                    ignore_user_abort(true);
1184
+                    $result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1185
+                        if (in_array('write', $hooks)) {
1186
+                            $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1187
+                        } else if (in_array('read', $hooks)) {
1188
+                            $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1189
+                        }
1190
+                    });
1191
+                }
1192
+
1193
+                if ($this->shouldEmitHooks($path) && $result !== false) {
1194
+                    if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1195
+                        $this->runHooks($hooks, $path, true);
1196
+                    }
1197
+                }
1198
+
1199
+                if (!$unlockLater
1200
+                    && (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1201
+                ) {
1202
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1203
+                }
1204
+                return $result;
1205
+            } else {
1206
+                $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1207
+            }
1208
+        }
1209
+        return null;
1210
+    }
1211
+
1212
+    /**
1213
+     * get the path relative to the default root for hook usage
1214
+     *
1215
+     * @param string $path
1216
+     * @return string
1217
+     */
1218
+    private function getHookPath($path) {
1219
+        if (!Filesystem::getView()) {
1220
+            return $path;
1221
+        }
1222
+        return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
1223
+    }
1224
+
1225
+    private function shouldEmitHooks($path = '') {
1226
+        if ($path && Cache\Scanner::isPartialFile($path)) {
1227
+            return false;
1228
+        }
1229
+        if (!Filesystem::$loaded) {
1230
+            return false;
1231
+        }
1232
+        $defaultRoot = Filesystem::getRoot();
1233
+        if ($defaultRoot === null) {
1234
+            return false;
1235
+        }
1236
+        if ($this->fakeRoot === $defaultRoot) {
1237
+            return true;
1238
+        }
1239
+        $fullPath = $this->getAbsolutePath($path);
1240
+
1241
+        if ($fullPath === $defaultRoot) {
1242
+            return true;
1243
+        }
1244
+
1245
+        return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1246
+    }
1247
+
1248
+    /**
1249
+     * @param string[] $hooks
1250
+     * @param string $path
1251
+     * @param bool $post
1252
+     * @return bool
1253
+     */
1254
+    private function runHooks($hooks, $path, $post = false) {
1255
+        $relativePath = $path;
1256
+        $path = $this->getHookPath($path);
1257
+        $prefix = ($post) ? 'post_' : '';
1258
+        $run = true;
1259
+        if ($this->shouldEmitHooks($relativePath)) {
1260
+            foreach ($hooks as $hook) {
1261
+                if ($hook != 'read') {
1262
+                    \OC_Hook::emit(
1263
+                        Filesystem::CLASSNAME,
1264
+                        $prefix . $hook,
1265
+                        array(
1266
+                            Filesystem::signal_param_run => &$run,
1267
+                            Filesystem::signal_param_path => $path
1268
+                        )
1269
+                    );
1270
+                } elseif (!$post) {
1271
+                    \OC_Hook::emit(
1272
+                        Filesystem::CLASSNAME,
1273
+                        $prefix . $hook,
1274
+                        array(
1275
+                            Filesystem::signal_param_path => $path
1276
+                        )
1277
+                    );
1278
+                }
1279
+            }
1280
+        }
1281
+        return $run;
1282
+    }
1283
+
1284
+    /**
1285
+     * check if a file or folder has been updated since $time
1286
+     *
1287
+     * @param string $path
1288
+     * @param int $time
1289
+     * @return bool
1290
+     */
1291
+    public function hasUpdated($path, $time) {
1292
+        return $this->basicOperation('hasUpdated', $path, array(), $time);
1293
+    }
1294
+
1295
+    /**
1296
+     * @param string $ownerId
1297
+     * @return \OC\User\User
1298
+     */
1299
+    private function getUserObjectForOwner($ownerId) {
1300
+        $owner = $this->userManager->get($ownerId);
1301
+        if ($owner instanceof IUser) {
1302
+            return $owner;
1303
+        } else {
1304
+            return new User($ownerId, null);
1305
+        }
1306
+    }
1307
+
1308
+    /**
1309
+     * Get file info from cache
1310
+     *
1311
+     * If the file is not in cached it will be scanned
1312
+     * If the file has changed on storage the cache will be updated
1313
+     *
1314
+     * @param \OC\Files\Storage\Storage $storage
1315
+     * @param string $internalPath
1316
+     * @param string $relativePath
1317
+     * @return ICacheEntry|bool
1318
+     */
1319
+    private function getCacheEntry($storage, $internalPath, $relativePath) {
1320
+        $cache = $storage->getCache($internalPath);
1321
+        $data = $cache->get($internalPath);
1322
+        $watcher = $storage->getWatcher($internalPath);
1323
+
1324
+        try {
1325
+            // if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1326
+            if (!$data || $data['size'] === -1) {
1327
+                if (!$storage->file_exists($internalPath)) {
1328
+                    return false;
1329
+                }
1330
+                // don't need to get a lock here since the scanner does it's own locking
1331
+                $scanner = $storage->getScanner($internalPath);
1332
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1333
+                $data = $cache->get($internalPath);
1334
+            } else if (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1335
+                $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1336
+                $watcher->update($internalPath, $data);
1337
+                $storage->getPropagator()->propagateChange($internalPath, time());
1338
+                $data = $cache->get($internalPath);
1339
+                $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1340
+            }
1341
+        } catch (LockedException $e) {
1342
+            // if the file is locked we just use the old cache info
1343
+        }
1344
+
1345
+        return $data;
1346
+    }
1347
+
1348
+    /**
1349
+     * get the filesystem info
1350
+     *
1351
+     * @param string $path
1352
+     * @param boolean|string $includeMountPoints true to add mountpoint sizes,
1353
+     * 'ext' to add only ext storage mount point sizes. Defaults to true.
1354
+     * defaults to true
1355
+     * @return \OC\Files\FileInfo|false False if file does not exist
1356
+     */
1357
+    public function getFileInfo($path, $includeMountPoints = true) {
1358
+        $this->assertPathLength($path);
1359
+        if (!Filesystem::isValidPath($path)) {
1360
+            return false;
1361
+        }
1362
+        if (Cache\Scanner::isPartialFile($path)) {
1363
+            return $this->getPartFileInfo($path);
1364
+        }
1365
+        $relativePath = $path;
1366
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1367
+
1368
+        $mount = Filesystem::getMountManager()->find($path);
1369
+        if (!$mount) {
1370
+            return false;
1371
+        }
1372
+        $storage = $mount->getStorage();
1373
+        $internalPath = $mount->getInternalPath($path);
1374
+        if ($storage) {
1375
+            $data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1376
+
1377
+            if (!$data instanceof ICacheEntry) {
1378
+                return false;
1379
+            }
1380
+
1381
+            if ($mount instanceof MoveableMount && $internalPath === '') {
1382
+                $data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1383
+            }
1384
+
1385
+            $owner = $this->getUserObjectForOwner($storage->getOwner($internalPath));
1386
+            $info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1387
+
1388
+            if ($data and isset($data['fileid'])) {
1389
+                if ($includeMountPoints and $data['mimetype'] === 'httpd/unix-directory') {
1390
+                    //add the sizes of other mount points to the folder
1391
+                    $extOnly = ($includeMountPoints === 'ext');
1392
+                    $mounts = Filesystem::getMountManager()->findIn($path);
1393
+                    $info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1394
+                        $subStorage = $mount->getStorage();
1395
+                        return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1396
+                    }));
1397
+                }
1398
+            }
1399
+
1400
+            return $info;
1401
+        }
1402
+
1403
+        return false;
1404
+    }
1405
+
1406
+    /**
1407
+     * get the content of a directory
1408
+     *
1409
+     * @param string $directory path under datadirectory
1410
+     * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1411
+     * @return FileInfo[]
1412
+     */
1413
+    public function getDirectoryContent($directory, $mimetype_filter = '') {
1414
+        $this->assertPathLength($directory);
1415
+        if (!Filesystem::isValidPath($directory)) {
1416
+            return [];
1417
+        }
1418
+        $path = $this->getAbsolutePath($directory);
1419
+        $path = Filesystem::normalizePath($path);
1420
+        $mount = $this->getMount($directory);
1421
+        if (!$mount) {
1422
+            return [];
1423
+        }
1424
+        $storage = $mount->getStorage();
1425
+        $internalPath = $mount->getInternalPath($path);
1426
+        if ($storage) {
1427
+            $cache = $storage->getCache($internalPath);
1428
+            $user = \OC_User::getUser();
1429
+
1430
+            $data = $this->getCacheEntry($storage, $internalPath, $directory);
1431
+
1432
+            if (!$data instanceof ICacheEntry || !isset($data['fileid']) || !($data->getPermissions() && Constants::PERMISSION_READ)) {
1433
+                return [];
1434
+            }
1435
+
1436
+            $folderId = $data['fileid'];
1437
+            $contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1438
+
1439
+            $sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1440
+
1441
+            $fileNames = array_map(function(ICacheEntry $content) {
1442
+                return $content->getName();
1443
+            }, $contents);
1444
+            /**
1445
+             * @var \OC\Files\FileInfo[] $fileInfos
1446
+             */
1447
+            $fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1448
+                if ($sharingDisabled) {
1449
+                    $content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1450
+                }
1451
+                $owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1452
+                return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1453
+            }, $contents);
1454
+            $files = array_combine($fileNames, $fileInfos);
1455
+
1456
+            //add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1457
+            $mounts = Filesystem::getMountManager()->findIn($path);
1458
+            $dirLength = strlen($path);
1459
+            foreach ($mounts as $mount) {
1460
+                $mountPoint = $mount->getMountPoint();
1461
+                $subStorage = $mount->getStorage();
1462
+                if ($subStorage) {
1463
+                    $subCache = $subStorage->getCache('');
1464
+
1465
+                    $rootEntry = $subCache->get('');
1466
+                    if (!$rootEntry) {
1467
+                        $subScanner = $subStorage->getScanner('');
1468
+                        try {
1469
+                            $subScanner->scanFile('');
1470
+                        } catch (\OCP\Files\StorageNotAvailableException $e) {
1471
+                            continue;
1472
+                        } catch (\OCP\Files\StorageInvalidException $e) {
1473
+                            continue;
1474
+                        } catch (\Exception $e) {
1475
+                            // sometimes when the storage is not available it can be any exception
1476
+                            \OCP\Util::writeLog(
1477
+                                'core',
1478
+                                'Exception while scanning storage "' . $subStorage->getId() . '": ' .
1479
+                                get_class($e) . ': ' . $e->getMessage(),
1480
+                                \OCP\Util::ERROR
1481
+                            );
1482
+                            continue;
1483
+                        }
1484
+                        $rootEntry = $subCache->get('');
1485
+                    }
1486
+
1487
+                    if ($rootEntry && ($rootEntry->getPermissions() && Constants::PERMISSION_READ)) {
1488
+                        $relativePath = trim(substr($mountPoint, $dirLength), '/');
1489
+                        if ($pos = strpos($relativePath, '/')) {
1490
+                            //mountpoint inside subfolder add size to the correct folder
1491
+                            $entryName = substr($relativePath, 0, $pos);
1492
+                            foreach ($files as &$entry) {
1493
+                                if ($entry->getName() === $entryName) {
1494
+                                    $entry->addSubEntry($rootEntry, $mountPoint);
1495
+                                }
1496
+                            }
1497
+                        } else { //mountpoint in this folder, add an entry for it
1498
+                            $rootEntry['name'] = $relativePath;
1499
+                            $rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1500
+                            $permissions = $rootEntry['permissions'];
1501
+                            // do not allow renaming/deleting the mount point if they are not shared files/folders
1502
+                            // for shared files/folders we use the permissions given by the owner
1503
+                            if ($mount instanceof MoveableMount) {
1504
+                                $rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1505
+                            } else {
1506
+                                $rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1507
+                            }
1508
+
1509
+                            $rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1510
+
1511
+                            // if sharing was disabled for the user we remove the share permissions
1512
+                            if (\OCP\Util::isSharingDisabledForUser()) {
1513
+                                $rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1514
+                            }
1515
+
1516
+                            $owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1517
+                            $files[$rootEntry->getName()] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1518
+                        }
1519
+                    }
1520
+                }
1521
+            }
1522
+
1523
+            if ($mimetype_filter) {
1524
+                $files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1525
+                    if (strpos($mimetype_filter, '/')) {
1526
+                        return $file->getMimetype() === $mimetype_filter;
1527
+                    } else {
1528
+                        return $file->getMimePart() === $mimetype_filter;
1529
+                    }
1530
+                });
1531
+            }
1532
+
1533
+            return array_values($files);
1534
+        } else {
1535
+            return [];
1536
+        }
1537
+    }
1538
+
1539
+    /**
1540
+     * change file metadata
1541
+     *
1542
+     * @param string $path
1543
+     * @param array|\OCP\Files\FileInfo $data
1544
+     * @return int
1545
+     *
1546
+     * returns the fileid of the updated file
1547
+     */
1548
+    public function putFileInfo($path, $data) {
1549
+        $this->assertPathLength($path);
1550
+        if ($data instanceof FileInfo) {
1551
+            $data = $data->getData();
1552
+        }
1553
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1554
+        /**
1555
+         * @var \OC\Files\Storage\Storage $storage
1556
+         * @var string $internalPath
1557
+         */
1558
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
1559
+        if ($storage) {
1560
+            $cache = $storage->getCache($path);
1561
+
1562
+            if (!$cache->inCache($internalPath)) {
1563
+                $scanner = $storage->getScanner($internalPath);
1564
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1565
+            }
1566
+
1567
+            return $cache->put($internalPath, $data);
1568
+        } else {
1569
+            return -1;
1570
+        }
1571
+    }
1572
+
1573
+    /**
1574
+     * search for files with the name matching $query
1575
+     *
1576
+     * @param string $query
1577
+     * @return FileInfo[]
1578
+     */
1579
+    public function search($query) {
1580
+        return $this->searchCommon('search', array('%' . $query . '%'));
1581
+    }
1582
+
1583
+    /**
1584
+     * search for files with the name matching $query
1585
+     *
1586
+     * @param string $query
1587
+     * @return FileInfo[]
1588
+     */
1589
+    public function searchRaw($query) {
1590
+        return $this->searchCommon('search', array($query));
1591
+    }
1592
+
1593
+    /**
1594
+     * search for files by mimetype
1595
+     *
1596
+     * @param string $mimetype
1597
+     * @return FileInfo[]
1598
+     */
1599
+    public function searchByMime($mimetype) {
1600
+        return $this->searchCommon('searchByMime', array($mimetype));
1601
+    }
1602
+
1603
+    /**
1604
+     * search for files by tag
1605
+     *
1606
+     * @param string|int $tag name or tag id
1607
+     * @param string $userId owner of the tags
1608
+     * @return FileInfo[]
1609
+     */
1610
+    public function searchByTag($tag, $userId) {
1611
+        return $this->searchCommon('searchByTag', array($tag, $userId));
1612
+    }
1613
+
1614
+    /**
1615
+     * @param string $method cache method
1616
+     * @param array $args
1617
+     * @return FileInfo[]
1618
+     */
1619
+    private function searchCommon($method, $args) {
1620
+        $files = array();
1621
+        $rootLength = strlen($this->fakeRoot);
1622
+
1623
+        $mount = $this->getMount('');
1624
+        $mountPoint = $mount->getMountPoint();
1625
+        $storage = $mount->getStorage();
1626
+        if ($storage) {
1627
+            $cache = $storage->getCache('');
1628
+
1629
+            $results = call_user_func_array(array($cache, $method), $args);
1630
+            foreach ($results as $result) {
1631
+                if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1632
+                    $internalPath = $result['path'];
1633
+                    $path = $mountPoint . $result['path'];
1634
+                    $result['path'] = substr($mountPoint . $result['path'], $rootLength);
1635
+                    $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1636
+                    $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1637
+                }
1638
+            }
1639
+
1640
+            $mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1641
+            foreach ($mounts as $mount) {
1642
+                $mountPoint = $mount->getMountPoint();
1643
+                $storage = $mount->getStorage();
1644
+                if ($storage) {
1645
+                    $cache = $storage->getCache('');
1646
+
1647
+                    $relativeMountPoint = substr($mountPoint, $rootLength);
1648
+                    $results = call_user_func_array(array($cache, $method), $args);
1649
+                    if ($results) {
1650
+                        foreach ($results as $result) {
1651
+                            $internalPath = $result['path'];
1652
+                            $result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1653
+                            $path = rtrim($mountPoint . $internalPath, '/');
1654
+                            $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1655
+                            $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1656
+                        }
1657
+                    }
1658
+                }
1659
+            }
1660
+        }
1661
+        return $files;
1662
+    }
1663
+
1664
+    /**
1665
+     * Get the owner for a file or folder
1666
+     *
1667
+     * @param string $path
1668
+     * @return string the user id of the owner
1669
+     * @throws NotFoundException
1670
+     */
1671
+    public function getOwner($path) {
1672
+        $info = $this->getFileInfo($path);
1673
+        if (!$info) {
1674
+            throw new NotFoundException($path . ' not found while trying to get owner');
1675
+        }
1676
+        return $info->getOwner()->getUID();
1677
+    }
1678
+
1679
+    /**
1680
+     * get the ETag for a file or folder
1681
+     *
1682
+     * @param string $path
1683
+     * @return string
1684
+     */
1685
+    public function getETag($path) {
1686
+        /**
1687
+         * @var Storage\Storage $storage
1688
+         * @var string $internalPath
1689
+         */
1690
+        list($storage, $internalPath) = $this->resolvePath($path);
1691
+        if ($storage) {
1692
+            return $storage->getETag($internalPath);
1693
+        } else {
1694
+            return null;
1695
+        }
1696
+    }
1697
+
1698
+    /**
1699
+     * Get the path of a file by id, relative to the view
1700
+     *
1701
+     * Note that the resulting path is not guarantied to be unique for the id, multiple paths can point to the same file
1702
+     *
1703
+     * @param int $id
1704
+     * @throws NotFoundException
1705
+     * @return string
1706
+     */
1707
+    public function getPath($id) {
1708
+        $id = (int)$id;
1709
+        $manager = Filesystem::getMountManager();
1710
+        $mounts = $manager->findIn($this->fakeRoot);
1711
+        $mounts[] = $manager->find($this->fakeRoot);
1712
+        // reverse the array so we start with the storage this view is in
1713
+        // which is the most likely to contain the file we're looking for
1714
+        $mounts = array_reverse($mounts);
1715
+        foreach ($mounts as $mount) {
1716
+            /**
1717
+             * @var \OC\Files\Mount\MountPoint $mount
1718
+             */
1719
+            if ($mount->getStorage()) {
1720
+                $cache = $mount->getStorage()->getCache();
1721
+                $internalPath = $cache->getPathById($id);
1722
+                if (is_string($internalPath)) {
1723
+                    $fullPath = $mount->getMountPoint() . $internalPath;
1724
+                    if (!is_null($path = $this->getRelativePath($fullPath))) {
1725
+                        return $path;
1726
+                    }
1727
+                }
1728
+            }
1729
+        }
1730
+        throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1731
+    }
1732
+
1733
+    /**
1734
+     * @param string $path
1735
+     * @throws InvalidPathException
1736
+     */
1737
+    private function assertPathLength($path) {
1738
+        $maxLen = min(PHP_MAXPATHLEN, 4000);
1739
+        // Check for the string length - performed using isset() instead of strlen()
1740
+        // because isset() is about 5x-40x faster.
1741
+        if (isset($path[$maxLen])) {
1742
+            $pathLen = strlen($path);
1743
+            throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1744
+        }
1745
+    }
1746
+
1747
+    /**
1748
+     * check if it is allowed to move a mount point to a given target.
1749
+     * It is not allowed to move a mount point into a different mount point or
1750
+     * into an already shared folder
1751
+     *
1752
+     * @param string $target path
1753
+     * @return boolean
1754
+     */
1755
+    private function isTargetAllowed($target) {
1756
+
1757
+        list($targetStorage, $targetInternalPath) = \OC\Files\Filesystem::resolvePath($target);
1758
+        if (!$targetStorage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
1759
+            \OCP\Util::writeLog('files',
1760
+                'It is not allowed to move one mount point into another one',
1761
+                \OCP\Util::DEBUG);
1762
+            return false;
1763
+        }
1764
+
1765
+        // note: cannot use the view because the target is already locked
1766
+        $fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1767
+        if ($fileId === -1) {
1768
+            // target might not exist, need to check parent instead
1769
+            $fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1770
+        }
1771
+
1772
+        // check if any of the parents were shared by the current owner (include collections)
1773
+        $shares = \OCP\Share::getItemShared(
1774
+            'folder',
1775
+            $fileId,
1776
+            \OCP\Share::FORMAT_NONE,
1777
+            null,
1778
+            true
1779
+        );
1780
+
1781
+        if (count($shares) > 0) {
1782
+            \OCP\Util::writeLog('files',
1783
+                'It is not allowed to move one mount point into a shared folder',
1784
+                \OCP\Util::DEBUG);
1785
+            return false;
1786
+        }
1787
+
1788
+        return true;
1789
+    }
1790
+
1791
+    /**
1792
+     * Get a fileinfo object for files that are ignored in the cache (part files)
1793
+     *
1794
+     * @param string $path
1795
+     * @return \OCP\Files\FileInfo
1796
+     */
1797
+    private function getPartFileInfo($path) {
1798
+        $mount = $this->getMount($path);
1799
+        $storage = $mount->getStorage();
1800
+        $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1801
+        $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1802
+        return new FileInfo(
1803
+            $this->getAbsolutePath($path),
1804
+            $storage,
1805
+            $internalPath,
1806
+            [
1807
+                'fileid' => null,
1808
+                'mimetype' => $storage->getMimeType($internalPath),
1809
+                'name' => basename($path),
1810
+                'etag' => null,
1811
+                'size' => $storage->filesize($internalPath),
1812
+                'mtime' => $storage->filemtime($internalPath),
1813
+                'encrypted' => false,
1814
+                'permissions' => \OCP\Constants::PERMISSION_ALL
1815
+            ],
1816
+            $mount,
1817
+            $owner
1818
+        );
1819
+    }
1820
+
1821
+    /**
1822
+     * @param string $path
1823
+     * @param string $fileName
1824
+     * @throws InvalidPathException
1825
+     */
1826
+    public function verifyPath($path, $fileName) {
1827
+        try {
1828
+            /** @type \OCP\Files\Storage $storage */
1829
+            list($storage, $internalPath) = $this->resolvePath($path);
1830
+            $storage->verifyPath($internalPath, $fileName);
1831
+        } catch (ReservedWordException $ex) {
1832
+            $l = \OC::$server->getL10N('lib');
1833
+            throw new InvalidPathException($l->t('File name is a reserved word'));
1834
+        } catch (InvalidCharacterInPathException $ex) {
1835
+            $l = \OC::$server->getL10N('lib');
1836
+            throw new InvalidPathException($l->t('File name contains at least one invalid character'));
1837
+        } catch (FileNameTooLongException $ex) {
1838
+            $l = \OC::$server->getL10N('lib');
1839
+            throw new InvalidPathException($l->t('File name is too long'));
1840
+        } catch (InvalidDirectoryException $ex) {
1841
+            $l = \OC::$server->getL10N('lib');
1842
+            throw new InvalidPathException($l->t('Dot files are not allowed'));
1843
+        } catch (EmptyFileNameException $ex) {
1844
+            $l = \OC::$server->getL10N('lib');
1845
+            throw new InvalidPathException($l->t('Empty filename is not allowed'));
1846
+        }
1847
+    }
1848
+
1849
+    /**
1850
+     * get all parent folders of $path
1851
+     *
1852
+     * @param string $path
1853
+     * @return string[]
1854
+     */
1855
+    private function getParents($path) {
1856
+        $path = trim($path, '/');
1857
+        if (!$path) {
1858
+            return [];
1859
+        }
1860
+
1861
+        $parts = explode('/', $path);
1862
+
1863
+        // remove the single file
1864
+        array_pop($parts);
1865
+        $result = array('/');
1866
+        $resultPath = '';
1867
+        foreach ($parts as $part) {
1868
+            if ($part) {
1869
+                $resultPath .= '/' . $part;
1870
+                $result[] = $resultPath;
1871
+            }
1872
+        }
1873
+        return $result;
1874
+    }
1875
+
1876
+    /**
1877
+     * Returns the mount point for which to lock
1878
+     *
1879
+     * @param string $absolutePath absolute path
1880
+     * @param bool $useParentMount true to return parent mount instead of whatever
1881
+     * is mounted directly on the given path, false otherwise
1882
+     * @return \OC\Files\Mount\MountPoint mount point for which to apply locks
1883
+     */
1884
+    private function getMountForLock($absolutePath, $useParentMount = false) {
1885
+        $results = [];
1886
+        $mount = Filesystem::getMountManager()->find($absolutePath);
1887
+        if (!$mount) {
1888
+            return $results;
1889
+        }
1890
+
1891
+        if ($useParentMount) {
1892
+            // find out if something is mounted directly on the path
1893
+            $internalPath = $mount->getInternalPath($absolutePath);
1894
+            if ($internalPath === '') {
1895
+                // resolve the parent mount instead
1896
+                $mount = Filesystem::getMountManager()->find(dirname($absolutePath));
1897
+            }
1898
+        }
1899
+
1900
+        return $mount;
1901
+    }
1902
+
1903
+    /**
1904
+     * Lock the given path
1905
+     *
1906
+     * @param string $path the path of the file to lock, relative to the view
1907
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1908
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1909
+     *
1910
+     * @return bool False if the path is excluded from locking, true otherwise
1911
+     * @throws \OCP\Lock\LockedException if the path is already locked
1912
+     */
1913
+    private function lockPath($path, $type, $lockMountPoint = false) {
1914
+        $absolutePath = $this->getAbsolutePath($path);
1915
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1916
+        if (!$this->shouldLockFile($absolutePath)) {
1917
+            return false;
1918
+        }
1919
+
1920
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1921
+        if ($mount) {
1922
+            try {
1923
+                $storage = $mount->getStorage();
1924
+                if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1925
+                    $storage->acquireLock(
1926
+                        $mount->getInternalPath($absolutePath),
1927
+                        $type,
1928
+                        $this->lockingProvider
1929
+                    );
1930
+                }
1931
+            } catch (\OCP\Lock\LockedException $e) {
1932
+                // rethrow with the a human-readable path
1933
+                throw new \OCP\Lock\LockedException(
1934
+                    $this->getPathRelativeToFiles($absolutePath),
1935
+                    $e
1936
+                );
1937
+            }
1938
+        }
1939
+
1940
+        return true;
1941
+    }
1942
+
1943
+    /**
1944
+     * Change the lock type
1945
+     *
1946
+     * @param string $path the path of the file to lock, relative to the view
1947
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1948
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1949
+     *
1950
+     * @return bool False if the path is excluded from locking, true otherwise
1951
+     * @throws \OCP\Lock\LockedException if the path is already locked
1952
+     */
1953
+    public function changeLock($path, $type, $lockMountPoint = false) {
1954
+        $path = Filesystem::normalizePath($path);
1955
+        $absolutePath = $this->getAbsolutePath($path);
1956
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1957
+        if (!$this->shouldLockFile($absolutePath)) {
1958
+            return false;
1959
+        }
1960
+
1961
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1962
+        if ($mount) {
1963
+            try {
1964
+                $storage = $mount->getStorage();
1965
+                if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1966
+                    $storage->changeLock(
1967
+                        $mount->getInternalPath($absolutePath),
1968
+                        $type,
1969
+                        $this->lockingProvider
1970
+                    );
1971
+                }
1972
+            } catch (\OCP\Lock\LockedException $e) {
1973
+                try {
1974
+                    // rethrow with the a human-readable path
1975
+                    throw new \OCP\Lock\LockedException(
1976
+                        $this->getPathRelativeToFiles($absolutePath),
1977
+                        $e
1978
+                    );
1979
+                } catch (\InvalidArgumentException $e) {
1980
+                    throw new \OCP\Lock\LockedException(
1981
+                        $absolutePath,
1982
+                        $e
1983
+                    );
1984
+                }
1985
+            }
1986
+        }
1987
+
1988
+        return true;
1989
+    }
1990
+
1991
+    /**
1992
+     * Unlock the given path
1993
+     *
1994
+     * @param string $path the path of the file to unlock, relative to the view
1995
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1996
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1997
+     *
1998
+     * @return bool False if the path is excluded from locking, true otherwise
1999
+     */
2000
+    private function unlockPath($path, $type, $lockMountPoint = false) {
2001
+        $absolutePath = $this->getAbsolutePath($path);
2002
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2003
+        if (!$this->shouldLockFile($absolutePath)) {
2004
+            return false;
2005
+        }
2006
+
2007
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2008
+        if ($mount) {
2009
+            $storage = $mount->getStorage();
2010
+            if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2011
+                $storage->releaseLock(
2012
+                    $mount->getInternalPath($absolutePath),
2013
+                    $type,
2014
+                    $this->lockingProvider
2015
+                );
2016
+            }
2017
+        }
2018
+
2019
+        return true;
2020
+    }
2021
+
2022
+    /**
2023
+     * Lock a path and all its parents up to the root of the view
2024
+     *
2025
+     * @param string $path the path of the file to lock relative to the view
2026
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2027
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2028
+     *
2029
+     * @return bool False if the path is excluded from locking, true otherwise
2030
+     */
2031
+    public function lockFile($path, $type, $lockMountPoint = false) {
2032
+        $absolutePath = $this->getAbsolutePath($path);
2033
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2034
+        if (!$this->shouldLockFile($absolutePath)) {
2035
+            return false;
2036
+        }
2037
+
2038
+        $this->lockPath($path, $type, $lockMountPoint);
2039
+
2040
+        $parents = $this->getParents($path);
2041
+        foreach ($parents as $parent) {
2042
+            $this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2043
+        }
2044
+
2045
+        return true;
2046
+    }
2047
+
2048
+    /**
2049
+     * Unlock a path and all its parents up to the root of the view
2050
+     *
2051
+     * @param string $path the path of the file to lock relative to the view
2052
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2053
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2054
+     *
2055
+     * @return bool False if the path is excluded from locking, true otherwise
2056
+     */
2057
+    public function unlockFile($path, $type, $lockMountPoint = false) {
2058
+        $absolutePath = $this->getAbsolutePath($path);
2059
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2060
+        if (!$this->shouldLockFile($absolutePath)) {
2061
+            return false;
2062
+        }
2063
+
2064
+        $this->unlockPath($path, $type, $lockMountPoint);
2065
+
2066
+        $parents = $this->getParents($path);
2067
+        foreach ($parents as $parent) {
2068
+            $this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2069
+        }
2070
+
2071
+        return true;
2072
+    }
2073
+
2074
+    /**
2075
+     * Only lock files in data/user/files/
2076
+     *
2077
+     * @param string $path Absolute path to the file/folder we try to (un)lock
2078
+     * @return bool
2079
+     */
2080
+    protected function shouldLockFile($path) {
2081
+        $path = Filesystem::normalizePath($path);
2082
+
2083
+        $pathSegments = explode('/', $path);
2084
+        if (isset($pathSegments[2])) {
2085
+            // E.g.: /username/files/path-to-file
2086
+            return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2087
+        }
2088
+
2089
+        return strpos($path, '/appdata_') !== 0;
2090
+    }
2091
+
2092
+    /**
2093
+     * Shortens the given absolute path to be relative to
2094
+     * "$user/files".
2095
+     *
2096
+     * @param string $absolutePath absolute path which is under "files"
2097
+     *
2098
+     * @return string path relative to "files" with trimmed slashes or null
2099
+     * if the path was NOT relative to files
2100
+     *
2101
+     * @throws \InvalidArgumentException if the given path was not under "files"
2102
+     * @since 8.1.0
2103
+     */
2104
+    public function getPathRelativeToFiles($absolutePath) {
2105
+        $path = Filesystem::normalizePath($absolutePath);
2106
+        $parts = explode('/', trim($path, '/'), 3);
2107
+        // "$user", "files", "path/to/dir"
2108
+        if (!isset($parts[1]) || $parts[1] !== 'files') {
2109
+            $this->logger->error(
2110
+                '$absolutePath must be relative to "files", value is "%s"',
2111
+                [
2112
+                    $absolutePath
2113
+                ]
2114
+            );
2115
+            throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2116
+        }
2117
+        if (isset($parts[2])) {
2118
+            return $parts[2];
2119
+        }
2120
+        return '';
2121
+    }
2122
+
2123
+    /**
2124
+     * @param string $filename
2125
+     * @return array
2126
+     * @throws \OC\User\NoUserException
2127
+     * @throws NotFoundException
2128
+     */
2129
+    public function getUidAndFilename($filename) {
2130
+        $info = $this->getFileInfo($filename);
2131
+        if (!$info instanceof \OCP\Files\FileInfo) {
2132
+            throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2133
+        }
2134
+        $uid = $info->getOwner()->getUID();
2135
+        if ($uid != \OCP\User::getUser()) {
2136
+            Filesystem::initMountPoints($uid);
2137
+            $ownerView = new View('/' . $uid . '/files');
2138
+            try {
2139
+                $filename = $ownerView->getPath($info['fileid']);
2140
+            } catch (NotFoundException $e) {
2141
+                throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2142
+            }
2143
+        }
2144
+        return [$uid, $filename];
2145
+    }
2146
+
2147
+    /**
2148
+     * Creates parent non-existing folders
2149
+     *
2150
+     * @param string $filePath
2151
+     * @return bool
2152
+     */
2153
+    private function createParentDirectories($filePath) {
2154
+        $directoryParts = explode('/', $filePath);
2155
+        $directoryParts = array_filter($directoryParts);
2156
+        foreach ($directoryParts as $key => $part) {
2157
+            $currentPathElements = array_slice($directoryParts, 0, $key);
2158
+            $currentPath = '/' . implode('/', $currentPathElements);
2159
+            if ($this->is_file($currentPath)) {
2160
+                return false;
2161
+            }
2162
+            if (!$this->file_exists($currentPath)) {
2163
+                $this->mkdir($currentPath);
2164
+            }
2165
+        }
2166
+
2167
+        return true;
2168
+    }
2169 2169
 }
Please login to merge, or discard this patch.
Spacing   +41 added lines, -41 removed lines patch added patch discarded remove patch
@@ -126,9 +126,9 @@  discard block
 block discarded – undo
126 126
 			$path = '/';
127 127
 		}
128 128
 		if ($path[0] !== '/') {
129
-			$path = '/' . $path;
129
+			$path = '/'.$path;
130 130
 		}
131
-		return $this->fakeRoot . $path;
131
+		return $this->fakeRoot.$path;
132 132
 	}
133 133
 
134 134
 	/**
@@ -140,7 +140,7 @@  discard block
 block discarded – undo
140 140
 	public function chroot($fakeRoot) {
141 141
 		if (!$fakeRoot == '') {
142 142
 			if ($fakeRoot[0] !== '/') {
143
-				$fakeRoot = '/' . $fakeRoot;
143
+				$fakeRoot = '/'.$fakeRoot;
144 144
 			}
145 145
 		}
146 146
 		$this->fakeRoot = $fakeRoot;
@@ -172,7 +172,7 @@  discard block
 block discarded – undo
172 172
 		}
173 173
 
174 174
 		// missing slashes can cause wrong matches!
175
-		$root = rtrim($this->fakeRoot, '/') . '/';
175
+		$root = rtrim($this->fakeRoot, '/').'/';
176 176
 
177 177
 		if (strpos($path, $root) !== 0) {
178 178
 			return null;
@@ -278,7 +278,7 @@  discard block
 block discarded – undo
278 278
 		if ($mount instanceof MoveableMount) {
279 279
 			// cut of /user/files to get the relative path to data/user/files
280 280
 			$pathParts = explode('/', $path, 4);
281
-			$relPath = '/' . $pathParts[3];
281
+			$relPath = '/'.$pathParts[3];
282 282
 			$this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
283 283
 			\OC_Hook::emit(
284 284
 				Filesystem::CLASSNAME, "umount",
@@ -700,7 +700,7 @@  discard block
 block discarded – undo
700 700
 		}
701 701
 		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
702 702
 		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
703
-		$mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
703
+		$mount = Filesystem::getMountManager()->find($absolutePath.$postFix);
704 704
 		if ($mount and $mount->getInternalPath($absolutePath) === '') {
705 705
 			return $this->removeMount($mount, $absolutePath);
706 706
 		}
@@ -820,7 +820,7 @@  discard block
 block discarded – undo
820 820
 								$this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
821 821
 							}
822 822
 						}
823
-					} catch(\Exception $e) {
823
+					} catch (\Exception $e) {
824 824
 						throw $e;
825 825
 					} finally {
826 826
 						$this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
@@ -844,7 +844,7 @@  discard block
 block discarded – undo
844 844
 						}
845 845
 					}
846 846
 				}
847
-			} catch(\Exception $e) {
847
+			} catch (\Exception $e) {
848 848
 				throw $e;
849 849
 			} finally {
850 850
 				$this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
@@ -977,7 +977,7 @@  discard block
 block discarded – undo
977 977
 				$hooks[] = 'write';
978 978
 				break;
979 979
 			default:
980
-				\OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, \OCP\Util::ERROR);
980
+				\OCP\Util::writeLog('core', 'invalid mode ('.$mode.') for '.$path, \OCP\Util::ERROR);
981 981
 		}
982 982
 
983 983
 		if ($mode !== 'r' && $mode !== 'w') {
@@ -1081,7 +1081,7 @@  discard block
 block discarded – undo
1081 1081
 					array(Filesystem::signal_param_path => $this->getHookPath($path))
1082 1082
 				);
1083 1083
 			}
1084
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1084
+			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath.$postFix);
1085 1085
 			if ($storage) {
1086 1086
 				$result = $storage->hash($type, $internalPath, $raw);
1087 1087
 				return $result;
@@ -1136,7 +1136,7 @@  discard block
 block discarded – undo
1136 1136
 
1137 1137
 			$run = $this->runHooks($hooks, $path);
1138 1138
 			/** @var \OC\Files\Storage\Storage $storage */
1139
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1139
+			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath.$postFix);
1140 1140
 			if ($run and $storage) {
1141 1141
 				if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1142 1142
 					try {
@@ -1181,7 +1181,7 @@  discard block
 block discarded – undo
1181 1181
 					$unlockLater = true;
1182 1182
 					// make sure our unlocking callback will still be called if connection is aborted
1183 1183
 					ignore_user_abort(true);
1184
-					$result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1184
+					$result = CallbackWrapper::wrap($result, null, null, function() use ($hooks, $path) {
1185 1185
 						if (in_array('write', $hooks)) {
1186 1186
 							$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1187 1187
 						} else if (in_array('read', $hooks)) {
@@ -1242,7 +1242,7 @@  discard block
 block discarded – undo
1242 1242
 			return true;
1243 1243
 		}
1244 1244
 
1245
-		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1245
+		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot.'/');
1246 1246
 	}
1247 1247
 
1248 1248
 	/**
@@ -1261,7 +1261,7 @@  discard block
 block discarded – undo
1261 1261
 				if ($hook != 'read') {
1262 1262
 					\OC_Hook::emit(
1263 1263
 						Filesystem::CLASSNAME,
1264
-						$prefix . $hook,
1264
+						$prefix.$hook,
1265 1265
 						array(
1266 1266
 							Filesystem::signal_param_run => &$run,
1267 1267
 							Filesystem::signal_param_path => $path
@@ -1270,7 +1270,7 @@  discard block
 block discarded – undo
1270 1270
 				} elseif (!$post) {
1271 1271
 					\OC_Hook::emit(
1272 1272
 						Filesystem::CLASSNAME,
1273
-						$prefix . $hook,
1273
+						$prefix.$hook,
1274 1274
 						array(
1275 1275
 							Filesystem::signal_param_path => $path
1276 1276
 						)
@@ -1363,7 +1363,7 @@  discard block
 block discarded – undo
1363 1363
 			return $this->getPartFileInfo($path);
1364 1364
 		}
1365 1365
 		$relativePath = $path;
1366
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1366
+		$path = Filesystem::normalizePath($this->fakeRoot.'/'.$path);
1367 1367
 
1368 1368
 		$mount = Filesystem::getMountManager()->find($path);
1369 1369
 		if (!$mount) {
@@ -1390,7 +1390,7 @@  discard block
 block discarded – undo
1390 1390
 					//add the sizes of other mount points to the folder
1391 1391
 					$extOnly = ($includeMountPoints === 'ext');
1392 1392
 					$mounts = Filesystem::getMountManager()->findIn($path);
1393
-					$info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1393
+					$info->setSubMounts(array_filter($mounts, function(IMountPoint $mount) use ($extOnly) {
1394 1394
 						$subStorage = $mount->getStorage();
1395 1395
 						return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1396 1396
 					}));
@@ -1444,12 +1444,12 @@  discard block
 block discarded – undo
1444 1444
 			/**
1445 1445
 			 * @var \OC\Files\FileInfo[] $fileInfos
1446 1446
 			 */
1447
-			$fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1447
+			$fileInfos = array_map(function(ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1448 1448
 				if ($sharingDisabled) {
1449 1449
 					$content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1450 1450
 				}
1451 1451
 				$owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1452
-				return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1452
+				return new FileInfo($path.'/'.$content['name'], $storage, $content['path'], $content, $mount, $owner);
1453 1453
 			}, $contents);
1454 1454
 			$files = array_combine($fileNames, $fileInfos);
1455 1455
 
@@ -1475,8 +1475,8 @@  discard block
 block discarded – undo
1475 1475
 							// sometimes when the storage is not available it can be any exception
1476 1476
 							\OCP\Util::writeLog(
1477 1477
 								'core',
1478
-								'Exception while scanning storage "' . $subStorage->getId() . '": ' .
1479
-								get_class($e) . ': ' . $e->getMessage(),
1478
+								'Exception while scanning storage "'.$subStorage->getId().'": '.
1479
+								get_class($e).': '.$e->getMessage(),
1480 1480
 								\OCP\Util::ERROR
1481 1481
 							);
1482 1482
 							continue;
@@ -1506,7 +1506,7 @@  discard block
 block discarded – undo
1506 1506
 								$rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1507 1507
 							}
1508 1508
 
1509
-							$rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1509
+							$rootEntry['path'] = substr(Filesystem::normalizePath($path.'/'.$rootEntry['name']), strlen($user) + 2); // full path without /$user/
1510 1510
 
1511 1511
 							// if sharing was disabled for the user we remove the share permissions
1512 1512
 							if (\OCP\Util::isSharingDisabledForUser()) {
@@ -1514,14 +1514,14 @@  discard block
 block discarded – undo
1514 1514
 							}
1515 1515
 
1516 1516
 							$owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1517
-							$files[$rootEntry->getName()] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1517
+							$files[$rootEntry->getName()] = new FileInfo($path.'/'.$rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1518 1518
 						}
1519 1519
 					}
1520 1520
 				}
1521 1521
 			}
1522 1522
 
1523 1523
 			if ($mimetype_filter) {
1524
-				$files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1524
+				$files = array_filter($files, function(FileInfo $file) use ($mimetype_filter) {
1525 1525
 					if (strpos($mimetype_filter, '/')) {
1526 1526
 						return $file->getMimetype() === $mimetype_filter;
1527 1527
 					} else {
@@ -1550,7 +1550,7 @@  discard block
 block discarded – undo
1550 1550
 		if ($data instanceof FileInfo) {
1551 1551
 			$data = $data->getData();
1552 1552
 		}
1553
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1553
+		$path = Filesystem::normalizePath($this->fakeRoot.'/'.$path);
1554 1554
 		/**
1555 1555
 		 * @var \OC\Files\Storage\Storage $storage
1556 1556
 		 * @var string $internalPath
@@ -1577,7 +1577,7 @@  discard block
 block discarded – undo
1577 1577
 	 * @return FileInfo[]
1578 1578
 	 */
1579 1579
 	public function search($query) {
1580
-		return $this->searchCommon('search', array('%' . $query . '%'));
1580
+		return $this->searchCommon('search', array('%'.$query.'%'));
1581 1581
 	}
1582 1582
 
1583 1583
 	/**
@@ -1628,10 +1628,10 @@  discard block
 block discarded – undo
1628 1628
 
1629 1629
 			$results = call_user_func_array(array($cache, $method), $args);
1630 1630
 			foreach ($results as $result) {
1631
-				if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1631
+				if (substr($mountPoint.$result['path'], 0, $rootLength + 1) === $this->fakeRoot.'/') {
1632 1632
 					$internalPath = $result['path'];
1633
-					$path = $mountPoint . $result['path'];
1634
-					$result['path'] = substr($mountPoint . $result['path'], $rootLength);
1633
+					$path = $mountPoint.$result['path'];
1634
+					$result['path'] = substr($mountPoint.$result['path'], $rootLength);
1635 1635
 					$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1636 1636
 					$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1637 1637
 				}
@@ -1649,8 +1649,8 @@  discard block
 block discarded – undo
1649 1649
 					if ($results) {
1650 1650
 						foreach ($results as $result) {
1651 1651
 							$internalPath = $result['path'];
1652
-							$result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1653
-							$path = rtrim($mountPoint . $internalPath, '/');
1652
+							$result['path'] = rtrim($relativeMountPoint.$result['path'], '/');
1653
+							$path = rtrim($mountPoint.$internalPath, '/');
1654 1654
 							$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1655 1655
 							$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1656 1656
 						}
@@ -1671,7 +1671,7 @@  discard block
 block discarded – undo
1671 1671
 	public function getOwner($path) {
1672 1672
 		$info = $this->getFileInfo($path);
1673 1673
 		if (!$info) {
1674
-			throw new NotFoundException($path . ' not found while trying to get owner');
1674
+			throw new NotFoundException($path.' not found while trying to get owner');
1675 1675
 		}
1676 1676
 		return $info->getOwner()->getUID();
1677 1677
 	}
@@ -1705,7 +1705,7 @@  discard block
 block discarded – undo
1705 1705
 	 * @return string
1706 1706
 	 */
1707 1707
 	public function getPath($id) {
1708
-		$id = (int)$id;
1708
+		$id = (int) $id;
1709 1709
 		$manager = Filesystem::getMountManager();
1710 1710
 		$mounts = $manager->findIn($this->fakeRoot);
1711 1711
 		$mounts[] = $manager->find($this->fakeRoot);
@@ -1720,7 +1720,7 @@  discard block
 block discarded – undo
1720 1720
 				$cache = $mount->getStorage()->getCache();
1721 1721
 				$internalPath = $cache->getPathById($id);
1722 1722
 				if (is_string($internalPath)) {
1723
-					$fullPath = $mount->getMountPoint() . $internalPath;
1723
+					$fullPath = $mount->getMountPoint().$internalPath;
1724 1724
 					if (!is_null($path = $this->getRelativePath($fullPath))) {
1725 1725
 						return $path;
1726 1726
 					}
@@ -1763,10 +1763,10 @@  discard block
 block discarded – undo
1763 1763
 		}
1764 1764
 
1765 1765
 		// note: cannot use the view because the target is already locked
1766
-		$fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1766
+		$fileId = (int) $targetStorage->getCache()->getId($targetInternalPath);
1767 1767
 		if ($fileId === -1) {
1768 1768
 			// target might not exist, need to check parent instead
1769
-			$fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1769
+			$fileId = (int) $targetStorage->getCache()->getId(dirname($targetInternalPath));
1770 1770
 		}
1771 1771
 
1772 1772
 		// check if any of the parents were shared by the current owner (include collections)
@@ -1866,7 +1866,7 @@  discard block
 block discarded – undo
1866 1866
 		$resultPath = '';
1867 1867
 		foreach ($parts as $part) {
1868 1868
 			if ($part) {
1869
-				$resultPath .= '/' . $part;
1869
+				$resultPath .= '/'.$part;
1870 1870
 				$result[] = $resultPath;
1871 1871
 			}
1872 1872
 		}
@@ -2129,16 +2129,16 @@  discard block
 block discarded – undo
2129 2129
 	public function getUidAndFilename($filename) {
2130 2130
 		$info = $this->getFileInfo($filename);
2131 2131
 		if (!$info instanceof \OCP\Files\FileInfo) {
2132
-			throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2132
+			throw new NotFoundException($this->getAbsolutePath($filename).' not found');
2133 2133
 		}
2134 2134
 		$uid = $info->getOwner()->getUID();
2135 2135
 		if ($uid != \OCP\User::getUser()) {
2136 2136
 			Filesystem::initMountPoints($uid);
2137
-			$ownerView = new View('/' . $uid . '/files');
2137
+			$ownerView = new View('/'.$uid.'/files');
2138 2138
 			try {
2139 2139
 				$filename = $ownerView->getPath($info['fileid']);
2140 2140
 			} catch (NotFoundException $e) {
2141
-				throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2141
+				throw new NotFoundException('File with id '.$info['fileid'].' not found for user '.$uid);
2142 2142
 			}
2143 2143
 		}
2144 2144
 		return [$uid, $filename];
@@ -2155,7 +2155,7 @@  discard block
 block discarded – undo
2155 2155
 		$directoryParts = array_filter($directoryParts);
2156 2156
 		foreach ($directoryParts as $key => $part) {
2157 2157
 			$currentPathElements = array_slice($directoryParts, 0, $key);
2158
-			$currentPath = '/' . implode('/', $currentPathElements);
2158
+			$currentPath = '/'.implode('/', $currentPathElements);
2159 2159
 			if ($this->is_file($currentPath)) {
2160 2160
 				return false;
2161 2161
 			}
Please login to merge, or discard this patch.
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.
apps/dav/lib/SystemTag/SystemTagsObjectMappingCollection.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -89,6 +89,9 @@
 block discarded – undo
89 89
 		$this->user = $user;
90 90
 	}
91 91
 
92
+	/**
93
+	 * @param string $tagId
94
+	 */
92 95
 	function createFile($tagId, $data = null) {
93 96
 		try {
94 97
 			$tags = $this->tagManager->getTagsByIds([$tagId]);
Please login to merge, or discard this patch.
Indentation   +165 added lines, -165 removed lines patch added patch discarded remove patch
@@ -39,169 +39,169 @@
 block discarded – undo
39 39
  */
40 40
 class SystemTagsObjectMappingCollection implements ICollection {
41 41
 
42
-	/**
43
-	 * @var string
44
-	 */
45
-	private $objectId;
46
-
47
-	/**
48
-	 * @var string
49
-	 */
50
-	private $objectType;
51
-
52
-	/**
53
-	 * @var ISystemTagManager
54
-	 */
55
-	private $tagManager;
56
-
57
-	/**
58
-	 * @var ISystemTagObjectMapper
59
-	 */
60
-	private $tagMapper;
61
-
62
-	/**
63
-	 * User
64
-	 *
65
-	 * @var IUser
66
-	 */
67
-	private $user;
68
-
69
-
70
-	/**
71
-	 * Constructor
72
-	 *
73
-	 * @param string $objectId object id
74
-	 * @param string $objectType object type
75
-	 * @param IUser $user user
76
-	 * @param ISystemTagManager $tagManager tag manager
77
-	 * @param ISystemTagObjectMapper $tagMapper tag mapper
78
-	 */
79
-	public function __construct(
80
-		$objectId,
81
-		$objectType,
82
-		IUser $user,
83
-		ISystemTagManager $tagManager,
84
-		ISystemTagObjectMapper $tagMapper
85
-	) {
86
-		$this->tagManager = $tagManager;
87
-		$this->tagMapper = $tagMapper;
88
-		$this->objectId = $objectId;
89
-		$this->objectType = $objectType;
90
-		$this->user = $user;
91
-	}
92
-
93
-	function createFile($tagId, $data = null) {
94
-		try {
95
-			$tags = $this->tagManager->getTagsByIds([$tagId]);
96
-			$tag = current($tags);
97
-			if (!$this->tagManager->canUserSeeTag($tag, $this->user)) {
98
-				throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
99
-			}
100
-			if (!$this->tagManager->canUserAssignTag($tag, $this->user)) {
101
-				throw new Forbidden('No permission to assign tag ' . $tagId);
102
-			}
103
-
104
-			$this->tagMapper->assignTags($this->objectId, $this->objectType, $tagId);
105
-		} catch (TagNotFoundException $e) {
106
-			throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
107
-		}
108
-	}
109
-
110
-	function createDirectory($name) {
111
-		throw new Forbidden('Permission denied to create collections');
112
-	}
113
-
114
-	function getChild($tagId) {
115
-		try {
116
-			if ($this->tagMapper->haveTag([$this->objectId], $this->objectType, $tagId, true)) {
117
-				$tag = $this->tagManager->getTagsByIds([$tagId]);
118
-				$tag = current($tag);
119
-				if ($this->tagManager->canUserSeeTag($tag, $this->user)) {
120
-					return $this->makeNode($tag);
121
-				}
122
-			}
123
-			throw new NotFound('Tag with id ' . $tagId . ' not present for object ' . $this->objectId);
124
-		} catch (\InvalidArgumentException $e) {
125
-			throw new BadRequest('Invalid tag id', 0, $e);
126
-		} catch (TagNotFoundException $e) {
127
-			throw new NotFound('Tag with id ' . $tagId . ' not found', 0, $e);
128
-		}
129
-	}
130
-
131
-	function getChildren() {
132
-		$tagIds = current($this->tagMapper->getTagIdsForObjects([$this->objectId], $this->objectType));
133
-		if (empty($tagIds)) {
134
-			return [];
135
-		}
136
-		$tags = $this->tagManager->getTagsByIds($tagIds);
137
-
138
-		// filter out non-visible tags
139
-		$tags = array_filter($tags, function($tag) {
140
-			return $this->tagManager->canUserSeeTag($tag, $this->user);
141
-		});
142
-
143
-		return array_values(array_map(function($tag) {
144
-			return $this->makeNode($tag);
145
-		}, $tags));
146
-	}
147
-
148
-	function childExists($tagId) {
149
-		try {
150
-			$result = ($this->tagMapper->haveTag([$this->objectId], $this->objectType, $tagId, true));
151
-
152
-			if ($result) {
153
-				$tags = $this->tagManager->getTagsByIds([$tagId]);
154
-				$tag = current($tags);
155
-				if (!$this->tagManager->canUserSeeTag($tag, $this->user)) {
156
-					return false;
157
-				}
158
-			}
159
-
160
-			return $result;
161
-		} catch (\InvalidArgumentException $e) {
162
-			throw new BadRequest('Invalid tag id', 0, $e);
163
-		} catch (TagNotFoundException $e) {
164
-			return false;
165
-		}
166
-	}
167
-
168
-	function delete() {
169
-		throw new Forbidden('Permission denied to delete this collection');
170
-	}
171
-
172
-	function getName() {
173
-		return $this->objectId;
174
-	}
175
-
176
-	function setName($name) {
177
-		throw new Forbidden('Permission denied to rename this collection');
178
-	}
179
-
180
-	/**
181
-	 * Returns the last modification time, as a unix timestamp
182
-	 *
183
-	 * @return int
184
-	 */
185
-	function getLastModified() {
186
-		return null;
187
-	}
188
-
189
-	/**
190
-	 * Create a sabre node for the mapping of the 
191
-	 * given system tag to the collection's object
192
-	 *
193
-	 * @param ISystemTag $tag
194
-	 *
195
-	 * @return SystemTagMappingNode
196
-	 */
197
-	private function makeNode(ISystemTag $tag) {
198
-		return new SystemTagMappingNode(
199
-			$tag,
200
-			$this->objectId,
201
-			$this->objectType,
202
-			$this->user,
203
-			$this->tagManager,
204
-			$this->tagMapper
205
-		);
206
-	}
42
+    /**
43
+     * @var string
44
+     */
45
+    private $objectId;
46
+
47
+    /**
48
+     * @var string
49
+     */
50
+    private $objectType;
51
+
52
+    /**
53
+     * @var ISystemTagManager
54
+     */
55
+    private $tagManager;
56
+
57
+    /**
58
+     * @var ISystemTagObjectMapper
59
+     */
60
+    private $tagMapper;
61
+
62
+    /**
63
+     * User
64
+     *
65
+     * @var IUser
66
+     */
67
+    private $user;
68
+
69
+
70
+    /**
71
+     * Constructor
72
+     *
73
+     * @param string $objectId object id
74
+     * @param string $objectType object type
75
+     * @param IUser $user user
76
+     * @param ISystemTagManager $tagManager tag manager
77
+     * @param ISystemTagObjectMapper $tagMapper tag mapper
78
+     */
79
+    public function __construct(
80
+        $objectId,
81
+        $objectType,
82
+        IUser $user,
83
+        ISystemTagManager $tagManager,
84
+        ISystemTagObjectMapper $tagMapper
85
+    ) {
86
+        $this->tagManager = $tagManager;
87
+        $this->tagMapper = $tagMapper;
88
+        $this->objectId = $objectId;
89
+        $this->objectType = $objectType;
90
+        $this->user = $user;
91
+    }
92
+
93
+    function createFile($tagId, $data = null) {
94
+        try {
95
+            $tags = $this->tagManager->getTagsByIds([$tagId]);
96
+            $tag = current($tags);
97
+            if (!$this->tagManager->canUserSeeTag($tag, $this->user)) {
98
+                throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
99
+            }
100
+            if (!$this->tagManager->canUserAssignTag($tag, $this->user)) {
101
+                throw new Forbidden('No permission to assign tag ' . $tagId);
102
+            }
103
+
104
+            $this->tagMapper->assignTags($this->objectId, $this->objectType, $tagId);
105
+        } catch (TagNotFoundException $e) {
106
+            throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
107
+        }
108
+    }
109
+
110
+    function createDirectory($name) {
111
+        throw new Forbidden('Permission denied to create collections');
112
+    }
113
+
114
+    function getChild($tagId) {
115
+        try {
116
+            if ($this->tagMapper->haveTag([$this->objectId], $this->objectType, $tagId, true)) {
117
+                $tag = $this->tagManager->getTagsByIds([$tagId]);
118
+                $tag = current($tag);
119
+                if ($this->tagManager->canUserSeeTag($tag, $this->user)) {
120
+                    return $this->makeNode($tag);
121
+                }
122
+            }
123
+            throw new NotFound('Tag with id ' . $tagId . ' not present for object ' . $this->objectId);
124
+        } catch (\InvalidArgumentException $e) {
125
+            throw new BadRequest('Invalid tag id', 0, $e);
126
+        } catch (TagNotFoundException $e) {
127
+            throw new NotFound('Tag with id ' . $tagId . ' not found', 0, $e);
128
+        }
129
+    }
130
+
131
+    function getChildren() {
132
+        $tagIds = current($this->tagMapper->getTagIdsForObjects([$this->objectId], $this->objectType));
133
+        if (empty($tagIds)) {
134
+            return [];
135
+        }
136
+        $tags = $this->tagManager->getTagsByIds($tagIds);
137
+
138
+        // filter out non-visible tags
139
+        $tags = array_filter($tags, function($tag) {
140
+            return $this->tagManager->canUserSeeTag($tag, $this->user);
141
+        });
142
+
143
+        return array_values(array_map(function($tag) {
144
+            return $this->makeNode($tag);
145
+        }, $tags));
146
+    }
147
+
148
+    function childExists($tagId) {
149
+        try {
150
+            $result = ($this->tagMapper->haveTag([$this->objectId], $this->objectType, $tagId, true));
151
+
152
+            if ($result) {
153
+                $tags = $this->tagManager->getTagsByIds([$tagId]);
154
+                $tag = current($tags);
155
+                if (!$this->tagManager->canUserSeeTag($tag, $this->user)) {
156
+                    return false;
157
+                }
158
+            }
159
+
160
+            return $result;
161
+        } catch (\InvalidArgumentException $e) {
162
+            throw new BadRequest('Invalid tag id', 0, $e);
163
+        } catch (TagNotFoundException $e) {
164
+            return false;
165
+        }
166
+    }
167
+
168
+    function delete() {
169
+        throw new Forbidden('Permission denied to delete this collection');
170
+    }
171
+
172
+    function getName() {
173
+        return $this->objectId;
174
+    }
175
+
176
+    function setName($name) {
177
+        throw new Forbidden('Permission denied to rename this collection');
178
+    }
179
+
180
+    /**
181
+     * Returns the last modification time, as a unix timestamp
182
+     *
183
+     * @return int
184
+     */
185
+    function getLastModified() {
186
+        return null;
187
+    }
188
+
189
+    /**
190
+     * Create a sabre node for the mapping of the 
191
+     * given system tag to the collection's object
192
+     *
193
+     * @param ISystemTag $tag
194
+     *
195
+     * @return SystemTagMappingNode
196
+     */
197
+    private function makeNode(ISystemTag $tag) {
198
+        return new SystemTagMappingNode(
199
+            $tag,
200
+            $this->objectId,
201
+            $this->objectType,
202
+            $this->user,
203
+            $this->tagManager,
204
+            $this->tagMapper
205
+        );
206
+    }
207 207
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -95,15 +95,15 @@  discard block
 block discarded – undo
95 95
 			$tags = $this->tagManager->getTagsByIds([$tagId]);
96 96
 			$tag = current($tags);
97 97
 			if (!$this->tagManager->canUserSeeTag($tag, $this->user)) {
98
-				throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
98
+				throw new PreconditionFailed('Tag with id '.$tagId.' does not exist, cannot assign');
99 99
 			}
100 100
 			if (!$this->tagManager->canUserAssignTag($tag, $this->user)) {
101
-				throw new Forbidden('No permission to assign tag ' . $tagId);
101
+				throw new Forbidden('No permission to assign tag '.$tagId);
102 102
 			}
103 103
 
104 104
 			$this->tagMapper->assignTags($this->objectId, $this->objectType, $tagId);
105 105
 		} catch (TagNotFoundException $e) {
106
-			throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
106
+			throw new PreconditionFailed('Tag with id '.$tagId.' does not exist, cannot assign');
107 107
 		}
108 108
 	}
109 109
 
@@ -120,11 +120,11 @@  discard block
 block discarded – undo
120 120
 					return $this->makeNode($tag);
121 121
 				}
122 122
 			}
123
-			throw new NotFound('Tag with id ' . $tagId . ' not present for object ' . $this->objectId);
123
+			throw new NotFound('Tag with id '.$tagId.' not present for object '.$this->objectId);
124 124
 		} catch (\InvalidArgumentException $e) {
125 125
 			throw new BadRequest('Invalid tag id', 0, $e);
126 126
 		} catch (TagNotFoundException $e) {
127
-			throw new NotFound('Tag with id ' . $tagId . ' not found', 0, $e);
127
+			throw new NotFound('Tag with id '.$tagId.' not found', 0, $e);
128 128
 		}
129 129
 	}
130 130
 
Please login to merge, or discard this patch.
lib/private/DB/Migrator.php 3 patches
Doc Comments   +8 added lines patch added patch discarded remove patch
@@ -273,6 +273,10 @@  discard block
 block discarded – undo
273 273
 		return '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
274 274
 	}
275 275
 
276
+	/**
277
+	 * @param integer $step
278
+	 * @param integer $max
279
+	 */
276 280
 	protected function emit($sql, $step, $max) {
277 281
 		if ($this->noEmit) {
278 282
 			return;
@@ -283,6 +287,10 @@  discard block
 block discarded – undo
283 287
 		$this->dispatcher->dispatch('\OC\DB\Migrator::executeSql', new GenericEvent($sql, [$step+1, $max]));
284 288
 	}
285 289
 
290
+	/**
291
+	 * @param integer $step
292
+	 * @param integer $max
293
+	 */
286 294
 	private function emitCheckStep($tableName, $step, $max) {
287 295
 		if(is_null($this->dispatcher)) {
288 296
 			return;
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -137,7 +137,7 @@  discard block
 block discarded – undo
137 137
 	 * @return string
138 138
 	 */
139 139
 	protected function generateTemporaryTableName($name) {
140
-		return $this->config->getSystemValue('dbtableprefix', 'oc_') . $name . '_' . $this->random->generate(13, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
140
+		return $this->config->getSystemValue('dbtableprefix', 'oc_').$name.'_'.$this->random->generate(13, ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_DIGITS);
141 141
 	}
142 142
 
143 143
 	/**
@@ -188,7 +188,7 @@  discard block
 block discarded – undo
188 188
 				$indexName = $index->getName();
189 189
 			} else {
190 190
 				// avoid conflicts in index names
191
-				$indexName = $this->config->getSystemValue('dbtableprefix', 'oc_') . $this->random->generate(13, ISecureRandom::CHAR_LOWER);
191
+				$indexName = $this->config->getSystemValue('dbtableprefix', 'oc_').$this->random->generate(13, ISecureRandom::CHAR_LOWER);
192 192
 			}
193 193
 			$newIndexes[] = new Index($indexName, $index->getColumns(), $index->isUnique(), $index->isPrimary());
194 194
 		}
@@ -268,15 +268,15 @@  discard block
 block discarded – undo
268 268
 		$quotedSource = $this->connection->quoteIdentifier($sourceName);
269 269
 		$quotedTarget = $this->connection->quoteIdentifier($targetName);
270 270
 
271
-		$this->connection->exec('CREATE TABLE ' . $quotedTarget . ' (LIKE ' . $quotedSource . ')');
272
-		$this->connection->exec('INSERT INTO ' . $quotedTarget . ' SELECT * FROM ' . $quotedSource);
271
+		$this->connection->exec('CREATE TABLE '.$quotedTarget.' (LIKE '.$quotedSource.')');
272
+		$this->connection->exec('INSERT INTO '.$quotedTarget.' SELECT * FROM '.$quotedSource);
273 273
 	}
274 274
 
275 275
 	/**
276 276
 	 * @param string $name
277 277
 	 */
278 278
 	protected function dropTable($name) {
279
-		$this->connection->exec('DROP TABLE ' . $this->connection->quoteIdentifier($name));
279
+		$this->connection->exec('DROP TABLE '.$this->connection->quoteIdentifier($name));
280 280
 	}
281 281
 
282 282
 	/**
@@ -284,30 +284,30 @@  discard block
 block discarded – undo
284 284
 	 * @return string
285 285
 	 */
286 286
 	protected function convertStatementToScript($statement) {
287
-		$script = $statement . ';';
287
+		$script = $statement.';';
288 288
 		$script .= PHP_EOL;
289 289
 		$script .= PHP_EOL;
290 290
 		return $script;
291 291
 	}
292 292
 
293 293
 	protected function getFilterExpression() {
294
-		return '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
294
+		return '/^'.preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')).'/';
295 295
 	}
296 296
 
297 297
 	protected function emit($sql, $step, $max) {
298 298
 		if ($this->noEmit) {
299 299
 			return;
300 300
 		}
301
-		if(is_null($this->dispatcher)) {
301
+		if (is_null($this->dispatcher)) {
302 302
 			return;
303 303
 		}
304
-		$this->dispatcher->dispatch('\OC\DB\Migrator::executeSql', new GenericEvent($sql, [$step+1, $max]));
304
+		$this->dispatcher->dispatch('\OC\DB\Migrator::executeSql', new GenericEvent($sql, [$step + 1, $max]));
305 305
 	}
306 306
 
307 307
 	private function emitCheckStep($tableName, $step, $max) {
308
-		if(is_null($this->dispatcher)) {
308
+		if (is_null($this->dispatcher)) {
309 309
 			return;
310 310
 		}
311
-		$this->dispatcher->dispatch('\OC\DB\Migrator::checkTable', new GenericEvent($tableName, [$step+1, $max]));
311
+		$this->dispatcher->dispatch('\OC\DB\Migrator::checkTable', new GenericEvent($tableName, [$step + 1, $max]));
312 312
 	}
313 313
 }
Please login to merge, or discard this patch.
Indentation   +268 added lines, -268 removed lines patch added patch discarded remove patch
@@ -43,272 +43,272 @@
 block discarded – undo
43 43
 
44 44
 class Migrator {
45 45
 
46
-	/** @var \Doctrine\DBAL\Connection */
47
-	protected $connection;
48
-
49
-	/** @var ISecureRandom */
50
-	private $random;
51
-
52
-	/** @var IConfig */
53
-	protected $config;
54
-
55
-	/** @var EventDispatcher  */
56
-	private $dispatcher;
57
-
58
-	/** @var bool */
59
-	private $noEmit = false;
60
-
61
-	/**
62
-	 * @param \Doctrine\DBAL\Connection|Connection $connection
63
-	 * @param ISecureRandom $random
64
-	 * @param IConfig $config
65
-	 * @param EventDispatcher $dispatcher
66
-	 */
67
-	public function __construct(\Doctrine\DBAL\Connection $connection,
68
-								ISecureRandom $random,
69
-								IConfig $config,
70
-								EventDispatcher $dispatcher = null) {
71
-		$this->connection = $connection;
72
-		$this->random = $random;
73
-		$this->config = $config;
74
-		$this->dispatcher = $dispatcher;
75
-	}
76
-
77
-	/**
78
-	 * @param \Doctrine\DBAL\Schema\Schema $targetSchema
79
-	 */
80
-	public function migrate(Schema $targetSchema) {
81
-		$this->noEmit = true;
82
-		$this->applySchema($targetSchema);
83
-	}
84
-
85
-	/**
86
-	 * @param \Doctrine\DBAL\Schema\Schema $targetSchema
87
-	 * @return string
88
-	 */
89
-	public function generateChangeScript(Schema $targetSchema) {
90
-		$schemaDiff = $this->getDiff($targetSchema, $this->connection);
91
-
92
-		$script = '';
93
-		$sqls = $schemaDiff->toSql($this->connection->getDatabasePlatform());
94
-		foreach ($sqls as $sql) {
95
-			$script .= $this->convertStatementToScript($sql);
96
-		}
97
-
98
-		return $script;
99
-	}
100
-
101
-	/**
102
-	 * @param Schema $targetSchema
103
-	 * @throws \OC\DB\MigrationException
104
-	 */
105
-	public function checkMigrate(Schema $targetSchema) {
106
-		$this->noEmit = true;
107
-		/**@var \Doctrine\DBAL\Schema\Table[] $tables */
108
-		$tables = $targetSchema->getTables();
109
-		$filterExpression = $this->getFilterExpression();
110
-		$this->connection->getConfiguration()->
111
-			setFilterSchemaAssetsExpression($filterExpression);
112
-		$existingTables = $this->connection->getSchemaManager()->listTableNames();
113
-
114
-		$step = 0;
115
-		foreach ($tables as $table) {
116
-			if (strpos($table->getName(), '.')) {
117
-				list(, $tableName) = explode('.', $table->getName());
118
-			} else {
119
-				$tableName = $table->getName();
120
-			}
121
-			$this->emitCheckStep($tableName, $step++, count($tables));
122
-			// don't need to check for new tables
123
-			if (array_search($tableName, $existingTables) !== false) {
124
-				$this->checkTableMigrate($table);
125
-			}
126
-		}
127
-	}
128
-
129
-	/**
130
-	 * Create a unique name for the temporary table
131
-	 *
132
-	 * @param string $name
133
-	 * @return string
134
-	 */
135
-	protected function generateTemporaryTableName($name) {
136
-		return $this->config->getSystemValue('dbtableprefix', 'oc_') . $name . '_' . $this->random->generate(13, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
137
-	}
138
-
139
-	/**
140
-	 * Check the migration of a table on a copy so we can detect errors before messing with the real table
141
-	 *
142
-	 * @param \Doctrine\DBAL\Schema\Table $table
143
-	 * @throws \OC\DB\MigrationException
144
-	 */
145
-	protected function checkTableMigrate(Table $table) {
146
-		$name = $table->getName();
147
-		$tmpName = $this->generateTemporaryTableName($name);
148
-
149
-		$this->copyTable($name, $tmpName);
150
-
151
-		//create the migration schema for the temporary table
152
-		$tmpTable = $this->renameTableSchema($table, $tmpName);
153
-		$schemaConfig = new SchemaConfig();
154
-		$schemaConfig->setName($this->connection->getDatabase());
155
-		$schema = new Schema(array($tmpTable), array(), $schemaConfig);
156
-
157
-		try {
158
-			$this->applySchema($schema);
159
-			$this->dropTable($tmpName);
160
-		} catch (DBALException $e) {
161
-			// pgsql needs to commit it's failed transaction before doing anything else
162
-			if ($this->connection->isTransactionActive()) {
163
-				$this->connection->commit();
164
-			}
165
-			$this->dropTable($tmpName);
166
-			throw new MigrationException($table->getName(), $e->getMessage());
167
-		}
168
-	}
169
-
170
-	/**
171
-	 * @param \Doctrine\DBAL\Schema\Table $table
172
-	 * @param string $newName
173
-	 * @return \Doctrine\DBAL\Schema\Table
174
-	 */
175
-	protected function renameTableSchema(Table $table, $newName) {
176
-		/**
177
-		 * @var \Doctrine\DBAL\Schema\Index[] $indexes
178
-		 */
179
-		$indexes = $table->getIndexes();
180
-		$newIndexes = array();
181
-		foreach ($indexes as $index) {
182
-			if ($index->isPrimary()) {
183
-				// do not rename primary key
184
-				$indexName = $index->getName();
185
-			} else {
186
-				// avoid conflicts in index names
187
-				$indexName = $this->config->getSystemValue('dbtableprefix', 'oc_') . $this->random->generate(13, ISecureRandom::CHAR_LOWER);
188
-			}
189
-			$newIndexes[] = new Index($indexName, $index->getColumns(), $index->isUnique(), $index->isPrimary());
190
-		}
191
-
192
-		// foreign keys are not supported so we just set it to an empty array
193
-		return new Table($newName, $table->getColumns(), $newIndexes, array(), 0, $table->getOptions());
194
-	}
195
-
196
-	public function createSchema() {
197
-		$filterExpression = $this->getFilterExpression();
198
-		$this->connection->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression);
199
-		return $this->connection->getSchemaManager()->createSchema();
200
-	}
201
-
202
-	/**
203
-	 * @param Schema $targetSchema
204
-	 * @param \Doctrine\DBAL\Connection $connection
205
-	 * @return \Doctrine\DBAL\Schema\SchemaDiff
206
-	 * @throws DBALException
207
-	 */
208
-	protected function getDiff(Schema $targetSchema, \Doctrine\DBAL\Connection $connection) {
209
-		// adjust varchar columns with a length higher then getVarcharMaxLength to clob
210
-		foreach ($targetSchema->getTables() as $table) {
211
-			foreach ($table->getColumns() as $column) {
212
-				if ($column->getType() instanceof StringType) {
213
-					if ($column->getLength() > $connection->getDatabasePlatform()->getVarcharMaxLength()) {
214
-						$column->setType(Type::getType('text'));
215
-						$column->setLength(null);
216
-					}
217
-				}
218
-			}
219
-		}
220
-
221
-		$filterExpression = $this->getFilterExpression();
222
-		$this->connection->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression);
223
-		$sourceSchema = $connection->getSchemaManager()->createSchema();
224
-
225
-		// remove tables we don't know about
226
-		/** @var $table \Doctrine\DBAL\Schema\Table */
227
-		foreach ($sourceSchema->getTables() as $table) {
228
-			if (!$targetSchema->hasTable($table->getName())) {
229
-				$sourceSchema->dropTable($table->getName());
230
-			}
231
-		}
232
-		// remove sequences we don't know about
233
-		foreach ($sourceSchema->getSequences() as $table) {
234
-			if (!$targetSchema->hasSequence($table->getName())) {
235
-				$sourceSchema->dropSequence($table->getName());
236
-			}
237
-		}
238
-
239
-		$comparator = new Comparator();
240
-		return $comparator->compare($sourceSchema, $targetSchema);
241
-	}
242
-
243
-	/**
244
-	 * @param \Doctrine\DBAL\Schema\Schema $targetSchema
245
-	 * @param \Doctrine\DBAL\Connection $connection
246
-	 */
247
-	protected function applySchema(Schema $targetSchema, \Doctrine\DBAL\Connection $connection = null) {
248
-		if (is_null($connection)) {
249
-			$connection = $this->connection;
250
-		}
251
-
252
-		$schemaDiff = $this->getDiff($targetSchema, $connection);
253
-
254
-		$connection->beginTransaction();
255
-		$sqls = $schemaDiff->toSql($connection->getDatabasePlatform());
256
-		$step = 0;
257
-		foreach ($sqls as $sql) {
258
-			$this->emit($sql, $step++, count($sqls));
259
-			$connection->query($sql);
260
-		}
261
-		$connection->commit();
262
-	}
263
-
264
-	/**
265
-	 * @param string $sourceName
266
-	 * @param string $targetName
267
-	 */
268
-	protected function copyTable($sourceName, $targetName) {
269
-		$quotedSource = $this->connection->quoteIdentifier($sourceName);
270
-		$quotedTarget = $this->connection->quoteIdentifier($targetName);
271
-
272
-		$this->connection->exec('CREATE TABLE ' . $quotedTarget . ' (LIKE ' . $quotedSource . ')');
273
-		$this->connection->exec('INSERT INTO ' . $quotedTarget . ' SELECT * FROM ' . $quotedSource);
274
-	}
275
-
276
-	/**
277
-	 * @param string $name
278
-	 */
279
-	protected function dropTable($name) {
280
-		$this->connection->exec('DROP TABLE ' . $this->connection->quoteIdentifier($name));
281
-	}
282
-
283
-	/**
284
-	 * @param $statement
285
-	 * @return string
286
-	 */
287
-	protected function convertStatementToScript($statement) {
288
-		$script = $statement . ';';
289
-		$script .= PHP_EOL;
290
-		$script .= PHP_EOL;
291
-		return $script;
292
-	}
293
-
294
-	protected function getFilterExpression() {
295
-		return '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
296
-	}
297
-
298
-	protected function emit($sql, $step, $max) {
299
-		if ($this->noEmit) {
300
-			return;
301
-		}
302
-		if(is_null($this->dispatcher)) {
303
-			return;
304
-		}
305
-		$this->dispatcher->dispatch('\OC\DB\Migrator::executeSql', new GenericEvent($sql, [$step+1, $max]));
306
-	}
307
-
308
-	private function emitCheckStep($tableName, $step, $max) {
309
-		if(is_null($this->dispatcher)) {
310
-			return;
311
-		}
312
-		$this->dispatcher->dispatch('\OC\DB\Migrator::checkTable', new GenericEvent($tableName, [$step+1, $max]));
313
-	}
46
+    /** @var \Doctrine\DBAL\Connection */
47
+    protected $connection;
48
+
49
+    /** @var ISecureRandom */
50
+    private $random;
51
+
52
+    /** @var IConfig */
53
+    protected $config;
54
+
55
+    /** @var EventDispatcher  */
56
+    private $dispatcher;
57
+
58
+    /** @var bool */
59
+    private $noEmit = false;
60
+
61
+    /**
62
+     * @param \Doctrine\DBAL\Connection|Connection $connection
63
+     * @param ISecureRandom $random
64
+     * @param IConfig $config
65
+     * @param EventDispatcher $dispatcher
66
+     */
67
+    public function __construct(\Doctrine\DBAL\Connection $connection,
68
+                                ISecureRandom $random,
69
+                                IConfig $config,
70
+                                EventDispatcher $dispatcher = null) {
71
+        $this->connection = $connection;
72
+        $this->random = $random;
73
+        $this->config = $config;
74
+        $this->dispatcher = $dispatcher;
75
+    }
76
+
77
+    /**
78
+     * @param \Doctrine\DBAL\Schema\Schema $targetSchema
79
+     */
80
+    public function migrate(Schema $targetSchema) {
81
+        $this->noEmit = true;
82
+        $this->applySchema($targetSchema);
83
+    }
84
+
85
+    /**
86
+     * @param \Doctrine\DBAL\Schema\Schema $targetSchema
87
+     * @return string
88
+     */
89
+    public function generateChangeScript(Schema $targetSchema) {
90
+        $schemaDiff = $this->getDiff($targetSchema, $this->connection);
91
+
92
+        $script = '';
93
+        $sqls = $schemaDiff->toSql($this->connection->getDatabasePlatform());
94
+        foreach ($sqls as $sql) {
95
+            $script .= $this->convertStatementToScript($sql);
96
+        }
97
+
98
+        return $script;
99
+    }
100
+
101
+    /**
102
+     * @param Schema $targetSchema
103
+     * @throws \OC\DB\MigrationException
104
+     */
105
+    public function checkMigrate(Schema $targetSchema) {
106
+        $this->noEmit = true;
107
+        /**@var \Doctrine\DBAL\Schema\Table[] $tables */
108
+        $tables = $targetSchema->getTables();
109
+        $filterExpression = $this->getFilterExpression();
110
+        $this->connection->getConfiguration()->
111
+            setFilterSchemaAssetsExpression($filterExpression);
112
+        $existingTables = $this->connection->getSchemaManager()->listTableNames();
113
+
114
+        $step = 0;
115
+        foreach ($tables as $table) {
116
+            if (strpos($table->getName(), '.')) {
117
+                list(, $tableName) = explode('.', $table->getName());
118
+            } else {
119
+                $tableName = $table->getName();
120
+            }
121
+            $this->emitCheckStep($tableName, $step++, count($tables));
122
+            // don't need to check for new tables
123
+            if (array_search($tableName, $existingTables) !== false) {
124
+                $this->checkTableMigrate($table);
125
+            }
126
+        }
127
+    }
128
+
129
+    /**
130
+     * Create a unique name for the temporary table
131
+     *
132
+     * @param string $name
133
+     * @return string
134
+     */
135
+    protected function generateTemporaryTableName($name) {
136
+        return $this->config->getSystemValue('dbtableprefix', 'oc_') . $name . '_' . $this->random->generate(13, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
137
+    }
138
+
139
+    /**
140
+     * Check the migration of a table on a copy so we can detect errors before messing with the real table
141
+     *
142
+     * @param \Doctrine\DBAL\Schema\Table $table
143
+     * @throws \OC\DB\MigrationException
144
+     */
145
+    protected function checkTableMigrate(Table $table) {
146
+        $name = $table->getName();
147
+        $tmpName = $this->generateTemporaryTableName($name);
148
+
149
+        $this->copyTable($name, $tmpName);
150
+
151
+        //create the migration schema for the temporary table
152
+        $tmpTable = $this->renameTableSchema($table, $tmpName);
153
+        $schemaConfig = new SchemaConfig();
154
+        $schemaConfig->setName($this->connection->getDatabase());
155
+        $schema = new Schema(array($tmpTable), array(), $schemaConfig);
156
+
157
+        try {
158
+            $this->applySchema($schema);
159
+            $this->dropTable($tmpName);
160
+        } catch (DBALException $e) {
161
+            // pgsql needs to commit it's failed transaction before doing anything else
162
+            if ($this->connection->isTransactionActive()) {
163
+                $this->connection->commit();
164
+            }
165
+            $this->dropTable($tmpName);
166
+            throw new MigrationException($table->getName(), $e->getMessage());
167
+        }
168
+    }
169
+
170
+    /**
171
+     * @param \Doctrine\DBAL\Schema\Table $table
172
+     * @param string $newName
173
+     * @return \Doctrine\DBAL\Schema\Table
174
+     */
175
+    protected function renameTableSchema(Table $table, $newName) {
176
+        /**
177
+         * @var \Doctrine\DBAL\Schema\Index[] $indexes
178
+         */
179
+        $indexes = $table->getIndexes();
180
+        $newIndexes = array();
181
+        foreach ($indexes as $index) {
182
+            if ($index->isPrimary()) {
183
+                // do not rename primary key
184
+                $indexName = $index->getName();
185
+            } else {
186
+                // avoid conflicts in index names
187
+                $indexName = $this->config->getSystemValue('dbtableprefix', 'oc_') . $this->random->generate(13, ISecureRandom::CHAR_LOWER);
188
+            }
189
+            $newIndexes[] = new Index($indexName, $index->getColumns(), $index->isUnique(), $index->isPrimary());
190
+        }
191
+
192
+        // foreign keys are not supported so we just set it to an empty array
193
+        return new Table($newName, $table->getColumns(), $newIndexes, array(), 0, $table->getOptions());
194
+    }
195
+
196
+    public function createSchema() {
197
+        $filterExpression = $this->getFilterExpression();
198
+        $this->connection->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression);
199
+        return $this->connection->getSchemaManager()->createSchema();
200
+    }
201
+
202
+    /**
203
+     * @param Schema $targetSchema
204
+     * @param \Doctrine\DBAL\Connection $connection
205
+     * @return \Doctrine\DBAL\Schema\SchemaDiff
206
+     * @throws DBALException
207
+     */
208
+    protected function getDiff(Schema $targetSchema, \Doctrine\DBAL\Connection $connection) {
209
+        // adjust varchar columns with a length higher then getVarcharMaxLength to clob
210
+        foreach ($targetSchema->getTables() as $table) {
211
+            foreach ($table->getColumns() as $column) {
212
+                if ($column->getType() instanceof StringType) {
213
+                    if ($column->getLength() > $connection->getDatabasePlatform()->getVarcharMaxLength()) {
214
+                        $column->setType(Type::getType('text'));
215
+                        $column->setLength(null);
216
+                    }
217
+                }
218
+            }
219
+        }
220
+
221
+        $filterExpression = $this->getFilterExpression();
222
+        $this->connection->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression);
223
+        $sourceSchema = $connection->getSchemaManager()->createSchema();
224
+
225
+        // remove tables we don't know about
226
+        /** @var $table \Doctrine\DBAL\Schema\Table */
227
+        foreach ($sourceSchema->getTables() as $table) {
228
+            if (!$targetSchema->hasTable($table->getName())) {
229
+                $sourceSchema->dropTable($table->getName());
230
+            }
231
+        }
232
+        // remove sequences we don't know about
233
+        foreach ($sourceSchema->getSequences() as $table) {
234
+            if (!$targetSchema->hasSequence($table->getName())) {
235
+                $sourceSchema->dropSequence($table->getName());
236
+            }
237
+        }
238
+
239
+        $comparator = new Comparator();
240
+        return $comparator->compare($sourceSchema, $targetSchema);
241
+    }
242
+
243
+    /**
244
+     * @param \Doctrine\DBAL\Schema\Schema $targetSchema
245
+     * @param \Doctrine\DBAL\Connection $connection
246
+     */
247
+    protected function applySchema(Schema $targetSchema, \Doctrine\DBAL\Connection $connection = null) {
248
+        if (is_null($connection)) {
249
+            $connection = $this->connection;
250
+        }
251
+
252
+        $schemaDiff = $this->getDiff($targetSchema, $connection);
253
+
254
+        $connection->beginTransaction();
255
+        $sqls = $schemaDiff->toSql($connection->getDatabasePlatform());
256
+        $step = 0;
257
+        foreach ($sqls as $sql) {
258
+            $this->emit($sql, $step++, count($sqls));
259
+            $connection->query($sql);
260
+        }
261
+        $connection->commit();
262
+    }
263
+
264
+    /**
265
+     * @param string $sourceName
266
+     * @param string $targetName
267
+     */
268
+    protected function copyTable($sourceName, $targetName) {
269
+        $quotedSource = $this->connection->quoteIdentifier($sourceName);
270
+        $quotedTarget = $this->connection->quoteIdentifier($targetName);
271
+
272
+        $this->connection->exec('CREATE TABLE ' . $quotedTarget . ' (LIKE ' . $quotedSource . ')');
273
+        $this->connection->exec('INSERT INTO ' . $quotedTarget . ' SELECT * FROM ' . $quotedSource);
274
+    }
275
+
276
+    /**
277
+     * @param string $name
278
+     */
279
+    protected function dropTable($name) {
280
+        $this->connection->exec('DROP TABLE ' . $this->connection->quoteIdentifier($name));
281
+    }
282
+
283
+    /**
284
+     * @param $statement
285
+     * @return string
286
+     */
287
+    protected function convertStatementToScript($statement) {
288
+        $script = $statement . ';';
289
+        $script .= PHP_EOL;
290
+        $script .= PHP_EOL;
291
+        return $script;
292
+    }
293
+
294
+    protected function getFilterExpression() {
295
+        return '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
296
+    }
297
+
298
+    protected function emit($sql, $step, $max) {
299
+        if ($this->noEmit) {
300
+            return;
301
+        }
302
+        if(is_null($this->dispatcher)) {
303
+            return;
304
+        }
305
+        $this->dispatcher->dispatch('\OC\DB\Migrator::executeSql', new GenericEvent($sql, [$step+1, $max]));
306
+    }
307
+
308
+    private function emitCheckStep($tableName, $step, $max) {
309
+        if(is_null($this->dispatcher)) {
310
+            return;
311
+        }
312
+        $this->dispatcher->dispatch('\OC\DB\Migrator::checkTable', new GenericEvent($tableName, [$step+1, $max]));
313
+    }
314 314
 }
Please login to merge, or discard this patch.
settings/Controller/CheckSetupController.php 3 patches
Doc Comments   +2 added lines, -1 removed lines patch added patch discarded remove patch
@@ -103,6 +103,7 @@  discard block
 block discarded – undo
103 103
 
104 104
 	/**
105 105
 	* Chceks if the ownCloud server can connect to a specific URL using both HTTPS and HTTP
106
+	* @param string $sitename
106 107
 	* @return bool
107 108
 	*/
108 109
 	private function isSiteReachable($sitename) {
@@ -285,7 +286,7 @@  discard block
 block discarded – undo
285 286
 
286 287
 	/**
287 288
 	 * @NoCSRFRequired
288
-	 * @return DataResponse
289
+	 * @return DataDisplayResponse
289 290
 	 */
290 291
 	public function getFailedIntegrityCheckFiles() {
291 292
 		if(!$this->checker->isCodeCheckEnforced()) {
Please login to merge, or discard this patch.
Spacing   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 						'www.google.com',
105 105
 						'www.github.com'];
106 106
 
107
-		foreach($siteArray as $site) {
107
+		foreach ($siteArray as $site) {
108 108
 			if ($this->isSiteReachable($site)) {
109 109
 				return true;
110 110
 			}
@@ -117,8 +117,8 @@  discard block
 block discarded – undo
117 117
 	* @return bool
118 118
 	*/
119 119
 	private function isSiteReachable($sitename) {
120
-		$httpSiteName = 'http://' . $sitename . '/';
121
-		$httpsSiteName = 'https://' . $sitename . '/';
120
+		$httpSiteName = 'http://'.$sitename.'/';
121
+		$httpsSiteName = 'https://'.$sitename.'/';
122 122
 
123 123
 		try {
124 124
 			$client = $this->clientService->newClient();
@@ -145,9 +145,9 @@  discard block
 block discarded – undo
145 145
 	 * @return bool
146 146
 	 */
147 147
 	private function isUrandomAvailable() {
148
-		if(@file_exists('/dev/urandom')) {
148
+		if (@file_exists('/dev/urandom')) {
149 149
 			$file = fopen('/dev/urandom', 'rb');
150
-			if($file) {
150
+			if ($file) {
151 151
 				fclose($file);
152 152
 				return true;
153 153
 			}
@@ -178,40 +178,40 @@  discard block
 block discarded – undo
178 178
 		// Don't run check when:
179 179
 		// 1. Server has `has_internet_connection` set to false
180 180
 		// 2. AppStore AND S2S is disabled
181
-		if(!$this->config->getSystemValue('has_internet_connection', true)) {
181
+		if (!$this->config->getSystemValue('has_internet_connection', true)) {
182 182
 			return '';
183 183
 		}
184
-		if(!$this->config->getSystemValue('appstoreenabled', true)
184
+		if (!$this->config->getSystemValue('appstoreenabled', true)
185 185
 			&& $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'no'
186 186
 			&& $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes') === 'no') {
187 187
 			return '';
188 188
 		}
189 189
 
190 190
 		$versionString = $this->getCurlVersion();
191
-		if(isset($versionString['ssl_version'])) {
191
+		if (isset($versionString['ssl_version'])) {
192 192
 			$versionString = $versionString['ssl_version'];
193 193
 		} else {
194 194
 			return '';
195 195
 		}
196 196
 
197
-		$features = (string)$this->l10n->t('installing and updating apps via the app store or Federated Cloud Sharing');
198
-		if(!$this->config->getSystemValue('appstoreenabled', true)) {
199
-			$features = (string)$this->l10n->t('Federated Cloud Sharing');
197
+		$features = (string) $this->l10n->t('installing and updating apps via the app store or Federated Cloud Sharing');
198
+		if (!$this->config->getSystemValue('appstoreenabled', true)) {
199
+			$features = (string) $this->l10n->t('Federated Cloud Sharing');
200 200
 		}
201 201
 
202 202
 		// Check if at least OpenSSL after 1.01d or 1.0.2b
203
-		if(strpos($versionString, 'OpenSSL/') === 0) {
203
+		if (strpos($versionString, 'OpenSSL/') === 0) {
204 204
 			$majorVersion = substr($versionString, 8, 5);
205 205
 			$patchRelease = substr($versionString, 13, 6);
206 206
 
207
-			if(($majorVersion === '1.0.1' && ord($patchRelease) < ord('d')) ||
207
+			if (($majorVersion === '1.0.1' && ord($patchRelease) < ord('d')) ||
208 208
 				($majorVersion === '1.0.2' && ord($patchRelease) < ord('b'))) {
209 209
 				return (string) $this->l10n->t('cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably.', ['OpenSSL', $versionString, $features]);
210 210
 			}
211 211
 		}
212 212
 
213 213
 		// Check if NSS and perform heuristic check
214
-		if(strpos($versionString, 'NSS/') === 0) {
214
+		if (strpos($versionString, 'NSS/') === 0) {
215 215
 			try {
216 216
 				$firstClient = $this->clientService->newClient();
217 217
 				$firstClient->get('https://nextcloud.com/');
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
 				$secondClient = $this->clientService->newClient();
220 220
 				$secondClient->get('https://nextcloud.com/');
221 221
 			} catch (ClientException $e) {
222
-				if($e->getResponse()->getStatusCode() === 400) {
222
+				if ($e->getResponse()->getStatusCode() === 400) {
223 223
 					return (string) $this->l10n->t('cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably.', ['NSS', $versionString, $features]);
224 224
 				}
225 225
 			}
@@ -314,13 +314,13 @@  discard block
 block discarded – undo
314 314
 	 * @return DataResponse
315 315
 	 */
316 316
 	public function getFailedIntegrityCheckFiles() {
317
-		if(!$this->checker->isCodeCheckEnforced()) {
317
+		if (!$this->checker->isCodeCheckEnforced()) {
318 318
 			return new DataDisplayResponse('Integrity checker has been disabled. Integrity cannot be verified.');
319 319
 		}
320 320
 
321 321
 		$completeResults = $this->checker->getResults();
322 322
 
323
-		if(!empty($completeResults)) {
323
+		if (!empty($completeResults)) {
324 324
 			$formattedTextResponse = 'Technical information
325 325
 =====================
326 326
 The following list covers which files have failed the integrity check. Please read
@@ -330,12 +330,12 @@  discard block
 block discarded – undo
330 330
 Results
331 331
 =======
332 332
 ';
333
-			foreach($completeResults as $context => $contextResult) {
333
+			foreach ($completeResults as $context => $contextResult) {
334 334
 				$formattedTextResponse .= "- $context\n";
335 335
 
336
-				foreach($contextResult as $category => $result) {
336
+				foreach ($contextResult as $category => $result) {
337 337
 					$formattedTextResponse .= "\t- $category\n";
338
-					if($category !== 'EXCEPTION') {
338
+					if ($category !== 'EXCEPTION') {
339 339
 						foreach ($result as $key => $results) {
340 340
 							$formattedTextResponse .= "\t\t- $key\n";
341 341
 						}
@@ -378,27 +378,27 @@  discard block
 block discarded – undo
378 378
 
379 379
 		$isOpcacheProperlySetUp = true;
380 380
 
381
-		if(!$iniWrapper->getBool('opcache.enable')) {
381
+		if (!$iniWrapper->getBool('opcache.enable')) {
382 382
 			$isOpcacheProperlySetUp = false;
383 383
 		}
384 384
 
385
-		if(!$iniWrapper->getBool('opcache.save_comments')) {
385
+		if (!$iniWrapper->getBool('opcache.save_comments')) {
386 386
 			$isOpcacheProperlySetUp = false;
387 387
 		}
388 388
 
389
-		if(!$iniWrapper->getBool('opcache.enable_cli')) {
389
+		if (!$iniWrapper->getBool('opcache.enable_cli')) {
390 390
 			$isOpcacheProperlySetUp = false;
391 391
 		}
392 392
 
393
-		if($iniWrapper->getNumeric('opcache.max_accelerated_files') < 10000) {
393
+		if ($iniWrapper->getNumeric('opcache.max_accelerated_files') < 10000) {
394 394
 			$isOpcacheProperlySetUp = false;
395 395
 		}
396 396
 
397
-		if($iniWrapper->getNumeric('opcache.memory_consumption') < 128) {
397
+		if ($iniWrapper->getNumeric('opcache.memory_consumption') < 128) {
398 398
 			$isOpcacheProperlySetUp = false;
399 399
 		}
400 400
 
401
-		if($iniWrapper->getNumeric('opcache.interned_strings_buffer') < 8) {
401
+		if ($iniWrapper->getNumeric('opcache.interned_strings_buffer') < 8) {
402 402
 			$isOpcacheProperlySetUp = false;
403 403
 		}
404 404
 
Please login to merge, or discard this patch.
Indentation   +381 added lines, -381 removed lines patch added patch discarded remove patch
@@ -50,282 +50,282 @@  discard block
 block discarded – undo
50 50
  * @package OC\Settings\Controller
51 51
  */
52 52
 class CheckSetupController extends Controller {
53
-	/** @var IConfig */
54
-	private $config;
55
-	/** @var IClientService */
56
-	private $clientService;
57
-	/** @var \OC_Util */
58
-	private $util;
59
-	/** @var IURLGenerator */
60
-	private $urlGenerator;
61
-	/** @var IL10N */
62
-	private $l10n;
63
-	/** @var Checker */
64
-	private $checker;
65
-	/** @var ILogger */
66
-	private $logger;
67
-
68
-	/**
69
-	 * @param string $AppName
70
-	 * @param IRequest $request
71
-	 * @param IConfig $config
72
-	 * @param IClientService $clientService
73
-	 * @param IURLGenerator $urlGenerator
74
-	 * @param \OC_Util $util
75
-	 * @param IL10N $l10n
76
-	 * @param Checker $checker
77
-	 * @param ILogger $logger
78
-	 */
79
-	public function __construct($AppName,
80
-								IRequest $request,
81
-								IConfig $config,
82
-								IClientService $clientService,
83
-								IURLGenerator $urlGenerator,
84
-								\OC_Util $util,
85
-								IL10N $l10n,
86
-								Checker $checker,
87
-								ILogger $logger) {
88
-		parent::__construct($AppName, $request);
89
-		$this->config = $config;
90
-		$this->clientService = $clientService;
91
-		$this->util = $util;
92
-		$this->urlGenerator = $urlGenerator;
93
-		$this->l10n = $l10n;
94
-		$this->checker = $checker;
95
-		$this->logger = $logger;
96
-	}
97
-
98
-	/**
99
-	 * Checks if the ownCloud server can connect to the internet using HTTPS and HTTP
100
-	 * @return bool
101
-	 */
102
-	private function isInternetConnectionWorking() {
103
-		if ($this->config->getSystemValue('has_internet_connection', true) === false) {
104
-			return false;
105
-		}
106
-
107
-		$siteArray = ['www.nextcloud.com',
108
-						'www.google.com',
109
-						'www.github.com'];
110
-
111
-		foreach($siteArray as $site) {
112
-			if ($this->isSiteReachable($site)) {
113
-				return true;
114
-			}
115
-		}
116
-		return false;
117
-	}
118
-
119
-	/**
120
-	* Chceks if the ownCloud server can connect to a specific URL using both HTTPS and HTTP
121
-	* @return bool
122
-	*/
123
-	private function isSiteReachable($sitename) {
124
-		$httpSiteName = 'http://' . $sitename . '/';
125
-		$httpsSiteName = 'https://' . $sitename . '/';
126
-
127
-		try {
128
-			$client = $this->clientService->newClient();
129
-			$client->get($httpSiteName);
130
-			$client->get($httpsSiteName);
131
-		} catch (\Exception $e) {
132
-			$this->logger->logException($e, ['app' => 'internet_connection_check']);
133
-			return false;
134
-		}
135
-		return true;
136
-	}
137
-
138
-	/**
139
-	 * Checks whether a local memcache is installed or not
140
-	 * @return bool
141
-	 */
142
-	private function isMemcacheConfigured() {
143
-		return $this->config->getSystemValue('memcache.local', null) !== null;
144
-	}
145
-
146
-	/**
147
-	 * Whether /dev/urandom is available to the PHP controller
148
-	 *
149
-	 * @return bool
150
-	 */
151
-	private function isUrandomAvailable() {
152
-		if(@file_exists('/dev/urandom')) {
153
-			$file = fopen('/dev/urandom', 'rb');
154
-			if($file) {
155
-				fclose($file);
156
-				return true;
157
-			}
158
-		}
159
-
160
-		return false;
161
-	}
162
-
163
-	/**
164
-	 * Public for the sake of unit-testing
165
-	 *
166
-	 * @return array
167
-	 */
168
-	protected function getCurlVersion() {
169
-		return curl_version();
170
-	}
171
-
172
-	/**
173
-	 * Check if the used  SSL lib is outdated. Older OpenSSL and NSS versions do
174
-	 * have multiple bugs which likely lead to problems in combination with
175
-	 * functionality required by ownCloud such as SNI.
176
-	 *
177
-	 * @link https://github.com/owncloud/core/issues/17446#issuecomment-122877546
178
-	 * @link https://bugzilla.redhat.com/show_bug.cgi?id=1241172
179
-	 * @return string
180
-	 */
181
-	private function isUsedTlsLibOutdated() {
182
-		// Don't run check when:
183
-		// 1. Server has `has_internet_connection` set to false
184
-		// 2. AppStore AND S2S is disabled
185
-		if(!$this->config->getSystemValue('has_internet_connection', true)) {
186
-			return '';
187
-		}
188
-		if(!$this->config->getSystemValue('appstoreenabled', true)
189
-			&& $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'no'
190
-			&& $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes') === 'no') {
191
-			return '';
192
-		}
193
-
194
-		$versionString = $this->getCurlVersion();
195
-		if(isset($versionString['ssl_version'])) {
196
-			$versionString = $versionString['ssl_version'];
197
-		} else {
198
-			return '';
199
-		}
200
-
201
-		$features = (string)$this->l10n->t('installing and updating apps via the app store or Federated Cloud Sharing');
202
-		if(!$this->config->getSystemValue('appstoreenabled', true)) {
203
-			$features = (string)$this->l10n->t('Federated Cloud Sharing');
204
-		}
205
-
206
-		// Check if at least OpenSSL after 1.01d or 1.0.2b
207
-		if(strpos($versionString, 'OpenSSL/') === 0) {
208
-			$majorVersion = substr($versionString, 8, 5);
209
-			$patchRelease = substr($versionString, 13, 6);
210
-
211
-			if(($majorVersion === '1.0.1' && ord($patchRelease) < ord('d')) ||
212
-				($majorVersion === '1.0.2' && ord($patchRelease) < ord('b'))) {
213
-				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]);
214
-			}
215
-		}
216
-
217
-		// Check if NSS and perform heuristic check
218
-		if(strpos($versionString, 'NSS/') === 0) {
219
-			try {
220
-				$firstClient = $this->clientService->newClient();
221
-				$firstClient->get('https://nextcloud.com/');
222
-
223
-				$secondClient = $this->clientService->newClient();
224
-				$secondClient->get('https://nextcloud.com/');
225
-			} catch (ClientException $e) {
226
-				if($e->getResponse()->getStatusCode() === 400) {
227
-					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]);
228
-				}
229
-			}
230
-		}
231
-
232
-		return '';
233
-	}
234
-
235
-	/**
236
-	 * Whether the version is outdated
237
-	 *
238
-	 * @return bool
239
-	 */
240
-	protected function isPhpOutdated() {
241
-		if (version_compare(PHP_VERSION, '7.0.0', '<')) {
242
-			return true;
243
-		}
244
-
245
-		return false;
246
-	}
247
-
248
-	/**
249
-	 * Whether the php version is still supported (at time of release)
250
-	 * according to: https://secure.php.net/supported-versions.php
251
-	 *
252
-	 * @return array
253
-	 */
254
-	private function isPhpSupported() {
255
-		return ['eol' => $this->isPhpOutdated(), 'version' => PHP_VERSION];
256
-	}
257
-
258
-	/**
259
-	 * Check if the reverse proxy configuration is working as expected
260
-	 *
261
-	 * @return bool
262
-	 */
263
-	private function forwardedForHeadersWorking() {
264
-		$trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
265
-		$remoteAddress = $this->request->getRemoteAddress();
266
-
267
-		if (is_array($trustedProxies) && in_array($remoteAddress, $trustedProxies)) {
268
-			return false;
269
-		}
270
-
271
-		// either not enabled or working correctly
272
-		return true;
273
-	}
274
-
275
-	/**
276
-	 * Checks if the correct memcache module for PHP is installed. Only
277
-	 * fails if memcached is configured and the working module is not installed.
278
-	 *
279
-	 * @return bool
280
-	 */
281
-	private function isCorrectMemcachedPHPModuleInstalled() {
282
-		if ($this->config->getSystemValue('memcache.distributed', null) !== '\OC\Memcache\Memcached') {
283
-			return true;
284
-		}
285
-
286
-		// there are two different memcached modules for PHP
287
-		// we only support memcached and not memcache
288
-		// https://code.google.com/p/memcached/wiki/PHPClientComparison
289
-		return !(!extension_loaded('memcached') && extension_loaded('memcache'));
290
-	}
291
-
292
-	/**
293
-	 * Checks if set_time_limit is not disabled.
294
-	 *
295
-	 * @return bool
296
-	 */
297
-	private function isSettimelimitAvailable() {
298
-		if (function_exists('set_time_limit')
299
-			&& strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
300
-			return true;
301
-		}
302
-
303
-		return false;
304
-	}
305
-
306
-	/**
307
-	 * @return RedirectResponse
308
-	 */
309
-	public function rescanFailedIntegrityCheck() {
310
-		$this->checker->runInstanceVerification();
311
-		return new RedirectResponse(
312
-			$this->urlGenerator->linkToRoute('settings.AdminSettings.index')
313
-		);
314
-	}
315
-
316
-	/**
317
-	 * @NoCSRFRequired
318
-	 * @return DataResponse
319
-	 */
320
-	public function getFailedIntegrityCheckFiles() {
321
-		if(!$this->checker->isCodeCheckEnforced()) {
322
-			return new DataDisplayResponse('Integrity checker has been disabled. Integrity cannot be verified.');
323
-		}
324
-
325
-		$completeResults = $this->checker->getResults();
326
-
327
-		if(!empty($completeResults)) {
328
-			$formattedTextResponse = 'Technical information
53
+    /** @var IConfig */
54
+    private $config;
55
+    /** @var IClientService */
56
+    private $clientService;
57
+    /** @var \OC_Util */
58
+    private $util;
59
+    /** @var IURLGenerator */
60
+    private $urlGenerator;
61
+    /** @var IL10N */
62
+    private $l10n;
63
+    /** @var Checker */
64
+    private $checker;
65
+    /** @var ILogger */
66
+    private $logger;
67
+
68
+    /**
69
+     * @param string $AppName
70
+     * @param IRequest $request
71
+     * @param IConfig $config
72
+     * @param IClientService $clientService
73
+     * @param IURLGenerator $urlGenerator
74
+     * @param \OC_Util $util
75
+     * @param IL10N $l10n
76
+     * @param Checker $checker
77
+     * @param ILogger $logger
78
+     */
79
+    public function __construct($AppName,
80
+                                IRequest $request,
81
+                                IConfig $config,
82
+                                IClientService $clientService,
83
+                                IURLGenerator $urlGenerator,
84
+                                \OC_Util $util,
85
+                                IL10N $l10n,
86
+                                Checker $checker,
87
+                                ILogger $logger) {
88
+        parent::__construct($AppName, $request);
89
+        $this->config = $config;
90
+        $this->clientService = $clientService;
91
+        $this->util = $util;
92
+        $this->urlGenerator = $urlGenerator;
93
+        $this->l10n = $l10n;
94
+        $this->checker = $checker;
95
+        $this->logger = $logger;
96
+    }
97
+
98
+    /**
99
+     * Checks if the ownCloud server can connect to the internet using HTTPS and HTTP
100
+     * @return bool
101
+     */
102
+    private function isInternetConnectionWorking() {
103
+        if ($this->config->getSystemValue('has_internet_connection', true) === false) {
104
+            return false;
105
+        }
106
+
107
+        $siteArray = ['www.nextcloud.com',
108
+                        'www.google.com',
109
+                        'www.github.com'];
110
+
111
+        foreach($siteArray as $site) {
112
+            if ($this->isSiteReachable($site)) {
113
+                return true;
114
+            }
115
+        }
116
+        return false;
117
+    }
118
+
119
+    /**
120
+     * Chceks if the ownCloud server can connect to a specific URL using both HTTPS and HTTP
121
+     * @return bool
122
+     */
123
+    private function isSiteReachable($sitename) {
124
+        $httpSiteName = 'http://' . $sitename . '/';
125
+        $httpsSiteName = 'https://' . $sitename . '/';
126
+
127
+        try {
128
+            $client = $this->clientService->newClient();
129
+            $client->get($httpSiteName);
130
+            $client->get($httpsSiteName);
131
+        } catch (\Exception $e) {
132
+            $this->logger->logException($e, ['app' => 'internet_connection_check']);
133
+            return false;
134
+        }
135
+        return true;
136
+    }
137
+
138
+    /**
139
+     * Checks whether a local memcache is installed or not
140
+     * @return bool
141
+     */
142
+    private function isMemcacheConfigured() {
143
+        return $this->config->getSystemValue('memcache.local', null) !== null;
144
+    }
145
+
146
+    /**
147
+     * Whether /dev/urandom is available to the PHP controller
148
+     *
149
+     * @return bool
150
+     */
151
+    private function isUrandomAvailable() {
152
+        if(@file_exists('/dev/urandom')) {
153
+            $file = fopen('/dev/urandom', 'rb');
154
+            if($file) {
155
+                fclose($file);
156
+                return true;
157
+            }
158
+        }
159
+
160
+        return false;
161
+    }
162
+
163
+    /**
164
+     * Public for the sake of unit-testing
165
+     *
166
+     * @return array
167
+     */
168
+    protected function getCurlVersion() {
169
+        return curl_version();
170
+    }
171
+
172
+    /**
173
+     * Check if the used  SSL lib is outdated. Older OpenSSL and NSS versions do
174
+     * have multiple bugs which likely lead to problems in combination with
175
+     * functionality required by ownCloud such as SNI.
176
+     *
177
+     * @link https://github.com/owncloud/core/issues/17446#issuecomment-122877546
178
+     * @link https://bugzilla.redhat.com/show_bug.cgi?id=1241172
179
+     * @return string
180
+     */
181
+    private function isUsedTlsLibOutdated() {
182
+        // Don't run check when:
183
+        // 1. Server has `has_internet_connection` set to false
184
+        // 2. AppStore AND S2S is disabled
185
+        if(!$this->config->getSystemValue('has_internet_connection', true)) {
186
+            return '';
187
+        }
188
+        if(!$this->config->getSystemValue('appstoreenabled', true)
189
+            && $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'no'
190
+            && $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes') === 'no') {
191
+            return '';
192
+        }
193
+
194
+        $versionString = $this->getCurlVersion();
195
+        if(isset($versionString['ssl_version'])) {
196
+            $versionString = $versionString['ssl_version'];
197
+        } else {
198
+            return '';
199
+        }
200
+
201
+        $features = (string)$this->l10n->t('installing and updating apps via the app store or Federated Cloud Sharing');
202
+        if(!$this->config->getSystemValue('appstoreenabled', true)) {
203
+            $features = (string)$this->l10n->t('Federated Cloud Sharing');
204
+        }
205
+
206
+        // Check if at least OpenSSL after 1.01d or 1.0.2b
207
+        if(strpos($versionString, 'OpenSSL/') === 0) {
208
+            $majorVersion = substr($versionString, 8, 5);
209
+            $patchRelease = substr($versionString, 13, 6);
210
+
211
+            if(($majorVersion === '1.0.1' && ord($patchRelease) < ord('d')) ||
212
+                ($majorVersion === '1.0.2' && ord($patchRelease) < ord('b'))) {
213
+                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]);
214
+            }
215
+        }
216
+
217
+        // Check if NSS and perform heuristic check
218
+        if(strpos($versionString, 'NSS/') === 0) {
219
+            try {
220
+                $firstClient = $this->clientService->newClient();
221
+                $firstClient->get('https://nextcloud.com/');
222
+
223
+                $secondClient = $this->clientService->newClient();
224
+                $secondClient->get('https://nextcloud.com/');
225
+            } catch (ClientException $e) {
226
+                if($e->getResponse()->getStatusCode() === 400) {
227
+                    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]);
228
+                }
229
+            }
230
+        }
231
+
232
+        return '';
233
+    }
234
+
235
+    /**
236
+     * Whether the version is outdated
237
+     *
238
+     * @return bool
239
+     */
240
+    protected function isPhpOutdated() {
241
+        if (version_compare(PHP_VERSION, '7.0.0', '<')) {
242
+            return true;
243
+        }
244
+
245
+        return false;
246
+    }
247
+
248
+    /**
249
+     * Whether the php version is still supported (at time of release)
250
+     * according to: https://secure.php.net/supported-versions.php
251
+     *
252
+     * @return array
253
+     */
254
+    private function isPhpSupported() {
255
+        return ['eol' => $this->isPhpOutdated(), 'version' => PHP_VERSION];
256
+    }
257
+
258
+    /**
259
+     * Check if the reverse proxy configuration is working as expected
260
+     *
261
+     * @return bool
262
+     */
263
+    private function forwardedForHeadersWorking() {
264
+        $trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
265
+        $remoteAddress = $this->request->getRemoteAddress();
266
+
267
+        if (is_array($trustedProxies) && in_array($remoteAddress, $trustedProxies)) {
268
+            return false;
269
+        }
270
+
271
+        // either not enabled or working correctly
272
+        return true;
273
+    }
274
+
275
+    /**
276
+     * Checks if the correct memcache module for PHP is installed. Only
277
+     * fails if memcached is configured and the working module is not installed.
278
+     *
279
+     * @return bool
280
+     */
281
+    private function isCorrectMemcachedPHPModuleInstalled() {
282
+        if ($this->config->getSystemValue('memcache.distributed', null) !== '\OC\Memcache\Memcached') {
283
+            return true;
284
+        }
285
+
286
+        // there are two different memcached modules for PHP
287
+        // we only support memcached and not memcache
288
+        // https://code.google.com/p/memcached/wiki/PHPClientComparison
289
+        return !(!extension_loaded('memcached') && extension_loaded('memcache'));
290
+    }
291
+
292
+    /**
293
+     * Checks if set_time_limit is not disabled.
294
+     *
295
+     * @return bool
296
+     */
297
+    private function isSettimelimitAvailable() {
298
+        if (function_exists('set_time_limit')
299
+            && strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
300
+            return true;
301
+        }
302
+
303
+        return false;
304
+    }
305
+
306
+    /**
307
+     * @return RedirectResponse
308
+     */
309
+    public function rescanFailedIntegrityCheck() {
310
+        $this->checker->runInstanceVerification();
311
+        return new RedirectResponse(
312
+            $this->urlGenerator->linkToRoute('settings.AdminSettings.index')
313
+        );
314
+    }
315
+
316
+    /**
317
+     * @NoCSRFRequired
318
+     * @return DataResponse
319
+     */
320
+    public function getFailedIntegrityCheckFiles() {
321
+        if(!$this->checker->isCodeCheckEnforced()) {
322
+            return new DataDisplayResponse('Integrity checker has been disabled. Integrity cannot be verified.');
323
+        }
324
+
325
+        $completeResults = $this->checker->getResults();
326
+
327
+        if(!empty($completeResults)) {
328
+            $formattedTextResponse = 'Technical information
329 329
 =====================
330 330
 The following list covers which files have failed the integrity check. Please read
331 331
 the previous linked documentation to learn more about the errors and how to fix
@@ -334,112 +334,112 @@  discard block
 block discarded – undo
334 334
 Results
335 335
 =======
336 336
 ';
337
-			foreach($completeResults as $context => $contextResult) {
338
-				$formattedTextResponse .= "- $context\n";
339
-
340
-				foreach($contextResult as $category => $result) {
341
-					$formattedTextResponse .= "\t- $category\n";
342
-					if($category !== 'EXCEPTION') {
343
-						foreach ($result as $key => $results) {
344
-							$formattedTextResponse .= "\t\t- $key\n";
345
-						}
346
-					} else {
347
-						foreach ($result as $key => $results) {
348
-							$formattedTextResponse .= "\t\t- $results\n";
349
-						}
350
-					}
351
-
352
-				}
353
-			}
354
-
355
-			$formattedTextResponse .= '
337
+            foreach($completeResults as $context => $contextResult) {
338
+                $formattedTextResponse .= "- $context\n";
339
+
340
+                foreach($contextResult as $category => $result) {
341
+                    $formattedTextResponse .= "\t- $category\n";
342
+                    if($category !== 'EXCEPTION') {
343
+                        foreach ($result as $key => $results) {
344
+                            $formattedTextResponse .= "\t\t- $key\n";
345
+                        }
346
+                    } else {
347
+                        foreach ($result as $key => $results) {
348
+                            $formattedTextResponse .= "\t\t- $results\n";
349
+                        }
350
+                    }
351
+
352
+                }
353
+            }
354
+
355
+            $formattedTextResponse .= '
356 356
 Raw output
357 357
 ==========
358 358
 ';
359
-			$formattedTextResponse .= print_r($completeResults, true);
360
-		} else {
361
-			$formattedTextResponse = 'No errors have been found.';
362
-		}
363
-
364
-
365
-		$response = new DataDisplayResponse(
366
-			$formattedTextResponse,
367
-			Http::STATUS_OK,
368
-			[
369
-				'Content-Type' => 'text/plain',
370
-			]
371
-		);
372
-
373
-		return $response;
374
-	}
375
-
376
-	/**
377
-	 * Checks whether a PHP opcache is properly set up
378
-	 * @return bool
379
-	 */
380
-	protected function isOpcacheProperlySetup() {
381
-		$iniWrapper = new IniGetWrapper();
382
-
383
-		$isOpcacheProperlySetUp = true;
384
-
385
-		if(!$iniWrapper->getBool('opcache.enable')) {
386
-			$isOpcacheProperlySetUp = false;
387
-		}
388
-
389
-		if(!$iniWrapper->getBool('opcache.save_comments')) {
390
-			$isOpcacheProperlySetUp = false;
391
-		}
392
-
393
-		if(!$iniWrapper->getBool('opcache.enable_cli')) {
394
-			$isOpcacheProperlySetUp = false;
395
-		}
396
-
397
-		if($iniWrapper->getNumeric('opcache.max_accelerated_files') < 10000) {
398
-			$isOpcacheProperlySetUp = false;
399
-		}
400
-
401
-		if($iniWrapper->getNumeric('opcache.memory_consumption') < 128) {
402
-			$isOpcacheProperlySetUp = false;
403
-		}
404
-
405
-		if($iniWrapper->getNumeric('opcache.interned_strings_buffer') < 8) {
406
-			$isOpcacheProperlySetUp = false;
407
-		}
408
-
409
-		return $isOpcacheProperlySetUp;
410
-	}
411
-
412
-	/**
413
-	 * Check if the required FreeType functions are present
414
-	 * @return bool
415
-	 */
416
-	protected function hasFreeTypeSupport() {
417
-		return function_exists('imagettfbbox') && function_exists('imagettftext');
418
-	}
419
-
420
-	/**
421
-	 * @return DataResponse
422
-	 */
423
-	public function check() {
424
-		return new DataResponse(
425
-			[
426
-				'serverHasInternetConnection' => $this->isInternetConnectionWorking(),
427
-				'isMemcacheConfigured' => $this->isMemcacheConfigured(),
428
-				'memcacheDocs' => $this->urlGenerator->linkToDocs('admin-performance'),
429
-				'isUrandomAvailable' => $this->isUrandomAvailable(),
430
-				'securityDocs' => $this->urlGenerator->linkToDocs('admin-security'),
431
-				'isUsedTlsLibOutdated' => $this->isUsedTlsLibOutdated(),
432
-				'phpSupported' => $this->isPhpSupported(),
433
-				'forwardedForHeadersWorking' => $this->forwardedForHeadersWorking(),
434
-				'reverseProxyDocs' => $this->urlGenerator->linkToDocs('admin-reverse-proxy'),
435
-				'isCorrectMemcachedPHPModuleInstalled' => $this->isCorrectMemcachedPHPModuleInstalled(),
436
-				'hasPassedCodeIntegrityCheck' => $this->checker->hasPassedCheck(),
437
-				'codeIntegrityCheckerDocumentation' => $this->urlGenerator->linkToDocs('admin-code-integrity'),
438
-				'isOpcacheProperlySetup' => $this->isOpcacheProperlySetup(),
439
-				'phpOpcacheDocumentation' => $this->urlGenerator->linkToDocs('admin-php-opcache'),
440
-				'isSettimelimitAvailable' => $this->isSettimelimitAvailable(),
441
-				'hasFreeTypeSupport' => $this->hasFreeTypeSupport(),
442
-			]
443
-		);
444
-	}
359
+            $formattedTextResponse .= print_r($completeResults, true);
360
+        } else {
361
+            $formattedTextResponse = 'No errors have been found.';
362
+        }
363
+
364
+
365
+        $response = new DataDisplayResponse(
366
+            $formattedTextResponse,
367
+            Http::STATUS_OK,
368
+            [
369
+                'Content-Type' => 'text/plain',
370
+            ]
371
+        );
372
+
373
+        return $response;
374
+    }
375
+
376
+    /**
377
+     * Checks whether a PHP opcache is properly set up
378
+     * @return bool
379
+     */
380
+    protected function isOpcacheProperlySetup() {
381
+        $iniWrapper = new IniGetWrapper();
382
+
383
+        $isOpcacheProperlySetUp = true;
384
+
385
+        if(!$iniWrapper->getBool('opcache.enable')) {
386
+            $isOpcacheProperlySetUp = false;
387
+        }
388
+
389
+        if(!$iniWrapper->getBool('opcache.save_comments')) {
390
+            $isOpcacheProperlySetUp = false;
391
+        }
392
+
393
+        if(!$iniWrapper->getBool('opcache.enable_cli')) {
394
+            $isOpcacheProperlySetUp = false;
395
+        }
396
+
397
+        if($iniWrapper->getNumeric('opcache.max_accelerated_files') < 10000) {
398
+            $isOpcacheProperlySetUp = false;
399
+        }
400
+
401
+        if($iniWrapper->getNumeric('opcache.memory_consumption') < 128) {
402
+            $isOpcacheProperlySetUp = false;
403
+        }
404
+
405
+        if($iniWrapper->getNumeric('opcache.interned_strings_buffer') < 8) {
406
+            $isOpcacheProperlySetUp = false;
407
+        }
408
+
409
+        return $isOpcacheProperlySetUp;
410
+    }
411
+
412
+    /**
413
+     * Check if the required FreeType functions are present
414
+     * @return bool
415
+     */
416
+    protected function hasFreeTypeSupport() {
417
+        return function_exists('imagettfbbox') && function_exists('imagettftext');
418
+    }
419
+
420
+    /**
421
+     * @return DataResponse
422
+     */
423
+    public function check() {
424
+        return new DataResponse(
425
+            [
426
+                'serverHasInternetConnection' => $this->isInternetConnectionWorking(),
427
+                'isMemcacheConfigured' => $this->isMemcacheConfigured(),
428
+                'memcacheDocs' => $this->urlGenerator->linkToDocs('admin-performance'),
429
+                'isUrandomAvailable' => $this->isUrandomAvailable(),
430
+                'securityDocs' => $this->urlGenerator->linkToDocs('admin-security'),
431
+                'isUsedTlsLibOutdated' => $this->isUsedTlsLibOutdated(),
432
+                'phpSupported' => $this->isPhpSupported(),
433
+                'forwardedForHeadersWorking' => $this->forwardedForHeadersWorking(),
434
+                'reverseProxyDocs' => $this->urlGenerator->linkToDocs('admin-reverse-proxy'),
435
+                'isCorrectMemcachedPHPModuleInstalled' => $this->isCorrectMemcachedPHPModuleInstalled(),
436
+                'hasPassedCodeIntegrityCheck' => $this->checker->hasPassedCheck(),
437
+                'codeIntegrityCheckerDocumentation' => $this->urlGenerator->linkToDocs('admin-code-integrity'),
438
+                'isOpcacheProperlySetup' => $this->isOpcacheProperlySetup(),
439
+                'phpOpcacheDocumentation' => $this->urlGenerator->linkToDocs('admin-php-opcache'),
440
+                'isSettimelimitAvailable' => $this->isSettimelimitAvailable(),
441
+                'hasFreeTypeSupport' => $this->hasFreeTypeSupport(),
442
+            ]
443
+        );
444
+    }
445 445
 }
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   +1305 added lines, -1305 removed lines patch added patch discarded remove patch
@@ -38,1311 +38,1311 @@
 block discarded – undo
38 38
 use OC\ServerNotAvailableException;
39 39
 
40 40
 class Wizard extends LDAPUtility {
41
-	/** @var \OCP\IL10N */
42
-	static protected $l;
43
-	protected $access;
44
-	protected $cr;
45
-	protected $configuration;
46
-	protected $result;
47
-	protected $resultCache = array();
48
-
49
-	const LRESULT_PROCESSED_OK = 2;
50
-	const LRESULT_PROCESSED_INVALID = 3;
51
-	const LRESULT_PROCESSED_SKIP = 4;
52
-
53
-	const LFILTER_LOGIN      = 2;
54
-	const LFILTER_USER_LIST  = 3;
55
-	const LFILTER_GROUP_LIST = 4;
56
-
57
-	const LFILTER_MODE_ASSISTED = 2;
58
-	const LFILTER_MODE_RAW = 1;
59
-
60
-	const LDAP_NW_TIMEOUT = 4;
61
-
62
-	/**
63
-	 * Constructor
64
-	 * @param Configuration $configuration an instance of Configuration
65
-	 * @param ILDAPWrapper $ldap an instance of ILDAPWrapper
66
-	 * @param Access $access
67
-	 */
68
-	public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) {
69
-		parent::__construct($ldap);
70
-		$this->configuration = $configuration;
71
-		if(is_null(Wizard::$l)) {
72
-			Wizard::$l = \OC::$server->getL10N('user_ldap');
73
-		}
74
-		$this->access = $access;
75
-		$this->result = new WizardResult();
76
-	}
77
-
78
-	public function  __destruct() {
79
-		if($this->result->hasChanges()) {
80
-			$this->configuration->saveConfiguration();
81
-		}
82
-	}
83
-
84
-	/**
85
-	 * counts entries in the LDAP directory
86
-	 *
87
-	 * @param string $filter the LDAP search filter
88
-	 * @param string $type a string being either 'users' or 'groups';
89
-	 * @return bool|int
90
-	 * @throws \Exception
91
-	 */
92
-	public function countEntries($filter, $type) {
93
-		$reqs = array('ldapHost', 'ldapPort', 'ldapBase');
94
-		if($type === 'users') {
95
-			$reqs[] = 'ldapUserFilter';
96
-		}
97
-		if(!$this->checkRequirements($reqs)) {
98
-			throw new \Exception('Requirements not met', 400);
99
-		}
100
-
101
-		$attr = array('dn'); // default
102
-		$limit = 1001;
103
-		if($type === 'groups') {
104
-			$result =  $this->access->countGroups($filter, $attr, $limit);
105
-		} else if($type === 'users') {
106
-			$result = $this->access->countUsers($filter, $attr, $limit);
107
-		} else if ($type === 'objects') {
108
-			$result = $this->access->countObjects($limit);
109
-		} else {
110
-			throw new \Exception('Internal error: Invalid object type', 500);
111
-		}
112
-
113
-		return $result;
114
-	}
115
-
116
-	/**
117
-	 * formats the return value of a count operation to the string to be
118
-	 * inserted.
119
-	 *
120
-	 * @param bool|int $count
121
-	 * @return int|string
122
-	 */
123
-	private function formatCountResult($count) {
124
-		$formatted = ($count !== false) ? $count : 0;
125
-		if($formatted > 1000) {
126
-			$formatted = '> 1000';
127
-		}
128
-		return $formatted;
129
-	}
130
-
131
-	public function countGroups() {
132
-		$filter = $this->configuration->ldapGroupFilter;
133
-
134
-		if(empty($filter)) {
135
-			$output = self::$l->n('%s group found', '%s groups found', 0, array(0));
136
-			$this->result->addChange('ldap_group_count', $output);
137
-			return $this->result;
138
-		}
139
-
140
-		try {
141
-			$groupsTotal = $this->formatCountResult($this->countEntries($filter, 'groups'));
142
-		} catch (\Exception $e) {
143
-			//400 can be ignored, 500 is forwarded
144
-			if($e->getCode() === 500) {
145
-				throw $e;
146
-			}
147
-			return false;
148
-		}
149
-		$output = self::$l->n('%s group found', '%s groups found', $groupsTotal, array($groupsTotal));
150
-		$this->result->addChange('ldap_group_count', $output);
151
-		return $this->result;
152
-	}
153
-
154
-	/**
155
-	 * @return WizardResult
156
-	 * @throws \Exception
157
-	 */
158
-	public function countUsers() {
159
-		$filter = $this->access->getFilterForUserCount();
160
-
161
-		$usersTotal = $this->formatCountResult($this->countEntries($filter, 'users'));
162
-		$output = self::$l->n('%s user found', '%s users found', $usersTotal, array($usersTotal));
163
-		$this->result->addChange('ldap_user_count', $output);
164
-		return $this->result;
165
-	}
166
-
167
-	/**
168
-	 * counts any objects in the currently set base dn
169
-	 *
170
-	 * @return WizardResult
171
-	 * @throws \Exception
172
-	 */
173
-	public function countInBaseDN() {
174
-		// we don't need to provide a filter in this case
175
-		$total = $this->countEntries(null, 'objects');
176
-		if($total === false) {
177
-			throw new \Exception('invalid results received');
178
-		}
179
-		$this->result->addChange('ldap_test_base', $total);
180
-		return $this->result;
181
-	}
182
-
183
-	/**
184
-	 * counts users with a specified attribute
185
-	 * @param string $attr
186
-	 * @param bool $existsCheck
187
-	 * @return int|bool
188
-	 */
189
-	public function countUsersWithAttribute($attr, $existsCheck = false) {
190
-		if(!$this->checkRequirements(array('ldapHost',
191
-										   'ldapPort',
192
-										   'ldapBase',
193
-										   'ldapUserFilter',
194
-										   ))) {
195
-			return  false;
196
-		}
197
-
198
-		$filter = $this->access->combineFilterWithAnd(array(
199
-			$this->configuration->ldapUserFilter,
200
-			$attr . '=*'
201
-		));
202
-
203
-		$limit = ($existsCheck === false) ? null : 1;
204
-
205
-		return $this->access->countUsers($filter, array('dn'), $limit);
206
-	}
207
-
208
-	/**
209
-	 * detects the display name attribute. If a setting is already present that
210
-	 * returns at least one hit, the detection will be canceled.
211
-	 * @return WizardResult|bool
212
-	 * @throws \Exception
213
-	 */
214
-	public function detectUserDisplayNameAttribute() {
215
-		if(!$this->checkRequirements(array('ldapHost',
216
-										'ldapPort',
217
-										'ldapBase',
218
-										'ldapUserFilter',
219
-										))) {
220
-			return  false;
221
-		}
222
-
223
-		$attr = $this->configuration->ldapUserDisplayName;
224
-		if ($attr !== '' && $attr !== 'displayName') {
225
-			// most likely not the default value with upper case N,
226
-			// verify it still produces a result
227
-			$count = intval($this->countUsersWithAttribute($attr, true));
228
-			if($count > 0) {
229
-				//no change, but we sent it back to make sure the user interface
230
-				//is still correct, even if the ajax call was cancelled meanwhile
231
-				$this->result->addChange('ldap_display_name', $attr);
232
-				return $this->result;
233
-			}
234
-		}
235
-
236
-		// first attribute that has at least one result wins
237
-		$displayNameAttrs = array('displayname', 'cn');
238
-		foreach ($displayNameAttrs as $attr) {
239
-			$count = intval($this->countUsersWithAttribute($attr, true));
240
-
241
-			if($count > 0) {
242
-				$this->applyFind('ldap_display_name', $attr);
243
-				return $this->result;
244
-			}
245
-		};
246
-
247
-		throw new \Exception(self::$l->t('Could not detect user display name attribute. Please specify it yourself in advanced LDAP settings.'));
248
-	}
249
-
250
-	/**
251
-	 * detects the most often used email attribute for users applying to the
252
-	 * user list filter. If a setting is already present that returns at least
253
-	 * one hit, the detection will be canceled.
254
-	 * @return WizardResult|bool
255
-	 */
256
-	public function detectEmailAttribute() {
257
-		if(!$this->checkRequirements(array('ldapHost',
258
-										   'ldapPort',
259
-										   'ldapBase',
260
-										   'ldapUserFilter',
261
-										   ))) {
262
-			return  false;
263
-		}
264
-
265
-		$attr = $this->configuration->ldapEmailAttribute;
266
-		if ($attr !== '') {
267
-			$count = intval($this->countUsersWithAttribute($attr, true));
268
-			if($count > 0) {
269
-				return false;
270
-			}
271
-			$writeLog = true;
272
-		} else {
273
-			$writeLog = false;
274
-		}
275
-
276
-		$emailAttributes = array('mail', 'mailPrimaryAddress');
277
-		$winner = '';
278
-		$maxUsers = 0;
279
-		foreach($emailAttributes as $attr) {
280
-			$count = $this->countUsersWithAttribute($attr);
281
-			if($count > $maxUsers) {
282
-				$maxUsers = $count;
283
-				$winner = $attr;
284
-			}
285
-		}
286
-
287
-		if($winner !== '') {
288
-			$this->applyFind('ldap_email_attr', $winner);
289
-			if($writeLog) {
290
-				\OCP\Util::writeLog('user_ldap', 'The mail attribute has ' .
291
-					'automatically been reset, because the original value ' .
292
-					'did not return any results.', \OCP\Util::INFO);
293
-			}
294
-		}
295
-
296
-		return $this->result;
297
-	}
298
-
299
-	/**
300
-	 * @return WizardResult
301
-	 * @throws \Exception
302
-	 */
303
-	public function determineAttributes() {
304
-		if(!$this->checkRequirements(array('ldapHost',
305
-										   'ldapPort',
306
-										   'ldapBase',
307
-										   'ldapUserFilter',
308
-										   ))) {
309
-			return  false;
310
-		}
311
-
312
-		$attributes = $this->getUserAttributes();
313
-
314
-		natcasesort($attributes);
315
-		$attributes = array_values($attributes);
316
-
317
-		$this->result->addOptions('ldap_loginfilter_attributes', $attributes);
318
-
319
-		$selected = $this->configuration->ldapLoginFilterAttributes;
320
-		if(is_array($selected) && !empty($selected)) {
321
-			$this->result->addChange('ldap_loginfilter_attributes', $selected);
322
-		}
323
-
324
-		return $this->result;
325
-	}
326
-
327
-	/**
328
-	 * detects the available LDAP attributes
329
-	 * @return array|false The instance's WizardResult instance
330
-	 * @throws \Exception
331
-	 */
332
-	private function getUserAttributes() {
333
-		if(!$this->checkRequirements(array('ldapHost',
334
-										   'ldapPort',
335
-										   'ldapBase',
336
-										   'ldapUserFilter',
337
-										   ))) {
338
-			return  false;
339
-		}
340
-		$cr = $this->getConnection();
341
-		if(!$cr) {
342
-			throw new \Exception('Could not connect to LDAP');
343
-		}
344
-
345
-		$base = $this->configuration->ldapBase[0];
346
-		$filter = $this->configuration->ldapUserFilter;
347
-		$rr = $this->ldap->search($cr, $base, $filter, array(), 1, 1);
348
-		if(!$this->ldap->isResource($rr)) {
349
-			return false;
350
-		}
351
-		$er = $this->ldap->firstEntry($cr, $rr);
352
-		$attributes = $this->ldap->getAttributes($cr, $er);
353
-		$pureAttributes = array();
354
-		for($i = 0; $i < $attributes['count']; $i++) {
355
-			$pureAttributes[] = $attributes[$i];
356
-		}
357
-
358
-		return $pureAttributes;
359
-	}
360
-
361
-	/**
362
-	 * detects the available LDAP groups
363
-	 * @return WizardResult|false the instance's WizardResult instance
364
-	 */
365
-	public function determineGroupsForGroups() {
366
-		return $this->determineGroups('ldap_groupfilter_groups',
367
-									  'ldapGroupFilterGroups',
368
-									  false);
369
-	}
370
-
371
-	/**
372
-	 * detects the available LDAP groups
373
-	 * @return WizardResult|false the instance's WizardResult instance
374
-	 */
375
-	public function determineGroupsForUsers() {
376
-		return $this->determineGroups('ldap_userfilter_groups',
377
-									  'ldapUserFilterGroups');
378
-	}
379
-
380
-	/**
381
-	 * detects the available LDAP groups
382
-	 * @param string $dbKey
383
-	 * @param string $confKey
384
-	 * @param bool $testMemberOf
385
-	 * @return WizardResult|false the instance's WizardResult instance
386
-	 * @throws \Exception
387
-	 */
388
-	private function determineGroups($dbKey, $confKey, $testMemberOf = true) {
389
-		if(!$this->checkRequirements(array('ldapHost',
390
-										   'ldapPort',
391
-										   'ldapBase',
392
-										   ))) {
393
-			return  false;
394
-		}
395
-		$cr = $this->getConnection();
396
-		if(!$cr) {
397
-			throw new \Exception('Could not connect to LDAP');
398
-		}
399
-
400
-		$this->fetchGroups($dbKey, $confKey);
401
-
402
-		if($testMemberOf) {
403
-			$this->configuration->hasMemberOfFilterSupport = $this->testMemberOf();
404
-			$this->result->markChange();
405
-			if(!$this->configuration->hasMemberOfFilterSupport) {
406
-				throw new \Exception('memberOf is not supported by the server');
407
-			}
408
-		}
409
-
410
-		return $this->result;
411
-	}
412
-
413
-	/**
414
-	 * fetches all groups from LDAP and adds them to the result object
415
-	 *
416
-	 * @param string $dbKey
417
-	 * @param string $confKey
418
-	 * @return array $groupEntries
419
-	 * @throws \Exception
420
-	 */
421
-	public function fetchGroups($dbKey, $confKey) {
422
-		$obclasses = array('posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames', 'groupOfUniqueNames');
423
-
424
-		$filterParts = array();
425
-		foreach($obclasses as $obclass) {
426
-			$filterParts[] = 'objectclass='.$obclass;
427
-		}
428
-		//we filter for everything
429
-		//- that looks like a group and
430
-		//- has the group display name set
431
-		$filter = $this->access->combineFilterWithOr($filterParts);
432
-		$filter = $this->access->combineFilterWithAnd(array($filter, 'cn=*'));
433
-
434
-		$groupNames = array();
435
-		$groupEntries = array();
436
-		$limit = 400;
437
-		$offset = 0;
438
-		do {
439
-			// we need to request dn additionally here, otherwise memberOf
440
-			// detection will fail later
441
-			$result = $this->access->searchGroups($filter, array('cn', 'dn'), $limit, $offset);
442
-			foreach($result as $item) {
443
-				if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
444
-					// just in case - no issue known
445
-					continue;
446
-				}
447
-				$groupNames[] = $item['cn'][0];
448
-				$groupEntries[] = $item;
449
-			}
450
-			$offset += $limit;
451
-		} while ($this->access->hasMoreResults());
452
-
453
-		if(count($groupNames) > 0) {
454
-			natsort($groupNames);
455
-			$this->result->addOptions($dbKey, array_values($groupNames));
456
-		} else {
457
-			throw new \Exception(self::$l->t('Could not find the desired feature'));
458
-		}
459
-
460
-		$setFeatures = $this->configuration->$confKey;
461
-		if(is_array($setFeatures) && !empty($setFeatures)) {
462
-			//something is already configured? pre-select it.
463
-			$this->result->addChange($dbKey, $setFeatures);
464
-		}
465
-		return $groupEntries;
466
-	}
467
-
468
-	public function determineGroupMemberAssoc() {
469
-		if(!$this->checkRequirements(array('ldapHost',
470
-										   'ldapPort',
471
-										   'ldapGroupFilter',
472
-										   ))) {
473
-			return  false;
474
-		}
475
-		$attribute = $this->detectGroupMemberAssoc();
476
-		if($attribute === false) {
477
-			return false;
478
-		}
479
-		$this->configuration->setConfiguration(array('ldapGroupMemberAssocAttr' => $attribute));
480
-		$this->result->addChange('ldap_group_member_assoc_attribute', $attribute);
481
-
482
-		return $this->result;
483
-	}
484
-
485
-	/**
486
-	 * Detects the available object classes
487
-	 * @return WizardResult|false the instance's WizardResult instance
488
-	 * @throws \Exception
489
-	 */
490
-	public function determineGroupObjectClasses() {
491
-		if(!$this->checkRequirements(array('ldapHost',
492
-										   'ldapPort',
493
-										   'ldapBase',
494
-										   ))) {
495
-			return  false;
496
-		}
497
-		$cr = $this->getConnection();
498
-		if(!$cr) {
499
-			throw new \Exception('Could not connect to LDAP');
500
-		}
501
-
502
-		$obclasses = array('groupOfNames', 'groupOfUniqueNames', 'group', 'posixGroup', '*');
503
-		$this->determineFeature($obclasses,
504
-								'objectclass',
505
-								'ldap_groupfilter_objectclass',
506
-								'ldapGroupFilterObjectclass',
507
-								false);
508
-
509
-		return $this->result;
510
-	}
511
-
512
-	/**
513
-	 * detects the available object classes
514
-	 * @return WizardResult
515
-	 * @throws \Exception
516
-	 */
517
-	public function determineUserObjectClasses() {
518
-		if(!$this->checkRequirements(array('ldapHost',
519
-										   'ldapPort',
520
-										   'ldapBase',
521
-										   ))) {
522
-			return  false;
523
-		}
524
-		$cr = $this->getConnection();
525
-		if(!$cr) {
526
-			throw new \Exception('Could not connect to LDAP');
527
-		}
528
-
529
-		$obclasses = array('inetOrgPerson', 'person', 'organizationalPerson',
530
-						   'user', 'posixAccount', '*');
531
-		$filter = $this->configuration->ldapUserFilter;
532
-		//if filter is empty, it is probably the first time the wizard is called
533
-		//then, apply suggestions.
534
-		$this->determineFeature($obclasses,
535
-								'objectclass',
536
-								'ldap_userfilter_objectclass',
537
-								'ldapUserFilterObjectclass',
538
-								empty($filter));
539
-
540
-		return $this->result;
541
-	}
542
-
543
-	/**
544
-	 * @return WizardResult|false
545
-	 * @throws \Exception
546
-	 */
547
-	public function getGroupFilter() {
548
-		if(!$this->checkRequirements(array('ldapHost',
549
-										   'ldapPort',
550
-										   'ldapBase',
551
-										   ))) {
552
-			return false;
553
-		}
554
-		//make sure the use display name is set
555
-		$displayName = $this->configuration->ldapGroupDisplayName;
556
-		if ($displayName === '') {
557
-			$d = $this->configuration->getDefaults();
558
-			$this->applyFind('ldap_group_display_name',
559
-							 $d['ldap_group_display_name']);
560
-		}
561
-		$filter = $this->composeLdapFilter(self::LFILTER_GROUP_LIST);
562
-
563
-		$this->applyFind('ldap_group_filter', $filter);
564
-		return $this->result;
565
-	}
566
-
567
-	/**
568
-	 * @return WizardResult|false
569
-	 * @throws \Exception
570
-	 */
571
-	public function getUserListFilter() {
572
-		if(!$this->checkRequirements(array('ldapHost',
573
-										   'ldapPort',
574
-										   'ldapBase',
575
-										   ))) {
576
-			return false;
577
-		}
578
-		//make sure the use display name is set
579
-		$displayName = $this->configuration->ldapUserDisplayName;
580
-		if ($displayName === '') {
581
-			$d = $this->configuration->getDefaults();
582
-			$this->applyFind('ldap_display_name', $d['ldap_display_name']);
583
-		}
584
-		$filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
585
-		if(!$filter) {
586
-			throw new \Exception('Cannot create filter');
587
-		}
588
-
589
-		$this->applyFind('ldap_userlist_filter', $filter);
590
-		return $this->result;
591
-	}
592
-
593
-	/**
594
-	 * @return bool|WizardResult
595
-	 * @throws \Exception
596
-	 */
597
-	public function getUserLoginFilter() {
598
-		if(!$this->checkRequirements(array('ldapHost',
599
-										   'ldapPort',
600
-										   'ldapBase',
601
-										   'ldapUserFilter',
602
-										   ))) {
603
-			return false;
604
-		}
605
-
606
-		$filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
607
-		if(!$filter) {
608
-			throw new \Exception('Cannot create filter');
609
-		}
610
-
611
-		$this->applyFind('ldap_login_filter', $filter);
612
-		return $this->result;
613
-	}
614
-
615
-	/**
616
-	 * @return bool|WizardResult
617
-	 * @param string $loginName
618
-	 * @throws \Exception
619
-	 */
620
-	public function testLoginName($loginName) {
621
-		if(!$this->checkRequirements(array('ldapHost',
622
-			'ldapPort',
623
-			'ldapBase',
624
-			'ldapLoginFilter',
625
-		))) {
626
-			return false;
627
-		}
628
-
629
-		$cr = $this->access->connection->getConnectionResource();
630
-		if(!$this->ldap->isResource($cr)) {
631
-			throw new \Exception('connection error');
632
-		}
633
-
634
-		if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
635
-			=== false) {
636
-			throw new \Exception('missing placeholder');
637
-		}
638
-
639
-		$users = $this->access->countUsersByLoginName($loginName);
640
-		if($this->ldap->errno($cr) !== 0) {
641
-			throw new \Exception($this->ldap->error($cr));
642
-		}
643
-		$filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
644
-		$this->result->addChange('ldap_test_loginname', $users);
645
-		$this->result->addChange('ldap_test_effective_filter', $filter);
646
-		return $this->result;
647
-	}
648
-
649
-	/**
650
-	 * Tries to determine the port, requires given Host, User DN and Password
651
-	 * @return WizardResult|false WizardResult on success, false otherwise
652
-	 * @throws \Exception
653
-	 */
654
-	public function guessPortAndTLS() {
655
-		if(!$this->checkRequirements(array('ldapHost',
656
-										   ))) {
657
-			return false;
658
-		}
659
-		$this->checkHost();
660
-		$portSettings = $this->getPortSettingsToTry();
661
-
662
-		if(!is_array($portSettings)) {
663
-			throw new \Exception(print_r($portSettings, true));
664
-		}
665
-
666
-		//proceed from the best configuration and return on first success
667
-		foreach($portSettings as $setting) {
668
-			$p = $setting['port'];
669
-			$t = $setting['tls'];
670
-			\OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, \OCP\Util::DEBUG);
671
-			//connectAndBind may throw Exception, it needs to be catched by the
672
-			//callee of this method
673
-
674
-			try {
675
-				$settingsFound = $this->connectAndBind($p, $t);
676
-			} catch (\Exception $e) {
677
-				// any reply other than -1 (= cannot connect) is already okay,
678
-				// because then we found the server
679
-				// unavailable startTLS returns -11
680
-				if($e->getCode() > 0) {
681
-					$settingsFound = true;
682
-				} else {
683
-					throw $e;
684
-				}
685
-			}
686
-
687
-			if ($settingsFound === true) {
688
-				$config = array(
689
-					'ldapPort' => $p,
690
-					'ldapTLS' => intval($t)
691
-				);
692
-				$this->configuration->setConfiguration($config);
693
-				\OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, \OCP\Util::DEBUG);
694
-				$this->result->addChange('ldap_port', $p);
695
-				return $this->result;
696
-			}
697
-		}
698
-
699
-		//custom port, undetected (we do not brute force)
700
-		return false;
701
-	}
702
-
703
-	/**
704
-	 * tries to determine a base dn from User DN or LDAP Host
705
-	 * @return WizardResult|false WizardResult on success, false otherwise
706
-	 */
707
-	public function guessBaseDN() {
708
-		if(!$this->checkRequirements(array('ldapHost',
709
-										   'ldapPort',
710
-										   ))) {
711
-			return false;
712
-		}
713
-
714
-		//check whether a DN is given in the agent name (99.9% of all cases)
715
-		$base = null;
716
-		$i = stripos($this->configuration->ldapAgentName, 'dc=');
717
-		if($i !== false) {
718
-			$base = substr($this->configuration->ldapAgentName, $i);
719
-			if($this->testBaseDN($base)) {
720
-				$this->applyFind('ldap_base', $base);
721
-				return $this->result;
722
-			}
723
-		}
724
-
725
-		//this did not help :(
726
-		//Let's see whether we can parse the Host URL and convert the domain to
727
-		//a base DN
728
-		$helper = new Helper(\OC::$server->getConfig());
729
-		$domain = $helper->getDomainFromURL($this->configuration->ldapHost);
730
-		if(!$domain) {
731
-			return false;
732
-		}
733
-
734
-		$dparts = explode('.', $domain);
735
-		while(count($dparts) > 0) {
736
-			$base2 = 'dc=' . implode(',dc=', $dparts);
737
-			if ($base !== $base2 && $this->testBaseDN($base2)) {
738
-				$this->applyFind('ldap_base', $base2);
739
-				return $this->result;
740
-			}
741
-			array_shift($dparts);
742
-		}
743
-
744
-		return false;
745
-	}
746
-
747
-	/**
748
-	 * sets the found value for the configuration key in the WizardResult
749
-	 * as well as in the Configuration instance
750
-	 * @param string $key the configuration key
751
-	 * @param string $value the (detected) value
752
-	 *
753
-	 */
754
-	private function applyFind($key, $value) {
755
-		$this->result->addChange($key, $value);
756
-		$this->configuration->setConfiguration(array($key => $value));
757
-	}
758
-
759
-	/**
760
-	 * Checks, whether a port was entered in the Host configuration
761
-	 * field. In this case the port will be stripped off, but also stored as
762
-	 * setting.
763
-	 */
764
-	private function checkHost() {
765
-		$host = $this->configuration->ldapHost;
766
-		$hostInfo = parse_url($host);
767
-
768
-		//removes Port from Host
769
-		if(is_array($hostInfo) && isset($hostInfo['port'])) {
770
-			$port = $hostInfo['port'];
771
-			$host = str_replace(':'.$port, '', $host);
772
-			$this->applyFind('ldap_host', $host);
773
-			$this->applyFind('ldap_port', $port);
774
-		}
775
-	}
776
-
777
-	/**
778
-	 * tries to detect the group member association attribute which is
779
-	 * one of 'uniqueMember', 'memberUid', 'member', 'gidNumber'
780
-	 * @return string|false, string with the attribute name, false on error
781
-	 * @throws \Exception
782
-	 */
783
-	private function detectGroupMemberAssoc() {
784
-		$possibleAttrs = array('uniqueMember', 'memberUid', 'member', 'gidNumber');
785
-		$filter = $this->configuration->ldapGroupFilter;
786
-		if(empty($filter)) {
787
-			return false;
788
-		}
789
-		$cr = $this->getConnection();
790
-		if(!$cr) {
791
-			throw new \Exception('Could not connect to LDAP');
792
-		}
793
-		$base = $this->configuration->ldapBase[0];
794
-		$rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
795
-		if(!$this->ldap->isResource($rr)) {
796
-			return false;
797
-		}
798
-		$er = $this->ldap->firstEntry($cr, $rr);
799
-		while(is_resource($er)) {
800
-			$this->ldap->getDN($cr, $er);
801
-			$attrs = $this->ldap->getAttributes($cr, $er);
802
-			$result = array();
803
-			$possibleAttrsCount = count($possibleAttrs);
804
-			for($i = 0; $i < $possibleAttrsCount; $i++) {
805
-				if(isset($attrs[$possibleAttrs[$i]])) {
806
-					$result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
807
-				}
808
-			}
809
-			if(!empty($result)) {
810
-				natsort($result);
811
-				return key($result);
812
-			}
813
-
814
-			$er = $this->ldap->nextEntry($cr, $er);
815
-		}
816
-
817
-		return false;
818
-	}
819
-
820
-	/**
821
-	 * Checks whether for a given BaseDN results will be returned
822
-	 * @param string $base the BaseDN to test
823
-	 * @return bool true on success, false otherwise
824
-	 * @throws \Exception
825
-	 */
826
-	private function testBaseDN($base) {
827
-		$cr = $this->getConnection();
828
-		if(!$cr) {
829
-			throw new \Exception('Could not connect to LDAP');
830
-		}
831
-
832
-		//base is there, let's validate it. If we search for anything, we should
833
-		//get a result set > 0 on a proper base
834
-		$rr = $this->ldap->search($cr, $base, 'objectClass=*', array('dn'), 0, 1);
835
-		if(!$this->ldap->isResource($rr)) {
836
-			$errorNo  = $this->ldap->errno($cr);
837
-			$errorMsg = $this->ldap->error($cr);
838
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base.
839
-							' Error '.$errorNo.': '.$errorMsg, \OCP\Util::INFO);
840
-			return false;
841
-		}
842
-		$entries = $this->ldap->countEntries($cr, $rr);
843
-		return ($entries !== false) && ($entries > 0);
844
-	}
845
-
846
-	/**
847
-	 * Checks whether the server supports memberOf in LDAP Filter.
848
-	 * Note: at least in OpenLDAP, availability of memberOf is dependent on
849
-	 * a configured objectClass. I.e. not necessarily for all available groups
850
-	 * memberOf does work.
851
-	 *
852
-	 * @return bool true if it does, false otherwise
853
-	 * @throws \Exception
854
-	 */
855
-	private function testMemberOf() {
856
-		$cr = $this->getConnection();
857
-		if(!$cr) {
858
-			throw new \Exception('Could not connect to LDAP');
859
-		}
860
-		$result = $this->access->countUsers('memberOf=*', array('memberOf'), 1);
861
-		if(is_int($result) &&  $result > 0) {
862
-			return true;
863
-		}
864
-		return false;
865
-	}
866
-
867
-	/**
868
-	 * creates an LDAP Filter from given configuration
869
-	 * @param integer $filterType int, for which use case the filter shall be created
870
-	 * can be any of self::LFILTER_USER_LIST, self::LFILTER_LOGIN or
871
-	 * self::LFILTER_GROUP_LIST
872
-	 * @return string|false string with the filter on success, false otherwise
873
-	 * @throws \Exception
874
-	 */
875
-	private function composeLdapFilter($filterType) {
876
-		$filter = '';
877
-		$parts = 0;
878
-		switch ($filterType) {
879
-			case self::LFILTER_USER_LIST:
880
-				$objcs = $this->configuration->ldapUserFilterObjectclass;
881
-				//glue objectclasses
882
-				if(is_array($objcs) && count($objcs) > 0) {
883
-					$filter .= '(|';
884
-					foreach($objcs as $objc) {
885
-						$filter .= '(objectclass=' . $objc . ')';
886
-					}
887
-					$filter .= ')';
888
-					$parts++;
889
-				}
890
-				//glue group memberships
891
-				if($this->configuration->hasMemberOfFilterSupport) {
892
-					$cns = $this->configuration->ldapUserFilterGroups;
893
-					if(is_array($cns) && count($cns) > 0) {
894
-						$filter .= '(|';
895
-						$cr = $this->getConnection();
896
-						if(!$cr) {
897
-							throw new \Exception('Could not connect to LDAP');
898
-						}
899
-						$base = $this->configuration->ldapBase[0];
900
-						foreach($cns as $cn) {
901
-							$rr = $this->ldap->search($cr, $base, 'cn=' . $cn, array('dn', 'primaryGroupToken'));
902
-							if(!$this->ldap->isResource($rr)) {
903
-								continue;
904
-							}
905
-							$er = $this->ldap->firstEntry($cr, $rr);
906
-							$attrs = $this->ldap->getAttributes($cr, $er);
907
-							$dn = $this->ldap->getDN($cr, $er);
908
-							if ($dn === false || $dn === '') {
909
-								continue;
910
-							}
911
-							$filterPart = '(memberof=' . $dn . ')';
912
-							if(isset($attrs['primaryGroupToken'])) {
913
-								$pgt = $attrs['primaryGroupToken'][0];
914
-								$primaryFilterPart = '(primaryGroupID=' . $pgt .')';
915
-								$filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
916
-							}
917
-							$filter .= $filterPart;
918
-						}
919
-						$filter .= ')';
920
-					}
921
-					$parts++;
922
-				}
923
-				//wrap parts in AND condition
924
-				if($parts > 1) {
925
-					$filter = '(&' . $filter . ')';
926
-				}
927
-				if ($filter === '') {
928
-					$filter = '(objectclass=*)';
929
-				}
930
-				break;
931
-
932
-			case self::LFILTER_GROUP_LIST:
933
-				$objcs = $this->configuration->ldapGroupFilterObjectclass;
934
-				//glue objectclasses
935
-				if(is_array($objcs) && count($objcs) > 0) {
936
-					$filter .= '(|';
937
-					foreach($objcs as $objc) {
938
-						$filter .= '(objectclass=' . $objc . ')';
939
-					}
940
-					$filter .= ')';
941
-					$parts++;
942
-				}
943
-				//glue group memberships
944
-				$cns = $this->configuration->ldapGroupFilterGroups;
945
-				if(is_array($cns) && count($cns) > 0) {
946
-					$filter .= '(|';
947
-					foreach($cns as $cn) {
948
-						$filter .= '(cn=' . $cn . ')';
949
-					}
950
-					$filter .= ')';
951
-				}
952
-				$parts++;
953
-				//wrap parts in AND condition
954
-				if($parts > 1) {
955
-					$filter = '(&' . $filter . ')';
956
-				}
957
-				break;
958
-
959
-			case self::LFILTER_LOGIN:
960
-				$ulf = $this->configuration->ldapUserFilter;
961
-				$loginpart = '=%uid';
962
-				$filterUsername = '';
963
-				$userAttributes = $this->getUserAttributes();
964
-				$userAttributes = array_change_key_case(array_flip($userAttributes));
965
-				$parts = 0;
966
-
967
-				if($this->configuration->ldapLoginFilterUsername === '1') {
968
-					$attr = '';
969
-					if(isset($userAttributes['uid'])) {
970
-						$attr = 'uid';
971
-					} else if(isset($userAttributes['samaccountname'])) {
972
-						$attr = 'samaccountname';
973
-					} else if(isset($userAttributes['cn'])) {
974
-						//fallback
975
-						$attr = 'cn';
976
-					}
977
-					if ($attr !== '') {
978
-						$filterUsername = '(' . $attr . $loginpart . ')';
979
-						$parts++;
980
-					}
981
-				}
982
-
983
-				$filterEmail = '';
984
-				if($this->configuration->ldapLoginFilterEmail === '1') {
985
-					$filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
986
-					$parts++;
987
-				}
988
-
989
-				$filterAttributes = '';
990
-				$attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
991
-				if(is_array($attrsToFilter) && count($attrsToFilter) > 0) {
992
-					$filterAttributes = '(|';
993
-					foreach($attrsToFilter as $attribute) {
994
-						$filterAttributes .= '(' . $attribute . $loginpart . ')';
995
-					}
996
-					$filterAttributes .= ')';
997
-					$parts++;
998
-				}
999
-
1000
-				$filterLogin = '';
1001
-				if($parts > 1) {
1002
-					$filterLogin = '(|';
1003
-				}
1004
-				$filterLogin .= $filterUsername;
1005
-				$filterLogin .= $filterEmail;
1006
-				$filterLogin .= $filterAttributes;
1007
-				if($parts > 1) {
1008
-					$filterLogin .= ')';
1009
-				}
1010
-
1011
-				$filter = '(&'.$ulf.$filterLogin.')';
1012
-				break;
1013
-		}
1014
-
1015
-		\OCP\Util::writeLog('user_ldap', 'Wiz: Final filter '.$filter, \OCP\Util::DEBUG);
1016
-
1017
-		return $filter;
1018
-	}
1019
-
1020
-	/**
1021
-	 * Connects and Binds to an LDAP Server
1022
-	 *
1023
-	 * @param int $port the port to connect with
1024
-	 * @param bool $tls whether startTLS is to be used
1025
-	 * @return bool
1026
-	 * @throws \Exception
1027
-	 */
1028
-	private function connectAndBind($port, $tls) {
1029
-		//connect, does not really trigger any server communication
1030
-		$host = $this->configuration->ldapHost;
1031
-		$hostInfo = parse_url($host);
1032
-		if(!$hostInfo) {
1033
-			throw new \Exception(self::$l->t('Invalid Host'));
1034
-		}
1035
-		\OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', \OCP\Util::DEBUG);
1036
-		$cr = $this->ldap->connect($host, $port);
1037
-		if(!is_resource($cr)) {
1038
-			throw new \Exception(self::$l->t('Invalid Host'));
1039
-		}
1040
-
1041
-		//set LDAP options
1042
-		$this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1043
-		$this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1044
-		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1045
-
1046
-		try {
1047
-			if($tls) {
1048
-				$isTlsWorking = @$this->ldap->startTls($cr);
1049
-				if(!$isTlsWorking) {
1050
-					return false;
1051
-				}
1052
-			}
1053
-
1054
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Attemping to Bind ', \OCP\Util::DEBUG);
1055
-			//interesting part: do the bind!
1056
-			$login = $this->ldap->bind($cr,
1057
-				$this->configuration->ldapAgentName,
1058
-				$this->configuration->ldapAgentPassword
1059
-			);
1060
-			$errNo = $this->ldap->errno($cr);
1061
-			$error = ldap_error($cr);
1062
-			$this->ldap->unbind($cr);
1063
-		} catch(ServerNotAvailableException $e) {
1064
-			return false;
1065
-		}
1066
-
1067
-		if($login === true) {
1068
-			$this->ldap->unbind($cr);
1069
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . intval($tls), \OCP\Util::DEBUG);
1070
-			return true;
1071
-		}
1072
-
1073
-		if($errNo === -1) {
1074
-			//host, port or TLS wrong
1075
-			return false;
1076
-		}
1077
-		throw new \Exception($error, $errNo);
1078
-	}
1079
-
1080
-	/**
1081
-	 * checks whether a valid combination of agent and password has been
1082
-	 * provided (either two values or nothing for anonymous connect)
1083
-	 * @return bool, true if everything is fine, false otherwise
1084
-	 */
1085
-	private function checkAgentRequirements() {
1086
-		$agent = $this->configuration->ldapAgentName;
1087
-		$pwd = $this->configuration->ldapAgentPassword;
1088
-
1089
-		return
1090
-			($agent !== '' && $pwd !== '')
1091
-			||  ($agent === '' && $pwd === '')
1092
-		;
1093
-	}
1094
-
1095
-	/**
1096
-	 * @param array $reqs
1097
-	 * @return bool
1098
-	 */
1099
-	private function checkRequirements($reqs) {
1100
-		$this->checkAgentRequirements();
1101
-		foreach($reqs as $option) {
1102
-			$value = $this->configuration->$option;
1103
-			if(empty($value)) {
1104
-				return false;
1105
-			}
1106
-		}
1107
-		return true;
1108
-	}
1109
-
1110
-	/**
1111
-	 * does a cumulativeSearch on LDAP to get different values of a
1112
-	 * specified attribute
1113
-	 * @param string[] $filters array, the filters that shall be used in the search
1114
-	 * @param string $attr the attribute of which a list of values shall be returned
1115
-	 * @param int $dnReadLimit the amount of how many DNs should be analyzed.
1116
-	 * The lower, the faster
1117
-	 * @param string $maxF string. if not null, this variable will have the filter that
1118
-	 * yields most result entries
1119
-	 * @return array|false an array with the values on success, false otherwise
1120
-	 */
1121
-	public function cumulativeSearchOnAttribute($filters, $attr, $dnReadLimit = 3, &$maxF = null) {
1122
-		$dnRead = array();
1123
-		$foundItems = array();
1124
-		$maxEntries = 0;
1125
-		if(!is_array($this->configuration->ldapBase)
1126
-		   || !isset($this->configuration->ldapBase[0])) {
1127
-			return false;
1128
-		}
1129
-		$base = $this->configuration->ldapBase[0];
1130
-		$cr = $this->getConnection();
1131
-		if(!$this->ldap->isResource($cr)) {
1132
-			return false;
1133
-		}
1134
-		$lastFilter = null;
1135
-		if(isset($filters[count($filters)-1])) {
1136
-			$lastFilter = $filters[count($filters)-1];
1137
-		}
1138
-		foreach($filters as $filter) {
1139
-			if($lastFilter === $filter && count($foundItems) > 0) {
1140
-				//skip when the filter is a wildcard and results were found
1141
-				continue;
1142
-			}
1143
-			// 20k limit for performance and reason
1144
-			$rr = $this->ldap->search($cr, $base, $filter, array($attr), 0, 20000);
1145
-			if(!$this->ldap->isResource($rr)) {
1146
-				continue;
1147
-			}
1148
-			$entries = $this->ldap->countEntries($cr, $rr);
1149
-			$getEntryFunc = 'firstEntry';
1150
-			if(($entries !== false) && ($entries > 0)) {
1151
-				if(!is_null($maxF) && $entries > $maxEntries) {
1152
-					$maxEntries = $entries;
1153
-					$maxF = $filter;
1154
-				}
1155
-				$dnReadCount = 0;
1156
-				do {
1157
-					$entry = $this->ldap->$getEntryFunc($cr, $rr);
1158
-					$getEntryFunc = 'nextEntry';
1159
-					if(!$this->ldap->isResource($entry)) {
1160
-						continue 2;
1161
-					}
1162
-					$rr = $entry; //will be expected by nextEntry next round
1163
-					$attributes = $this->ldap->getAttributes($cr, $entry);
1164
-					$dn = $this->ldap->getDN($cr, $entry);
1165
-					if($dn === false || in_array($dn, $dnRead)) {
1166
-						continue;
1167
-					}
1168
-					$newItems = array();
1169
-					$state = $this->getAttributeValuesFromEntry($attributes,
1170
-																$attr,
1171
-																$newItems);
1172
-					$dnReadCount++;
1173
-					$foundItems = array_merge($foundItems, $newItems);
1174
-					$this->resultCache[$dn][$attr] = $newItems;
1175
-					$dnRead[] = $dn;
1176
-				} while(($state === self::LRESULT_PROCESSED_SKIP
1177
-						|| $this->ldap->isResource($entry))
1178
-						&& ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit));
1179
-			}
1180
-		}
1181
-
1182
-		return array_unique($foundItems);
1183
-	}
1184
-
1185
-	/**
1186
-	 * determines if and which $attr are available on the LDAP server
1187
-	 * @param string[] $objectclasses the objectclasses to use as search filter
1188
-	 * @param string $attr the attribute to look for
1189
-	 * @param string $dbkey the dbkey of the setting the feature is connected to
1190
-	 * @param string $confkey the confkey counterpart for the $dbkey as used in the
1191
-	 * Configuration class
1192
-	 * @param bool $po whether the objectClass with most result entries
1193
-	 * shall be pre-selected via the result
1194
-	 * @return array|false list of found items.
1195
-	 * @throws \Exception
1196
-	 */
1197
-	private function determineFeature($objectclasses, $attr, $dbkey, $confkey, $po = false) {
1198
-		$cr = $this->getConnection();
1199
-		if(!$cr) {
1200
-			throw new \Exception('Could not connect to LDAP');
1201
-		}
1202
-		$p = 'objectclass=';
1203
-		foreach($objectclasses as $key => $value) {
1204
-			$objectclasses[$key] = $p.$value;
1205
-		}
1206
-		$maxEntryObjC = '';
1207
-
1208
-		//how deep to dig?
1209
-		//When looking for objectclasses, testing few entries is sufficient,
1210
-		$dig = 3;
1211
-
1212
-		$availableFeatures =
1213
-			$this->cumulativeSearchOnAttribute($objectclasses, $attr,
1214
-											   $dig, $maxEntryObjC);
1215
-		if(is_array($availableFeatures)
1216
-		   && count($availableFeatures) > 0) {
1217
-			natcasesort($availableFeatures);
1218
-			//natcasesort keeps indices, but we must get rid of them for proper
1219
-			//sorting in the web UI. Therefore: array_values
1220
-			$this->result->addOptions($dbkey, array_values($availableFeatures));
1221
-		} else {
1222
-			throw new \Exception(self::$l->t('Could not find the desired feature'));
1223
-		}
1224
-
1225
-		$setFeatures = $this->configuration->$confkey;
1226
-		if(is_array($setFeatures) && !empty($setFeatures)) {
1227
-			//something is already configured? pre-select it.
1228
-			$this->result->addChange($dbkey, $setFeatures);
1229
-		} else if ($po && $maxEntryObjC !== '') {
1230
-			//pre-select objectclass with most result entries
1231
-			$maxEntryObjC = str_replace($p, '', $maxEntryObjC);
1232
-			$this->applyFind($dbkey, $maxEntryObjC);
1233
-			$this->result->addChange($dbkey, $maxEntryObjC);
1234
-		}
1235
-
1236
-		return $availableFeatures;
1237
-	}
1238
-
1239
-	/**
1240
-	 * appends a list of values fr
1241
-	 * @param resource $result the return value from ldap_get_attributes
1242
-	 * @param string $attribute the attribute values to look for
1243
-	 * @param array &$known new values will be appended here
1244
-	 * @return int, state on of the class constants LRESULT_PROCESSED_OK,
1245
-	 * LRESULT_PROCESSED_INVALID or LRESULT_PROCESSED_SKIP
1246
-	 */
1247
-	private function getAttributeValuesFromEntry($result, $attribute, &$known) {
1248
-		if(!is_array($result)
1249
-		   || !isset($result['count'])
1250
-		   || !$result['count'] > 0) {
1251
-			return self::LRESULT_PROCESSED_INVALID;
1252
-		}
1253
-
1254
-		// strtolower on all keys for proper comparison
1255
-		$result = \OCP\Util::mb_array_change_key_case($result);
1256
-		$attribute = strtolower($attribute);
1257
-		if(isset($result[$attribute])) {
1258
-			foreach($result[$attribute] as $key => $val) {
1259
-				if($key === 'count') {
1260
-					continue;
1261
-				}
1262
-				if(!in_array($val, $known)) {
1263
-					$known[] = $val;
1264
-				}
1265
-			}
1266
-			return self::LRESULT_PROCESSED_OK;
1267
-		} else {
1268
-			return self::LRESULT_PROCESSED_SKIP;
1269
-		}
1270
-	}
1271
-
1272
-	/**
1273
-	 * @return bool|mixed
1274
-	 */
1275
-	private function getConnection() {
1276
-		if(!is_null($this->cr)) {
1277
-			return $this->cr;
1278
-		}
1279
-
1280
-		$cr = $this->ldap->connect(
1281
-			$this->configuration->ldapHost,
1282
-			$this->configuration->ldapPort
1283
-		);
1284
-
1285
-		$this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1286
-		$this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1287
-		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1288
-		if($this->configuration->ldapTLS === 1) {
1289
-			$this->ldap->startTls($cr);
1290
-		}
1291
-
1292
-		$lo = @$this->ldap->bind($cr,
1293
-								 $this->configuration->ldapAgentName,
1294
-								 $this->configuration->ldapAgentPassword);
1295
-		if($lo === true) {
1296
-			$this->$cr = $cr;
1297
-			return $cr;
1298
-		}
1299
-
1300
-		return false;
1301
-	}
1302
-
1303
-	/**
1304
-	 * @return array
1305
-	 */
1306
-	private function getDefaultLdapPortSettings() {
1307
-		static $settings = array(
1308
-								array('port' => 7636, 'tls' => false),
1309
-								array('port' =>  636, 'tls' => false),
1310
-								array('port' => 7389, 'tls' => true),
1311
-								array('port' =>  389, 'tls' => true),
1312
-								array('port' => 7389, 'tls' => false),
1313
-								array('port' =>  389, 'tls' => false),
1314
-						  );
1315
-		return $settings;
1316
-	}
1317
-
1318
-	/**
1319
-	 * @return array
1320
-	 */
1321
-	private function getPortSettingsToTry() {
1322
-		//389 ← LDAP / Unencrypted or StartTLS
1323
-		//636 ← LDAPS / SSL
1324
-		//7xxx ← UCS. need to be checked first, because both ports may be open
1325
-		$host = $this->configuration->ldapHost;
1326
-		$port = intval($this->configuration->ldapPort);
1327
-		$portSettings = array();
1328
-
1329
-		//In case the port is already provided, we will check this first
1330
-		if($port > 0) {
1331
-			$hostInfo = parse_url($host);
1332
-			if(!(is_array($hostInfo)
1333
-				&& isset($hostInfo['scheme'])
1334
-				&& stripos($hostInfo['scheme'], 'ldaps') !== false)) {
1335
-				$portSettings[] = array('port' => $port, 'tls' => true);
1336
-			}
1337
-			$portSettings[] =array('port' => $port, 'tls' => false);
1338
-		}
1339
-
1340
-		//default ports
1341
-		$portSettings = array_merge($portSettings,
1342
-		                            $this->getDefaultLdapPortSettings());
1343
-
1344
-		return $portSettings;
1345
-	}
41
+    /** @var \OCP\IL10N */
42
+    static protected $l;
43
+    protected $access;
44
+    protected $cr;
45
+    protected $configuration;
46
+    protected $result;
47
+    protected $resultCache = array();
48
+
49
+    const LRESULT_PROCESSED_OK = 2;
50
+    const LRESULT_PROCESSED_INVALID = 3;
51
+    const LRESULT_PROCESSED_SKIP = 4;
52
+
53
+    const LFILTER_LOGIN      = 2;
54
+    const LFILTER_USER_LIST  = 3;
55
+    const LFILTER_GROUP_LIST = 4;
56
+
57
+    const LFILTER_MODE_ASSISTED = 2;
58
+    const LFILTER_MODE_RAW = 1;
59
+
60
+    const LDAP_NW_TIMEOUT = 4;
61
+
62
+    /**
63
+     * Constructor
64
+     * @param Configuration $configuration an instance of Configuration
65
+     * @param ILDAPWrapper $ldap an instance of ILDAPWrapper
66
+     * @param Access $access
67
+     */
68
+    public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) {
69
+        parent::__construct($ldap);
70
+        $this->configuration = $configuration;
71
+        if(is_null(Wizard::$l)) {
72
+            Wizard::$l = \OC::$server->getL10N('user_ldap');
73
+        }
74
+        $this->access = $access;
75
+        $this->result = new WizardResult();
76
+    }
77
+
78
+    public function  __destruct() {
79
+        if($this->result->hasChanges()) {
80
+            $this->configuration->saveConfiguration();
81
+        }
82
+    }
83
+
84
+    /**
85
+     * counts entries in the LDAP directory
86
+     *
87
+     * @param string $filter the LDAP search filter
88
+     * @param string $type a string being either 'users' or 'groups';
89
+     * @return bool|int
90
+     * @throws \Exception
91
+     */
92
+    public function countEntries($filter, $type) {
93
+        $reqs = array('ldapHost', 'ldapPort', 'ldapBase');
94
+        if($type === 'users') {
95
+            $reqs[] = 'ldapUserFilter';
96
+        }
97
+        if(!$this->checkRequirements($reqs)) {
98
+            throw new \Exception('Requirements not met', 400);
99
+        }
100
+
101
+        $attr = array('dn'); // default
102
+        $limit = 1001;
103
+        if($type === 'groups') {
104
+            $result =  $this->access->countGroups($filter, $attr, $limit);
105
+        } else if($type === 'users') {
106
+            $result = $this->access->countUsers($filter, $attr, $limit);
107
+        } else if ($type === 'objects') {
108
+            $result = $this->access->countObjects($limit);
109
+        } else {
110
+            throw new \Exception('Internal error: Invalid object type', 500);
111
+        }
112
+
113
+        return $result;
114
+    }
115
+
116
+    /**
117
+     * formats the return value of a count operation to the string to be
118
+     * inserted.
119
+     *
120
+     * @param bool|int $count
121
+     * @return int|string
122
+     */
123
+    private function formatCountResult($count) {
124
+        $formatted = ($count !== false) ? $count : 0;
125
+        if($formatted > 1000) {
126
+            $formatted = '> 1000';
127
+        }
128
+        return $formatted;
129
+    }
130
+
131
+    public function countGroups() {
132
+        $filter = $this->configuration->ldapGroupFilter;
133
+
134
+        if(empty($filter)) {
135
+            $output = self::$l->n('%s group found', '%s groups found', 0, array(0));
136
+            $this->result->addChange('ldap_group_count', $output);
137
+            return $this->result;
138
+        }
139
+
140
+        try {
141
+            $groupsTotal = $this->formatCountResult($this->countEntries($filter, 'groups'));
142
+        } catch (\Exception $e) {
143
+            //400 can be ignored, 500 is forwarded
144
+            if($e->getCode() === 500) {
145
+                throw $e;
146
+            }
147
+            return false;
148
+        }
149
+        $output = self::$l->n('%s group found', '%s groups found', $groupsTotal, array($groupsTotal));
150
+        $this->result->addChange('ldap_group_count', $output);
151
+        return $this->result;
152
+    }
153
+
154
+    /**
155
+     * @return WizardResult
156
+     * @throws \Exception
157
+     */
158
+    public function countUsers() {
159
+        $filter = $this->access->getFilterForUserCount();
160
+
161
+        $usersTotal = $this->formatCountResult($this->countEntries($filter, 'users'));
162
+        $output = self::$l->n('%s user found', '%s users found', $usersTotal, array($usersTotal));
163
+        $this->result->addChange('ldap_user_count', $output);
164
+        return $this->result;
165
+    }
166
+
167
+    /**
168
+     * counts any objects in the currently set base dn
169
+     *
170
+     * @return WizardResult
171
+     * @throws \Exception
172
+     */
173
+    public function countInBaseDN() {
174
+        // we don't need to provide a filter in this case
175
+        $total = $this->countEntries(null, 'objects');
176
+        if($total === false) {
177
+            throw new \Exception('invalid results received');
178
+        }
179
+        $this->result->addChange('ldap_test_base', $total);
180
+        return $this->result;
181
+    }
182
+
183
+    /**
184
+     * counts users with a specified attribute
185
+     * @param string $attr
186
+     * @param bool $existsCheck
187
+     * @return int|bool
188
+     */
189
+    public function countUsersWithAttribute($attr, $existsCheck = false) {
190
+        if(!$this->checkRequirements(array('ldapHost',
191
+                                            'ldapPort',
192
+                                            'ldapBase',
193
+                                            'ldapUserFilter',
194
+                                            ))) {
195
+            return  false;
196
+        }
197
+
198
+        $filter = $this->access->combineFilterWithAnd(array(
199
+            $this->configuration->ldapUserFilter,
200
+            $attr . '=*'
201
+        ));
202
+
203
+        $limit = ($existsCheck === false) ? null : 1;
204
+
205
+        return $this->access->countUsers($filter, array('dn'), $limit);
206
+    }
207
+
208
+    /**
209
+     * detects the display name attribute. If a setting is already present that
210
+     * returns at least one hit, the detection will be canceled.
211
+     * @return WizardResult|bool
212
+     * @throws \Exception
213
+     */
214
+    public function detectUserDisplayNameAttribute() {
215
+        if(!$this->checkRequirements(array('ldapHost',
216
+                                        'ldapPort',
217
+                                        'ldapBase',
218
+                                        'ldapUserFilter',
219
+                                        ))) {
220
+            return  false;
221
+        }
222
+
223
+        $attr = $this->configuration->ldapUserDisplayName;
224
+        if ($attr !== '' && $attr !== 'displayName') {
225
+            // most likely not the default value with upper case N,
226
+            // verify it still produces a result
227
+            $count = intval($this->countUsersWithAttribute($attr, true));
228
+            if($count > 0) {
229
+                //no change, but we sent it back to make sure the user interface
230
+                //is still correct, even if the ajax call was cancelled meanwhile
231
+                $this->result->addChange('ldap_display_name', $attr);
232
+                return $this->result;
233
+            }
234
+        }
235
+
236
+        // first attribute that has at least one result wins
237
+        $displayNameAttrs = array('displayname', 'cn');
238
+        foreach ($displayNameAttrs as $attr) {
239
+            $count = intval($this->countUsersWithAttribute($attr, true));
240
+
241
+            if($count > 0) {
242
+                $this->applyFind('ldap_display_name', $attr);
243
+                return $this->result;
244
+            }
245
+        };
246
+
247
+        throw new \Exception(self::$l->t('Could not detect user display name attribute. Please specify it yourself in advanced LDAP settings.'));
248
+    }
249
+
250
+    /**
251
+     * detects the most often used email attribute for users applying to the
252
+     * user list filter. If a setting is already present that returns at least
253
+     * one hit, the detection will be canceled.
254
+     * @return WizardResult|bool
255
+     */
256
+    public function detectEmailAttribute() {
257
+        if(!$this->checkRequirements(array('ldapHost',
258
+                                            'ldapPort',
259
+                                            'ldapBase',
260
+                                            'ldapUserFilter',
261
+                                            ))) {
262
+            return  false;
263
+        }
264
+
265
+        $attr = $this->configuration->ldapEmailAttribute;
266
+        if ($attr !== '') {
267
+            $count = intval($this->countUsersWithAttribute($attr, true));
268
+            if($count > 0) {
269
+                return false;
270
+            }
271
+            $writeLog = true;
272
+        } else {
273
+            $writeLog = false;
274
+        }
275
+
276
+        $emailAttributes = array('mail', 'mailPrimaryAddress');
277
+        $winner = '';
278
+        $maxUsers = 0;
279
+        foreach($emailAttributes as $attr) {
280
+            $count = $this->countUsersWithAttribute($attr);
281
+            if($count > $maxUsers) {
282
+                $maxUsers = $count;
283
+                $winner = $attr;
284
+            }
285
+        }
286
+
287
+        if($winner !== '') {
288
+            $this->applyFind('ldap_email_attr', $winner);
289
+            if($writeLog) {
290
+                \OCP\Util::writeLog('user_ldap', 'The mail attribute has ' .
291
+                    'automatically been reset, because the original value ' .
292
+                    'did not return any results.', \OCP\Util::INFO);
293
+            }
294
+        }
295
+
296
+        return $this->result;
297
+    }
298
+
299
+    /**
300
+     * @return WizardResult
301
+     * @throws \Exception
302
+     */
303
+    public function determineAttributes() {
304
+        if(!$this->checkRequirements(array('ldapHost',
305
+                                            'ldapPort',
306
+                                            'ldapBase',
307
+                                            'ldapUserFilter',
308
+                                            ))) {
309
+            return  false;
310
+        }
311
+
312
+        $attributes = $this->getUserAttributes();
313
+
314
+        natcasesort($attributes);
315
+        $attributes = array_values($attributes);
316
+
317
+        $this->result->addOptions('ldap_loginfilter_attributes', $attributes);
318
+
319
+        $selected = $this->configuration->ldapLoginFilterAttributes;
320
+        if(is_array($selected) && !empty($selected)) {
321
+            $this->result->addChange('ldap_loginfilter_attributes', $selected);
322
+        }
323
+
324
+        return $this->result;
325
+    }
326
+
327
+    /**
328
+     * detects the available LDAP attributes
329
+     * @return array|false The instance's WizardResult instance
330
+     * @throws \Exception
331
+     */
332
+    private function getUserAttributes() {
333
+        if(!$this->checkRequirements(array('ldapHost',
334
+                                            'ldapPort',
335
+                                            'ldapBase',
336
+                                            'ldapUserFilter',
337
+                                            ))) {
338
+            return  false;
339
+        }
340
+        $cr = $this->getConnection();
341
+        if(!$cr) {
342
+            throw new \Exception('Could not connect to LDAP');
343
+        }
344
+
345
+        $base = $this->configuration->ldapBase[0];
346
+        $filter = $this->configuration->ldapUserFilter;
347
+        $rr = $this->ldap->search($cr, $base, $filter, array(), 1, 1);
348
+        if(!$this->ldap->isResource($rr)) {
349
+            return false;
350
+        }
351
+        $er = $this->ldap->firstEntry($cr, $rr);
352
+        $attributes = $this->ldap->getAttributes($cr, $er);
353
+        $pureAttributes = array();
354
+        for($i = 0; $i < $attributes['count']; $i++) {
355
+            $pureAttributes[] = $attributes[$i];
356
+        }
357
+
358
+        return $pureAttributes;
359
+    }
360
+
361
+    /**
362
+     * detects the available LDAP groups
363
+     * @return WizardResult|false the instance's WizardResult instance
364
+     */
365
+    public function determineGroupsForGroups() {
366
+        return $this->determineGroups('ldap_groupfilter_groups',
367
+                                        'ldapGroupFilterGroups',
368
+                                        false);
369
+    }
370
+
371
+    /**
372
+     * detects the available LDAP groups
373
+     * @return WizardResult|false the instance's WizardResult instance
374
+     */
375
+    public function determineGroupsForUsers() {
376
+        return $this->determineGroups('ldap_userfilter_groups',
377
+                                        'ldapUserFilterGroups');
378
+    }
379
+
380
+    /**
381
+     * detects the available LDAP groups
382
+     * @param string $dbKey
383
+     * @param string $confKey
384
+     * @param bool $testMemberOf
385
+     * @return WizardResult|false the instance's WizardResult instance
386
+     * @throws \Exception
387
+     */
388
+    private function determineGroups($dbKey, $confKey, $testMemberOf = true) {
389
+        if(!$this->checkRequirements(array('ldapHost',
390
+                                            'ldapPort',
391
+                                            'ldapBase',
392
+                                            ))) {
393
+            return  false;
394
+        }
395
+        $cr = $this->getConnection();
396
+        if(!$cr) {
397
+            throw new \Exception('Could not connect to LDAP');
398
+        }
399
+
400
+        $this->fetchGroups($dbKey, $confKey);
401
+
402
+        if($testMemberOf) {
403
+            $this->configuration->hasMemberOfFilterSupport = $this->testMemberOf();
404
+            $this->result->markChange();
405
+            if(!$this->configuration->hasMemberOfFilterSupport) {
406
+                throw new \Exception('memberOf is not supported by the server');
407
+            }
408
+        }
409
+
410
+        return $this->result;
411
+    }
412
+
413
+    /**
414
+     * fetches all groups from LDAP and adds them to the result object
415
+     *
416
+     * @param string $dbKey
417
+     * @param string $confKey
418
+     * @return array $groupEntries
419
+     * @throws \Exception
420
+     */
421
+    public function fetchGroups($dbKey, $confKey) {
422
+        $obclasses = array('posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames', 'groupOfUniqueNames');
423
+
424
+        $filterParts = array();
425
+        foreach($obclasses as $obclass) {
426
+            $filterParts[] = 'objectclass='.$obclass;
427
+        }
428
+        //we filter for everything
429
+        //- that looks like a group and
430
+        //- has the group display name set
431
+        $filter = $this->access->combineFilterWithOr($filterParts);
432
+        $filter = $this->access->combineFilterWithAnd(array($filter, 'cn=*'));
433
+
434
+        $groupNames = array();
435
+        $groupEntries = array();
436
+        $limit = 400;
437
+        $offset = 0;
438
+        do {
439
+            // we need to request dn additionally here, otherwise memberOf
440
+            // detection will fail later
441
+            $result = $this->access->searchGroups($filter, array('cn', 'dn'), $limit, $offset);
442
+            foreach($result as $item) {
443
+                if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
444
+                    // just in case - no issue known
445
+                    continue;
446
+                }
447
+                $groupNames[] = $item['cn'][0];
448
+                $groupEntries[] = $item;
449
+            }
450
+            $offset += $limit;
451
+        } while ($this->access->hasMoreResults());
452
+
453
+        if(count($groupNames) > 0) {
454
+            natsort($groupNames);
455
+            $this->result->addOptions($dbKey, array_values($groupNames));
456
+        } else {
457
+            throw new \Exception(self::$l->t('Could not find the desired feature'));
458
+        }
459
+
460
+        $setFeatures = $this->configuration->$confKey;
461
+        if(is_array($setFeatures) && !empty($setFeatures)) {
462
+            //something is already configured? pre-select it.
463
+            $this->result->addChange($dbKey, $setFeatures);
464
+        }
465
+        return $groupEntries;
466
+    }
467
+
468
+    public function determineGroupMemberAssoc() {
469
+        if(!$this->checkRequirements(array('ldapHost',
470
+                                            'ldapPort',
471
+                                            'ldapGroupFilter',
472
+                                            ))) {
473
+            return  false;
474
+        }
475
+        $attribute = $this->detectGroupMemberAssoc();
476
+        if($attribute === false) {
477
+            return false;
478
+        }
479
+        $this->configuration->setConfiguration(array('ldapGroupMemberAssocAttr' => $attribute));
480
+        $this->result->addChange('ldap_group_member_assoc_attribute', $attribute);
481
+
482
+        return $this->result;
483
+    }
484
+
485
+    /**
486
+     * Detects the available object classes
487
+     * @return WizardResult|false the instance's WizardResult instance
488
+     * @throws \Exception
489
+     */
490
+    public function determineGroupObjectClasses() {
491
+        if(!$this->checkRequirements(array('ldapHost',
492
+                                            'ldapPort',
493
+                                            'ldapBase',
494
+                                            ))) {
495
+            return  false;
496
+        }
497
+        $cr = $this->getConnection();
498
+        if(!$cr) {
499
+            throw new \Exception('Could not connect to LDAP');
500
+        }
501
+
502
+        $obclasses = array('groupOfNames', 'groupOfUniqueNames', 'group', 'posixGroup', '*');
503
+        $this->determineFeature($obclasses,
504
+                                'objectclass',
505
+                                'ldap_groupfilter_objectclass',
506
+                                'ldapGroupFilterObjectclass',
507
+                                false);
508
+
509
+        return $this->result;
510
+    }
511
+
512
+    /**
513
+     * detects the available object classes
514
+     * @return WizardResult
515
+     * @throws \Exception
516
+     */
517
+    public function determineUserObjectClasses() {
518
+        if(!$this->checkRequirements(array('ldapHost',
519
+                                            'ldapPort',
520
+                                            'ldapBase',
521
+                                            ))) {
522
+            return  false;
523
+        }
524
+        $cr = $this->getConnection();
525
+        if(!$cr) {
526
+            throw new \Exception('Could not connect to LDAP');
527
+        }
528
+
529
+        $obclasses = array('inetOrgPerson', 'person', 'organizationalPerson',
530
+                            'user', 'posixAccount', '*');
531
+        $filter = $this->configuration->ldapUserFilter;
532
+        //if filter is empty, it is probably the first time the wizard is called
533
+        //then, apply suggestions.
534
+        $this->determineFeature($obclasses,
535
+                                'objectclass',
536
+                                'ldap_userfilter_objectclass',
537
+                                'ldapUserFilterObjectclass',
538
+                                empty($filter));
539
+
540
+        return $this->result;
541
+    }
542
+
543
+    /**
544
+     * @return WizardResult|false
545
+     * @throws \Exception
546
+     */
547
+    public function getGroupFilter() {
548
+        if(!$this->checkRequirements(array('ldapHost',
549
+                                            'ldapPort',
550
+                                            'ldapBase',
551
+                                            ))) {
552
+            return false;
553
+        }
554
+        //make sure the use display name is set
555
+        $displayName = $this->configuration->ldapGroupDisplayName;
556
+        if ($displayName === '') {
557
+            $d = $this->configuration->getDefaults();
558
+            $this->applyFind('ldap_group_display_name',
559
+                                $d['ldap_group_display_name']);
560
+        }
561
+        $filter = $this->composeLdapFilter(self::LFILTER_GROUP_LIST);
562
+
563
+        $this->applyFind('ldap_group_filter', $filter);
564
+        return $this->result;
565
+    }
566
+
567
+    /**
568
+     * @return WizardResult|false
569
+     * @throws \Exception
570
+     */
571
+    public function getUserListFilter() {
572
+        if(!$this->checkRequirements(array('ldapHost',
573
+                                            'ldapPort',
574
+                                            'ldapBase',
575
+                                            ))) {
576
+            return false;
577
+        }
578
+        //make sure the use display name is set
579
+        $displayName = $this->configuration->ldapUserDisplayName;
580
+        if ($displayName === '') {
581
+            $d = $this->configuration->getDefaults();
582
+            $this->applyFind('ldap_display_name', $d['ldap_display_name']);
583
+        }
584
+        $filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
585
+        if(!$filter) {
586
+            throw new \Exception('Cannot create filter');
587
+        }
588
+
589
+        $this->applyFind('ldap_userlist_filter', $filter);
590
+        return $this->result;
591
+    }
592
+
593
+    /**
594
+     * @return bool|WizardResult
595
+     * @throws \Exception
596
+     */
597
+    public function getUserLoginFilter() {
598
+        if(!$this->checkRequirements(array('ldapHost',
599
+                                            'ldapPort',
600
+                                            'ldapBase',
601
+                                            'ldapUserFilter',
602
+                                            ))) {
603
+            return false;
604
+        }
605
+
606
+        $filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
607
+        if(!$filter) {
608
+            throw new \Exception('Cannot create filter');
609
+        }
610
+
611
+        $this->applyFind('ldap_login_filter', $filter);
612
+        return $this->result;
613
+    }
614
+
615
+    /**
616
+     * @return bool|WizardResult
617
+     * @param string $loginName
618
+     * @throws \Exception
619
+     */
620
+    public function testLoginName($loginName) {
621
+        if(!$this->checkRequirements(array('ldapHost',
622
+            'ldapPort',
623
+            'ldapBase',
624
+            'ldapLoginFilter',
625
+        ))) {
626
+            return false;
627
+        }
628
+
629
+        $cr = $this->access->connection->getConnectionResource();
630
+        if(!$this->ldap->isResource($cr)) {
631
+            throw new \Exception('connection error');
632
+        }
633
+
634
+        if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
635
+            === false) {
636
+            throw new \Exception('missing placeholder');
637
+        }
638
+
639
+        $users = $this->access->countUsersByLoginName($loginName);
640
+        if($this->ldap->errno($cr) !== 0) {
641
+            throw new \Exception($this->ldap->error($cr));
642
+        }
643
+        $filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
644
+        $this->result->addChange('ldap_test_loginname', $users);
645
+        $this->result->addChange('ldap_test_effective_filter', $filter);
646
+        return $this->result;
647
+    }
648
+
649
+    /**
650
+     * Tries to determine the port, requires given Host, User DN and Password
651
+     * @return WizardResult|false WizardResult on success, false otherwise
652
+     * @throws \Exception
653
+     */
654
+    public function guessPortAndTLS() {
655
+        if(!$this->checkRequirements(array('ldapHost',
656
+                                            ))) {
657
+            return false;
658
+        }
659
+        $this->checkHost();
660
+        $portSettings = $this->getPortSettingsToTry();
661
+
662
+        if(!is_array($portSettings)) {
663
+            throw new \Exception(print_r($portSettings, true));
664
+        }
665
+
666
+        //proceed from the best configuration and return on first success
667
+        foreach($portSettings as $setting) {
668
+            $p = $setting['port'];
669
+            $t = $setting['tls'];
670
+            \OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, \OCP\Util::DEBUG);
671
+            //connectAndBind may throw Exception, it needs to be catched by the
672
+            //callee of this method
673
+
674
+            try {
675
+                $settingsFound = $this->connectAndBind($p, $t);
676
+            } catch (\Exception $e) {
677
+                // any reply other than -1 (= cannot connect) is already okay,
678
+                // because then we found the server
679
+                // unavailable startTLS returns -11
680
+                if($e->getCode() > 0) {
681
+                    $settingsFound = true;
682
+                } else {
683
+                    throw $e;
684
+                }
685
+            }
686
+
687
+            if ($settingsFound === true) {
688
+                $config = array(
689
+                    'ldapPort' => $p,
690
+                    'ldapTLS' => intval($t)
691
+                );
692
+                $this->configuration->setConfiguration($config);
693
+                \OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, \OCP\Util::DEBUG);
694
+                $this->result->addChange('ldap_port', $p);
695
+                return $this->result;
696
+            }
697
+        }
698
+
699
+        //custom port, undetected (we do not brute force)
700
+        return false;
701
+    }
702
+
703
+    /**
704
+     * tries to determine a base dn from User DN or LDAP Host
705
+     * @return WizardResult|false WizardResult on success, false otherwise
706
+     */
707
+    public function guessBaseDN() {
708
+        if(!$this->checkRequirements(array('ldapHost',
709
+                                            'ldapPort',
710
+                                            ))) {
711
+            return false;
712
+        }
713
+
714
+        //check whether a DN is given in the agent name (99.9% of all cases)
715
+        $base = null;
716
+        $i = stripos($this->configuration->ldapAgentName, 'dc=');
717
+        if($i !== false) {
718
+            $base = substr($this->configuration->ldapAgentName, $i);
719
+            if($this->testBaseDN($base)) {
720
+                $this->applyFind('ldap_base', $base);
721
+                return $this->result;
722
+            }
723
+        }
724
+
725
+        //this did not help :(
726
+        //Let's see whether we can parse the Host URL and convert the domain to
727
+        //a base DN
728
+        $helper = new Helper(\OC::$server->getConfig());
729
+        $domain = $helper->getDomainFromURL($this->configuration->ldapHost);
730
+        if(!$domain) {
731
+            return false;
732
+        }
733
+
734
+        $dparts = explode('.', $domain);
735
+        while(count($dparts) > 0) {
736
+            $base2 = 'dc=' . implode(',dc=', $dparts);
737
+            if ($base !== $base2 && $this->testBaseDN($base2)) {
738
+                $this->applyFind('ldap_base', $base2);
739
+                return $this->result;
740
+            }
741
+            array_shift($dparts);
742
+        }
743
+
744
+        return false;
745
+    }
746
+
747
+    /**
748
+     * sets the found value for the configuration key in the WizardResult
749
+     * as well as in the Configuration instance
750
+     * @param string $key the configuration key
751
+     * @param string $value the (detected) value
752
+     *
753
+     */
754
+    private function applyFind($key, $value) {
755
+        $this->result->addChange($key, $value);
756
+        $this->configuration->setConfiguration(array($key => $value));
757
+    }
758
+
759
+    /**
760
+     * Checks, whether a port was entered in the Host configuration
761
+     * field. In this case the port will be stripped off, but also stored as
762
+     * setting.
763
+     */
764
+    private function checkHost() {
765
+        $host = $this->configuration->ldapHost;
766
+        $hostInfo = parse_url($host);
767
+
768
+        //removes Port from Host
769
+        if(is_array($hostInfo) && isset($hostInfo['port'])) {
770
+            $port = $hostInfo['port'];
771
+            $host = str_replace(':'.$port, '', $host);
772
+            $this->applyFind('ldap_host', $host);
773
+            $this->applyFind('ldap_port', $port);
774
+        }
775
+    }
776
+
777
+    /**
778
+     * tries to detect the group member association attribute which is
779
+     * one of 'uniqueMember', 'memberUid', 'member', 'gidNumber'
780
+     * @return string|false, string with the attribute name, false on error
781
+     * @throws \Exception
782
+     */
783
+    private function detectGroupMemberAssoc() {
784
+        $possibleAttrs = array('uniqueMember', 'memberUid', 'member', 'gidNumber');
785
+        $filter = $this->configuration->ldapGroupFilter;
786
+        if(empty($filter)) {
787
+            return false;
788
+        }
789
+        $cr = $this->getConnection();
790
+        if(!$cr) {
791
+            throw new \Exception('Could not connect to LDAP');
792
+        }
793
+        $base = $this->configuration->ldapBase[0];
794
+        $rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
795
+        if(!$this->ldap->isResource($rr)) {
796
+            return false;
797
+        }
798
+        $er = $this->ldap->firstEntry($cr, $rr);
799
+        while(is_resource($er)) {
800
+            $this->ldap->getDN($cr, $er);
801
+            $attrs = $this->ldap->getAttributes($cr, $er);
802
+            $result = array();
803
+            $possibleAttrsCount = count($possibleAttrs);
804
+            for($i = 0; $i < $possibleAttrsCount; $i++) {
805
+                if(isset($attrs[$possibleAttrs[$i]])) {
806
+                    $result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
807
+                }
808
+            }
809
+            if(!empty($result)) {
810
+                natsort($result);
811
+                return key($result);
812
+            }
813
+
814
+            $er = $this->ldap->nextEntry($cr, $er);
815
+        }
816
+
817
+        return false;
818
+    }
819
+
820
+    /**
821
+     * Checks whether for a given BaseDN results will be returned
822
+     * @param string $base the BaseDN to test
823
+     * @return bool true on success, false otherwise
824
+     * @throws \Exception
825
+     */
826
+    private function testBaseDN($base) {
827
+        $cr = $this->getConnection();
828
+        if(!$cr) {
829
+            throw new \Exception('Could not connect to LDAP');
830
+        }
831
+
832
+        //base is there, let's validate it. If we search for anything, we should
833
+        //get a result set > 0 on a proper base
834
+        $rr = $this->ldap->search($cr, $base, 'objectClass=*', array('dn'), 0, 1);
835
+        if(!$this->ldap->isResource($rr)) {
836
+            $errorNo  = $this->ldap->errno($cr);
837
+            $errorMsg = $this->ldap->error($cr);
838
+            \OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base.
839
+                            ' Error '.$errorNo.': '.$errorMsg, \OCP\Util::INFO);
840
+            return false;
841
+        }
842
+        $entries = $this->ldap->countEntries($cr, $rr);
843
+        return ($entries !== false) && ($entries > 0);
844
+    }
845
+
846
+    /**
847
+     * Checks whether the server supports memberOf in LDAP Filter.
848
+     * Note: at least in OpenLDAP, availability of memberOf is dependent on
849
+     * a configured objectClass. I.e. not necessarily for all available groups
850
+     * memberOf does work.
851
+     *
852
+     * @return bool true if it does, false otherwise
853
+     * @throws \Exception
854
+     */
855
+    private function testMemberOf() {
856
+        $cr = $this->getConnection();
857
+        if(!$cr) {
858
+            throw new \Exception('Could not connect to LDAP');
859
+        }
860
+        $result = $this->access->countUsers('memberOf=*', array('memberOf'), 1);
861
+        if(is_int($result) &&  $result > 0) {
862
+            return true;
863
+        }
864
+        return false;
865
+    }
866
+
867
+    /**
868
+     * creates an LDAP Filter from given configuration
869
+     * @param integer $filterType int, for which use case the filter shall be created
870
+     * can be any of self::LFILTER_USER_LIST, self::LFILTER_LOGIN or
871
+     * self::LFILTER_GROUP_LIST
872
+     * @return string|false string with the filter on success, false otherwise
873
+     * @throws \Exception
874
+     */
875
+    private function composeLdapFilter($filterType) {
876
+        $filter = '';
877
+        $parts = 0;
878
+        switch ($filterType) {
879
+            case self::LFILTER_USER_LIST:
880
+                $objcs = $this->configuration->ldapUserFilterObjectclass;
881
+                //glue objectclasses
882
+                if(is_array($objcs) && count($objcs) > 0) {
883
+                    $filter .= '(|';
884
+                    foreach($objcs as $objc) {
885
+                        $filter .= '(objectclass=' . $objc . ')';
886
+                    }
887
+                    $filter .= ')';
888
+                    $parts++;
889
+                }
890
+                //glue group memberships
891
+                if($this->configuration->hasMemberOfFilterSupport) {
892
+                    $cns = $this->configuration->ldapUserFilterGroups;
893
+                    if(is_array($cns) && count($cns) > 0) {
894
+                        $filter .= '(|';
895
+                        $cr = $this->getConnection();
896
+                        if(!$cr) {
897
+                            throw new \Exception('Could not connect to LDAP');
898
+                        }
899
+                        $base = $this->configuration->ldapBase[0];
900
+                        foreach($cns as $cn) {
901
+                            $rr = $this->ldap->search($cr, $base, 'cn=' . $cn, array('dn', 'primaryGroupToken'));
902
+                            if(!$this->ldap->isResource($rr)) {
903
+                                continue;
904
+                            }
905
+                            $er = $this->ldap->firstEntry($cr, $rr);
906
+                            $attrs = $this->ldap->getAttributes($cr, $er);
907
+                            $dn = $this->ldap->getDN($cr, $er);
908
+                            if ($dn === false || $dn === '') {
909
+                                continue;
910
+                            }
911
+                            $filterPart = '(memberof=' . $dn . ')';
912
+                            if(isset($attrs['primaryGroupToken'])) {
913
+                                $pgt = $attrs['primaryGroupToken'][0];
914
+                                $primaryFilterPart = '(primaryGroupID=' . $pgt .')';
915
+                                $filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
916
+                            }
917
+                            $filter .= $filterPart;
918
+                        }
919
+                        $filter .= ')';
920
+                    }
921
+                    $parts++;
922
+                }
923
+                //wrap parts in AND condition
924
+                if($parts > 1) {
925
+                    $filter = '(&' . $filter . ')';
926
+                }
927
+                if ($filter === '') {
928
+                    $filter = '(objectclass=*)';
929
+                }
930
+                break;
931
+
932
+            case self::LFILTER_GROUP_LIST:
933
+                $objcs = $this->configuration->ldapGroupFilterObjectclass;
934
+                //glue objectclasses
935
+                if(is_array($objcs) && count($objcs) > 0) {
936
+                    $filter .= '(|';
937
+                    foreach($objcs as $objc) {
938
+                        $filter .= '(objectclass=' . $objc . ')';
939
+                    }
940
+                    $filter .= ')';
941
+                    $parts++;
942
+                }
943
+                //glue group memberships
944
+                $cns = $this->configuration->ldapGroupFilterGroups;
945
+                if(is_array($cns) && count($cns) > 0) {
946
+                    $filter .= '(|';
947
+                    foreach($cns as $cn) {
948
+                        $filter .= '(cn=' . $cn . ')';
949
+                    }
950
+                    $filter .= ')';
951
+                }
952
+                $parts++;
953
+                //wrap parts in AND condition
954
+                if($parts > 1) {
955
+                    $filter = '(&' . $filter . ')';
956
+                }
957
+                break;
958
+
959
+            case self::LFILTER_LOGIN:
960
+                $ulf = $this->configuration->ldapUserFilter;
961
+                $loginpart = '=%uid';
962
+                $filterUsername = '';
963
+                $userAttributes = $this->getUserAttributes();
964
+                $userAttributes = array_change_key_case(array_flip($userAttributes));
965
+                $parts = 0;
966
+
967
+                if($this->configuration->ldapLoginFilterUsername === '1') {
968
+                    $attr = '';
969
+                    if(isset($userAttributes['uid'])) {
970
+                        $attr = 'uid';
971
+                    } else if(isset($userAttributes['samaccountname'])) {
972
+                        $attr = 'samaccountname';
973
+                    } else if(isset($userAttributes['cn'])) {
974
+                        //fallback
975
+                        $attr = 'cn';
976
+                    }
977
+                    if ($attr !== '') {
978
+                        $filterUsername = '(' . $attr . $loginpart . ')';
979
+                        $parts++;
980
+                    }
981
+                }
982
+
983
+                $filterEmail = '';
984
+                if($this->configuration->ldapLoginFilterEmail === '1') {
985
+                    $filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
986
+                    $parts++;
987
+                }
988
+
989
+                $filterAttributes = '';
990
+                $attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
991
+                if(is_array($attrsToFilter) && count($attrsToFilter) > 0) {
992
+                    $filterAttributes = '(|';
993
+                    foreach($attrsToFilter as $attribute) {
994
+                        $filterAttributes .= '(' . $attribute . $loginpart . ')';
995
+                    }
996
+                    $filterAttributes .= ')';
997
+                    $parts++;
998
+                }
999
+
1000
+                $filterLogin = '';
1001
+                if($parts > 1) {
1002
+                    $filterLogin = '(|';
1003
+                }
1004
+                $filterLogin .= $filterUsername;
1005
+                $filterLogin .= $filterEmail;
1006
+                $filterLogin .= $filterAttributes;
1007
+                if($parts > 1) {
1008
+                    $filterLogin .= ')';
1009
+                }
1010
+
1011
+                $filter = '(&'.$ulf.$filterLogin.')';
1012
+                break;
1013
+        }
1014
+
1015
+        \OCP\Util::writeLog('user_ldap', 'Wiz: Final filter '.$filter, \OCP\Util::DEBUG);
1016
+
1017
+        return $filter;
1018
+    }
1019
+
1020
+    /**
1021
+     * Connects and Binds to an LDAP Server
1022
+     *
1023
+     * @param int $port the port to connect with
1024
+     * @param bool $tls whether startTLS is to be used
1025
+     * @return bool
1026
+     * @throws \Exception
1027
+     */
1028
+    private function connectAndBind($port, $tls) {
1029
+        //connect, does not really trigger any server communication
1030
+        $host = $this->configuration->ldapHost;
1031
+        $hostInfo = parse_url($host);
1032
+        if(!$hostInfo) {
1033
+            throw new \Exception(self::$l->t('Invalid Host'));
1034
+        }
1035
+        \OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', \OCP\Util::DEBUG);
1036
+        $cr = $this->ldap->connect($host, $port);
1037
+        if(!is_resource($cr)) {
1038
+            throw new \Exception(self::$l->t('Invalid Host'));
1039
+        }
1040
+
1041
+        //set LDAP options
1042
+        $this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1043
+        $this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1044
+        $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1045
+
1046
+        try {
1047
+            if($tls) {
1048
+                $isTlsWorking = @$this->ldap->startTls($cr);
1049
+                if(!$isTlsWorking) {
1050
+                    return false;
1051
+                }
1052
+            }
1053
+
1054
+            \OCP\Util::writeLog('user_ldap', 'Wiz: Attemping to Bind ', \OCP\Util::DEBUG);
1055
+            //interesting part: do the bind!
1056
+            $login = $this->ldap->bind($cr,
1057
+                $this->configuration->ldapAgentName,
1058
+                $this->configuration->ldapAgentPassword
1059
+            );
1060
+            $errNo = $this->ldap->errno($cr);
1061
+            $error = ldap_error($cr);
1062
+            $this->ldap->unbind($cr);
1063
+        } catch(ServerNotAvailableException $e) {
1064
+            return false;
1065
+        }
1066
+
1067
+        if($login === true) {
1068
+            $this->ldap->unbind($cr);
1069
+            \OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . intval($tls), \OCP\Util::DEBUG);
1070
+            return true;
1071
+        }
1072
+
1073
+        if($errNo === -1) {
1074
+            //host, port or TLS wrong
1075
+            return false;
1076
+        }
1077
+        throw new \Exception($error, $errNo);
1078
+    }
1079
+
1080
+    /**
1081
+     * checks whether a valid combination of agent and password has been
1082
+     * provided (either two values or nothing for anonymous connect)
1083
+     * @return bool, true if everything is fine, false otherwise
1084
+     */
1085
+    private function checkAgentRequirements() {
1086
+        $agent = $this->configuration->ldapAgentName;
1087
+        $pwd = $this->configuration->ldapAgentPassword;
1088
+
1089
+        return
1090
+            ($agent !== '' && $pwd !== '')
1091
+            ||  ($agent === '' && $pwd === '')
1092
+        ;
1093
+    }
1094
+
1095
+    /**
1096
+     * @param array $reqs
1097
+     * @return bool
1098
+     */
1099
+    private function checkRequirements($reqs) {
1100
+        $this->checkAgentRequirements();
1101
+        foreach($reqs as $option) {
1102
+            $value = $this->configuration->$option;
1103
+            if(empty($value)) {
1104
+                return false;
1105
+            }
1106
+        }
1107
+        return true;
1108
+    }
1109
+
1110
+    /**
1111
+     * does a cumulativeSearch on LDAP to get different values of a
1112
+     * specified attribute
1113
+     * @param string[] $filters array, the filters that shall be used in the search
1114
+     * @param string $attr the attribute of which a list of values shall be returned
1115
+     * @param int $dnReadLimit the amount of how many DNs should be analyzed.
1116
+     * The lower, the faster
1117
+     * @param string $maxF string. if not null, this variable will have the filter that
1118
+     * yields most result entries
1119
+     * @return array|false an array with the values on success, false otherwise
1120
+     */
1121
+    public function cumulativeSearchOnAttribute($filters, $attr, $dnReadLimit = 3, &$maxF = null) {
1122
+        $dnRead = array();
1123
+        $foundItems = array();
1124
+        $maxEntries = 0;
1125
+        if(!is_array($this->configuration->ldapBase)
1126
+           || !isset($this->configuration->ldapBase[0])) {
1127
+            return false;
1128
+        }
1129
+        $base = $this->configuration->ldapBase[0];
1130
+        $cr = $this->getConnection();
1131
+        if(!$this->ldap->isResource($cr)) {
1132
+            return false;
1133
+        }
1134
+        $lastFilter = null;
1135
+        if(isset($filters[count($filters)-1])) {
1136
+            $lastFilter = $filters[count($filters)-1];
1137
+        }
1138
+        foreach($filters as $filter) {
1139
+            if($lastFilter === $filter && count($foundItems) > 0) {
1140
+                //skip when the filter is a wildcard and results were found
1141
+                continue;
1142
+            }
1143
+            // 20k limit for performance and reason
1144
+            $rr = $this->ldap->search($cr, $base, $filter, array($attr), 0, 20000);
1145
+            if(!$this->ldap->isResource($rr)) {
1146
+                continue;
1147
+            }
1148
+            $entries = $this->ldap->countEntries($cr, $rr);
1149
+            $getEntryFunc = 'firstEntry';
1150
+            if(($entries !== false) && ($entries > 0)) {
1151
+                if(!is_null($maxF) && $entries > $maxEntries) {
1152
+                    $maxEntries = $entries;
1153
+                    $maxF = $filter;
1154
+                }
1155
+                $dnReadCount = 0;
1156
+                do {
1157
+                    $entry = $this->ldap->$getEntryFunc($cr, $rr);
1158
+                    $getEntryFunc = 'nextEntry';
1159
+                    if(!$this->ldap->isResource($entry)) {
1160
+                        continue 2;
1161
+                    }
1162
+                    $rr = $entry; //will be expected by nextEntry next round
1163
+                    $attributes = $this->ldap->getAttributes($cr, $entry);
1164
+                    $dn = $this->ldap->getDN($cr, $entry);
1165
+                    if($dn === false || in_array($dn, $dnRead)) {
1166
+                        continue;
1167
+                    }
1168
+                    $newItems = array();
1169
+                    $state = $this->getAttributeValuesFromEntry($attributes,
1170
+                                                                $attr,
1171
+                                                                $newItems);
1172
+                    $dnReadCount++;
1173
+                    $foundItems = array_merge($foundItems, $newItems);
1174
+                    $this->resultCache[$dn][$attr] = $newItems;
1175
+                    $dnRead[] = $dn;
1176
+                } while(($state === self::LRESULT_PROCESSED_SKIP
1177
+                        || $this->ldap->isResource($entry))
1178
+                        && ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit));
1179
+            }
1180
+        }
1181
+
1182
+        return array_unique($foundItems);
1183
+    }
1184
+
1185
+    /**
1186
+     * determines if and which $attr are available on the LDAP server
1187
+     * @param string[] $objectclasses the objectclasses to use as search filter
1188
+     * @param string $attr the attribute to look for
1189
+     * @param string $dbkey the dbkey of the setting the feature is connected to
1190
+     * @param string $confkey the confkey counterpart for the $dbkey as used in the
1191
+     * Configuration class
1192
+     * @param bool $po whether the objectClass with most result entries
1193
+     * shall be pre-selected via the result
1194
+     * @return array|false list of found items.
1195
+     * @throws \Exception
1196
+     */
1197
+    private function determineFeature($objectclasses, $attr, $dbkey, $confkey, $po = false) {
1198
+        $cr = $this->getConnection();
1199
+        if(!$cr) {
1200
+            throw new \Exception('Could not connect to LDAP');
1201
+        }
1202
+        $p = 'objectclass=';
1203
+        foreach($objectclasses as $key => $value) {
1204
+            $objectclasses[$key] = $p.$value;
1205
+        }
1206
+        $maxEntryObjC = '';
1207
+
1208
+        //how deep to dig?
1209
+        //When looking for objectclasses, testing few entries is sufficient,
1210
+        $dig = 3;
1211
+
1212
+        $availableFeatures =
1213
+            $this->cumulativeSearchOnAttribute($objectclasses, $attr,
1214
+                                                $dig, $maxEntryObjC);
1215
+        if(is_array($availableFeatures)
1216
+           && count($availableFeatures) > 0) {
1217
+            natcasesort($availableFeatures);
1218
+            //natcasesort keeps indices, but we must get rid of them for proper
1219
+            //sorting in the web UI. Therefore: array_values
1220
+            $this->result->addOptions($dbkey, array_values($availableFeatures));
1221
+        } else {
1222
+            throw new \Exception(self::$l->t('Could not find the desired feature'));
1223
+        }
1224
+
1225
+        $setFeatures = $this->configuration->$confkey;
1226
+        if(is_array($setFeatures) && !empty($setFeatures)) {
1227
+            //something is already configured? pre-select it.
1228
+            $this->result->addChange($dbkey, $setFeatures);
1229
+        } else if ($po && $maxEntryObjC !== '') {
1230
+            //pre-select objectclass with most result entries
1231
+            $maxEntryObjC = str_replace($p, '', $maxEntryObjC);
1232
+            $this->applyFind($dbkey, $maxEntryObjC);
1233
+            $this->result->addChange($dbkey, $maxEntryObjC);
1234
+        }
1235
+
1236
+        return $availableFeatures;
1237
+    }
1238
+
1239
+    /**
1240
+     * appends a list of values fr
1241
+     * @param resource $result the return value from ldap_get_attributes
1242
+     * @param string $attribute the attribute values to look for
1243
+     * @param array &$known new values will be appended here
1244
+     * @return int, state on of the class constants LRESULT_PROCESSED_OK,
1245
+     * LRESULT_PROCESSED_INVALID or LRESULT_PROCESSED_SKIP
1246
+     */
1247
+    private function getAttributeValuesFromEntry($result, $attribute, &$known) {
1248
+        if(!is_array($result)
1249
+           || !isset($result['count'])
1250
+           || !$result['count'] > 0) {
1251
+            return self::LRESULT_PROCESSED_INVALID;
1252
+        }
1253
+
1254
+        // strtolower on all keys for proper comparison
1255
+        $result = \OCP\Util::mb_array_change_key_case($result);
1256
+        $attribute = strtolower($attribute);
1257
+        if(isset($result[$attribute])) {
1258
+            foreach($result[$attribute] as $key => $val) {
1259
+                if($key === 'count') {
1260
+                    continue;
1261
+                }
1262
+                if(!in_array($val, $known)) {
1263
+                    $known[] = $val;
1264
+                }
1265
+            }
1266
+            return self::LRESULT_PROCESSED_OK;
1267
+        } else {
1268
+            return self::LRESULT_PROCESSED_SKIP;
1269
+        }
1270
+    }
1271
+
1272
+    /**
1273
+     * @return bool|mixed
1274
+     */
1275
+    private function getConnection() {
1276
+        if(!is_null($this->cr)) {
1277
+            return $this->cr;
1278
+        }
1279
+
1280
+        $cr = $this->ldap->connect(
1281
+            $this->configuration->ldapHost,
1282
+            $this->configuration->ldapPort
1283
+        );
1284
+
1285
+        $this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1286
+        $this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1287
+        $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1288
+        if($this->configuration->ldapTLS === 1) {
1289
+            $this->ldap->startTls($cr);
1290
+        }
1291
+
1292
+        $lo = @$this->ldap->bind($cr,
1293
+                                    $this->configuration->ldapAgentName,
1294
+                                    $this->configuration->ldapAgentPassword);
1295
+        if($lo === true) {
1296
+            $this->$cr = $cr;
1297
+            return $cr;
1298
+        }
1299
+
1300
+        return false;
1301
+    }
1302
+
1303
+    /**
1304
+     * @return array
1305
+     */
1306
+    private function getDefaultLdapPortSettings() {
1307
+        static $settings = array(
1308
+                                array('port' => 7636, 'tls' => false),
1309
+                                array('port' =>  636, 'tls' => false),
1310
+                                array('port' => 7389, 'tls' => true),
1311
+                                array('port' =>  389, 'tls' => true),
1312
+                                array('port' => 7389, 'tls' => false),
1313
+                                array('port' =>  389, 'tls' => false),
1314
+                            );
1315
+        return $settings;
1316
+    }
1317
+
1318
+    /**
1319
+     * @return array
1320
+     */
1321
+    private function getPortSettingsToTry() {
1322
+        //389 ← LDAP / Unencrypted or StartTLS
1323
+        //636 ← LDAPS / SSL
1324
+        //7xxx ← UCS. need to be checked first, because both ports may be open
1325
+        $host = $this->configuration->ldapHost;
1326
+        $port = intval($this->configuration->ldapPort);
1327
+        $portSettings = array();
1328
+
1329
+        //In case the port is already provided, we will check this first
1330
+        if($port > 0) {
1331
+            $hostInfo = parse_url($host);
1332
+            if(!(is_array($hostInfo)
1333
+                && isset($hostInfo['scheme'])
1334
+                && stripos($hostInfo['scheme'], 'ldaps') !== false)) {
1335
+                $portSettings[] = array('port' => $port, 'tls' => true);
1336
+            }
1337
+            $portSettings[] =array('port' => $port, 'tls' => false);
1338
+        }
1339
+
1340
+        //default ports
1341
+        $portSettings = array_merge($portSettings,
1342
+                                    $this->getDefaultLdapPortSettings());
1343
+
1344
+        return $portSettings;
1345
+    }
1346 1346
 
1347 1347
 
1348 1348
 }
Please login to merge, or discard this patch.
Spacing   +149 added lines, -149 removed lines patch added patch discarded remove patch
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
 	public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) {
69 69
 		parent::__construct($ldap);
70 70
 		$this->configuration = $configuration;
71
-		if(is_null(Wizard::$l)) {
71
+		if (is_null(Wizard::$l)) {
72 72
 			Wizard::$l = \OC::$server->getL10N('user_ldap');
73 73
 		}
74 74
 		$this->access = $access;
@@ -76,7 +76,7 @@  discard block
 block discarded – undo
76 76
 	}
77 77
 
78 78
 	public function  __destruct() {
79
-		if($this->result->hasChanges()) {
79
+		if ($this->result->hasChanges()) {
80 80
 			$this->configuration->saveConfiguration();
81 81
 		}
82 82
 	}
@@ -91,18 +91,18 @@  discard block
 block discarded – undo
91 91
 	 */
92 92
 	public function countEntries($filter, $type) {
93 93
 		$reqs = array('ldapHost', 'ldapPort', 'ldapBase');
94
-		if($type === 'users') {
94
+		if ($type === 'users') {
95 95
 			$reqs[] = 'ldapUserFilter';
96 96
 		}
97
-		if(!$this->checkRequirements($reqs)) {
97
+		if (!$this->checkRequirements($reqs)) {
98 98
 			throw new \Exception('Requirements not met', 400);
99 99
 		}
100 100
 
101 101
 		$attr = array('dn'); // default
102 102
 		$limit = 1001;
103
-		if($type === 'groups') {
104
-			$result =  $this->access->countGroups($filter, $attr, $limit);
105
-		} else if($type === 'users') {
103
+		if ($type === 'groups') {
104
+			$result = $this->access->countGroups($filter, $attr, $limit);
105
+		} else if ($type === 'users') {
106 106
 			$result = $this->access->countUsers($filter, $attr, $limit);
107 107
 		} else if ($type === 'objects') {
108 108
 			$result = $this->access->countObjects($limit);
@@ -122,7 +122,7 @@  discard block
 block discarded – undo
122 122
 	 */
123 123
 	private function formatCountResult($count) {
124 124
 		$formatted = ($count !== false) ? $count : 0;
125
-		if($formatted > 1000) {
125
+		if ($formatted > 1000) {
126 126
 			$formatted = '> 1000';
127 127
 		}
128 128
 		return $formatted;
@@ -131,7 +131,7 @@  discard block
 block discarded – undo
131 131
 	public function countGroups() {
132 132
 		$filter = $this->configuration->ldapGroupFilter;
133 133
 
134
-		if(empty($filter)) {
134
+		if (empty($filter)) {
135 135
 			$output = self::$l->n('%s group found', '%s groups found', 0, array(0));
136 136
 			$this->result->addChange('ldap_group_count', $output);
137 137
 			return $this->result;
@@ -141,7 +141,7 @@  discard block
 block discarded – undo
141 141
 			$groupsTotal = $this->formatCountResult($this->countEntries($filter, 'groups'));
142 142
 		} catch (\Exception $e) {
143 143
 			//400 can be ignored, 500 is forwarded
144
-			if($e->getCode() === 500) {
144
+			if ($e->getCode() === 500) {
145 145
 				throw $e;
146 146
 			}
147 147
 			return false;
@@ -173,7 +173,7 @@  discard block
 block discarded – undo
173 173
 	public function countInBaseDN() {
174 174
 		// we don't need to provide a filter in this case
175 175
 		$total = $this->countEntries(null, 'objects');
176
-		if($total === false) {
176
+		if ($total === false) {
177 177
 			throw new \Exception('invalid results received');
178 178
 		}
179 179
 		$this->result->addChange('ldap_test_base', $total);
@@ -187,7 +187,7 @@  discard block
 block discarded – undo
187 187
 	 * @return int|bool
188 188
 	 */
189 189
 	public function countUsersWithAttribute($attr, $existsCheck = false) {
190
-		if(!$this->checkRequirements(array('ldapHost',
190
+		if (!$this->checkRequirements(array('ldapHost',
191 191
 										   'ldapPort',
192 192
 										   'ldapBase',
193 193
 										   'ldapUserFilter',
@@ -197,7 +197,7 @@  discard block
 block discarded – undo
197 197
 
198 198
 		$filter = $this->access->combineFilterWithAnd(array(
199 199
 			$this->configuration->ldapUserFilter,
200
-			$attr . '=*'
200
+			$attr.'=*'
201 201
 		));
202 202
 
203 203
 		$limit = ($existsCheck === false) ? null : 1;
@@ -212,7 +212,7 @@  discard block
 block discarded – undo
212 212
 	 * @throws \Exception
213 213
 	 */
214 214
 	public function detectUserDisplayNameAttribute() {
215
-		if(!$this->checkRequirements(array('ldapHost',
215
+		if (!$this->checkRequirements(array('ldapHost',
216 216
 										'ldapPort',
217 217
 										'ldapBase',
218 218
 										'ldapUserFilter',
@@ -225,7 +225,7 @@  discard block
 block discarded – undo
225 225
 			// most likely not the default value with upper case N,
226 226
 			// verify it still produces a result
227 227
 			$count = intval($this->countUsersWithAttribute($attr, true));
228
-			if($count > 0) {
228
+			if ($count > 0) {
229 229
 				//no change, but we sent it back to make sure the user interface
230 230
 				//is still correct, even if the ajax call was cancelled meanwhile
231 231
 				$this->result->addChange('ldap_display_name', $attr);
@@ -238,7 +238,7 @@  discard block
 block discarded – undo
238 238
 		foreach ($displayNameAttrs as $attr) {
239 239
 			$count = intval($this->countUsersWithAttribute($attr, true));
240 240
 
241
-			if($count > 0) {
241
+			if ($count > 0) {
242 242
 				$this->applyFind('ldap_display_name', $attr);
243 243
 				return $this->result;
244 244
 			}
@@ -254,7 +254,7 @@  discard block
 block discarded – undo
254 254
 	 * @return WizardResult|bool
255 255
 	 */
256 256
 	public function detectEmailAttribute() {
257
-		if(!$this->checkRequirements(array('ldapHost',
257
+		if (!$this->checkRequirements(array('ldapHost',
258 258
 										   'ldapPort',
259 259
 										   'ldapBase',
260 260
 										   'ldapUserFilter',
@@ -265,7 +265,7 @@  discard block
 block discarded – undo
265 265
 		$attr = $this->configuration->ldapEmailAttribute;
266 266
 		if ($attr !== '') {
267 267
 			$count = intval($this->countUsersWithAttribute($attr, true));
268
-			if($count > 0) {
268
+			if ($count > 0) {
269 269
 				return false;
270 270
 			}
271 271
 			$writeLog = true;
@@ -276,19 +276,19 @@  discard block
 block discarded – undo
276 276
 		$emailAttributes = array('mail', 'mailPrimaryAddress');
277 277
 		$winner = '';
278 278
 		$maxUsers = 0;
279
-		foreach($emailAttributes as $attr) {
279
+		foreach ($emailAttributes as $attr) {
280 280
 			$count = $this->countUsersWithAttribute($attr);
281
-			if($count > $maxUsers) {
281
+			if ($count > $maxUsers) {
282 282
 				$maxUsers = $count;
283 283
 				$winner = $attr;
284 284
 			}
285 285
 		}
286 286
 
287
-		if($winner !== '') {
287
+		if ($winner !== '') {
288 288
 			$this->applyFind('ldap_email_attr', $winner);
289
-			if($writeLog) {
290
-				\OCP\Util::writeLog('user_ldap', 'The mail attribute has ' .
291
-					'automatically been reset, because the original value ' .
289
+			if ($writeLog) {
290
+				\OCP\Util::writeLog('user_ldap', 'The mail attribute has '.
291
+					'automatically been reset, because the original value '.
292 292
 					'did not return any results.', \OCP\Util::INFO);
293 293
 			}
294 294
 		}
@@ -301,7 +301,7 @@  discard block
 block discarded – undo
301 301
 	 * @throws \Exception
302 302
 	 */
303 303
 	public function determineAttributes() {
304
-		if(!$this->checkRequirements(array('ldapHost',
304
+		if (!$this->checkRequirements(array('ldapHost',
305 305
 										   'ldapPort',
306 306
 										   'ldapBase',
307 307
 										   'ldapUserFilter',
@@ -317,7 +317,7 @@  discard block
 block discarded – undo
317 317
 		$this->result->addOptions('ldap_loginfilter_attributes', $attributes);
318 318
 
319 319
 		$selected = $this->configuration->ldapLoginFilterAttributes;
320
-		if(is_array($selected) && !empty($selected)) {
320
+		if (is_array($selected) && !empty($selected)) {
321 321
 			$this->result->addChange('ldap_loginfilter_attributes', $selected);
322 322
 		}
323 323
 
@@ -330,7 +330,7 @@  discard block
 block discarded – undo
330 330
 	 * @throws \Exception
331 331
 	 */
332 332
 	private function getUserAttributes() {
333
-		if(!$this->checkRequirements(array('ldapHost',
333
+		if (!$this->checkRequirements(array('ldapHost',
334 334
 										   'ldapPort',
335 335
 										   'ldapBase',
336 336
 										   'ldapUserFilter',
@@ -338,20 +338,20 @@  discard block
 block discarded – undo
338 338
 			return  false;
339 339
 		}
340 340
 		$cr = $this->getConnection();
341
-		if(!$cr) {
341
+		if (!$cr) {
342 342
 			throw new \Exception('Could not connect to LDAP');
343 343
 		}
344 344
 
345 345
 		$base = $this->configuration->ldapBase[0];
346 346
 		$filter = $this->configuration->ldapUserFilter;
347 347
 		$rr = $this->ldap->search($cr, $base, $filter, array(), 1, 1);
348
-		if(!$this->ldap->isResource($rr)) {
348
+		if (!$this->ldap->isResource($rr)) {
349 349
 			return false;
350 350
 		}
351 351
 		$er = $this->ldap->firstEntry($cr, $rr);
352 352
 		$attributes = $this->ldap->getAttributes($cr, $er);
353 353
 		$pureAttributes = array();
354
-		for($i = 0; $i < $attributes['count']; $i++) {
354
+		for ($i = 0; $i < $attributes['count']; $i++) {
355 355
 			$pureAttributes[] = $attributes[$i];
356 356
 		}
357 357
 
@@ -386,23 +386,23 @@  discard block
 block discarded – undo
386 386
 	 * @throws \Exception
387 387
 	 */
388 388
 	private function determineGroups($dbKey, $confKey, $testMemberOf = true) {
389
-		if(!$this->checkRequirements(array('ldapHost',
389
+		if (!$this->checkRequirements(array('ldapHost',
390 390
 										   'ldapPort',
391 391
 										   'ldapBase',
392 392
 										   ))) {
393 393
 			return  false;
394 394
 		}
395 395
 		$cr = $this->getConnection();
396
-		if(!$cr) {
396
+		if (!$cr) {
397 397
 			throw new \Exception('Could not connect to LDAP');
398 398
 		}
399 399
 
400 400
 		$this->fetchGroups($dbKey, $confKey);
401 401
 
402
-		if($testMemberOf) {
402
+		if ($testMemberOf) {
403 403
 			$this->configuration->hasMemberOfFilterSupport = $this->testMemberOf();
404 404
 			$this->result->markChange();
405
-			if(!$this->configuration->hasMemberOfFilterSupport) {
405
+			if (!$this->configuration->hasMemberOfFilterSupport) {
406 406
 				throw new \Exception('memberOf is not supported by the server');
407 407
 			}
408 408
 		}
@@ -422,7 +422,7 @@  discard block
 block discarded – undo
422 422
 		$obclasses = array('posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames', 'groupOfUniqueNames');
423 423
 
424 424
 		$filterParts = array();
425
-		foreach($obclasses as $obclass) {
425
+		foreach ($obclasses as $obclass) {
426 426
 			$filterParts[] = 'objectclass='.$obclass;
427 427
 		}
428 428
 		//we filter for everything
@@ -439,8 +439,8 @@  discard block
 block discarded – undo
439 439
 			// we need to request dn additionally here, otherwise memberOf
440 440
 			// detection will fail later
441 441
 			$result = $this->access->searchGroups($filter, array('cn', 'dn'), $limit, $offset);
442
-			foreach($result as $item) {
443
-				if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
442
+			foreach ($result as $item) {
443
+				if (!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
444 444
 					// just in case - no issue known
445 445
 					continue;
446 446
 				}
@@ -450,7 +450,7 @@  discard block
 block discarded – undo
450 450
 			$offset += $limit;
451 451
 		} while ($this->access->hasMoreResults());
452 452
 
453
-		if(count($groupNames) > 0) {
453
+		if (count($groupNames) > 0) {
454 454
 			natsort($groupNames);
455 455
 			$this->result->addOptions($dbKey, array_values($groupNames));
456 456
 		} else {
@@ -458,7 +458,7 @@  discard block
 block discarded – undo
458 458
 		}
459 459
 
460 460
 		$setFeatures = $this->configuration->$confKey;
461
-		if(is_array($setFeatures) && !empty($setFeatures)) {
461
+		if (is_array($setFeatures) && !empty($setFeatures)) {
462 462
 			//something is already configured? pre-select it.
463 463
 			$this->result->addChange($dbKey, $setFeatures);
464 464
 		}
@@ -466,14 +466,14 @@  discard block
 block discarded – undo
466 466
 	}
467 467
 
468 468
 	public function determineGroupMemberAssoc() {
469
-		if(!$this->checkRequirements(array('ldapHost',
469
+		if (!$this->checkRequirements(array('ldapHost',
470 470
 										   'ldapPort',
471 471
 										   'ldapGroupFilter',
472 472
 										   ))) {
473 473
 			return  false;
474 474
 		}
475 475
 		$attribute = $this->detectGroupMemberAssoc();
476
-		if($attribute === false) {
476
+		if ($attribute === false) {
477 477
 			return false;
478 478
 		}
479 479
 		$this->configuration->setConfiguration(array('ldapGroupMemberAssocAttr' => $attribute));
@@ -488,14 +488,14 @@  discard block
 block discarded – undo
488 488
 	 * @throws \Exception
489 489
 	 */
490 490
 	public function determineGroupObjectClasses() {
491
-		if(!$this->checkRequirements(array('ldapHost',
491
+		if (!$this->checkRequirements(array('ldapHost',
492 492
 										   'ldapPort',
493 493
 										   'ldapBase',
494 494
 										   ))) {
495 495
 			return  false;
496 496
 		}
497 497
 		$cr = $this->getConnection();
498
-		if(!$cr) {
498
+		if (!$cr) {
499 499
 			throw new \Exception('Could not connect to LDAP');
500 500
 		}
501 501
 
@@ -515,14 +515,14 @@  discard block
 block discarded – undo
515 515
 	 * @throws \Exception
516 516
 	 */
517 517
 	public function determineUserObjectClasses() {
518
-		if(!$this->checkRequirements(array('ldapHost',
518
+		if (!$this->checkRequirements(array('ldapHost',
519 519
 										   'ldapPort',
520 520
 										   'ldapBase',
521 521
 										   ))) {
522 522
 			return  false;
523 523
 		}
524 524
 		$cr = $this->getConnection();
525
-		if(!$cr) {
525
+		if (!$cr) {
526 526
 			throw new \Exception('Could not connect to LDAP');
527 527
 		}
528 528
 
@@ -545,7 +545,7 @@  discard block
 block discarded – undo
545 545
 	 * @throws \Exception
546 546
 	 */
547 547
 	public function getGroupFilter() {
548
-		if(!$this->checkRequirements(array('ldapHost',
548
+		if (!$this->checkRequirements(array('ldapHost',
549 549
 										   'ldapPort',
550 550
 										   'ldapBase',
551 551
 										   ))) {
@@ -569,7 +569,7 @@  discard block
 block discarded – undo
569 569
 	 * @throws \Exception
570 570
 	 */
571 571
 	public function getUserListFilter() {
572
-		if(!$this->checkRequirements(array('ldapHost',
572
+		if (!$this->checkRequirements(array('ldapHost',
573 573
 										   'ldapPort',
574 574
 										   'ldapBase',
575 575
 										   ))) {
@@ -582,7 +582,7 @@  discard block
 block discarded – undo
582 582
 			$this->applyFind('ldap_display_name', $d['ldap_display_name']);
583 583
 		}
584 584
 		$filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
585
-		if(!$filter) {
585
+		if (!$filter) {
586 586
 			throw new \Exception('Cannot create filter');
587 587
 		}
588 588
 
@@ -595,7 +595,7 @@  discard block
 block discarded – undo
595 595
 	 * @throws \Exception
596 596
 	 */
597 597
 	public function getUserLoginFilter() {
598
-		if(!$this->checkRequirements(array('ldapHost',
598
+		if (!$this->checkRequirements(array('ldapHost',
599 599
 										   'ldapPort',
600 600
 										   'ldapBase',
601 601
 										   'ldapUserFilter',
@@ -604,7 +604,7 @@  discard block
 block discarded – undo
604 604
 		}
605 605
 
606 606
 		$filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
607
-		if(!$filter) {
607
+		if (!$filter) {
608 608
 			throw new \Exception('Cannot create filter');
609 609
 		}
610 610
 
@@ -618,7 +618,7 @@  discard block
 block discarded – undo
618 618
 	 * @throws \Exception
619 619
 	 */
620 620
 	public function testLoginName($loginName) {
621
-		if(!$this->checkRequirements(array('ldapHost',
621
+		if (!$this->checkRequirements(array('ldapHost',
622 622
 			'ldapPort',
623 623
 			'ldapBase',
624 624
 			'ldapLoginFilter',
@@ -627,17 +627,17 @@  discard block
 block discarded – undo
627 627
 		}
628 628
 
629 629
 		$cr = $this->access->connection->getConnectionResource();
630
-		if(!$this->ldap->isResource($cr)) {
630
+		if (!$this->ldap->isResource($cr)) {
631 631
 			throw new \Exception('connection error');
632 632
 		}
633 633
 
634
-		if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
634
+		if (mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
635 635
 			=== false) {
636 636
 			throw new \Exception('missing placeholder');
637 637
 		}
638 638
 
639 639
 		$users = $this->access->countUsersByLoginName($loginName);
640
-		if($this->ldap->errno($cr) !== 0) {
640
+		if ($this->ldap->errno($cr) !== 0) {
641 641
 			throw new \Exception($this->ldap->error($cr));
642 642
 		}
643 643
 		$filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
@@ -652,22 +652,22 @@  discard block
 block discarded – undo
652 652
 	 * @throws \Exception
653 653
 	 */
654 654
 	public function guessPortAndTLS() {
655
-		if(!$this->checkRequirements(array('ldapHost',
655
+		if (!$this->checkRequirements(array('ldapHost',
656 656
 										   ))) {
657 657
 			return false;
658 658
 		}
659 659
 		$this->checkHost();
660 660
 		$portSettings = $this->getPortSettingsToTry();
661 661
 
662
-		if(!is_array($portSettings)) {
662
+		if (!is_array($portSettings)) {
663 663
 			throw new \Exception(print_r($portSettings, true));
664 664
 		}
665 665
 
666 666
 		//proceed from the best configuration and return on first success
667
-		foreach($portSettings as $setting) {
667
+		foreach ($portSettings as $setting) {
668 668
 			$p = $setting['port'];
669 669
 			$t = $setting['tls'];
670
-			\OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, \OCP\Util::DEBUG);
670
+			\OCP\Util::writeLog('user_ldap', 'Wiz: trying port '.$p.', TLS '.$t, \OCP\Util::DEBUG);
671 671
 			//connectAndBind may throw Exception, it needs to be catched by the
672 672
 			//callee of this method
673 673
 
@@ -677,7 +677,7 @@  discard block
 block discarded – undo
677 677
 				// any reply other than -1 (= cannot connect) is already okay,
678 678
 				// because then we found the server
679 679
 				// unavailable startTLS returns -11
680
-				if($e->getCode() > 0) {
680
+				if ($e->getCode() > 0) {
681 681
 					$settingsFound = true;
682 682
 				} else {
683 683
 					throw $e;
@@ -690,7 +690,7 @@  discard block
 block discarded – undo
690 690
 					'ldapTLS' => intval($t)
691 691
 				);
692 692
 				$this->configuration->setConfiguration($config);
693
-				\OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, \OCP\Util::DEBUG);
693
+				\OCP\Util::writeLog('user_ldap', 'Wiz: detected Port '.$p, \OCP\Util::DEBUG);
694 694
 				$this->result->addChange('ldap_port', $p);
695 695
 				return $this->result;
696 696
 			}
@@ -705,7 +705,7 @@  discard block
 block discarded – undo
705 705
 	 * @return WizardResult|false WizardResult on success, false otherwise
706 706
 	 */
707 707
 	public function guessBaseDN() {
708
-		if(!$this->checkRequirements(array('ldapHost',
708
+		if (!$this->checkRequirements(array('ldapHost',
709 709
 										   'ldapPort',
710 710
 										   ))) {
711 711
 			return false;
@@ -714,9 +714,9 @@  discard block
 block discarded – undo
714 714
 		//check whether a DN is given in the agent name (99.9% of all cases)
715 715
 		$base = null;
716 716
 		$i = stripos($this->configuration->ldapAgentName, 'dc=');
717
-		if($i !== false) {
717
+		if ($i !== false) {
718 718
 			$base = substr($this->configuration->ldapAgentName, $i);
719
-			if($this->testBaseDN($base)) {
719
+			if ($this->testBaseDN($base)) {
720 720
 				$this->applyFind('ldap_base', $base);
721 721
 				return $this->result;
722 722
 			}
@@ -727,13 +727,13 @@  discard block
 block discarded – undo
727 727
 		//a base DN
728 728
 		$helper = new Helper(\OC::$server->getConfig());
729 729
 		$domain = $helper->getDomainFromURL($this->configuration->ldapHost);
730
-		if(!$domain) {
730
+		if (!$domain) {
731 731
 			return false;
732 732
 		}
733 733
 
734 734
 		$dparts = explode('.', $domain);
735
-		while(count($dparts) > 0) {
736
-			$base2 = 'dc=' . implode(',dc=', $dparts);
735
+		while (count($dparts) > 0) {
736
+			$base2 = 'dc='.implode(',dc=', $dparts);
737 737
 			if ($base !== $base2 && $this->testBaseDN($base2)) {
738 738
 				$this->applyFind('ldap_base', $base2);
739 739
 				return $this->result;
@@ -766,7 +766,7 @@  discard block
 block discarded – undo
766 766
 		$hostInfo = parse_url($host);
767 767
 
768 768
 		//removes Port from Host
769
-		if(is_array($hostInfo) && isset($hostInfo['port'])) {
769
+		if (is_array($hostInfo) && isset($hostInfo['port'])) {
770 770
 			$port = $hostInfo['port'];
771 771
 			$host = str_replace(':'.$port, '', $host);
772 772
 			$this->applyFind('ldap_host', $host);
@@ -783,30 +783,30 @@  discard block
 block discarded – undo
783 783
 	private function detectGroupMemberAssoc() {
784 784
 		$possibleAttrs = array('uniqueMember', 'memberUid', 'member', 'gidNumber');
785 785
 		$filter = $this->configuration->ldapGroupFilter;
786
-		if(empty($filter)) {
786
+		if (empty($filter)) {
787 787
 			return false;
788 788
 		}
789 789
 		$cr = $this->getConnection();
790
-		if(!$cr) {
790
+		if (!$cr) {
791 791
 			throw new \Exception('Could not connect to LDAP');
792 792
 		}
793 793
 		$base = $this->configuration->ldapBase[0];
794 794
 		$rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
795
-		if(!$this->ldap->isResource($rr)) {
795
+		if (!$this->ldap->isResource($rr)) {
796 796
 			return false;
797 797
 		}
798 798
 		$er = $this->ldap->firstEntry($cr, $rr);
799
-		while(is_resource($er)) {
799
+		while (is_resource($er)) {
800 800
 			$this->ldap->getDN($cr, $er);
801 801
 			$attrs = $this->ldap->getAttributes($cr, $er);
802 802
 			$result = array();
803 803
 			$possibleAttrsCount = count($possibleAttrs);
804
-			for($i = 0; $i < $possibleAttrsCount; $i++) {
805
-				if(isset($attrs[$possibleAttrs[$i]])) {
804
+			for ($i = 0; $i < $possibleAttrsCount; $i++) {
805
+				if (isset($attrs[$possibleAttrs[$i]])) {
806 806
 					$result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
807 807
 				}
808 808
 			}
809
-			if(!empty($result)) {
809
+			if (!empty($result)) {
810 810
 				natsort($result);
811 811
 				return key($result);
812 812
 			}
@@ -825,14 +825,14 @@  discard block
 block discarded – undo
825 825
 	 */
826 826
 	private function testBaseDN($base) {
827 827
 		$cr = $this->getConnection();
828
-		if(!$cr) {
828
+		if (!$cr) {
829 829
 			throw new \Exception('Could not connect to LDAP');
830 830
 		}
831 831
 
832 832
 		//base is there, let's validate it. If we search for anything, we should
833 833
 		//get a result set > 0 on a proper base
834 834
 		$rr = $this->ldap->search($cr, $base, 'objectClass=*', array('dn'), 0, 1);
835
-		if(!$this->ldap->isResource($rr)) {
835
+		if (!$this->ldap->isResource($rr)) {
836 836
 			$errorNo  = $this->ldap->errno($cr);
837 837
 			$errorMsg = $this->ldap->error($cr);
838 838
 			\OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base.
@@ -854,11 +854,11 @@  discard block
 block discarded – undo
854 854
 	 */
855 855
 	private function testMemberOf() {
856 856
 		$cr = $this->getConnection();
857
-		if(!$cr) {
857
+		if (!$cr) {
858 858
 			throw new \Exception('Could not connect to LDAP');
859 859
 		}
860 860
 		$result = $this->access->countUsers('memberOf=*', array('memberOf'), 1);
861
-		if(is_int($result) &&  $result > 0) {
861
+		if (is_int($result) && $result > 0) {
862 862
 			return true;
863 863
 		}
864 864
 		return false;
@@ -879,27 +879,27 @@  discard block
 block discarded – undo
879 879
 			case self::LFILTER_USER_LIST:
880 880
 				$objcs = $this->configuration->ldapUserFilterObjectclass;
881 881
 				//glue objectclasses
882
-				if(is_array($objcs) && count($objcs) > 0) {
882
+				if (is_array($objcs) && count($objcs) > 0) {
883 883
 					$filter .= '(|';
884
-					foreach($objcs as $objc) {
885
-						$filter .= '(objectclass=' . $objc . ')';
884
+					foreach ($objcs as $objc) {
885
+						$filter .= '(objectclass='.$objc.')';
886 886
 					}
887 887
 					$filter .= ')';
888 888
 					$parts++;
889 889
 				}
890 890
 				//glue group memberships
891
-				if($this->configuration->hasMemberOfFilterSupport) {
891
+				if ($this->configuration->hasMemberOfFilterSupport) {
892 892
 					$cns = $this->configuration->ldapUserFilterGroups;
893
-					if(is_array($cns) && count($cns) > 0) {
893
+					if (is_array($cns) && count($cns) > 0) {
894 894
 						$filter .= '(|';
895 895
 						$cr = $this->getConnection();
896
-						if(!$cr) {
896
+						if (!$cr) {
897 897
 							throw new \Exception('Could not connect to LDAP');
898 898
 						}
899 899
 						$base = $this->configuration->ldapBase[0];
900
-						foreach($cns as $cn) {
901
-							$rr = $this->ldap->search($cr, $base, 'cn=' . $cn, array('dn', 'primaryGroupToken'));
902
-							if(!$this->ldap->isResource($rr)) {
900
+						foreach ($cns as $cn) {
901
+							$rr = $this->ldap->search($cr, $base, 'cn='.$cn, array('dn', 'primaryGroupToken'));
902
+							if (!$this->ldap->isResource($rr)) {
903 903
 								continue;
904 904
 							}
905 905
 							$er = $this->ldap->firstEntry($cr, $rr);
@@ -908,11 +908,11 @@  discard block
 block discarded – undo
908 908
 							if ($dn === false || $dn === '') {
909 909
 								continue;
910 910
 							}
911
-							$filterPart = '(memberof=' . $dn . ')';
912
-							if(isset($attrs['primaryGroupToken'])) {
911
+							$filterPart = '(memberof='.$dn.')';
912
+							if (isset($attrs['primaryGroupToken'])) {
913 913
 								$pgt = $attrs['primaryGroupToken'][0];
914
-								$primaryFilterPart = '(primaryGroupID=' . $pgt .')';
915
-								$filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
914
+								$primaryFilterPart = '(primaryGroupID='.$pgt.')';
915
+								$filterPart = '(|'.$filterPart.$primaryFilterPart.')';
916 916
 							}
917 917
 							$filter .= $filterPart;
918 918
 						}
@@ -921,8 +921,8 @@  discard block
 block discarded – undo
921 921
 					$parts++;
922 922
 				}
923 923
 				//wrap parts in AND condition
924
-				if($parts > 1) {
925
-					$filter = '(&' . $filter . ')';
924
+				if ($parts > 1) {
925
+					$filter = '(&'.$filter.')';
926 926
 				}
927 927
 				if ($filter === '') {
928 928
 					$filter = '(objectclass=*)';
@@ -932,27 +932,27 @@  discard block
 block discarded – undo
932 932
 			case self::LFILTER_GROUP_LIST:
933 933
 				$objcs = $this->configuration->ldapGroupFilterObjectclass;
934 934
 				//glue objectclasses
935
-				if(is_array($objcs) && count($objcs) > 0) {
935
+				if (is_array($objcs) && count($objcs) > 0) {
936 936
 					$filter .= '(|';
937
-					foreach($objcs as $objc) {
938
-						$filter .= '(objectclass=' . $objc . ')';
937
+					foreach ($objcs as $objc) {
938
+						$filter .= '(objectclass='.$objc.')';
939 939
 					}
940 940
 					$filter .= ')';
941 941
 					$parts++;
942 942
 				}
943 943
 				//glue group memberships
944 944
 				$cns = $this->configuration->ldapGroupFilterGroups;
945
-				if(is_array($cns) && count($cns) > 0) {
945
+				if (is_array($cns) && count($cns) > 0) {
946 946
 					$filter .= '(|';
947
-					foreach($cns as $cn) {
948
-						$filter .= '(cn=' . $cn . ')';
947
+					foreach ($cns as $cn) {
948
+						$filter .= '(cn='.$cn.')';
949 949
 					}
950 950
 					$filter .= ')';
951 951
 				}
952 952
 				$parts++;
953 953
 				//wrap parts in AND condition
954
-				if($parts > 1) {
955
-					$filter = '(&' . $filter . ')';
954
+				if ($parts > 1) {
955
+					$filter = '(&'.$filter.')';
956 956
 				}
957 957
 				break;
958 958
 
@@ -964,47 +964,47 @@  discard block
 block discarded – undo
964 964
 				$userAttributes = array_change_key_case(array_flip($userAttributes));
965 965
 				$parts = 0;
966 966
 
967
-				if($this->configuration->ldapLoginFilterUsername === '1') {
967
+				if ($this->configuration->ldapLoginFilterUsername === '1') {
968 968
 					$attr = '';
969
-					if(isset($userAttributes['uid'])) {
969
+					if (isset($userAttributes['uid'])) {
970 970
 						$attr = 'uid';
971
-					} else if(isset($userAttributes['samaccountname'])) {
971
+					} else if (isset($userAttributes['samaccountname'])) {
972 972
 						$attr = 'samaccountname';
973
-					} else if(isset($userAttributes['cn'])) {
973
+					} else if (isset($userAttributes['cn'])) {
974 974
 						//fallback
975 975
 						$attr = 'cn';
976 976
 					}
977 977
 					if ($attr !== '') {
978
-						$filterUsername = '(' . $attr . $loginpart . ')';
978
+						$filterUsername = '('.$attr.$loginpart.')';
979 979
 						$parts++;
980 980
 					}
981 981
 				}
982 982
 
983 983
 				$filterEmail = '';
984
-				if($this->configuration->ldapLoginFilterEmail === '1') {
984
+				if ($this->configuration->ldapLoginFilterEmail === '1') {
985 985
 					$filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
986 986
 					$parts++;
987 987
 				}
988 988
 
989 989
 				$filterAttributes = '';
990 990
 				$attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
991
-				if(is_array($attrsToFilter) && count($attrsToFilter) > 0) {
991
+				if (is_array($attrsToFilter) && count($attrsToFilter) > 0) {
992 992
 					$filterAttributes = '(|';
993
-					foreach($attrsToFilter as $attribute) {
994
-						$filterAttributes .= '(' . $attribute . $loginpart . ')';
993
+					foreach ($attrsToFilter as $attribute) {
994
+						$filterAttributes .= '('.$attribute.$loginpart.')';
995 995
 					}
996 996
 					$filterAttributes .= ')';
997 997
 					$parts++;
998 998
 				}
999 999
 
1000 1000
 				$filterLogin = '';
1001
-				if($parts > 1) {
1001
+				if ($parts > 1) {
1002 1002
 					$filterLogin = '(|';
1003 1003
 				}
1004 1004
 				$filterLogin .= $filterUsername;
1005 1005
 				$filterLogin .= $filterEmail;
1006 1006
 				$filterLogin .= $filterAttributes;
1007
-				if($parts > 1) {
1007
+				if ($parts > 1) {
1008 1008
 					$filterLogin .= ')';
1009 1009
 				}
1010 1010
 
@@ -1029,12 +1029,12 @@  discard block
 block discarded – undo
1029 1029
 		//connect, does not really trigger any server communication
1030 1030
 		$host = $this->configuration->ldapHost;
1031 1031
 		$hostInfo = parse_url($host);
1032
-		if(!$hostInfo) {
1032
+		if (!$hostInfo) {
1033 1033
 			throw new \Exception(self::$l->t('Invalid Host'));
1034 1034
 		}
1035 1035
 		\OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', \OCP\Util::DEBUG);
1036 1036
 		$cr = $this->ldap->connect($host, $port);
1037
-		if(!is_resource($cr)) {
1037
+		if (!is_resource($cr)) {
1038 1038
 			throw new \Exception(self::$l->t('Invalid Host'));
1039 1039
 		}
1040 1040
 
@@ -1044,9 +1044,9 @@  discard block
 block discarded – undo
1044 1044
 		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1045 1045
 
1046 1046
 		try {
1047
-			if($tls) {
1047
+			if ($tls) {
1048 1048
 				$isTlsWorking = @$this->ldap->startTls($cr);
1049
-				if(!$isTlsWorking) {
1049
+				if (!$isTlsWorking) {
1050 1050
 					return false;
1051 1051
 				}
1052 1052
 			}
@@ -1060,17 +1060,17 @@  discard block
 block discarded – undo
1060 1060
 			$errNo = $this->ldap->errno($cr);
1061 1061
 			$error = ldap_error($cr);
1062 1062
 			$this->ldap->unbind($cr);
1063
-		} catch(ServerNotAvailableException $e) {
1063
+		} catch (ServerNotAvailableException $e) {
1064 1064
 			return false;
1065 1065
 		}
1066 1066
 
1067
-		if($login === true) {
1067
+		if ($login === true) {
1068 1068
 			$this->ldap->unbind($cr);
1069
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . intval($tls), \OCP\Util::DEBUG);
1069
+			\OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '.$port.' TLS '.intval($tls), \OCP\Util::DEBUG);
1070 1070
 			return true;
1071 1071
 		}
1072 1072
 
1073
-		if($errNo === -1) {
1073
+		if ($errNo === -1) {
1074 1074
 			//host, port or TLS wrong
1075 1075
 			return false;
1076 1076
 		}
@@ -1098,9 +1098,9 @@  discard block
 block discarded – undo
1098 1098
 	 */
1099 1099
 	private function checkRequirements($reqs) {
1100 1100
 		$this->checkAgentRequirements();
1101
-		foreach($reqs as $option) {
1101
+		foreach ($reqs as $option) {
1102 1102
 			$value = $this->configuration->$option;
1103
-			if(empty($value)) {
1103
+			if (empty($value)) {
1104 1104
 				return false;
1105 1105
 			}
1106 1106
 		}
@@ -1122,33 +1122,33 @@  discard block
 block discarded – undo
1122 1122
 		$dnRead = array();
1123 1123
 		$foundItems = array();
1124 1124
 		$maxEntries = 0;
1125
-		if(!is_array($this->configuration->ldapBase)
1125
+		if (!is_array($this->configuration->ldapBase)
1126 1126
 		   || !isset($this->configuration->ldapBase[0])) {
1127 1127
 			return false;
1128 1128
 		}
1129 1129
 		$base = $this->configuration->ldapBase[0];
1130 1130
 		$cr = $this->getConnection();
1131
-		if(!$this->ldap->isResource($cr)) {
1131
+		if (!$this->ldap->isResource($cr)) {
1132 1132
 			return false;
1133 1133
 		}
1134 1134
 		$lastFilter = null;
1135
-		if(isset($filters[count($filters)-1])) {
1136
-			$lastFilter = $filters[count($filters)-1];
1135
+		if (isset($filters[count($filters) - 1])) {
1136
+			$lastFilter = $filters[count($filters) - 1];
1137 1137
 		}
1138
-		foreach($filters as $filter) {
1139
-			if($lastFilter === $filter && count($foundItems) > 0) {
1138
+		foreach ($filters as $filter) {
1139
+			if ($lastFilter === $filter && count($foundItems) > 0) {
1140 1140
 				//skip when the filter is a wildcard and results were found
1141 1141
 				continue;
1142 1142
 			}
1143 1143
 			// 20k limit for performance and reason
1144 1144
 			$rr = $this->ldap->search($cr, $base, $filter, array($attr), 0, 20000);
1145
-			if(!$this->ldap->isResource($rr)) {
1145
+			if (!$this->ldap->isResource($rr)) {
1146 1146
 				continue;
1147 1147
 			}
1148 1148
 			$entries = $this->ldap->countEntries($cr, $rr);
1149 1149
 			$getEntryFunc = 'firstEntry';
1150
-			if(($entries !== false) && ($entries > 0)) {
1151
-				if(!is_null($maxF) && $entries > $maxEntries) {
1150
+			if (($entries !== false) && ($entries > 0)) {
1151
+				if (!is_null($maxF) && $entries > $maxEntries) {
1152 1152
 					$maxEntries = $entries;
1153 1153
 					$maxF = $filter;
1154 1154
 				}
@@ -1156,13 +1156,13 @@  discard block
 block discarded – undo
1156 1156
 				do {
1157 1157
 					$entry = $this->ldap->$getEntryFunc($cr, $rr);
1158 1158
 					$getEntryFunc = 'nextEntry';
1159
-					if(!$this->ldap->isResource($entry)) {
1159
+					if (!$this->ldap->isResource($entry)) {
1160 1160
 						continue 2;
1161 1161
 					}
1162 1162
 					$rr = $entry; //will be expected by nextEntry next round
1163 1163
 					$attributes = $this->ldap->getAttributes($cr, $entry);
1164 1164
 					$dn = $this->ldap->getDN($cr, $entry);
1165
-					if($dn === false || in_array($dn, $dnRead)) {
1165
+					if ($dn === false || in_array($dn, $dnRead)) {
1166 1166
 						continue;
1167 1167
 					}
1168 1168
 					$newItems = array();
@@ -1173,7 +1173,7 @@  discard block
 block discarded – undo
1173 1173
 					$foundItems = array_merge($foundItems, $newItems);
1174 1174
 					$this->resultCache[$dn][$attr] = $newItems;
1175 1175
 					$dnRead[] = $dn;
1176
-				} while(($state === self::LRESULT_PROCESSED_SKIP
1176
+				} while (($state === self::LRESULT_PROCESSED_SKIP
1177 1177
 						|| $this->ldap->isResource($entry))
1178 1178
 						&& ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit));
1179 1179
 			}
@@ -1196,11 +1196,11 @@  discard block
 block discarded – undo
1196 1196
 	 */
1197 1197
 	private function determineFeature($objectclasses, $attr, $dbkey, $confkey, $po = false) {
1198 1198
 		$cr = $this->getConnection();
1199
-		if(!$cr) {
1199
+		if (!$cr) {
1200 1200
 			throw new \Exception('Could not connect to LDAP');
1201 1201
 		}
1202 1202
 		$p = 'objectclass=';
1203
-		foreach($objectclasses as $key => $value) {
1203
+		foreach ($objectclasses as $key => $value) {
1204 1204
 			$objectclasses[$key] = $p.$value;
1205 1205
 		}
1206 1206
 		$maxEntryObjC = '';
@@ -1212,7 +1212,7 @@  discard block
 block discarded – undo
1212 1212
 		$availableFeatures =
1213 1213
 			$this->cumulativeSearchOnAttribute($objectclasses, $attr,
1214 1214
 											   $dig, $maxEntryObjC);
1215
-		if(is_array($availableFeatures)
1215
+		if (is_array($availableFeatures)
1216 1216
 		   && count($availableFeatures) > 0) {
1217 1217
 			natcasesort($availableFeatures);
1218 1218
 			//natcasesort keeps indices, but we must get rid of them for proper
@@ -1223,7 +1223,7 @@  discard block
 block discarded – undo
1223 1223
 		}
1224 1224
 
1225 1225
 		$setFeatures = $this->configuration->$confkey;
1226
-		if(is_array($setFeatures) && !empty($setFeatures)) {
1226
+		if (is_array($setFeatures) && !empty($setFeatures)) {
1227 1227
 			//something is already configured? pre-select it.
1228 1228
 			$this->result->addChange($dbkey, $setFeatures);
1229 1229
 		} else if ($po && $maxEntryObjC !== '') {
@@ -1245,7 +1245,7 @@  discard block
 block discarded – undo
1245 1245
 	 * LRESULT_PROCESSED_INVALID or LRESULT_PROCESSED_SKIP
1246 1246
 	 */
1247 1247
 	private function getAttributeValuesFromEntry($result, $attribute, &$known) {
1248
-		if(!is_array($result)
1248
+		if (!is_array($result)
1249 1249
 		   || !isset($result['count'])
1250 1250
 		   || !$result['count'] > 0) {
1251 1251
 			return self::LRESULT_PROCESSED_INVALID;
@@ -1254,12 +1254,12 @@  discard block
 block discarded – undo
1254 1254
 		// strtolower on all keys for proper comparison
1255 1255
 		$result = \OCP\Util::mb_array_change_key_case($result);
1256 1256
 		$attribute = strtolower($attribute);
1257
-		if(isset($result[$attribute])) {
1258
-			foreach($result[$attribute] as $key => $val) {
1259
-				if($key === 'count') {
1257
+		if (isset($result[$attribute])) {
1258
+			foreach ($result[$attribute] as $key => $val) {
1259
+				if ($key === 'count') {
1260 1260
 					continue;
1261 1261
 				}
1262
-				if(!in_array($val, $known)) {
1262
+				if (!in_array($val, $known)) {
1263 1263
 					$known[] = $val;
1264 1264
 				}
1265 1265
 			}
@@ -1273,7 +1273,7 @@  discard block
 block discarded – undo
1273 1273
 	 * @return bool|mixed
1274 1274
 	 */
1275 1275
 	private function getConnection() {
1276
-		if(!is_null($this->cr)) {
1276
+		if (!is_null($this->cr)) {
1277 1277
 			return $this->cr;
1278 1278
 		}
1279 1279
 
@@ -1285,14 +1285,14 @@  discard block
 block discarded – undo
1285 1285
 		$this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1286 1286
 		$this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1287 1287
 		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1288
-		if($this->configuration->ldapTLS === 1) {
1288
+		if ($this->configuration->ldapTLS === 1) {
1289 1289
 			$this->ldap->startTls($cr);
1290 1290
 		}
1291 1291
 
1292 1292
 		$lo = @$this->ldap->bind($cr,
1293 1293
 								 $this->configuration->ldapAgentName,
1294 1294
 								 $this->configuration->ldapAgentPassword);
1295
-		if($lo === true) {
1295
+		if ($lo === true) {
1296 1296
 			$this->$cr = $cr;
1297 1297
 			return $cr;
1298 1298
 		}
@@ -1327,14 +1327,14 @@  discard block
 block discarded – undo
1327 1327
 		$portSettings = array();
1328 1328
 
1329 1329
 		//In case the port is already provided, we will check this first
1330
-		if($port > 0) {
1330
+		if ($port > 0) {
1331 1331
 			$hostInfo = parse_url($host);
1332
-			if(!(is_array($hostInfo)
1332
+			if (!(is_array($hostInfo)
1333 1333
 				&& isset($hostInfo['scheme'])
1334 1334
 				&& stripos($hostInfo['scheme'], 'ldaps') !== false)) {
1335 1335
 				$portSettings[] = array('port' => $port, 'tls' => true);
1336 1336
 			}
1337
-			$portSettings[] =array('port' => $port, 'tls' => false);
1337
+			$portSettings[] = array('port' => $port, 'tls' => false);
1338 1338
 		}
1339 1339
 
1340 1340
 		//default ports
Please login to merge, or discard this patch.