Completed
Pull Request — master (#3676)
by Individual IT
12:49
created
apps/dav/lib/DAV/Sharing/Plugin.php 4 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -24,7 +24,6 @@
 block discarded – undo
24 24
 use OCA\DAV\Connector\Sabre\Auth;
25 25
 use OCA\DAV\DAV\Sharing\Xml\Invite;
26 26
 use OCP\IRequest;
27
-use Sabre\DAV\Exception\BadRequest;
28 27
 use Sabre\DAV\Exception\NotFound;
29 28
 use Sabre\DAV\INode;
30 29
 use Sabre\DAV\PropFind;
Please login to merge, or discard this patch.
Indentation   +161 added lines, -161 removed lines patch added patch discarded remove patch
@@ -36,166 +36,166 @@
 block discarded – undo
36 36
 
37 37
 class Plugin extends ServerPlugin {
38 38
 
39
-	const NS_OWNCLOUD = 'http://owncloud.org/ns';
40
-
41
-	/** @var Auth */
42
-	private $auth;
43
-
44
-	/** @var IRequest */
45
-	private $request;
46
-
47
-	/**
48
-	 * Plugin constructor.
49
-	 *
50
-	 * @param Auth $authBackEnd
51
-	 * @param IRequest $request
52
-	 */
53
-	public function __construct(Auth $authBackEnd, IRequest $request) {
54
-		$this->auth = $authBackEnd;
55
-		$this->request = $request;
56
-	}
57
-
58
-	/**
59
-	 * Reference to SabreDAV server object.
60
-	 *
61
-	 * @var \Sabre\DAV\Server
62
-	 */
63
-	protected $server;
64
-
65
-	/**
66
-	 * This method should return a list of server-features.
67
-	 *
68
-	 * This is for example 'versioning' and is added to the DAV: header
69
-	 * in an OPTIONS response.
70
-	 *
71
-	 * @return string[]
72
-	 */
73
-	function getFeatures() {
74
-		return ['oc-resource-sharing'];
75
-	}
76
-
77
-	/**
78
-	 * Returns a plugin name.
79
-	 *
80
-	 * Using this name other plugins will be able to access other plugins
81
-	 * using Sabre\DAV\Server::getPlugin
82
-	 *
83
-	 * @return string
84
-	 */
85
-	function getPluginName() {
86
-		return 'oc-resource-sharing';
87
-	}
88
-
89
-	/**
90
-	 * This initializes the plugin.
91
-	 *
92
-	 * This function is called by Sabre\DAV\Server, after
93
-	 * addPlugin is called.
94
-	 *
95
-	 * This method should set up the required event subscriptions.
96
-	 *
97
-	 * @param Server $server
98
-	 * @return void
99
-	 */
100
-	function initialize(Server $server) {
101
-		$this->server = $server;
102
-		$this->server->xml->elementMap['{' . Plugin::NS_OWNCLOUD . '}share'] = 'OCA\\DAV\\DAV\\Sharing\\Xml\\ShareRequest';
103
-		$this->server->xml->elementMap['{' . Plugin::NS_OWNCLOUD . '}invite'] = 'OCA\\DAV\\DAV\\Sharing\\Xml\\Invite';
104
-
105
-		$this->server->on('method:POST', [$this, 'httpPost']);
106
-		$this->server->on('propFind',    [$this, 'propFind']);
107
-	}
108
-
109
-	/**
110
-	 * We intercept this to handle POST requests on a dav resource.
111
-	 *
112
-	 * @param RequestInterface $request
113
-	 * @param ResponseInterface $response
114
-	 * @return null|false
115
-	 */
116
-	function httpPost(RequestInterface $request, ResponseInterface $response) {
117
-
118
-		$path = $request->getPath();
119
-
120
-		// Only handling xml
121
-		$contentType = $request->getHeader('Content-Type');
122
-		if (strpos($contentType, 'application/xml') === false && strpos($contentType, 'text/xml') === false)
123
-			return;
124
-
125
-		// Making sure the node exists
126
-		try {
127
-			$node = $this->server->tree->getNodeForPath($path);
128
-		} catch (NotFound $e) {
129
-			return;
130
-		}
131
-
132
-		$requestBody = $request->getBodyAsString();
133
-
134
-		// If this request handler could not deal with this POST request, it
135
-		// will return 'null' and other plugins get a chance to handle the
136
-		// request.
137
-		//
138
-		// However, we already requested the full body. This is a problem,
139
-		// because a body can only be read once. This is why we preemptively
140
-		// re-populated the request body with the existing data.
141
-		$request->setBody($requestBody);
142
-
143
-		$message = $this->server->xml->parse($requestBody, $request->getUrl(), $documentType);
144
-
145
-		switch ($documentType) {
146
-
147
-			// Dealing with the 'share' document, which modified invitees on a
148
-			// calendar.
149
-			case '{' . self::NS_OWNCLOUD . '}share' :
150
-
151
-				// We can only deal with IShareableCalendar objects
152
-				if (!$node instanceof IShareable) {
153
-					return;
154
-				}
155
-
156
-				$this->server->transactionType = 'post-oc-resource-share';
157
-
158
-				// Getting ACL info
159
-				$acl = $this->server->getPlugin('acl');
160
-
161
-				// If there's no ACL support, we allow everything
162
-				if ($acl) {
163
-					/** @var \Sabre\DAVACL\Plugin $acl */
164
-					$acl->checkPrivileges($path, '{DAV:}write');
165
-				}
166
-
167
-				$node->updateShares($message->set, $message->remove);
168
-
169
-				$response->setStatus(200);
170
-				// Adding this because sending a response body may cause issues,
171
-				// and I wanted some type of indicator the response was handled.
172
-				$response->setHeader('X-Sabre-Status', 'everything-went-well');
173
-
174
-				// Breaking the event chain
175
-				return false;
176
-		}
177
-	}
178
-
179
-	/**
180
-	 * This event is triggered when properties are requested for a certain
181
-	 * node.
182
-	 *
183
-	 * This allows us to inject any properties early.
184
-	 *
185
-	 * @param PropFind $propFind
186
-	 * @param INode $node
187
-	 * @return void
188
-	 */
189
-	function propFind(PropFind $propFind, INode $node) {
190
-		if ($node instanceof IShareable) {
191
-
192
-			$propFind->handle('{' . Plugin::NS_OWNCLOUD . '}invite', function() use ($node) {
193
-				return new Invite(
194
-					$node->getShares()
195
-				);
196
-			});
197
-
198
-		}
199
-	}
39
+    const NS_OWNCLOUD = 'http://owncloud.org/ns';
40
+
41
+    /** @var Auth */
42
+    private $auth;
43
+
44
+    /** @var IRequest */
45
+    private $request;
46
+
47
+    /**
48
+     * Plugin constructor.
49
+     *
50
+     * @param Auth $authBackEnd
51
+     * @param IRequest $request
52
+     */
53
+    public function __construct(Auth $authBackEnd, IRequest $request) {
54
+        $this->auth = $authBackEnd;
55
+        $this->request = $request;
56
+    }
57
+
58
+    /**
59
+     * Reference to SabreDAV server object.
60
+     *
61
+     * @var \Sabre\DAV\Server
62
+     */
63
+    protected $server;
64
+
65
+    /**
66
+     * This method should return a list of server-features.
67
+     *
68
+     * This is for example 'versioning' and is added to the DAV: header
69
+     * in an OPTIONS response.
70
+     *
71
+     * @return string[]
72
+     */
73
+    function getFeatures() {
74
+        return ['oc-resource-sharing'];
75
+    }
76
+
77
+    /**
78
+     * Returns a plugin name.
79
+     *
80
+     * Using this name other plugins will be able to access other plugins
81
+     * using Sabre\DAV\Server::getPlugin
82
+     *
83
+     * @return string
84
+     */
85
+    function getPluginName() {
86
+        return 'oc-resource-sharing';
87
+    }
88
+
89
+    /**
90
+     * This initializes the plugin.
91
+     *
92
+     * This function is called by Sabre\DAV\Server, after
93
+     * addPlugin is called.
94
+     *
95
+     * This method should set up the required event subscriptions.
96
+     *
97
+     * @param Server $server
98
+     * @return void
99
+     */
100
+    function initialize(Server $server) {
101
+        $this->server = $server;
102
+        $this->server->xml->elementMap['{' . Plugin::NS_OWNCLOUD . '}share'] = 'OCA\\DAV\\DAV\\Sharing\\Xml\\ShareRequest';
103
+        $this->server->xml->elementMap['{' . Plugin::NS_OWNCLOUD . '}invite'] = 'OCA\\DAV\\DAV\\Sharing\\Xml\\Invite';
104
+
105
+        $this->server->on('method:POST', [$this, 'httpPost']);
106
+        $this->server->on('propFind',    [$this, 'propFind']);
107
+    }
108
+
109
+    /**
110
+     * We intercept this to handle POST requests on a dav resource.
111
+     *
112
+     * @param RequestInterface $request
113
+     * @param ResponseInterface $response
114
+     * @return null|false
115
+     */
116
+    function httpPost(RequestInterface $request, ResponseInterface $response) {
117
+
118
+        $path = $request->getPath();
119
+
120
+        // Only handling xml
121
+        $contentType = $request->getHeader('Content-Type');
122
+        if (strpos($contentType, 'application/xml') === false && strpos($contentType, 'text/xml') === false)
123
+            return;
124
+
125
+        // Making sure the node exists
126
+        try {
127
+            $node = $this->server->tree->getNodeForPath($path);
128
+        } catch (NotFound $e) {
129
+            return;
130
+        }
131
+
132
+        $requestBody = $request->getBodyAsString();
133
+
134
+        // If this request handler could not deal with this POST request, it
135
+        // will return 'null' and other plugins get a chance to handle the
136
+        // request.
137
+        //
138
+        // However, we already requested the full body. This is a problem,
139
+        // because a body can only be read once. This is why we preemptively
140
+        // re-populated the request body with the existing data.
141
+        $request->setBody($requestBody);
142
+
143
+        $message = $this->server->xml->parse($requestBody, $request->getUrl(), $documentType);
144
+
145
+        switch ($documentType) {
146
+
147
+            // Dealing with the 'share' document, which modified invitees on a
148
+            // calendar.
149
+            case '{' . self::NS_OWNCLOUD . '}share' :
150
+
151
+                // We can only deal with IShareableCalendar objects
152
+                if (!$node instanceof IShareable) {
153
+                    return;
154
+                }
155
+
156
+                $this->server->transactionType = 'post-oc-resource-share';
157
+
158
+                // Getting ACL info
159
+                $acl = $this->server->getPlugin('acl');
160
+
161
+                // If there's no ACL support, we allow everything
162
+                if ($acl) {
163
+                    /** @var \Sabre\DAVACL\Plugin $acl */
164
+                    $acl->checkPrivileges($path, '{DAV:}write');
165
+                }
166
+
167
+                $node->updateShares($message->set, $message->remove);
168
+
169
+                $response->setStatus(200);
170
+                // Adding this because sending a response body may cause issues,
171
+                // and I wanted some type of indicator the response was handled.
172
+                $response->setHeader('X-Sabre-Status', 'everything-went-well');
173
+
174
+                // Breaking the event chain
175
+                return false;
176
+        }
177
+    }
178
+
179
+    /**
180
+     * This event is triggered when properties are requested for a certain
181
+     * node.
182
+     *
183
+     * This allows us to inject any properties early.
184
+     *
185
+     * @param PropFind $propFind
186
+     * @param INode $node
187
+     * @return void
188
+     */
189
+    function propFind(PropFind $propFind, INode $node) {
190
+        if ($node instanceof IShareable) {
191
+
192
+            $propFind->handle('{' . Plugin::NS_OWNCLOUD . '}invite', function() use ($node) {
193
+                return new Invite(
194
+                    $node->getShares()
195
+                );
196
+            });
197
+
198
+        }
199
+    }
200 200
 
201 201
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -99,11 +99,11 @@  discard block
 block discarded – undo
99 99
 	 */
100 100
 	function initialize(Server $server) {
101 101
 		$this->server = $server;
102
-		$this->server->xml->elementMap['{' . Plugin::NS_OWNCLOUD . '}share'] = 'OCA\\DAV\\DAV\\Sharing\\Xml\\ShareRequest';
103
-		$this->server->xml->elementMap['{' . Plugin::NS_OWNCLOUD . '}invite'] = 'OCA\\DAV\\DAV\\Sharing\\Xml\\Invite';
102
+		$this->server->xml->elementMap['{'.Plugin::NS_OWNCLOUD.'}share'] = 'OCA\\DAV\\DAV\\Sharing\\Xml\\ShareRequest';
103
+		$this->server->xml->elementMap['{'.Plugin::NS_OWNCLOUD.'}invite'] = 'OCA\\DAV\\DAV\\Sharing\\Xml\\Invite';
104 104
 
105 105
 		$this->server->on('method:POST', [$this, 'httpPost']);
106
-		$this->server->on('propFind',    [$this, 'propFind']);
106
+		$this->server->on('propFind', [$this, 'propFind']);
107 107
 	}
108 108
 
109 109
 	/**
@@ -146,7 +146,7 @@  discard block
 block discarded – undo
146 146
 
147 147
 			// Dealing with the 'share' document, which modified invitees on a
148 148
 			// calendar.
149
-			case '{' . self::NS_OWNCLOUD . '}share' :
149
+			case '{'.self::NS_OWNCLOUD.'}share' :
150 150
 
151 151
 				// We can only deal with IShareableCalendar objects
152 152
 				if (!$node instanceof IShareable) {
@@ -189,7 +189,7 @@  discard block
 block discarded – undo
189 189
 	function propFind(PropFind $propFind, INode $node) {
190 190
 		if ($node instanceof IShareable) {
191 191
 
192
-			$propFind->handle('{' . Plugin::NS_OWNCLOUD . '}invite', function() use ($node) {
192
+			$propFind->handle('{'.Plugin::NS_OWNCLOUD.'}invite', function() use ($node) {
193 193
 				return new Invite(
194 194
 					$node->getShares()
195 195
 				);
Please login to merge, or discard this patch.
Braces   +3 added lines, -2 removed lines patch added patch discarded remove patch
@@ -119,8 +119,9 @@
 block discarded – undo
119 119
 
120 120
 		// Only handling xml
121 121
 		$contentType = $request->getHeader('Content-Type');
122
-		if (strpos($contentType, 'application/xml') === false && strpos($contentType, 'text/xml') === false)
123
-			return;
122
+		if (strpos($contentType, 'application/xml') === false && strpos($contentType, 'text/xml') === false) {
123
+					return;
124
+		}
124 125
 
125 126
 		// Making sure the node exists
126 127
 		try {
Please login to merge, or discard this patch.
apps/dav/lib/DAV/SystemPrincipalBackend.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -132,7 +132,7 @@
 block discarded – undo
132 132
 	 * Returns the list of members for a group-principal
133 133
 	 *
134 134
 	 * @param string $principal
135
-	 * @return array
135
+	 * @return string[]
136 136
 	 */
137 137
 	function getGroupMemberSet($principal) {
138 138
 		// TODO: for now the group principal has only one member, the user itself
Please login to merge, or discard this patch.
Indentation   +161 added lines, -161 removed lines patch added patch discarded remove patch
@@ -27,165 +27,165 @@
 block discarded – undo
27 27
 
28 28
 class SystemPrincipalBackend extends AbstractBackend {
29 29
 
30
-	/**
31
-	 * Returns a list of principals based on a prefix.
32
-	 *
33
-	 * This prefix will often contain something like 'principals'. You are only
34
-	 * expected to return principals that are in this base path.
35
-	 *
36
-	 * You are expected to return at least a 'uri' for every user, you can
37
-	 * return any additional properties if you wish so. Common properties are:
38
-	 *   {DAV:}displayname
39
-	 *   {http://sabredav.org/ns}email-address - This is a custom SabreDAV
40
-	 *     field that's actually injected in a number of other properties. If
41
-	 *     you have an email address, use this property.
42
-	 *
43
-	 * @param string $prefixPath
44
-	 * @return array
45
-	 */
46
-	function getPrincipalsByPrefix($prefixPath) {
47
-		$principals = [];
48
-
49
-		if ($prefixPath === 'principals/system') {
50
-			$principals[] = [
51
-				'uri' => 'principals/system/system',
52
-				'{DAV:}displayname' => 'system',
53
-			];
54
-			$principals[] = [
55
-				'uri' => 'principals/system/public',
56
-				'{DAV:}displayname' => 'public',
57
-			];
58
-		}
59
-
60
-		return $principals;
61
-	}
62
-
63
-	/**
64
-	 * Returns a specific principal, specified by it's path.
65
-	 * The returned structure should be the exact same as from
66
-	 * getPrincipalsByPrefix.
67
-	 *
68
-	 * @param string $path
69
-	 * @return array
70
-	 */
71
-	function getPrincipalByPath($path) {
72
-
73
-		if ($path === 'principals/system/system') {
74
-			$principal = [
75
-				'uri' => 'principals/system/system',
76
-				'{DAV:}displayname' => 'system',
77
-			];
78
-			return $principal;
79
-		}
80
-		if ($path === 'principals/system/public') {
81
-			$principal = [
82
-				'uri' => 'principals/system/public',
83
-				'{DAV:}displayname' => 'public',
84
-			];
85
-			return $principal;
86
-		}
87
-
88
-		return null;
89
-	}
90
-
91
-	/**
92
-	 * Updates one ore more webdav properties on a principal.
93
-	 *
94
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
95
-	 * To do the actual updates, you must tell this object which properties
96
-	 * you're going to process with the handle() method.
97
-	 *
98
-	 * Calling the handle method is like telling the PropPatch object "I
99
-	 * promise I can handle updating this property".
100
-	 *
101
-	 * Read the PropPatch documentation for more info and examples.
102
-	 *
103
-	 * @param string $path
104
-	 * @param \Sabre\DAV\PropPatch $propPatch
105
-	 * @return void
106
-	 */
107
-	function updatePrincipal($path, \Sabre\DAV\PropPatch $propPatch) {
108
-	}
109
-
110
-	/**
111
-	 * This method is used to search for principals matching a set of
112
-	 * properties.
113
-	 *
114
-	 * This search is specifically used by RFC3744's principal-property-search
115
-	 * REPORT.
116
-	 *
117
-	 * The actual search should be a unicode-non-case-sensitive search. The
118
-	 * keys in searchProperties are the WebDAV property names, while the values
119
-	 * are the property values to search on.
120
-	 *
121
-	 * By default, if multiple properties are submitted to this method, the
122
-	 * various properties should be combined with 'AND'. If $test is set to
123
-	 * 'anyof', it should be combined using 'OR'.
124
-	 *
125
-	 * This method should simply return an array with full principal uri's.
126
-	 *
127
-	 * If somebody attempted to search on a property the backend does not
128
-	 * support, you should simply return 0 results.
129
-	 *
130
-	 * You can also just return 0 results if you choose to not support
131
-	 * searching at all, but keep in mind that this may stop certain features
132
-	 * from working.
133
-	 *
134
-	 * @param string $prefixPath
135
-	 * @param array $searchProperties
136
-	 * @param string $test
137
-	 * @return array
138
-	 */
139
-	function searchPrincipals($prefixPath, array $searchProperties, $test = 'allof') {
140
-		return [];
141
-	}
142
-
143
-	/**
144
-	 * Returns the list of members for a group-principal
145
-	 *
146
-	 * @param string $principal
147
-	 * @return array
148
-	 */
149
-	function getGroupMemberSet($principal) {
150
-		// TODO: for now the group principal has only one member, the user itself
151
-		$principal = $this->getPrincipalByPath($principal);
152
-		if (!$principal) {
153
-			throw new \Sabre\DAV\Exception('Principal not found');
154
-		}
155
-
156
-		return [$principal['uri']];
157
-	}
158
-
159
-	/**
160
-	 * Returns the list of groups a principal is a member of
161
-	 *
162
-	 * @param string $principal
163
-	 * @return array
164
-	 */
165
-	function getGroupMembership($principal) {
166
-		list($prefix, $name) = URLUtil::splitPath($principal);
167
-
168
-		if ($prefix === 'principals/system') {
169
-			$principal = $this->getPrincipalByPath($principal);
170
-			if (!$principal) {
171
-				throw new \Sabre\DAV\Exception('Principal not found');
172
-			}
173
-
174
-			return [];
175
-		}
176
-		return [];
177
-	}
178
-
179
-	/**
180
-	 * Updates the list of group members for a group principal.
181
-	 *
182
-	 * The principals should be passed as a list of uri's.
183
-	 *
184
-	 * @param string $principal
185
-	 * @param array $members
186
-	 * @return void
187
-	 */
188
-	function setGroupMemberSet($principal, array $members) {
189
-		throw new \Sabre\DAV\Exception('Setting members of the group is not supported yet');
190
-	}
30
+    /**
31
+     * Returns a list of principals based on a prefix.
32
+     *
33
+     * This prefix will often contain something like 'principals'. You are only
34
+     * expected to return principals that are in this base path.
35
+     *
36
+     * You are expected to return at least a 'uri' for every user, you can
37
+     * return any additional properties if you wish so. Common properties are:
38
+     *   {DAV:}displayname
39
+     *   {http://sabredav.org/ns}email-address - This is a custom SabreDAV
40
+     *     field that's actually injected in a number of other properties. If
41
+     *     you have an email address, use this property.
42
+     *
43
+     * @param string $prefixPath
44
+     * @return array
45
+     */
46
+    function getPrincipalsByPrefix($prefixPath) {
47
+        $principals = [];
48
+
49
+        if ($prefixPath === 'principals/system') {
50
+            $principals[] = [
51
+                'uri' => 'principals/system/system',
52
+                '{DAV:}displayname' => 'system',
53
+            ];
54
+            $principals[] = [
55
+                'uri' => 'principals/system/public',
56
+                '{DAV:}displayname' => 'public',
57
+            ];
58
+        }
59
+
60
+        return $principals;
61
+    }
62
+
63
+    /**
64
+     * Returns a specific principal, specified by it's path.
65
+     * The returned structure should be the exact same as from
66
+     * getPrincipalsByPrefix.
67
+     *
68
+     * @param string $path
69
+     * @return array
70
+     */
71
+    function getPrincipalByPath($path) {
72
+
73
+        if ($path === 'principals/system/system') {
74
+            $principal = [
75
+                'uri' => 'principals/system/system',
76
+                '{DAV:}displayname' => 'system',
77
+            ];
78
+            return $principal;
79
+        }
80
+        if ($path === 'principals/system/public') {
81
+            $principal = [
82
+                'uri' => 'principals/system/public',
83
+                '{DAV:}displayname' => 'public',
84
+            ];
85
+            return $principal;
86
+        }
87
+
88
+        return null;
89
+    }
90
+
91
+    /**
92
+     * Updates one ore more webdav properties on a principal.
93
+     *
94
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
95
+     * To do the actual updates, you must tell this object which properties
96
+     * you're going to process with the handle() method.
97
+     *
98
+     * Calling the handle method is like telling the PropPatch object "I
99
+     * promise I can handle updating this property".
100
+     *
101
+     * Read the PropPatch documentation for more info and examples.
102
+     *
103
+     * @param string $path
104
+     * @param \Sabre\DAV\PropPatch $propPatch
105
+     * @return void
106
+     */
107
+    function updatePrincipal($path, \Sabre\DAV\PropPatch $propPatch) {
108
+    }
109
+
110
+    /**
111
+     * This method is used to search for principals matching a set of
112
+     * properties.
113
+     *
114
+     * This search is specifically used by RFC3744's principal-property-search
115
+     * REPORT.
116
+     *
117
+     * The actual search should be a unicode-non-case-sensitive search. The
118
+     * keys in searchProperties are the WebDAV property names, while the values
119
+     * are the property values to search on.
120
+     *
121
+     * By default, if multiple properties are submitted to this method, the
122
+     * various properties should be combined with 'AND'. If $test is set to
123
+     * 'anyof', it should be combined using 'OR'.
124
+     *
125
+     * This method should simply return an array with full principal uri's.
126
+     *
127
+     * If somebody attempted to search on a property the backend does not
128
+     * support, you should simply return 0 results.
129
+     *
130
+     * You can also just return 0 results if you choose to not support
131
+     * searching at all, but keep in mind that this may stop certain features
132
+     * from working.
133
+     *
134
+     * @param string $prefixPath
135
+     * @param array $searchProperties
136
+     * @param string $test
137
+     * @return array
138
+     */
139
+    function searchPrincipals($prefixPath, array $searchProperties, $test = 'allof') {
140
+        return [];
141
+    }
142
+
143
+    /**
144
+     * Returns the list of members for a group-principal
145
+     *
146
+     * @param string $principal
147
+     * @return array
148
+     */
149
+    function getGroupMemberSet($principal) {
150
+        // TODO: for now the group principal has only one member, the user itself
151
+        $principal = $this->getPrincipalByPath($principal);
152
+        if (!$principal) {
153
+            throw new \Sabre\DAV\Exception('Principal not found');
154
+        }
155
+
156
+        return [$principal['uri']];
157
+    }
158
+
159
+    /**
160
+     * Returns the list of groups a principal is a member of
161
+     *
162
+     * @param string $principal
163
+     * @return array
164
+     */
165
+    function getGroupMembership($principal) {
166
+        list($prefix, $name) = URLUtil::splitPath($principal);
167
+
168
+        if ($prefix === 'principals/system') {
169
+            $principal = $this->getPrincipalByPath($principal);
170
+            if (!$principal) {
171
+                throw new \Sabre\DAV\Exception('Principal not found');
172
+            }
173
+
174
+            return [];
175
+        }
176
+        return [];
177
+    }
178
+
179
+    /**
180
+     * Updates the list of group members for a group principal.
181
+     *
182
+     * The principals should be passed as a list of uri's.
183
+     *
184
+     * @param string $principal
185
+     * @param array $members
186
+     * @return void
187
+     */
188
+    function setGroupMemberSet($principal, array $members) {
189
+        throw new \Sabre\DAV\Exception('Setting members of the group is not supported yet');
190
+    }
191 191
 }
Please login to merge, or discard this patch.
apps/dav/lib/SystemTag/SystemTagPlugin.php 3 patches
Unused Use Statements   -2 removed lines patch added patch discarded remove patch
@@ -29,9 +29,7 @@
 block discarded – undo
29 29
 use Sabre\DAV\Exception\BadRequest;
30 30
 use Sabre\DAV\Exception\Conflict;
31 31
 use Sabre\DAV\Exception\Forbidden;
32
-use Sabre\DAV\Exception\NotFound;
33 32
 use Sabre\DAV\Exception\UnsupportedMediaType;
34
-
35 33
 use OCP\SystemTag\ISystemTag;
36 34
 use OCP\SystemTag\ISystemTagManager;
37 35
 use OCP\SystemTag\TagAlreadyExistsException;
Please login to merge, or discard this patch.
Indentation   +276 added lines, -276 removed lines patch added patch discarded remove patch
@@ -49,280 +49,280 @@
 block discarded – undo
49 49
  */
50 50
 class SystemTagPlugin extends \Sabre\DAV\ServerPlugin {
51 51
 
52
-	// namespace
53
-	const NS_OWNCLOUD = 'http://owncloud.org/ns';
54
-	const ID_PROPERTYNAME = '{http://owncloud.org/ns}id';
55
-	const DISPLAYNAME_PROPERTYNAME = '{http://owncloud.org/ns}display-name';
56
-	const USERVISIBLE_PROPERTYNAME = '{http://owncloud.org/ns}user-visible';
57
-	const USERASSIGNABLE_PROPERTYNAME = '{http://owncloud.org/ns}user-assignable';
58
-	const GROUPS_PROPERTYNAME = '{http://owncloud.org/ns}groups';
59
-	const CANASSIGN_PROPERTYNAME = '{http://owncloud.org/ns}can-assign';
60
-
61
-	/**
62
-	 * @var \Sabre\DAV\Server $server
63
-	 */
64
-	private $server;
65
-
66
-	/**
67
-	 * @var ISystemTagManager
68
-	 */
69
-	protected $tagManager;
70
-
71
-	/**
72
-	 * @var IUserSession
73
-	 */
74
-	protected $userSession;
75
-
76
-	/**
77
-	 * @var IGroupManager
78
-	 */
79
-	protected $groupManager;
80
-
81
-	/**
82
-	 * @param ISystemTagManager $tagManager tag manager
83
-	 * @param IGroupManager $groupManager
84
-	 * @param IUserSession $userSession
85
-	 */
86
-	public function __construct(ISystemTagManager $tagManager,
87
-								IGroupManager $groupManager,
88
-								IUserSession $userSession) {
89
-		$this->tagManager = $tagManager;
90
-		$this->userSession = $userSession;
91
-		$this->groupManager = $groupManager;
92
-	}
93
-
94
-	/**
95
-	 * This initializes the plugin.
96
-	 *
97
-	 * This function is called by \Sabre\DAV\Server, after
98
-	 * addPlugin is called.
99
-	 *
100
-	 * This method should set up the required event subscriptions.
101
-	 *
102
-	 * @param \Sabre\DAV\Server $server
103
-	 * @return void
104
-	 */
105
-	public function initialize(\Sabre\DAV\Server $server) {
106
-
107
-		$server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc';
108
-
109
-		$server->protectedProperties[] = self::ID_PROPERTYNAME;
110
-
111
-		$server->on('propFind', array($this, 'handleGetProperties'));
112
-		$server->on('propPatch', array($this, 'handleUpdateProperties'));
113
-		$server->on('method:POST', [$this, 'httpPost']);
114
-
115
-		$this->server = $server;
116
-	}
117
-
118
-	/**
119
-	 * POST operation on system tag collections
120
-	 *
121
-	 * @param RequestInterface $request request object
122
-	 * @param ResponseInterface $response response object
123
-	 * @return null|false
124
-	 */
125
-	public function httpPost(RequestInterface $request, ResponseInterface $response) {
126
-		$path = $request->getPath();
127
-
128
-		// Making sure the node exists
129
-		$node = $this->server->tree->getNodeForPath($path);
130
-		if ($node instanceof SystemTagsByIdCollection || $node instanceof SystemTagsObjectMappingCollection) {
131
-			$data = $request->getBodyAsString();
132
-
133
-			$tag = $this->createTag($data, $request->getHeader('Content-Type'));
134
-
135
-			if ($node instanceof SystemTagsObjectMappingCollection) {
136
-				// also add to collection
137
-				$node->createFile($tag->getId());
138
-				$url = $request->getBaseUrl() . 'systemtags/';
139
-			} else {
140
-				$url = $request->getUrl();
141
-			}
142
-
143
-			if ($url[strlen($url) - 1] !== '/') {
144
-				$url .= '/';
145
-			}
146
-
147
-			$response->setHeader('Content-Location', $url . $tag->getId());
148
-
149
-			// created
150
-			$response->setStatus(201);
151
-			return false;
152
-		}
153
-	}
154
-
155
-	/**
156
-	 * Creates a new tag
157
-	 *
158
-	 * @param string $data JSON encoded string containing the properties of the tag to create
159
-	 * @param string $contentType content type of the data
160
-	 * @return ISystemTag newly created system tag
161
-	 *
162
-	 * @throws BadRequest if a field was missing
163
-	 * @throws Conflict if a tag with the same properties already exists
164
-	 * @throws UnsupportedMediaType if the content type is not supported
165
-	 */
166
-	private function createTag($data, $contentType = 'application/json') {
167
-		if (explode(';', $contentType)[0] === 'application/json') {
168
-			$data = json_decode($data, true);
169
-		} else {
170
-			throw new UnsupportedMediaType();
171
-		}
172
-
173
-		if (!isset($data['name'])) {
174
-			throw new BadRequest('Missing "name" attribute');
175
-		}
176
-
177
-		$tagName = $data['name'];
178
-		$userVisible = true;
179
-		$userAssignable = true;
180
-
181
-		if (isset($data['userVisible'])) {
182
-			$userVisible = (bool)$data['userVisible'];
183
-		}
184
-
185
-		if (isset($data['userAssignable'])) {
186
-			$userAssignable = (bool)$data['userAssignable'];
187
-		}
188
-
189
-		$groups = [];
190
-		if (isset($data['groups'])) {
191
-			$groups = $data['groups'];
192
-			if (is_string($groups)) {
193
-				$groups = explode('|', $groups);
194
-			}
195
-		}
196
-
197
-		if($userVisible === false || $userAssignable === false || !empty($groups)) {
198
-			if(!$this->userSession->isLoggedIn() || !$this->groupManager->isAdmin($this->userSession->getUser()->getUID())) {
199
-				throw new BadRequest('Not sufficient permissions');
200
-			}
201
-		}
202
-
203
-		try {
204
-			$tag = $this->tagManager->createTag($tagName, $userVisible, $userAssignable);
205
-			if (!empty($groups)) {
206
-				$this->tagManager->setTagGroups($tag, $groups);
207
-			}
208
-			return $tag;
209
-		} catch (TagAlreadyExistsException $e) {
210
-			throw new Conflict('Tag already exists', 0, $e);
211
-		}
212
-	}
213
-
214
-
215
-	/**
216
-	 * Retrieves system tag properties
217
-	 *
218
-	 * @param PropFind $propFind
219
-	 * @param \Sabre\DAV\INode $node
220
-	 */
221
-	public function handleGetProperties(
222
-		PropFind $propFind,
223
-		\Sabre\DAV\INode $node
224
-	) {
225
-		if (!($node instanceof SystemTagNode) && !($node instanceof SystemTagMappingNode)) {
226
-			return;
227
-		}
228
-
229
-		$propFind->handle(self::ID_PROPERTYNAME, function() use ($node) {
230
-			return $node->getSystemTag()->getId();
231
-		});
232
-
233
-		$propFind->handle(self::DISPLAYNAME_PROPERTYNAME, function() use ($node) {
234
-			return $node->getSystemTag()->getName();
235
-		});
236
-
237
-		$propFind->handle(self::USERVISIBLE_PROPERTYNAME, function() use ($node) {
238
-			return $node->getSystemTag()->isUserVisible() ? 'true' : 'false';
239
-		});
240
-
241
-		$propFind->handle(self::USERASSIGNABLE_PROPERTYNAME, function() use ($node) {
242
-			// this is the tag's inherent property "is user assignable"
243
-			return $node->getSystemTag()->isUserAssignable() ? 'true' : 'false';
244
-		});
245
-
246
-		$propFind->handle(self::CANASSIGN_PROPERTYNAME, function() use ($node) {
247
-			// this is the effective permission for the current user
248
-			return $this->tagManager->canUserAssignTag($node->getSystemTag(), $this->userSession->getUser()) ? 'true' : 'false';
249
-		});
250
-
251
-		$propFind->handle(self::GROUPS_PROPERTYNAME, function() use ($node) {
252
-			if (!$this->groupManager->isAdmin($this->userSession->getUser()->getUID())) {
253
-				// property only available for admins
254
-				throw new Forbidden();
255
-			}
256
-			$groups = [];
257
-			// no need to retrieve groups for namespaces that don't qualify
258
-			if ($node->getSystemTag()->isUserVisible() && !$node->getSystemTag()->isUserAssignable()) {
259
-				$groups = $this->tagManager->getTagGroups($node->getSystemTag());
260
-			}
261
-			return implode('|', $groups);
262
-		});
263
-	}
264
-
265
-	/**
266
-	 * Updates tag attributes
267
-	 *
268
-	 * @param string $path
269
-	 * @param PropPatch $propPatch
270
-	 *
271
-	 * @return void
272
-	 */
273
-	public function handleUpdateProperties($path, PropPatch $propPatch) {
274
-		$propPatch->handle([
275
-			self::DISPLAYNAME_PROPERTYNAME,
276
-			self::USERVISIBLE_PROPERTYNAME,
277
-			self::USERASSIGNABLE_PROPERTYNAME,
278
-			self::GROUPS_PROPERTYNAME,
279
-		], function($props) use ($path) {
280
-			$node = $this->server->tree->getNodeForPath($path);
281
-			if (!($node instanceof SystemTagNode)) {
282
-				return;
283
-			}
284
-
285
-			$tag = $node->getSystemTag();
286
-			$name = $tag->getName();
287
-			$userVisible = $tag->isUserVisible();
288
-			$userAssignable = $tag->isUserAssignable();
289
-
290
-			$updateTag = false;
291
-
292
-			if (isset($props[self::DISPLAYNAME_PROPERTYNAME])) {
293
-				$name = $props[self::DISPLAYNAME_PROPERTYNAME];
294
-				$updateTag = true;
295
-			}
296
-
297
-			if (isset($props[self::USERVISIBLE_PROPERTYNAME])) {
298
-				$propValue = $props[self::USERVISIBLE_PROPERTYNAME];
299
-				$userVisible = ($propValue !== 'false' && $propValue !== '0');
300
-				$updateTag = true;
301
-			}
302
-
303
-			if (isset($props[self::USERASSIGNABLE_PROPERTYNAME])) {
304
-				$propValue = $props[self::USERASSIGNABLE_PROPERTYNAME];
305
-				$userAssignable = ($propValue !== 'false' && $propValue !== '0');
306
-				$updateTag = true;
307
-			}
308
-
309
-			if (isset($props[self::GROUPS_PROPERTYNAME])) {
310
-				if (!$this->groupManager->isAdmin($this->userSession->getUser()->getUID())) {
311
-					// property only available for admins
312
-					throw new Forbidden();
313
-				}
314
-
315
-				$propValue = $props[self::GROUPS_PROPERTYNAME];
316
-				$groupIds = explode('|', $propValue);
317
-				$this->tagManager->setTagGroups($tag, $groupIds);
318
-			}
319
-
320
-			if ($updateTag) {
321
-				$node->update($name, $userVisible, $userAssignable);
322
-			}
323
-
324
-			return true;
325
-		});
326
-
327
-	}
52
+    // namespace
53
+    const NS_OWNCLOUD = 'http://owncloud.org/ns';
54
+    const ID_PROPERTYNAME = '{http://owncloud.org/ns}id';
55
+    const DISPLAYNAME_PROPERTYNAME = '{http://owncloud.org/ns}display-name';
56
+    const USERVISIBLE_PROPERTYNAME = '{http://owncloud.org/ns}user-visible';
57
+    const USERASSIGNABLE_PROPERTYNAME = '{http://owncloud.org/ns}user-assignable';
58
+    const GROUPS_PROPERTYNAME = '{http://owncloud.org/ns}groups';
59
+    const CANASSIGN_PROPERTYNAME = '{http://owncloud.org/ns}can-assign';
60
+
61
+    /**
62
+     * @var \Sabre\DAV\Server $server
63
+     */
64
+    private $server;
65
+
66
+    /**
67
+     * @var ISystemTagManager
68
+     */
69
+    protected $tagManager;
70
+
71
+    /**
72
+     * @var IUserSession
73
+     */
74
+    protected $userSession;
75
+
76
+    /**
77
+     * @var IGroupManager
78
+     */
79
+    protected $groupManager;
80
+
81
+    /**
82
+     * @param ISystemTagManager $tagManager tag manager
83
+     * @param IGroupManager $groupManager
84
+     * @param IUserSession $userSession
85
+     */
86
+    public function __construct(ISystemTagManager $tagManager,
87
+                                IGroupManager $groupManager,
88
+                                IUserSession $userSession) {
89
+        $this->tagManager = $tagManager;
90
+        $this->userSession = $userSession;
91
+        $this->groupManager = $groupManager;
92
+    }
93
+
94
+    /**
95
+     * This initializes the plugin.
96
+     *
97
+     * This function is called by \Sabre\DAV\Server, after
98
+     * addPlugin is called.
99
+     *
100
+     * This method should set up the required event subscriptions.
101
+     *
102
+     * @param \Sabre\DAV\Server $server
103
+     * @return void
104
+     */
105
+    public function initialize(\Sabre\DAV\Server $server) {
106
+
107
+        $server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc';
108
+
109
+        $server->protectedProperties[] = self::ID_PROPERTYNAME;
110
+
111
+        $server->on('propFind', array($this, 'handleGetProperties'));
112
+        $server->on('propPatch', array($this, 'handleUpdateProperties'));
113
+        $server->on('method:POST', [$this, 'httpPost']);
114
+
115
+        $this->server = $server;
116
+    }
117
+
118
+    /**
119
+     * POST operation on system tag collections
120
+     *
121
+     * @param RequestInterface $request request object
122
+     * @param ResponseInterface $response response object
123
+     * @return null|false
124
+     */
125
+    public function httpPost(RequestInterface $request, ResponseInterface $response) {
126
+        $path = $request->getPath();
127
+
128
+        // Making sure the node exists
129
+        $node = $this->server->tree->getNodeForPath($path);
130
+        if ($node instanceof SystemTagsByIdCollection || $node instanceof SystemTagsObjectMappingCollection) {
131
+            $data = $request->getBodyAsString();
132
+
133
+            $tag = $this->createTag($data, $request->getHeader('Content-Type'));
134
+
135
+            if ($node instanceof SystemTagsObjectMappingCollection) {
136
+                // also add to collection
137
+                $node->createFile($tag->getId());
138
+                $url = $request->getBaseUrl() . 'systemtags/';
139
+            } else {
140
+                $url = $request->getUrl();
141
+            }
142
+
143
+            if ($url[strlen($url) - 1] !== '/') {
144
+                $url .= '/';
145
+            }
146
+
147
+            $response->setHeader('Content-Location', $url . $tag->getId());
148
+
149
+            // created
150
+            $response->setStatus(201);
151
+            return false;
152
+        }
153
+    }
154
+
155
+    /**
156
+     * Creates a new tag
157
+     *
158
+     * @param string $data JSON encoded string containing the properties of the tag to create
159
+     * @param string $contentType content type of the data
160
+     * @return ISystemTag newly created system tag
161
+     *
162
+     * @throws BadRequest if a field was missing
163
+     * @throws Conflict if a tag with the same properties already exists
164
+     * @throws UnsupportedMediaType if the content type is not supported
165
+     */
166
+    private function createTag($data, $contentType = 'application/json') {
167
+        if (explode(';', $contentType)[0] === 'application/json') {
168
+            $data = json_decode($data, true);
169
+        } else {
170
+            throw new UnsupportedMediaType();
171
+        }
172
+
173
+        if (!isset($data['name'])) {
174
+            throw new BadRequest('Missing "name" attribute');
175
+        }
176
+
177
+        $tagName = $data['name'];
178
+        $userVisible = true;
179
+        $userAssignable = true;
180
+
181
+        if (isset($data['userVisible'])) {
182
+            $userVisible = (bool)$data['userVisible'];
183
+        }
184
+
185
+        if (isset($data['userAssignable'])) {
186
+            $userAssignable = (bool)$data['userAssignable'];
187
+        }
188
+
189
+        $groups = [];
190
+        if (isset($data['groups'])) {
191
+            $groups = $data['groups'];
192
+            if (is_string($groups)) {
193
+                $groups = explode('|', $groups);
194
+            }
195
+        }
196
+
197
+        if($userVisible === false || $userAssignable === false || !empty($groups)) {
198
+            if(!$this->userSession->isLoggedIn() || !$this->groupManager->isAdmin($this->userSession->getUser()->getUID())) {
199
+                throw new BadRequest('Not sufficient permissions');
200
+            }
201
+        }
202
+
203
+        try {
204
+            $tag = $this->tagManager->createTag($tagName, $userVisible, $userAssignable);
205
+            if (!empty($groups)) {
206
+                $this->tagManager->setTagGroups($tag, $groups);
207
+            }
208
+            return $tag;
209
+        } catch (TagAlreadyExistsException $e) {
210
+            throw new Conflict('Tag already exists', 0, $e);
211
+        }
212
+    }
213
+
214
+
215
+    /**
216
+     * Retrieves system tag properties
217
+     *
218
+     * @param PropFind $propFind
219
+     * @param \Sabre\DAV\INode $node
220
+     */
221
+    public function handleGetProperties(
222
+        PropFind $propFind,
223
+        \Sabre\DAV\INode $node
224
+    ) {
225
+        if (!($node instanceof SystemTagNode) && !($node instanceof SystemTagMappingNode)) {
226
+            return;
227
+        }
228
+
229
+        $propFind->handle(self::ID_PROPERTYNAME, function() use ($node) {
230
+            return $node->getSystemTag()->getId();
231
+        });
232
+
233
+        $propFind->handle(self::DISPLAYNAME_PROPERTYNAME, function() use ($node) {
234
+            return $node->getSystemTag()->getName();
235
+        });
236
+
237
+        $propFind->handle(self::USERVISIBLE_PROPERTYNAME, function() use ($node) {
238
+            return $node->getSystemTag()->isUserVisible() ? 'true' : 'false';
239
+        });
240
+
241
+        $propFind->handle(self::USERASSIGNABLE_PROPERTYNAME, function() use ($node) {
242
+            // this is the tag's inherent property "is user assignable"
243
+            return $node->getSystemTag()->isUserAssignable() ? 'true' : 'false';
244
+        });
245
+
246
+        $propFind->handle(self::CANASSIGN_PROPERTYNAME, function() use ($node) {
247
+            // this is the effective permission for the current user
248
+            return $this->tagManager->canUserAssignTag($node->getSystemTag(), $this->userSession->getUser()) ? 'true' : 'false';
249
+        });
250
+
251
+        $propFind->handle(self::GROUPS_PROPERTYNAME, function() use ($node) {
252
+            if (!$this->groupManager->isAdmin($this->userSession->getUser()->getUID())) {
253
+                // property only available for admins
254
+                throw new Forbidden();
255
+            }
256
+            $groups = [];
257
+            // no need to retrieve groups for namespaces that don't qualify
258
+            if ($node->getSystemTag()->isUserVisible() && !$node->getSystemTag()->isUserAssignable()) {
259
+                $groups = $this->tagManager->getTagGroups($node->getSystemTag());
260
+            }
261
+            return implode('|', $groups);
262
+        });
263
+    }
264
+
265
+    /**
266
+     * Updates tag attributes
267
+     *
268
+     * @param string $path
269
+     * @param PropPatch $propPatch
270
+     *
271
+     * @return void
272
+     */
273
+    public function handleUpdateProperties($path, PropPatch $propPatch) {
274
+        $propPatch->handle([
275
+            self::DISPLAYNAME_PROPERTYNAME,
276
+            self::USERVISIBLE_PROPERTYNAME,
277
+            self::USERASSIGNABLE_PROPERTYNAME,
278
+            self::GROUPS_PROPERTYNAME,
279
+        ], function($props) use ($path) {
280
+            $node = $this->server->tree->getNodeForPath($path);
281
+            if (!($node instanceof SystemTagNode)) {
282
+                return;
283
+            }
284
+
285
+            $tag = $node->getSystemTag();
286
+            $name = $tag->getName();
287
+            $userVisible = $tag->isUserVisible();
288
+            $userAssignable = $tag->isUserAssignable();
289
+
290
+            $updateTag = false;
291
+
292
+            if (isset($props[self::DISPLAYNAME_PROPERTYNAME])) {
293
+                $name = $props[self::DISPLAYNAME_PROPERTYNAME];
294
+                $updateTag = true;
295
+            }
296
+
297
+            if (isset($props[self::USERVISIBLE_PROPERTYNAME])) {
298
+                $propValue = $props[self::USERVISIBLE_PROPERTYNAME];
299
+                $userVisible = ($propValue !== 'false' && $propValue !== '0');
300
+                $updateTag = true;
301
+            }
302
+
303
+            if (isset($props[self::USERASSIGNABLE_PROPERTYNAME])) {
304
+                $propValue = $props[self::USERASSIGNABLE_PROPERTYNAME];
305
+                $userAssignable = ($propValue !== 'false' && $propValue !== '0');
306
+                $updateTag = true;
307
+            }
308
+
309
+            if (isset($props[self::GROUPS_PROPERTYNAME])) {
310
+                if (!$this->groupManager->isAdmin($this->userSession->getUser()->getUID())) {
311
+                    // property only available for admins
312
+                    throw new Forbidden();
313
+                }
314
+
315
+                $propValue = $props[self::GROUPS_PROPERTYNAME];
316
+                $groupIds = explode('|', $propValue);
317
+                $this->tagManager->setTagGroups($tag, $groupIds);
318
+            }
319
+
320
+            if ($updateTag) {
321
+                $node->update($name, $userVisible, $userAssignable);
322
+            }
323
+
324
+            return true;
325
+        });
326
+
327
+    }
328 328
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -135,7 +135,7 @@  discard block
 block discarded – undo
135 135
 			if ($node instanceof SystemTagsObjectMappingCollection) {
136 136
 				// also add to collection
137 137
 				$node->createFile($tag->getId());
138
-				$url = $request->getBaseUrl() . 'systemtags/';
138
+				$url = $request->getBaseUrl().'systemtags/';
139 139
 			} else {
140 140
 				$url = $request->getUrl();
141 141
 			}
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
 				$url .= '/';
145 145
 			}
146 146
 
147
-			$response->setHeader('Content-Location', $url . $tag->getId());
147
+			$response->setHeader('Content-Location', $url.$tag->getId());
148 148
 
149 149
 			// created
150 150
 			$response->setStatus(201);
@@ -179,11 +179,11 @@  discard block
 block discarded – undo
179 179
 		$userAssignable = true;
180 180
 
181 181
 		if (isset($data['userVisible'])) {
182
-			$userVisible = (bool)$data['userVisible'];
182
+			$userVisible = (bool) $data['userVisible'];
183 183
 		}
184 184
 
185 185
 		if (isset($data['userAssignable'])) {
186
-			$userAssignable = (bool)$data['userAssignable'];
186
+			$userAssignable = (bool) $data['userAssignable'];
187 187
 		}
188 188
 
189 189
 		$groups = [];
@@ -194,8 +194,8 @@  discard block
 block discarded – undo
194 194
 			}
195 195
 		}
196 196
 
197
-		if($userVisible === false || $userAssignable === false || !empty($groups)) {
198
-			if(!$this->userSession->isLoggedIn() || !$this->groupManager->isAdmin($this->userSession->getUser()->getUID())) {
197
+		if ($userVisible === false || $userAssignable === false || !empty($groups)) {
198
+			if (!$this->userSession->isLoggedIn() || !$this->groupManager->isAdmin($this->userSession->getUser()->getUID())) {
199 199
 				throw new BadRequest('Not sufficient permissions');
200 200
 			}
201 201
 		}
Please login to merge, or discard this patch.
apps/dav/lib/SystemTag/SystemTagsByIdCollection.php 3 patches
Unused Use Statements   -2 removed lines patch added patch discarded remove patch
@@ -26,13 +26,11 @@
 block discarded – undo
26 26
 use Sabre\DAV\Exception\NotFound;
27 27
 use Sabre\DAV\Exception\BadRequest;
28 28
 use Sabre\DAV\ICollection;
29
-
30 29
 use OCP\SystemTag\ISystemTagManager;
31 30
 use OCP\SystemTag\ISystemTag;
32 31
 use OCP\SystemTag\TagNotFoundException;
33 32
 use OCP\IGroupManager;
34 33
 use OCP\IUserSession;
35
-use OC\User\NoUserException;
36 34
 
37 35
 class SystemTagsByIdCollection implements ICollection {
38 36
 
Please login to merge, or discard this patch.
Indentation   +140 added lines, -140 removed lines patch added patch discarded remove patch
@@ -37,144 +37,144 @@
 block discarded – undo
37 37
 
38 38
 class SystemTagsByIdCollection implements ICollection {
39 39
 
40
-	/**
41
-	 * @var ISystemTagManager
42
-	 */
43
-	private $tagManager;
44
-
45
-	/**
46
-	 * @var IGroupManager
47
-	 */
48
-	private $groupManager;
49
-
50
-	/**
51
-	 * @var IUserSession
52
-	 */
53
-	private $userSession;
54
-
55
-	/**
56
-	 * SystemTagsByIdCollection constructor.
57
-	 *
58
-	 * @param ISystemTagManager $tagManager
59
-	 * @param IUserSession $userSession
60
-	 * @param IGroupManager $groupManager
61
-	 */
62
-	public function __construct(
63
-		ISystemTagManager $tagManager,
64
-		IUserSession $userSession,
65
-		IGroupManager $groupManager
66
-	) {
67
-		$this->tagManager = $tagManager;
68
-		$this->userSession = $userSession;
69
-		$this->groupManager = $groupManager;
70
-	}
71
-
72
-	/**
73
-	 * Returns whether the currently logged in user is an administrator
74
-	 *
75
-	 * @return bool true if the user is an admin
76
-	 */
77
-	private function isAdmin() {
78
-		$user = $this->userSession->getUser();
79
-		if ($user !== null) {
80
-			return $this->groupManager->isAdmin($user->getUID());
81
-		}
82
-		return false;
83
-	}
84
-
85
-	/**
86
-	 * @param string $name
87
-	 * @param resource|string $data Initial payload
88
-	 * @throws Forbidden
89
-	 */
90
-	function createFile($name, $data = null) {
91
-		throw new Forbidden('Cannot create tags by id');
92
-	}
93
-
94
-	/**
95
-	 * @param string $name
96
-	 */
97
-	function createDirectory($name) {
98
-		throw new Forbidden('Permission denied to create collections');
99
-	}
100
-
101
-	/**
102
-	 * @param string $name
103
-	 */
104
-	function getChild($name) {
105
-		try {
106
-			$tag = $this->tagManager->getTagsByIds([$name]);
107
-			$tag = current($tag);
108
-			if (!$this->tagManager->canUserSeeTag($tag, $this->userSession->getUser())) {
109
-				throw new NotFound('Tag with id ' . $name . ' not found');
110
-			}
111
-			return $this->makeNode($tag);
112
-		} catch (\InvalidArgumentException $e) {
113
-			throw new BadRequest('Invalid tag id', 0, $e);
114
-		} catch (TagNotFoundException $e) {
115
-			throw new NotFound('Tag with id ' . $name . ' not found', 0, $e);
116
-		}
117
-	}
118
-
119
-	function getChildren() {
120
-		$visibilityFilter = true;
121
-		if ($this->isAdmin()) {
122
-			$visibilityFilter = null;
123
-		}
124
-
125
-		$tags = $this->tagManager->getAllTags($visibilityFilter);
126
-		return array_map(function($tag) {
127
-			return $this->makeNode($tag);
128
-		}, $tags);
129
-	}
130
-
131
-	/**
132
-	 * @param string $name
133
-	 */
134
-	function childExists($name) {
135
-		try {
136
-			$tag = $this->tagManager->getTagsByIds([$name]);
137
-			$tag = current($tag);
138
-			if (!$this->tagManager->canUserSeeTag($tag, $this->userSession->getUser())) {
139
-				return false;
140
-			}
141
-			return true;
142
-		} catch (\InvalidArgumentException $e) {
143
-			throw new BadRequest('Invalid tag id', 0, $e);
144
-		} catch (TagNotFoundException $e) {
145
-			return false;
146
-		}
147
-	}
148
-
149
-	function delete() {
150
-		throw new Forbidden('Permission denied to delete this collection');
151
-	}
152
-
153
-	function getName() {
154
-		return 'systemtags';
155
-	}
156
-
157
-	function setName($name) {
158
-		throw new Forbidden('Permission denied to rename this collection');
159
-	}
160
-
161
-	/**
162
-	 * Returns the last modification time, as a unix timestamp
163
-	 *
164
-	 * @return int
165
-	 */
166
-	function getLastModified() {
167
-		return null;
168
-	}
169
-
170
-	/**
171
-	 * Create a sabre node for the given system tag
172
-	 *
173
-	 * @param ISystemTag $tag
174
-	 *
175
-	 * @return SystemTagNode
176
-	 */
177
-	private function makeNode(ISystemTag $tag) {
178
-		return new SystemTagNode($tag, $this->userSession->getUser(), $this->isAdmin(), $this->tagManager);
179
-	}
40
+    /**
41
+     * @var ISystemTagManager
42
+     */
43
+    private $tagManager;
44
+
45
+    /**
46
+     * @var IGroupManager
47
+     */
48
+    private $groupManager;
49
+
50
+    /**
51
+     * @var IUserSession
52
+     */
53
+    private $userSession;
54
+
55
+    /**
56
+     * SystemTagsByIdCollection constructor.
57
+     *
58
+     * @param ISystemTagManager $tagManager
59
+     * @param IUserSession $userSession
60
+     * @param IGroupManager $groupManager
61
+     */
62
+    public function __construct(
63
+        ISystemTagManager $tagManager,
64
+        IUserSession $userSession,
65
+        IGroupManager $groupManager
66
+    ) {
67
+        $this->tagManager = $tagManager;
68
+        $this->userSession = $userSession;
69
+        $this->groupManager = $groupManager;
70
+    }
71
+
72
+    /**
73
+     * Returns whether the currently logged in user is an administrator
74
+     *
75
+     * @return bool true if the user is an admin
76
+     */
77
+    private function isAdmin() {
78
+        $user = $this->userSession->getUser();
79
+        if ($user !== null) {
80
+            return $this->groupManager->isAdmin($user->getUID());
81
+        }
82
+        return false;
83
+    }
84
+
85
+    /**
86
+     * @param string $name
87
+     * @param resource|string $data Initial payload
88
+     * @throws Forbidden
89
+     */
90
+    function createFile($name, $data = null) {
91
+        throw new Forbidden('Cannot create tags by id');
92
+    }
93
+
94
+    /**
95
+     * @param string $name
96
+     */
97
+    function createDirectory($name) {
98
+        throw new Forbidden('Permission denied to create collections');
99
+    }
100
+
101
+    /**
102
+     * @param string $name
103
+     */
104
+    function getChild($name) {
105
+        try {
106
+            $tag = $this->tagManager->getTagsByIds([$name]);
107
+            $tag = current($tag);
108
+            if (!$this->tagManager->canUserSeeTag($tag, $this->userSession->getUser())) {
109
+                throw new NotFound('Tag with id ' . $name . ' not found');
110
+            }
111
+            return $this->makeNode($tag);
112
+        } catch (\InvalidArgumentException $e) {
113
+            throw new BadRequest('Invalid tag id', 0, $e);
114
+        } catch (TagNotFoundException $e) {
115
+            throw new NotFound('Tag with id ' . $name . ' not found', 0, $e);
116
+        }
117
+    }
118
+
119
+    function getChildren() {
120
+        $visibilityFilter = true;
121
+        if ($this->isAdmin()) {
122
+            $visibilityFilter = null;
123
+        }
124
+
125
+        $tags = $this->tagManager->getAllTags($visibilityFilter);
126
+        return array_map(function($tag) {
127
+            return $this->makeNode($tag);
128
+        }, $tags);
129
+    }
130
+
131
+    /**
132
+     * @param string $name
133
+     */
134
+    function childExists($name) {
135
+        try {
136
+            $tag = $this->tagManager->getTagsByIds([$name]);
137
+            $tag = current($tag);
138
+            if (!$this->tagManager->canUserSeeTag($tag, $this->userSession->getUser())) {
139
+                return false;
140
+            }
141
+            return true;
142
+        } catch (\InvalidArgumentException $e) {
143
+            throw new BadRequest('Invalid tag id', 0, $e);
144
+        } catch (TagNotFoundException $e) {
145
+            return false;
146
+        }
147
+    }
148
+
149
+    function delete() {
150
+        throw new Forbidden('Permission denied to delete this collection');
151
+    }
152
+
153
+    function getName() {
154
+        return 'systemtags';
155
+    }
156
+
157
+    function setName($name) {
158
+        throw new Forbidden('Permission denied to rename this collection');
159
+    }
160
+
161
+    /**
162
+     * Returns the last modification time, as a unix timestamp
163
+     *
164
+     * @return int
165
+     */
166
+    function getLastModified() {
167
+        return null;
168
+    }
169
+
170
+    /**
171
+     * Create a sabre node for the given system tag
172
+     *
173
+     * @param ISystemTag $tag
174
+     *
175
+     * @return SystemTagNode
176
+     */
177
+    private function makeNode(ISystemTag $tag) {
178
+        return new SystemTagNode($tag, $this->userSession->getUser(), $this->isAdmin(), $this->tagManager);
179
+    }
180 180
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -106,13 +106,13 @@
 block discarded – undo
106 106
 			$tag = $this->tagManager->getTagsByIds([$name]);
107 107
 			$tag = current($tag);
108 108
 			if (!$this->tagManager->canUserSeeTag($tag, $this->userSession->getUser())) {
109
-				throw new NotFound('Tag with id ' . $name . ' not found');
109
+				throw new NotFound('Tag with id '.$name.' not found');
110 110
 			}
111 111
 			return $this->makeNode($tag);
112 112
 		} catch (\InvalidArgumentException $e) {
113 113
 			throw new BadRequest('Invalid tag id', 0, $e);
114 114
 		} catch (TagNotFoundException $e) {
115
-			throw new NotFound('Tag with id ' . $name . ' not found', 0, $e);
115
+			throw new NotFound('Tag with id '.$name.' not found', 0, $e);
116 116
 		}
117 117
 	}
118 118
 
Please login to merge, or discard this patch.
apps/dav/lib/SystemTag/SystemTagsObjectMappingCollection.php 4 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -26,7 +26,6 @@
 block discarded – undo
26 26
 use Sabre\DAV\Exception\BadRequest;
27 27
 use Sabre\DAV\Exception\PreconditionFailed;
28 28
 use Sabre\DAV\ICollection;
29
-
30 29
 use OCP\SystemTag\ISystemTagManager;
31 30
 use OCP\SystemTag\ISystemTagObjectMapper;
32 31
 use OCP\SystemTag\ISystemTag;
Please login to merge, or discard this patch.
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.
apps/dav/lib/SystemTag/SystemTagsObjectTypeCollection.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -26,7 +26,6 @@
 block discarded – undo
26 26
 use Sabre\DAV\Exception\MethodNotAllowed;
27 27
 use Sabre\DAV\Exception\NotFound;
28 28
 use Sabre\DAV\ICollection;
29
-
30 29
 use OCP\SystemTag\ISystemTagManager;
31 30
 use OCP\SystemTag\ISystemTagObjectMapper;
32 31
 use OCP\IUserSession;
Please login to merge, or discard this patch.
Indentation   +132 added lines, -132 removed lines patch added patch discarded remove patch
@@ -39,136 +39,136 @@
 block discarded – undo
39 39
  */
40 40
 class SystemTagsObjectTypeCollection implements ICollection {
41 41
 
42
-	/**
43
-	 * @var string
44
-	 */
45
-	private $objectType;
46
-
47
-	/**
48
-	 * @var ISystemTagManager
49
-	 */
50
-	private $tagManager;
51
-
52
-	/**
53
-	 * @var ISystemTagObjectMapper
54
-	 */
55
-	private $tagMapper;
56
-
57
-	/**
58
-	 * @var IGroupManager
59
-	 */
60
-	private $groupManager;
61
-
62
-	/**
63
-	 * @var IUserSession
64
-	 */
65
-	private $userSession;
66
-
67
-	/**
68
-	 * @var \Closure
69
-	 **/
70
-	protected $childExistsFunction;
71
-
72
-	/**
73
-	 * Constructor
74
-	 *
75
-	 * @param string $objectType object type
76
-	 * @param ISystemTagManager $tagManager
77
-	 * @param ISystemTagObjectMapper $tagMapper
78
-	 * @param IUserSession $userSession
79
-	 * @param IGroupManager $groupManager
80
-	 * @param \Closure $childExistsFunction
81
-	 */
82
-	public function __construct(
83
-		$objectType, 
84
-		ISystemTagManager $tagManager,
85
-		ISystemTagObjectMapper $tagMapper,
86
-		IUserSession $userSession,
87
-		IGroupManager $groupManager,
88
-		\Closure $childExistsFunction
89
-	) {
90
-		$this->tagManager = $tagManager;
91
-		$this->tagMapper = $tagMapper;
92
-		$this->objectType = $objectType;
93
-		$this->userSession = $userSession;
94
-		$this->groupManager = $groupManager;
95
-		$this->childExistsFunction = $childExistsFunction;
96
-	}
97
-
98
-	/**
99
-	 * @param string $name
100
-	 * @param resource|string $data Initial payload
101
-	 * @return null|string
102
-	 * @throws Forbidden
103
-	 */
104
-	function createFile($name, $data = null) {
105
-		throw new Forbidden('Permission denied to create nodes');
106
-	}
107
-
108
-	/**
109
-	 * @param string $name
110
-	 * @throws Forbidden
111
-	 */
112
-	function createDirectory($name) {
113
-		throw new Forbidden('Permission denied to create collections');
114
-	}
115
-
116
-	/**
117
-	 * @param string $objectId
118
-	 * @return SystemTagsObjectMappingCollection
119
-	 * @throws NotFound
120
-	 */
121
-	function getChild($objectId) {
122
-		// make sure the object exists and is reachable
123
-		if(!$this->childExists($objectId)) {
124
-			throw new NotFound('Entity does not exist or is not available');
125
-		}
126
-		return new SystemTagsObjectMappingCollection(
127
-			$objectId,
128
-			$this->objectType,
129
-			$this->userSession->getUser(),
130
-			$this->tagManager,
131
-			$this->tagMapper
132
-		);
133
-	}
134
-
135
-	function getChildren() {
136
-		// do not list object ids
137
-		throw new MethodNotAllowed();
138
-	}
139
-
140
-	/**
141
-	 * Checks if a child-node with the specified name exists
142
-	 *
143
-	 * @param string $name
144
-	 * @return bool
145
-	 */
146
-	function childExists($name) {
147
-		return call_user_func($this->childExistsFunction, $name);
148
-	}
149
-
150
-	function delete() {
151
-		throw new Forbidden('Permission denied to delete this collection');
152
-	}
153
-
154
-	function getName() {
155
-		return $this->objectType;
156
-	}
157
-
158
-	/**
159
-	 * @param string $name
160
-	 * @throws Forbidden
161
-	 */
162
-	function setName($name) {
163
-		throw new Forbidden('Permission denied to rename this collection');
164
-	}
165
-
166
-	/**
167
-	 * Returns the last modification time, as a unix timestamp
168
-	 *
169
-	 * @return int
170
-	 */
171
-	function getLastModified() {
172
-		return null;
173
-	}
42
+    /**
43
+     * @var string
44
+     */
45
+    private $objectType;
46
+
47
+    /**
48
+     * @var ISystemTagManager
49
+     */
50
+    private $tagManager;
51
+
52
+    /**
53
+     * @var ISystemTagObjectMapper
54
+     */
55
+    private $tagMapper;
56
+
57
+    /**
58
+     * @var IGroupManager
59
+     */
60
+    private $groupManager;
61
+
62
+    /**
63
+     * @var IUserSession
64
+     */
65
+    private $userSession;
66
+
67
+    /**
68
+     * @var \Closure
69
+     **/
70
+    protected $childExistsFunction;
71
+
72
+    /**
73
+     * Constructor
74
+     *
75
+     * @param string $objectType object type
76
+     * @param ISystemTagManager $tagManager
77
+     * @param ISystemTagObjectMapper $tagMapper
78
+     * @param IUserSession $userSession
79
+     * @param IGroupManager $groupManager
80
+     * @param \Closure $childExistsFunction
81
+     */
82
+    public function __construct(
83
+        $objectType, 
84
+        ISystemTagManager $tagManager,
85
+        ISystemTagObjectMapper $tagMapper,
86
+        IUserSession $userSession,
87
+        IGroupManager $groupManager,
88
+        \Closure $childExistsFunction
89
+    ) {
90
+        $this->tagManager = $tagManager;
91
+        $this->tagMapper = $tagMapper;
92
+        $this->objectType = $objectType;
93
+        $this->userSession = $userSession;
94
+        $this->groupManager = $groupManager;
95
+        $this->childExistsFunction = $childExistsFunction;
96
+    }
97
+
98
+    /**
99
+     * @param string $name
100
+     * @param resource|string $data Initial payload
101
+     * @return null|string
102
+     * @throws Forbidden
103
+     */
104
+    function createFile($name, $data = null) {
105
+        throw new Forbidden('Permission denied to create nodes');
106
+    }
107
+
108
+    /**
109
+     * @param string $name
110
+     * @throws Forbidden
111
+     */
112
+    function createDirectory($name) {
113
+        throw new Forbidden('Permission denied to create collections');
114
+    }
115
+
116
+    /**
117
+     * @param string $objectId
118
+     * @return SystemTagsObjectMappingCollection
119
+     * @throws NotFound
120
+     */
121
+    function getChild($objectId) {
122
+        // make sure the object exists and is reachable
123
+        if(!$this->childExists($objectId)) {
124
+            throw new NotFound('Entity does not exist or is not available');
125
+        }
126
+        return new SystemTagsObjectMappingCollection(
127
+            $objectId,
128
+            $this->objectType,
129
+            $this->userSession->getUser(),
130
+            $this->tagManager,
131
+            $this->tagMapper
132
+        );
133
+    }
134
+
135
+    function getChildren() {
136
+        // do not list object ids
137
+        throw new MethodNotAllowed();
138
+    }
139
+
140
+    /**
141
+     * Checks if a child-node with the specified name exists
142
+     *
143
+     * @param string $name
144
+     * @return bool
145
+     */
146
+    function childExists($name) {
147
+        return call_user_func($this->childExistsFunction, $name);
148
+    }
149
+
150
+    function delete() {
151
+        throw new Forbidden('Permission denied to delete this collection');
152
+    }
153
+
154
+    function getName() {
155
+        return $this->objectType;
156
+    }
157
+
158
+    /**
159
+     * @param string $name
160
+     * @throws Forbidden
161
+     */
162
+    function setName($name) {
163
+        throw new Forbidden('Permission denied to rename this collection');
164
+    }
165
+
166
+    /**
167
+     * Returns the last modification time, as a unix timestamp
168
+     *
169
+     * @return int
170
+     */
171
+    function getLastModified() {
172
+        return null;
173
+    }
174 174
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -120,7 +120,7 @@
 block discarded – undo
120 120
 	 */
121 121
 	function getChild($objectId) {
122 122
 		// make sure the object exists and is reachable
123
-		if(!$this->childExists($objectId)) {
123
+		if (!$this->childExists($objectId)) {
124 124
 			throw new NotFound('Entity does not exist or is not available');
125 125
 		}
126 126
 		return new SystemTagsObjectMappingCollection(
Please login to merge, or discard this patch.
apps/dav/lib/Upload/AssemblyStream.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -118,7 +118,7 @@  discard block
 block discarded – undo
118 118
 
119 119
 	/**
120 120
 	 * @param string $data
121
-	 * @return int
121
+	 * @return boolean
122 122
 	 */
123 123
 	public function stream_write($data) {
124 124
 		return false;
@@ -224,7 +224,7 @@  discard block
 block discarded – undo
224 224
 	}
225 225
 
226 226
 	/**
227
-	 * @param $pos
227
+	 * @param integer $pos
228 228
 	 * @return IFile | null
229 229
 	 */
230 230
 	private function getNodeForPosition($pos) {
Please login to merge, or discard this patch.
Indentation   +238 added lines, -238 removed lines patch added patch discarded remove patch
@@ -35,243 +35,243 @@
 block discarded – undo
35 35
  */
36 36
 class AssemblyStream implements \Icewind\Streams\File {
37 37
 
38
-	/** @var resource */
39
-	private $context;
40
-
41
-	/** @var IFile[] */
42
-	private $nodes;
43
-
44
-	/** @var int */
45
-	private $pos = 0;
46
-
47
-	/** @var array */
48
-	private $sortedNodes;
49
-
50
-	/** @var int */
51
-	private $size;
52
-
53
-	/** @var resource */
54
-	private $currentStream = null;
55
-
56
-	/**
57
-	 * @param string $path
58
-	 * @param string $mode
59
-	 * @param int $options
60
-	 * @param string &$opened_path
61
-	 * @return bool
62
-	 */
63
-	public function stream_open($path, $mode, $options, &$opened_path) {
64
-		$this->loadContext('assembly');
65
-
66
-		// sort the nodes
67
-		$nodes = $this->nodes;
68
-		// http://stackoverflow.com/a/10985500
69
-		@usort($nodes, function(IFile $a, IFile $b) {
70
-			return strcmp($a->getName(), $b->getName());
71
-		});
72
-		$this->nodes = $nodes;
73
-
74
-		// build additional information
75
-		$this->sortedNodes = [];
76
-		$start = 0;
77
-		foreach($this->nodes as $node) {
78
-			$size = $node->getSize();
79
-			$name = $node->getName();
80
-			$this->sortedNodes[$name] = ['node' => $node, 'start' => $start, 'end' => $start + $size];
81
-			$start += $size;
82
-			$this->size = $start;
83
-		}
84
-		return true;
85
-	}
86
-
87
-	/**
88
-	 * @param string $offset
89
-	 * @param int $whence
90
-	 * @return bool
91
-	 */
92
-	public function stream_seek($offset, $whence = SEEK_SET) {
93
-		return false;
94
-	}
95
-
96
-	/**
97
-	 * @return int
98
-	 */
99
-	public function stream_tell() {
100
-		return $this->pos;
101
-	}
102
-
103
-	/**
104
-	 * @param int $count
105
-	 * @return string
106
-	 */
107
-	public function stream_read($count) {
108
-		do {
109
-			if ($this->currentStream === null) {
110
-				list($node, $posInNode) = $this->getNodeForPosition($this->pos);
111
-				if (is_null($node)) {
112
-					// reached last node, no more data
113
-					return '';
114
-				}
115
-				$this->currentStream = $this->getStream($node);
116
-				fseek($this->currentStream, $posInNode);
117
-			}
118
-
119
-			$data = fread($this->currentStream, $count);
120
-			// isset is faster than strlen
121
-			if (isset($data[$count - 1])) {
122
-				// we read the full count
123
-				$read = $count;
124
-			} else {
125
-				// reaching end of stream, which happens less often so strlen is ok
126
-				$read = strlen($data);
127
-			}
128
-
129
-			if (feof($this->currentStream)) {
130
-				fclose($this->currentStream);
131
-				$this->currentNode = null;
132
-				$this->currentStream = null;
133
-			}
134
-			// if no data read, try again with the next node because
135
-			// returning empty data can make the caller think there is no more
136
-			// data left to read
137
-		} while ($read === 0);
138
-
139
-		// update position
140
-		$this->pos += $read;
141
-		return $data;
142
-	}
143
-
144
-	/**
145
-	 * @param string $data
146
-	 * @return int
147
-	 */
148
-	public function stream_write($data) {
149
-		return false;
150
-	}
151
-
152
-	/**
153
-	 * @param int $option
154
-	 * @param int $arg1
155
-	 * @param int $arg2
156
-	 * @return bool
157
-	 */
158
-	public function stream_set_option($option, $arg1, $arg2) {
159
-		return false;
160
-	}
161
-
162
-	/**
163
-	 * @param int $size
164
-	 * @return bool
165
-	 */
166
-	public function stream_truncate($size) {
167
-		return false;
168
-	}
169
-
170
-	/**
171
-	 * @return array
172
-	 */
173
-	public function stream_stat() {
174
-		return [];
175
-	}
176
-
177
-	/**
178
-	 * @param int $operation
179
-	 * @return bool
180
-	 */
181
-	public function stream_lock($operation) {
182
-		return false;
183
-	}
184
-
185
-	/**
186
-	 * @return bool
187
-	 */
188
-	public function stream_flush() {
189
-		return false;
190
-	}
191
-
192
-	/**
193
-	 * @return bool
194
-	 */
195
-	public function stream_eof() {
196
-		return $this->pos >= $this->size;
197
-	}
198
-
199
-	/**
200
-	 * @return bool
201
-	 */
202
-	public function stream_close() {
203
-		return true;
204
-	}
205
-
206
-
207
-	/**
208
-	 * Load the source from the stream context and return the context options
209
-	 *
210
-	 * @param string $name
211
-	 * @return array
212
-	 * @throws \Exception
213
-	 */
214
-	protected function loadContext($name) {
215
-		$context = stream_context_get_options($this->context);
216
-		if (isset($context[$name])) {
217
-			$context = $context[$name];
218
-		} else {
219
-			throw new \BadMethodCallException('Invalid context, "' . $name . '" options not set');
220
-		}
221
-		if (isset($context['nodes']) and is_array($context['nodes'])) {
222
-			$this->nodes = $context['nodes'];
223
-		} else {
224
-			throw new \BadMethodCallException('Invalid context, nodes not set');
225
-		}
226
-		return $context;
227
-	}
228
-
229
-	/**
230
-	 * @param IFile[] $nodes
231
-	 * @return resource
232
-	 *
233
-	 * @throws \BadMethodCallException
234
-	 */
235
-	public static function wrap(array $nodes) {
236
-		$context = stream_context_create([
237
-			'assembly' => [
238
-				'nodes' => $nodes]
239
-		]);
240
-		stream_wrapper_register('assembly', '\OCA\DAV\Upload\AssemblyStream');
241
-		try {
242
-			$wrapped = fopen('assembly://', 'r', null, $context);
243
-		} catch (\BadMethodCallException $e) {
244
-			stream_wrapper_unregister('assembly');
245
-			throw $e;
246
-		}
247
-		stream_wrapper_unregister('assembly');
248
-		return $wrapped;
249
-	}
250
-
251
-	/**
252
-	 * @param $pos
253
-	 * @return IFile | null
254
-	 */
255
-	private function getNodeForPosition($pos) {
256
-		foreach($this->sortedNodes as $node) {
257
-			if ($pos >= $node['start'] && $pos < $node['end']) {
258
-				return [$node['node'], $pos - $node['start']];
259
-			}
260
-		}
261
-		return null;
262
-	}
263
-
264
-	/**
265
-	 * @param IFile $node
266
-	 * @return resource
267
-	 */
268
-	private function getStream(IFile $node) {
269
-		$data = $node->get();
270
-		if (is_resource($data)) {
271
-			return $data;
272
-		}
273
-
274
-		return fopen('data://text/plain,' . $data,'r');
275
-	}
38
+    /** @var resource */
39
+    private $context;
40
+
41
+    /** @var IFile[] */
42
+    private $nodes;
43
+
44
+    /** @var int */
45
+    private $pos = 0;
46
+
47
+    /** @var array */
48
+    private $sortedNodes;
49
+
50
+    /** @var int */
51
+    private $size;
52
+
53
+    /** @var resource */
54
+    private $currentStream = null;
55
+
56
+    /**
57
+     * @param string $path
58
+     * @param string $mode
59
+     * @param int $options
60
+     * @param string &$opened_path
61
+     * @return bool
62
+     */
63
+    public function stream_open($path, $mode, $options, &$opened_path) {
64
+        $this->loadContext('assembly');
65
+
66
+        // sort the nodes
67
+        $nodes = $this->nodes;
68
+        // http://stackoverflow.com/a/10985500
69
+        @usort($nodes, function(IFile $a, IFile $b) {
70
+            return strcmp($a->getName(), $b->getName());
71
+        });
72
+        $this->nodes = $nodes;
73
+
74
+        // build additional information
75
+        $this->sortedNodes = [];
76
+        $start = 0;
77
+        foreach($this->nodes as $node) {
78
+            $size = $node->getSize();
79
+            $name = $node->getName();
80
+            $this->sortedNodes[$name] = ['node' => $node, 'start' => $start, 'end' => $start + $size];
81
+            $start += $size;
82
+            $this->size = $start;
83
+        }
84
+        return true;
85
+    }
86
+
87
+    /**
88
+     * @param string $offset
89
+     * @param int $whence
90
+     * @return bool
91
+     */
92
+    public function stream_seek($offset, $whence = SEEK_SET) {
93
+        return false;
94
+    }
95
+
96
+    /**
97
+     * @return int
98
+     */
99
+    public function stream_tell() {
100
+        return $this->pos;
101
+    }
102
+
103
+    /**
104
+     * @param int $count
105
+     * @return string
106
+     */
107
+    public function stream_read($count) {
108
+        do {
109
+            if ($this->currentStream === null) {
110
+                list($node, $posInNode) = $this->getNodeForPosition($this->pos);
111
+                if (is_null($node)) {
112
+                    // reached last node, no more data
113
+                    return '';
114
+                }
115
+                $this->currentStream = $this->getStream($node);
116
+                fseek($this->currentStream, $posInNode);
117
+            }
118
+
119
+            $data = fread($this->currentStream, $count);
120
+            // isset is faster than strlen
121
+            if (isset($data[$count - 1])) {
122
+                // we read the full count
123
+                $read = $count;
124
+            } else {
125
+                // reaching end of stream, which happens less often so strlen is ok
126
+                $read = strlen($data);
127
+            }
128
+
129
+            if (feof($this->currentStream)) {
130
+                fclose($this->currentStream);
131
+                $this->currentNode = null;
132
+                $this->currentStream = null;
133
+            }
134
+            // if no data read, try again with the next node because
135
+            // returning empty data can make the caller think there is no more
136
+            // data left to read
137
+        } while ($read === 0);
138
+
139
+        // update position
140
+        $this->pos += $read;
141
+        return $data;
142
+    }
143
+
144
+    /**
145
+     * @param string $data
146
+     * @return int
147
+     */
148
+    public function stream_write($data) {
149
+        return false;
150
+    }
151
+
152
+    /**
153
+     * @param int $option
154
+     * @param int $arg1
155
+     * @param int $arg2
156
+     * @return bool
157
+     */
158
+    public function stream_set_option($option, $arg1, $arg2) {
159
+        return false;
160
+    }
161
+
162
+    /**
163
+     * @param int $size
164
+     * @return bool
165
+     */
166
+    public function stream_truncate($size) {
167
+        return false;
168
+    }
169
+
170
+    /**
171
+     * @return array
172
+     */
173
+    public function stream_stat() {
174
+        return [];
175
+    }
176
+
177
+    /**
178
+     * @param int $operation
179
+     * @return bool
180
+     */
181
+    public function stream_lock($operation) {
182
+        return false;
183
+    }
184
+
185
+    /**
186
+     * @return bool
187
+     */
188
+    public function stream_flush() {
189
+        return false;
190
+    }
191
+
192
+    /**
193
+     * @return bool
194
+     */
195
+    public function stream_eof() {
196
+        return $this->pos >= $this->size;
197
+    }
198
+
199
+    /**
200
+     * @return bool
201
+     */
202
+    public function stream_close() {
203
+        return true;
204
+    }
205
+
206
+
207
+    /**
208
+     * Load the source from the stream context and return the context options
209
+     *
210
+     * @param string $name
211
+     * @return array
212
+     * @throws \Exception
213
+     */
214
+    protected function loadContext($name) {
215
+        $context = stream_context_get_options($this->context);
216
+        if (isset($context[$name])) {
217
+            $context = $context[$name];
218
+        } else {
219
+            throw new \BadMethodCallException('Invalid context, "' . $name . '" options not set');
220
+        }
221
+        if (isset($context['nodes']) and is_array($context['nodes'])) {
222
+            $this->nodes = $context['nodes'];
223
+        } else {
224
+            throw new \BadMethodCallException('Invalid context, nodes not set');
225
+        }
226
+        return $context;
227
+    }
228
+
229
+    /**
230
+     * @param IFile[] $nodes
231
+     * @return resource
232
+     *
233
+     * @throws \BadMethodCallException
234
+     */
235
+    public static function wrap(array $nodes) {
236
+        $context = stream_context_create([
237
+            'assembly' => [
238
+                'nodes' => $nodes]
239
+        ]);
240
+        stream_wrapper_register('assembly', '\OCA\DAV\Upload\AssemblyStream');
241
+        try {
242
+            $wrapped = fopen('assembly://', 'r', null, $context);
243
+        } catch (\BadMethodCallException $e) {
244
+            stream_wrapper_unregister('assembly');
245
+            throw $e;
246
+        }
247
+        stream_wrapper_unregister('assembly');
248
+        return $wrapped;
249
+    }
250
+
251
+    /**
252
+     * @param $pos
253
+     * @return IFile | null
254
+     */
255
+    private function getNodeForPosition($pos) {
256
+        foreach($this->sortedNodes as $node) {
257
+            if ($pos >= $node['start'] && $pos < $node['end']) {
258
+                return [$node['node'], $pos - $node['start']];
259
+            }
260
+        }
261
+        return null;
262
+    }
263
+
264
+    /**
265
+     * @param IFile $node
266
+     * @return resource
267
+     */
268
+    private function getStream(IFile $node) {
269
+        $data = $node->get();
270
+        if (is_resource($data)) {
271
+            return $data;
272
+        }
273
+
274
+        return fopen('data://text/plain,' . $data,'r');
275
+    }
276 276
 
277 277
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -74,7 +74,7 @@  discard block
 block discarded – undo
74 74
 		// build additional information
75 75
 		$this->sortedNodes = [];
76 76
 		$start = 0;
77
-		foreach($this->nodes as $node) {
77
+		foreach ($this->nodes as $node) {
78 78
 			$size = $node->getSize();
79 79
 			$name = $node->getName();
80 80
 			$this->sortedNodes[$name] = ['node' => $node, 'start' => $start, 'end' => $start + $size];
@@ -216,7 +216,7 @@  discard block
 block discarded – undo
216 216
 		if (isset($context[$name])) {
217 217
 			$context = $context[$name];
218 218
 		} else {
219
-			throw new \BadMethodCallException('Invalid context, "' . $name . '" options not set');
219
+			throw new \BadMethodCallException('Invalid context, "'.$name.'" options not set');
220 220
 		}
221 221
 		if (isset($context['nodes']) and is_array($context['nodes'])) {
222 222
 			$this->nodes = $context['nodes'];
@@ -253,7 +253,7 @@  discard block
 block discarded – undo
253 253
 	 * @return IFile | null
254 254
 	 */
255 255
 	private function getNodeForPosition($pos) {
256
-		foreach($this->sortedNodes as $node) {
256
+		foreach ($this->sortedNodes as $node) {
257 257
 			if ($pos >= $node['start'] && $pos < $node['end']) {
258 258
 				return [$node['node'], $pos - $node['start']];
259 259
 			}
@@ -271,7 +271,7 @@  discard block
 block discarded – undo
271 271
 			return $data;
272 272
 		}
273 273
 
274
-		return fopen('data://text/plain,' . $data,'r');
274
+		return fopen('data://text/plain,'.$data, 'r');
275 275
 	}
276 276
 
277 277
 }
Please login to merge, or discard this patch.
apps/encryption/lib/Crypto/Encryption.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -369,7 +369,7 @@
 block discarded – undo
369 369
 	 * @param string $path path to the file which should be updated
370 370
 	 * @param string $uid of the user who performs the operation
371 371
 	 * @param array $accessList who has access to the file contains the key 'users' and 'public'
372
-	 * @return boolean
372
+	 * @return null|boolean
373 373
 	 */
374 374
 	public function update($path, $uid, array $accessList) {
375 375
 
Please login to merge, or discard this patch.
Indentation   +526 added lines, -526 removed lines patch added patch discarded remove patch
@@ -43,530 +43,530 @@
 block discarded – undo
43 43
 
44 44
 class Encryption implements IEncryptionModule {
45 45
 
46
-	const ID = 'OC_DEFAULT_MODULE';
47
-	const DISPLAY_NAME = 'Default encryption module';
48
-
49
-	/**
50
-	 * @var Crypt
51
-	 */
52
-	private $crypt;
53
-
54
-	/** @var string */
55
-	private $cipher;
56
-
57
-	/** @var string */
58
-	private $path;
59
-
60
-	/** @var string */
61
-	private $user;
62
-
63
-	/** @var string */
64
-	private $fileKey;
65
-
66
-	/** @var string */
67
-	private $writeCache;
68
-
69
-	/** @var KeyManager */
70
-	private $keyManager;
71
-
72
-	/** @var array */
73
-	private $accessList;
74
-
75
-	/** @var boolean */
76
-	private $isWriteOperation;
77
-
78
-	/** @var Util */
79
-	private $util;
80
-
81
-	/** @var  Session */
82
-	private $session;
83
-
84
-	/** @var  ILogger */
85
-	private $logger;
86
-
87
-	/** @var IL10N */
88
-	private $l;
89
-
90
-	/** @var EncryptAll */
91
-	private $encryptAll;
92
-
93
-	/** @var  bool */
94
-	private $useMasterPassword;
95
-
96
-	/** @var DecryptAll  */
97
-	private $decryptAll;
98
-
99
-	/** @var int unencrypted block size if block contains signature */
100
-	private $unencryptedBlockSizeSigned = 6072;
101
-
102
-	/** @var int unencrypted block size */
103
-	private $unencryptedBlockSize = 6126;
104
-
105
-	/** @var int Current version of the file */
106
-	private $version = 0;
107
-
108
-	/** @var array remember encryption signature version */
109
-	private static $rememberVersion = [];
110
-
111
-
112
-	/**
113
-	 *
114
-	 * @param Crypt $crypt
115
-	 * @param KeyManager $keyManager
116
-	 * @param Util $util
117
-	 * @param Session $session
118
-	 * @param EncryptAll $encryptAll
119
-	 * @param DecryptAll $decryptAll
120
-	 * @param ILogger $logger
121
-	 * @param IL10N $il10n
122
-	 */
123
-	public function __construct(Crypt $crypt,
124
-								KeyManager $keyManager,
125
-								Util $util,
126
-								Session $session,
127
-								EncryptAll $encryptAll,
128
-								DecryptAll $decryptAll,
129
-								ILogger $logger,
130
-								IL10N $il10n) {
131
-		$this->crypt = $crypt;
132
-		$this->keyManager = $keyManager;
133
-		$this->util = $util;
134
-		$this->session = $session;
135
-		$this->encryptAll = $encryptAll;
136
-		$this->decryptAll = $decryptAll;
137
-		$this->logger = $logger;
138
-		$this->l = $il10n;
139
-		$this->useMasterPassword = $util->isMasterKeyEnabled();
140
-	}
141
-
142
-	/**
143
-	 * @return string defining the technical unique id
144
-	 */
145
-	public function getId() {
146
-		return self::ID;
147
-	}
148
-
149
-	/**
150
-	 * In comparison to getKey() this function returns a human readable (maybe translated) name
151
-	 *
152
-	 * @return string
153
-	 */
154
-	public function getDisplayName() {
155
-		return self::DISPLAY_NAME;
156
-	}
157
-
158
-	/**
159
-	 * start receiving chunks from a file. This is the place where you can
160
-	 * perform some initial step before starting encrypting/decrypting the
161
-	 * chunks
162
-	 *
163
-	 * @param string $path to the file
164
-	 * @param string $user who read/write the file
165
-	 * @param string $mode php stream open mode
166
-	 * @param array $header contains the header data read from the file
167
-	 * @param array $accessList who has access to the file contains the key 'users' and 'public'
168
-	 *
169
-	 * @return array $header contain data as key-value pairs which should be
170
-	 *                       written to the header, in case of a write operation
171
-	 *                       or if no additional data is needed return a empty array
172
-	 */
173
-	public function begin($path, $user, $mode, array $header, array $accessList) {
174
-		$this->path = $this->getPathToRealFile($path);
175
-		$this->accessList = $accessList;
176
-		$this->user = $user;
177
-		$this->isWriteOperation = false;
178
-		$this->writeCache = '';
179
-
180
-		if($this->session->isReady() === false) {
181
-			// if the master key is enabled we can initialize encryption
182
-			// with a empty password and user name
183
-			if ($this->util->isMasterKeyEnabled()) {
184
-				$this->keyManager->init('', '');
185
-			}
186
-		}
187
-
188
-		if ($this->session->decryptAllModeActivated()) {
189
-			$encryptedFileKey = $this->keyManager->getEncryptedFileKey($this->path);
190
-			$shareKey = $this->keyManager->getShareKey($this->path, $this->session->getDecryptAllUid());
191
-			$this->fileKey = $this->crypt->multiKeyDecrypt($encryptedFileKey,
192
-				$shareKey,
193
-				$this->session->getDecryptAllKey());
194
-		} else {
195
-			$this->fileKey = $this->keyManager->getFileKey($this->path, $this->user);
196
-		}
197
-
198
-		// always use the version from the original file, also part files
199
-		// need to have a correct version number if they get moved over to the
200
-		// final location
201
-		$this->version = (int)$this->keyManager->getVersion($this->stripPartFileExtension($path), new View());
202
-
203
-		if (
204
-			$mode === 'w'
205
-			|| $mode === 'w+'
206
-			|| $mode === 'wb'
207
-			|| $mode === 'wb+'
208
-		) {
209
-			$this->isWriteOperation = true;
210
-			if (empty($this->fileKey)) {
211
-				$this->fileKey = $this->crypt->generateFileKey();
212
-			}
213
-		} else {
214
-			// if we read a part file we need to increase the version by 1
215
-			// because the version number was also increased by writing
216
-			// the part file
217
-			if(Scanner::isPartialFile($path)) {
218
-				$this->version = $this->version + 1;
219
-			}
220
-		}
221
-
222
-		if ($this->isWriteOperation) {
223
-			$this->cipher = $this->crypt->getCipher();
224
-		} elseif (isset($header['cipher'])) {
225
-			$this->cipher = $header['cipher'];
226
-		} else {
227
-			// if we read a file without a header we fall-back to the legacy cipher
228
-			// which was used in <=oC6
229
-			$this->cipher = $this->crypt->getLegacyCipher();
230
-		}
231
-
232
-		return array('cipher' => $this->cipher, 'signed' => 'true');
233
-	}
234
-
235
-	/**
236
-	 * last chunk received. This is the place where you can perform some final
237
-	 * operation and return some remaining data if something is left in your
238
-	 * buffer.
239
-	 *
240
-	 * @param string $path to the file
241
-	 * @param int $position
242
-	 * @return string remained data which should be written to the file in case
243
-	 *                of a write operation
244
-	 * @throws PublicKeyMissingException
245
-	 * @throws \Exception
246
-	 * @throws \OCA\Encryption\Exceptions\MultiKeyEncryptException
247
-	 */
248
-	public function end($path, $position = 0) {
249
-		$result = '';
250
-		if ($this->isWriteOperation) {
251
-			$this->keyManager->setVersion($path, $this->version + 1, new View());
252
-			// in case of a part file we remember the new signature versions
253
-			// the version will be set later on update.
254
-			// This way we make sure that other apps listening to the pre-hooks
255
-			// still get the old version which should be the correct value for them
256
-			if (Scanner::isPartialFile($path)) {
257
-				self::$rememberVersion[$this->stripPartFileExtension($path)] = $this->version + 1;
258
-			}
259
-			if (!empty($this->writeCache)) {
260
-				$result = $this->crypt->symmetricEncryptFileContent($this->writeCache, $this->fileKey, $this->version + 1, $position);
261
-				$this->writeCache = '';
262
-			}
263
-			$publicKeys = array();
264
-			if ($this->useMasterPassword === true) {
265
-				$publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey();
266
-			} else {
267
-				foreach ($this->accessList['users'] as $uid) {
268
-					try {
269
-						$publicKeys[$uid] = $this->keyManager->getPublicKey($uid);
270
-					} catch (PublicKeyMissingException $e) {
271
-						$this->logger->warning(
272
-							'no public key found for user "{uid}", user will not be able to read the file',
273
-							['app' => 'encryption', 'uid' => $uid]
274
-						);
275
-						// if the public key of the owner is missing we should fail
276
-						if ($uid === $this->user) {
277
-							throw $e;
278
-						}
279
-					}
280
-				}
281
-			}
282
-
283
-			$publicKeys = $this->keyManager->addSystemKeys($this->accessList, $publicKeys, $this->user);
284
-			$encryptedKeyfiles = $this->crypt->multiKeyEncrypt($this->fileKey, $publicKeys);
285
-			$this->keyManager->setAllFileKeys($this->path, $encryptedKeyfiles);
286
-		}
287
-		return $result;
288
-	}
289
-
290
-	/**
291
-	 * encrypt data
292
-	 *
293
-	 * @param string $data you want to encrypt
294
-	 * @param int $position
295
-	 * @return string encrypted data
296
-	 */
297
-	public function encrypt($data, $position = 0) {
298
-		// If extra data is left over from the last round, make sure it
299
-		// is integrated into the next block
300
-		if ($this->writeCache) {
301
-
302
-			// Concat writeCache to start of $data
303
-			$data = $this->writeCache . $data;
304
-
305
-			// Clear the write cache, ready for reuse - it has been
306
-			// flushed and its old contents processed
307
-			$this->writeCache = '';
308
-
309
-		}
310
-
311
-		$encrypted = '';
312
-		// While there still remains some data to be processed & written
313
-		while (strlen($data) > 0) {
314
-
315
-			// Remaining length for this iteration, not of the
316
-			// entire file (may be greater than 8192 bytes)
317
-			$remainingLength = strlen($data);
318
-
319
-			// If data remaining to be written is less than the
320
-			// size of 1 6126 byte block
321
-			if ($remainingLength < $this->unencryptedBlockSizeSigned) {
322
-
323
-				// Set writeCache to contents of $data
324
-				// The writeCache will be carried over to the
325
-				// next write round, and added to the start of
326
-				// $data to ensure that written blocks are
327
-				// always the correct length. If there is still
328
-				// data in writeCache after the writing round
329
-				// has finished, then the data will be written
330
-				// to disk by $this->flush().
331
-				$this->writeCache = $data;
332
-
333
-				// Clear $data ready for next round
334
-				$data = '';
335
-
336
-			} else {
337
-
338
-				// Read the chunk from the start of $data
339
-				$chunk = substr($data, 0, $this->unencryptedBlockSizeSigned);
340
-
341
-				$encrypted .= $this->crypt->symmetricEncryptFileContent($chunk, $this->fileKey, $this->version + 1, $position);
342
-
343
-				// Remove the chunk we just processed from
344
-				// $data, leaving only unprocessed data in $data
345
-				// var, for handling on the next round
346
-				$data = substr($data, $this->unencryptedBlockSizeSigned);
347
-
348
-			}
349
-
350
-		}
351
-
352
-		return $encrypted;
353
-	}
354
-
355
-	/**
356
-	 * decrypt data
357
-	 *
358
-	 * @param string $data you want to decrypt
359
-	 * @param int $position
360
-	 * @return string decrypted data
361
-	 * @throws DecryptionFailedException
362
-	 */
363
-	public function decrypt($data, $position = 0) {
364
-		if (empty($this->fileKey)) {
365
-			$msg = 'Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.';
366
-			$hint = $this->l->t('Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.');
367
-			$this->logger->error($msg);
368
-
369
-			throw new DecryptionFailedException($msg, $hint);
370
-		}
371
-
372
-		return $this->crypt->symmetricDecryptFileContent($data, $this->fileKey, $this->cipher, $this->version, $position);
373
-	}
374
-
375
-	/**
376
-	 * update encrypted file, e.g. give additional users access to the file
377
-	 *
378
-	 * @param string $path path to the file which should be updated
379
-	 * @param string $uid of the user who performs the operation
380
-	 * @param array $accessList who has access to the file contains the key 'users' and 'public'
381
-	 * @return boolean
382
-	 */
383
-	public function update($path, $uid, array $accessList) {
384
-
385
-		if (empty($accessList)) {
386
-			if (isset(self::$rememberVersion[$path])) {
387
-				$this->keyManager->setVersion($path, self::$rememberVersion[$path], new View());
388
-				unset(self::$rememberVersion[$path]);
389
-			}
390
-			return;
391
-		}
392
-
393
-		$fileKey = $this->keyManager->getFileKey($path, $uid);
394
-
395
-		if (!empty($fileKey)) {
396
-
397
-			$publicKeys = array();
398
-			if ($this->useMasterPassword === true) {
399
-				$publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey();
400
-			} else {
401
-				foreach ($accessList['users'] as $user) {
402
-					try {
403
-						$publicKeys[$user] = $this->keyManager->getPublicKey($user);
404
-					} catch (PublicKeyMissingException $e) {
405
-						$this->logger->warning('Could not encrypt file for ' . $user . ': ' . $e->getMessage());
406
-					}
407
-				}
408
-			}
409
-
410
-			$publicKeys = $this->keyManager->addSystemKeys($accessList, $publicKeys, $uid);
411
-
412
-			$encryptedFileKey = $this->crypt->multiKeyEncrypt($fileKey, $publicKeys);
413
-
414
-			$this->keyManager->deleteAllFileKeys($path);
415
-
416
-			$this->keyManager->setAllFileKeys($path, $encryptedFileKey);
417
-
418
-		} else {
419
-			$this->logger->debug('no file key found, we assume that the file "{file}" is not encrypted',
420
-				array('file' => $path, 'app' => 'encryption'));
421
-
422
-			return false;
423
-		}
424
-
425
-		return true;
426
-	}
427
-
428
-	/**
429
-	 * should the file be encrypted or not
430
-	 *
431
-	 * @param string $path
432
-	 * @return boolean
433
-	 */
434
-	public function shouldEncrypt($path) {
435
-		if ($this->util->shouldEncryptHomeStorage() === false) {
436
-			$storage = $this->util->getStorage($path);
437
-			if ($storage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
438
-				return false;
439
-			}
440
-		}
441
-		$parts = explode('/', $path);
442
-		if (count($parts) < 4) {
443
-			return false;
444
-		}
445
-
446
-		if ($parts[2] == 'files') {
447
-			return true;
448
-		}
449
-		if ($parts[2] == 'files_versions') {
450
-			return true;
451
-		}
452
-		if ($parts[2] == 'files_trashbin') {
453
-			return true;
454
-		}
455
-
456
-		return false;
457
-	}
458
-
459
-	/**
460
-	 * get size of the unencrypted payload per block.
461
-	 * ownCloud read/write files with a block size of 8192 byte
462
-	 *
463
-	 * @param bool $signed
464
-	 * @return int
465
-	 */
466
-	public function getUnencryptedBlockSize($signed = false) {
467
-		if ($signed === false) {
468
-			return $this->unencryptedBlockSize;
469
-		}
470
-
471
-		return $this->unencryptedBlockSizeSigned;
472
-	}
473
-
474
-	/**
475
-	 * check if the encryption module is able to read the file,
476
-	 * e.g. if all encryption keys exists
477
-	 *
478
-	 * @param string $path
479
-	 * @param string $uid user for whom we want to check if he can read the file
480
-	 * @return bool
481
-	 * @throws DecryptionFailedException
482
-	 */
483
-	public function isReadable($path, $uid) {
484
-		$fileKey = $this->keyManager->getFileKey($path, $uid);
485
-		if (empty($fileKey)) {
486
-			$owner = $this->util->getOwner($path);
487
-			if ($owner !== $uid) {
488
-				// if it is a shared file we throw a exception with a useful
489
-				// error message because in this case it means that the file was
490
-				// shared with the user at a point where the user didn't had a
491
-				// valid private/public key
492
-				$msg = 'Encryption module "' . $this->getDisplayName() .
493
-					'" is not able to read ' . $path;
494
-				$hint = $this->l->t('Can not read this file, probably this is a shared file. Please ask the file owner to reshare the file with you.');
495
-				$this->logger->warning($msg);
496
-				throw new DecryptionFailedException($msg, $hint);
497
-			}
498
-			return false;
499
-		}
500
-
501
-		return true;
502
-	}
503
-
504
-	/**
505
-	 * Initial encryption of all files
506
-	 *
507
-	 * @param InputInterface $input
508
-	 * @param OutputInterface $output write some status information to the terminal during encryption
509
-	 */
510
-	public function encryptAll(InputInterface $input, OutputInterface $output) {
511
-		$this->encryptAll->encryptAll($input, $output);
512
-	}
513
-
514
-	/**
515
-	 * prepare module to perform decrypt all operation
516
-	 *
517
-	 * @param InputInterface $input
518
-	 * @param OutputInterface $output
519
-	 * @param string $user
520
-	 * @return bool
521
-	 */
522
-	public function prepareDecryptAll(InputInterface $input, OutputInterface $output, $user = '') {
523
-		return $this->decryptAll->prepare($input, $output, $user);
524
-	}
525
-
526
-
527
-	/**
528
-	 * @param string $path
529
-	 * @return string
530
-	 */
531
-	protected function getPathToRealFile($path) {
532
-		$realPath = $path;
533
-		$parts = explode('/', $path);
534
-		if ($parts[2] === 'files_versions') {
535
-			$realPath = '/' . $parts[1] . '/files/' . implode('/', array_slice($parts, 3));
536
-			$length = strrpos($realPath, '.');
537
-			$realPath = substr($realPath, 0, $length);
538
-		}
539
-
540
-		return $realPath;
541
-	}
542
-
543
-	/**
544
-	 * remove .part file extension and the ocTransferId from the file to get the
545
-	 * original file name
546
-	 *
547
-	 * @param string $path
548
-	 * @return string
549
-	 */
550
-	protected function stripPartFileExtension($path) {
551
-		if (pathinfo($path, PATHINFO_EXTENSION) === 'part') {
552
-			$pos = strrpos($path, '.', -6);
553
-			$path = substr($path, 0, $pos);
554
-		}
555
-
556
-		return $path;
557
-	}
558
-
559
-	/**
560
-	 * Check if the module is ready to be used by that specific user.
561
-	 * In case a module is not ready - because e.g. key pairs have not been generated
562
-	 * upon login this method can return false before any operation starts and might
563
-	 * cause issues during operations.
564
-	 *
565
-	 * @param string $user
566
-	 * @return boolean
567
-	 * @since 9.1.0
568
-	 */
569
-	public function isReadyForUser($user) {
570
-		return $this->keyManager->userHasKeys($user);
571
-	}
46
+    const ID = 'OC_DEFAULT_MODULE';
47
+    const DISPLAY_NAME = 'Default encryption module';
48
+
49
+    /**
50
+     * @var Crypt
51
+     */
52
+    private $crypt;
53
+
54
+    /** @var string */
55
+    private $cipher;
56
+
57
+    /** @var string */
58
+    private $path;
59
+
60
+    /** @var string */
61
+    private $user;
62
+
63
+    /** @var string */
64
+    private $fileKey;
65
+
66
+    /** @var string */
67
+    private $writeCache;
68
+
69
+    /** @var KeyManager */
70
+    private $keyManager;
71
+
72
+    /** @var array */
73
+    private $accessList;
74
+
75
+    /** @var boolean */
76
+    private $isWriteOperation;
77
+
78
+    /** @var Util */
79
+    private $util;
80
+
81
+    /** @var  Session */
82
+    private $session;
83
+
84
+    /** @var  ILogger */
85
+    private $logger;
86
+
87
+    /** @var IL10N */
88
+    private $l;
89
+
90
+    /** @var EncryptAll */
91
+    private $encryptAll;
92
+
93
+    /** @var  bool */
94
+    private $useMasterPassword;
95
+
96
+    /** @var DecryptAll  */
97
+    private $decryptAll;
98
+
99
+    /** @var int unencrypted block size if block contains signature */
100
+    private $unencryptedBlockSizeSigned = 6072;
101
+
102
+    /** @var int unencrypted block size */
103
+    private $unencryptedBlockSize = 6126;
104
+
105
+    /** @var int Current version of the file */
106
+    private $version = 0;
107
+
108
+    /** @var array remember encryption signature version */
109
+    private static $rememberVersion = [];
110
+
111
+
112
+    /**
113
+     *
114
+     * @param Crypt $crypt
115
+     * @param KeyManager $keyManager
116
+     * @param Util $util
117
+     * @param Session $session
118
+     * @param EncryptAll $encryptAll
119
+     * @param DecryptAll $decryptAll
120
+     * @param ILogger $logger
121
+     * @param IL10N $il10n
122
+     */
123
+    public function __construct(Crypt $crypt,
124
+                                KeyManager $keyManager,
125
+                                Util $util,
126
+                                Session $session,
127
+                                EncryptAll $encryptAll,
128
+                                DecryptAll $decryptAll,
129
+                                ILogger $logger,
130
+                                IL10N $il10n) {
131
+        $this->crypt = $crypt;
132
+        $this->keyManager = $keyManager;
133
+        $this->util = $util;
134
+        $this->session = $session;
135
+        $this->encryptAll = $encryptAll;
136
+        $this->decryptAll = $decryptAll;
137
+        $this->logger = $logger;
138
+        $this->l = $il10n;
139
+        $this->useMasterPassword = $util->isMasterKeyEnabled();
140
+    }
141
+
142
+    /**
143
+     * @return string defining the technical unique id
144
+     */
145
+    public function getId() {
146
+        return self::ID;
147
+    }
148
+
149
+    /**
150
+     * In comparison to getKey() this function returns a human readable (maybe translated) name
151
+     *
152
+     * @return string
153
+     */
154
+    public function getDisplayName() {
155
+        return self::DISPLAY_NAME;
156
+    }
157
+
158
+    /**
159
+     * start receiving chunks from a file. This is the place where you can
160
+     * perform some initial step before starting encrypting/decrypting the
161
+     * chunks
162
+     *
163
+     * @param string $path to the file
164
+     * @param string $user who read/write the file
165
+     * @param string $mode php stream open mode
166
+     * @param array $header contains the header data read from the file
167
+     * @param array $accessList who has access to the file contains the key 'users' and 'public'
168
+     *
169
+     * @return array $header contain data as key-value pairs which should be
170
+     *                       written to the header, in case of a write operation
171
+     *                       or if no additional data is needed return a empty array
172
+     */
173
+    public function begin($path, $user, $mode, array $header, array $accessList) {
174
+        $this->path = $this->getPathToRealFile($path);
175
+        $this->accessList = $accessList;
176
+        $this->user = $user;
177
+        $this->isWriteOperation = false;
178
+        $this->writeCache = '';
179
+
180
+        if($this->session->isReady() === false) {
181
+            // if the master key is enabled we can initialize encryption
182
+            // with a empty password and user name
183
+            if ($this->util->isMasterKeyEnabled()) {
184
+                $this->keyManager->init('', '');
185
+            }
186
+        }
187
+
188
+        if ($this->session->decryptAllModeActivated()) {
189
+            $encryptedFileKey = $this->keyManager->getEncryptedFileKey($this->path);
190
+            $shareKey = $this->keyManager->getShareKey($this->path, $this->session->getDecryptAllUid());
191
+            $this->fileKey = $this->crypt->multiKeyDecrypt($encryptedFileKey,
192
+                $shareKey,
193
+                $this->session->getDecryptAllKey());
194
+        } else {
195
+            $this->fileKey = $this->keyManager->getFileKey($this->path, $this->user);
196
+        }
197
+
198
+        // always use the version from the original file, also part files
199
+        // need to have a correct version number if they get moved over to the
200
+        // final location
201
+        $this->version = (int)$this->keyManager->getVersion($this->stripPartFileExtension($path), new View());
202
+
203
+        if (
204
+            $mode === 'w'
205
+            || $mode === 'w+'
206
+            || $mode === 'wb'
207
+            || $mode === 'wb+'
208
+        ) {
209
+            $this->isWriteOperation = true;
210
+            if (empty($this->fileKey)) {
211
+                $this->fileKey = $this->crypt->generateFileKey();
212
+            }
213
+        } else {
214
+            // if we read a part file we need to increase the version by 1
215
+            // because the version number was also increased by writing
216
+            // the part file
217
+            if(Scanner::isPartialFile($path)) {
218
+                $this->version = $this->version + 1;
219
+            }
220
+        }
221
+
222
+        if ($this->isWriteOperation) {
223
+            $this->cipher = $this->crypt->getCipher();
224
+        } elseif (isset($header['cipher'])) {
225
+            $this->cipher = $header['cipher'];
226
+        } else {
227
+            // if we read a file without a header we fall-back to the legacy cipher
228
+            // which was used in <=oC6
229
+            $this->cipher = $this->crypt->getLegacyCipher();
230
+        }
231
+
232
+        return array('cipher' => $this->cipher, 'signed' => 'true');
233
+    }
234
+
235
+    /**
236
+     * last chunk received. This is the place where you can perform some final
237
+     * operation and return some remaining data if something is left in your
238
+     * buffer.
239
+     *
240
+     * @param string $path to the file
241
+     * @param int $position
242
+     * @return string remained data which should be written to the file in case
243
+     *                of a write operation
244
+     * @throws PublicKeyMissingException
245
+     * @throws \Exception
246
+     * @throws \OCA\Encryption\Exceptions\MultiKeyEncryptException
247
+     */
248
+    public function end($path, $position = 0) {
249
+        $result = '';
250
+        if ($this->isWriteOperation) {
251
+            $this->keyManager->setVersion($path, $this->version + 1, new View());
252
+            // in case of a part file we remember the new signature versions
253
+            // the version will be set later on update.
254
+            // This way we make sure that other apps listening to the pre-hooks
255
+            // still get the old version which should be the correct value for them
256
+            if (Scanner::isPartialFile($path)) {
257
+                self::$rememberVersion[$this->stripPartFileExtension($path)] = $this->version + 1;
258
+            }
259
+            if (!empty($this->writeCache)) {
260
+                $result = $this->crypt->symmetricEncryptFileContent($this->writeCache, $this->fileKey, $this->version + 1, $position);
261
+                $this->writeCache = '';
262
+            }
263
+            $publicKeys = array();
264
+            if ($this->useMasterPassword === true) {
265
+                $publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey();
266
+            } else {
267
+                foreach ($this->accessList['users'] as $uid) {
268
+                    try {
269
+                        $publicKeys[$uid] = $this->keyManager->getPublicKey($uid);
270
+                    } catch (PublicKeyMissingException $e) {
271
+                        $this->logger->warning(
272
+                            'no public key found for user "{uid}", user will not be able to read the file',
273
+                            ['app' => 'encryption', 'uid' => $uid]
274
+                        );
275
+                        // if the public key of the owner is missing we should fail
276
+                        if ($uid === $this->user) {
277
+                            throw $e;
278
+                        }
279
+                    }
280
+                }
281
+            }
282
+
283
+            $publicKeys = $this->keyManager->addSystemKeys($this->accessList, $publicKeys, $this->user);
284
+            $encryptedKeyfiles = $this->crypt->multiKeyEncrypt($this->fileKey, $publicKeys);
285
+            $this->keyManager->setAllFileKeys($this->path, $encryptedKeyfiles);
286
+        }
287
+        return $result;
288
+    }
289
+
290
+    /**
291
+     * encrypt data
292
+     *
293
+     * @param string $data you want to encrypt
294
+     * @param int $position
295
+     * @return string encrypted data
296
+     */
297
+    public function encrypt($data, $position = 0) {
298
+        // If extra data is left over from the last round, make sure it
299
+        // is integrated into the next block
300
+        if ($this->writeCache) {
301
+
302
+            // Concat writeCache to start of $data
303
+            $data = $this->writeCache . $data;
304
+
305
+            // Clear the write cache, ready for reuse - it has been
306
+            // flushed and its old contents processed
307
+            $this->writeCache = '';
308
+
309
+        }
310
+
311
+        $encrypted = '';
312
+        // While there still remains some data to be processed & written
313
+        while (strlen($data) > 0) {
314
+
315
+            // Remaining length for this iteration, not of the
316
+            // entire file (may be greater than 8192 bytes)
317
+            $remainingLength = strlen($data);
318
+
319
+            // If data remaining to be written is less than the
320
+            // size of 1 6126 byte block
321
+            if ($remainingLength < $this->unencryptedBlockSizeSigned) {
322
+
323
+                // Set writeCache to contents of $data
324
+                // The writeCache will be carried over to the
325
+                // next write round, and added to the start of
326
+                // $data to ensure that written blocks are
327
+                // always the correct length. If there is still
328
+                // data in writeCache after the writing round
329
+                // has finished, then the data will be written
330
+                // to disk by $this->flush().
331
+                $this->writeCache = $data;
332
+
333
+                // Clear $data ready for next round
334
+                $data = '';
335
+
336
+            } else {
337
+
338
+                // Read the chunk from the start of $data
339
+                $chunk = substr($data, 0, $this->unencryptedBlockSizeSigned);
340
+
341
+                $encrypted .= $this->crypt->symmetricEncryptFileContent($chunk, $this->fileKey, $this->version + 1, $position);
342
+
343
+                // Remove the chunk we just processed from
344
+                // $data, leaving only unprocessed data in $data
345
+                // var, for handling on the next round
346
+                $data = substr($data, $this->unencryptedBlockSizeSigned);
347
+
348
+            }
349
+
350
+        }
351
+
352
+        return $encrypted;
353
+    }
354
+
355
+    /**
356
+     * decrypt data
357
+     *
358
+     * @param string $data you want to decrypt
359
+     * @param int $position
360
+     * @return string decrypted data
361
+     * @throws DecryptionFailedException
362
+     */
363
+    public function decrypt($data, $position = 0) {
364
+        if (empty($this->fileKey)) {
365
+            $msg = 'Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.';
366
+            $hint = $this->l->t('Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.');
367
+            $this->logger->error($msg);
368
+
369
+            throw new DecryptionFailedException($msg, $hint);
370
+        }
371
+
372
+        return $this->crypt->symmetricDecryptFileContent($data, $this->fileKey, $this->cipher, $this->version, $position);
373
+    }
374
+
375
+    /**
376
+     * update encrypted file, e.g. give additional users access to the file
377
+     *
378
+     * @param string $path path to the file which should be updated
379
+     * @param string $uid of the user who performs the operation
380
+     * @param array $accessList who has access to the file contains the key 'users' and 'public'
381
+     * @return boolean
382
+     */
383
+    public function update($path, $uid, array $accessList) {
384
+
385
+        if (empty($accessList)) {
386
+            if (isset(self::$rememberVersion[$path])) {
387
+                $this->keyManager->setVersion($path, self::$rememberVersion[$path], new View());
388
+                unset(self::$rememberVersion[$path]);
389
+            }
390
+            return;
391
+        }
392
+
393
+        $fileKey = $this->keyManager->getFileKey($path, $uid);
394
+
395
+        if (!empty($fileKey)) {
396
+
397
+            $publicKeys = array();
398
+            if ($this->useMasterPassword === true) {
399
+                $publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey();
400
+            } else {
401
+                foreach ($accessList['users'] as $user) {
402
+                    try {
403
+                        $publicKeys[$user] = $this->keyManager->getPublicKey($user);
404
+                    } catch (PublicKeyMissingException $e) {
405
+                        $this->logger->warning('Could not encrypt file for ' . $user . ': ' . $e->getMessage());
406
+                    }
407
+                }
408
+            }
409
+
410
+            $publicKeys = $this->keyManager->addSystemKeys($accessList, $publicKeys, $uid);
411
+
412
+            $encryptedFileKey = $this->crypt->multiKeyEncrypt($fileKey, $publicKeys);
413
+
414
+            $this->keyManager->deleteAllFileKeys($path);
415
+
416
+            $this->keyManager->setAllFileKeys($path, $encryptedFileKey);
417
+
418
+        } else {
419
+            $this->logger->debug('no file key found, we assume that the file "{file}" is not encrypted',
420
+                array('file' => $path, 'app' => 'encryption'));
421
+
422
+            return false;
423
+        }
424
+
425
+        return true;
426
+    }
427
+
428
+    /**
429
+     * should the file be encrypted or not
430
+     *
431
+     * @param string $path
432
+     * @return boolean
433
+     */
434
+    public function shouldEncrypt($path) {
435
+        if ($this->util->shouldEncryptHomeStorage() === false) {
436
+            $storage = $this->util->getStorage($path);
437
+            if ($storage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
438
+                return false;
439
+            }
440
+        }
441
+        $parts = explode('/', $path);
442
+        if (count($parts) < 4) {
443
+            return false;
444
+        }
445
+
446
+        if ($parts[2] == 'files') {
447
+            return true;
448
+        }
449
+        if ($parts[2] == 'files_versions') {
450
+            return true;
451
+        }
452
+        if ($parts[2] == 'files_trashbin') {
453
+            return true;
454
+        }
455
+
456
+        return false;
457
+    }
458
+
459
+    /**
460
+     * get size of the unencrypted payload per block.
461
+     * ownCloud read/write files with a block size of 8192 byte
462
+     *
463
+     * @param bool $signed
464
+     * @return int
465
+     */
466
+    public function getUnencryptedBlockSize($signed = false) {
467
+        if ($signed === false) {
468
+            return $this->unencryptedBlockSize;
469
+        }
470
+
471
+        return $this->unencryptedBlockSizeSigned;
472
+    }
473
+
474
+    /**
475
+     * check if the encryption module is able to read the file,
476
+     * e.g. if all encryption keys exists
477
+     *
478
+     * @param string $path
479
+     * @param string $uid user for whom we want to check if he can read the file
480
+     * @return bool
481
+     * @throws DecryptionFailedException
482
+     */
483
+    public function isReadable($path, $uid) {
484
+        $fileKey = $this->keyManager->getFileKey($path, $uid);
485
+        if (empty($fileKey)) {
486
+            $owner = $this->util->getOwner($path);
487
+            if ($owner !== $uid) {
488
+                // if it is a shared file we throw a exception with a useful
489
+                // error message because in this case it means that the file was
490
+                // shared with the user at a point where the user didn't had a
491
+                // valid private/public key
492
+                $msg = 'Encryption module "' . $this->getDisplayName() .
493
+                    '" is not able to read ' . $path;
494
+                $hint = $this->l->t('Can not read this file, probably this is a shared file. Please ask the file owner to reshare the file with you.');
495
+                $this->logger->warning($msg);
496
+                throw new DecryptionFailedException($msg, $hint);
497
+            }
498
+            return false;
499
+        }
500
+
501
+        return true;
502
+    }
503
+
504
+    /**
505
+     * Initial encryption of all files
506
+     *
507
+     * @param InputInterface $input
508
+     * @param OutputInterface $output write some status information to the terminal during encryption
509
+     */
510
+    public function encryptAll(InputInterface $input, OutputInterface $output) {
511
+        $this->encryptAll->encryptAll($input, $output);
512
+    }
513
+
514
+    /**
515
+     * prepare module to perform decrypt all operation
516
+     *
517
+     * @param InputInterface $input
518
+     * @param OutputInterface $output
519
+     * @param string $user
520
+     * @return bool
521
+     */
522
+    public function prepareDecryptAll(InputInterface $input, OutputInterface $output, $user = '') {
523
+        return $this->decryptAll->prepare($input, $output, $user);
524
+    }
525
+
526
+
527
+    /**
528
+     * @param string $path
529
+     * @return string
530
+     */
531
+    protected function getPathToRealFile($path) {
532
+        $realPath = $path;
533
+        $parts = explode('/', $path);
534
+        if ($parts[2] === 'files_versions') {
535
+            $realPath = '/' . $parts[1] . '/files/' . implode('/', array_slice($parts, 3));
536
+            $length = strrpos($realPath, '.');
537
+            $realPath = substr($realPath, 0, $length);
538
+        }
539
+
540
+        return $realPath;
541
+    }
542
+
543
+    /**
544
+     * remove .part file extension and the ocTransferId from the file to get the
545
+     * original file name
546
+     *
547
+     * @param string $path
548
+     * @return string
549
+     */
550
+    protected function stripPartFileExtension($path) {
551
+        if (pathinfo($path, PATHINFO_EXTENSION) === 'part') {
552
+            $pos = strrpos($path, '.', -6);
553
+            $path = substr($path, 0, $pos);
554
+        }
555
+
556
+        return $path;
557
+    }
558
+
559
+    /**
560
+     * Check if the module is ready to be used by that specific user.
561
+     * In case a module is not ready - because e.g. key pairs have not been generated
562
+     * upon login this method can return false before any operation starts and might
563
+     * cause issues during operations.
564
+     *
565
+     * @param string $user
566
+     * @return boolean
567
+     * @since 9.1.0
568
+     */
569
+    public function isReadyForUser($user) {
570
+        return $this->keyManager->userHasKeys($user);
571
+    }
572 572
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -177,7 +177,7 @@  discard block
 block discarded – undo
177 177
 		$this->isWriteOperation = false;
178 178
 		$this->writeCache = '';
179 179
 
180
-		if($this->session->isReady() === false) {
180
+		if ($this->session->isReady() === false) {
181 181
 			// if the master key is enabled we can initialize encryption
182 182
 			// with a empty password and user name
183 183
 			if ($this->util->isMasterKeyEnabled()) {
@@ -198,7 +198,7 @@  discard block
 block discarded – undo
198 198
 		// always use the version from the original file, also part files
199 199
 		// need to have a correct version number if they get moved over to the
200 200
 		// final location
201
-		$this->version = (int)$this->keyManager->getVersion($this->stripPartFileExtension($path), new View());
201
+		$this->version = (int) $this->keyManager->getVersion($this->stripPartFileExtension($path), new View());
202 202
 
203 203
 		if (
204 204
 			$mode === 'w'
@@ -214,7 +214,7 @@  discard block
 block discarded – undo
214 214
 			// if we read a part file we need to increase the version by 1
215 215
 			// because the version number was also increased by writing
216 216
 			// the part file
217
-			if(Scanner::isPartialFile($path)) {
217
+			if (Scanner::isPartialFile($path)) {
218 218
 				$this->version = $this->version + 1;
219 219
 			}
220 220
 		}
@@ -300,7 +300,7 @@  discard block
 block discarded – undo
300 300
 		if ($this->writeCache) {
301 301
 
302 302
 			// Concat writeCache to start of $data
303
-			$data = $this->writeCache . $data;
303
+			$data = $this->writeCache.$data;
304 304
 
305 305
 			// Clear the write cache, ready for reuse - it has been
306 306
 			// flushed and its old contents processed
@@ -402,7 +402,7 @@  discard block
 block discarded – undo
402 402
 					try {
403 403
 						$publicKeys[$user] = $this->keyManager->getPublicKey($user);
404 404
 					} catch (PublicKeyMissingException $e) {
405
-						$this->logger->warning('Could not encrypt file for ' . $user . ': ' . $e->getMessage());
405
+						$this->logger->warning('Could not encrypt file for '.$user.': '.$e->getMessage());
406 406
 					}
407 407
 				}
408 408
 			}
@@ -489,8 +489,8 @@  discard block
 block discarded – undo
489 489
 				// error message because in this case it means that the file was
490 490
 				// shared with the user at a point where the user didn't had a
491 491
 				// valid private/public key
492
-				$msg = 'Encryption module "' . $this->getDisplayName() .
493
-					'" is not able to read ' . $path;
492
+				$msg = 'Encryption module "'.$this->getDisplayName().
493
+					'" is not able to read '.$path;
494 494
 				$hint = $this->l->t('Can not read this file, probably this is a shared file. Please ask the file owner to reshare the file with you.');
495 495
 				$this->logger->warning($msg);
496 496
 				throw new DecryptionFailedException($msg, $hint);
@@ -532,7 +532,7 @@  discard block
 block discarded – undo
532 532
 		$realPath = $path;
533 533
 		$parts = explode('/', $path);
534 534
 		if ($parts[2] === 'files_versions') {
535
-			$realPath = '/' . $parts[1] . '/files/' . implode('/', array_slice($parts, 3));
535
+			$realPath = '/'.$parts[1].'/files/'.implode('/', array_slice($parts, 3));
536 536
 			$length = strrpos($realPath, '.');
537 537
 			$realPath = substr($realPath, 0, $length);
538 538
 		}
Please login to merge, or discard this patch.
apps/encryption/lib/KeyManager.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -488,7 +488,7 @@
 block discarded – undo
488 488
 
489 489
 
490 490
 	/**
491
-	 * @param $path
491
+	 * @param string $path
492 492
 	 * @param $uid
493 493
 	 * @return mixed
494 494
 	 */
Please login to merge, or discard this patch.
Indentation   +661 added lines, -661 removed lines patch added patch discarded remove patch
@@ -38,665 +38,665 @@
 block discarded – undo
38 38
 
39 39
 class KeyManager {
40 40
 
41
-	/**
42
-	 * @var Session
43
-	 */
44
-	protected $session;
45
-	/**
46
-	 * @var IStorage
47
-	 */
48
-	private $keyStorage;
49
-	/**
50
-	 * @var Crypt
51
-	 */
52
-	private $crypt;
53
-	/**
54
-	 * @var string
55
-	 */
56
-	private $recoveryKeyId;
57
-	/**
58
-	 * @var string
59
-	 */
60
-	private $publicShareKeyId;
61
-	/**
62
-	 * @var string
63
-	 */
64
-	private $masterKeyId;
65
-	/**
66
-	 * @var string UserID
67
-	 */
68
-	private $keyId;
69
-	/**
70
-	 * @var string
71
-	 */
72
-	private $publicKeyId = 'publicKey';
73
-	/**
74
-	 * @var string
75
-	 */
76
-	private $privateKeyId = 'privateKey';
77
-
78
-	/**
79
-	 * @var string
80
-	 */
81
-	private $shareKeyId = 'shareKey';
82
-
83
-	/**
84
-	 * @var string
85
-	 */
86
-	private $fileKeyId = 'fileKey';
87
-	/**
88
-	 * @var IConfig
89
-	 */
90
-	private $config;
91
-	/**
92
-	 * @var ILogger
93
-	 */
94
-	private $log;
95
-	/**
96
-	 * @var Util
97
-	 */
98
-	private $util;
99
-
100
-	/**
101
-	 * @param IStorage $keyStorage
102
-	 * @param Crypt $crypt
103
-	 * @param IConfig $config
104
-	 * @param IUserSession $userSession
105
-	 * @param Session $session
106
-	 * @param ILogger $log
107
-	 * @param Util $util
108
-	 */
109
-	public function __construct(
110
-		IStorage $keyStorage,
111
-		Crypt $crypt,
112
-		IConfig $config,
113
-		IUserSession $userSession,
114
-		Session $session,
115
-		ILogger $log,
116
-		Util $util
117
-	) {
118
-
119
-		$this->util = $util;
120
-		$this->session = $session;
121
-		$this->keyStorage = $keyStorage;
122
-		$this->crypt = $crypt;
123
-		$this->config = $config;
124
-		$this->log = $log;
125
-
126
-		$this->recoveryKeyId = $this->config->getAppValue('encryption',
127
-			'recoveryKeyId');
128
-		if (empty($this->recoveryKeyId)) {
129
-			$this->recoveryKeyId = 'recoveryKey_' . substr(md5(time()), 0, 8);
130
-			$this->config->setAppValue('encryption',
131
-				'recoveryKeyId',
132
-				$this->recoveryKeyId);
133
-		}
134
-
135
-		$this->publicShareKeyId = $this->config->getAppValue('encryption',
136
-			'publicShareKeyId');
137
-		if (empty($this->publicShareKeyId)) {
138
-			$this->publicShareKeyId = 'pubShare_' . substr(md5(time()), 0, 8);
139
-			$this->config->setAppValue('encryption', 'publicShareKeyId', $this->publicShareKeyId);
140
-		}
141
-
142
-		$this->masterKeyId = $this->config->getAppValue('encryption',
143
-			'masterKeyId');
144
-		if (empty($this->masterKeyId)) {
145
-			$this->masterKeyId = 'master_' . substr(md5(time()), 0, 8);
146
-			$this->config->setAppValue('encryption', 'masterKeyId', $this->masterKeyId);
147
-		}
148
-
149
-		$this->keyId = $userSession && $userSession->isLoggedIn() ? $userSession->getUser()->getUID() : false;
150
-		$this->log = $log;
151
-	}
152
-
153
-	/**
154
-	 * check if key pair for public link shares exists, if not we create one
155
-	 */
156
-	public function validateShareKey() {
157
-		$shareKey = $this->getPublicShareKey();
158
-		if (empty($shareKey)) {
159
-			$keyPair = $this->crypt->createKeyPair();
160
-
161
-			// Save public key
162
-			$this->keyStorage->setSystemUserKey(
163
-				$this->publicShareKeyId . '.publicKey', $keyPair['publicKey'],
164
-				Encryption::ID);
165
-
166
-			// Encrypt private key empty passphrase
167
-			$encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], '');
168
-			$header = $this->crypt->generateHeader();
169
-			$this->setSystemPrivateKey($this->publicShareKeyId, $header . $encryptedKey);
170
-		}
171
-	}
172
-
173
-	/**
174
-	 * check if a key pair for the master key exists, if not we create one
175
-	 */
176
-	public function validateMasterKey() {
177
-
178
-		if ($this->util->isMasterKeyEnabled() === false) {
179
-			return;
180
-		}
181
-
182
-		$masterKey = $this->getPublicMasterKey();
183
-		if (empty($masterKey)) {
184
-			$keyPair = $this->crypt->createKeyPair();
185
-
186
-			// Save public key
187
-			$this->keyStorage->setSystemUserKey(
188
-				$this->masterKeyId . '.publicKey', $keyPair['publicKey'],
189
-				Encryption::ID);
190
-
191
-			// Encrypt private key with system password
192
-			$encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $this->getMasterKeyPassword(), $this->masterKeyId);
193
-			$header = $this->crypt->generateHeader();
194
-			$this->setSystemPrivateKey($this->masterKeyId, $header . $encryptedKey);
195
-		}
196
-	}
197
-
198
-	/**
199
-	 * @return bool
200
-	 */
201
-	public function recoveryKeyExists() {
202
-		$key = $this->getRecoveryKey();
203
-		return (!empty($key));
204
-	}
205
-
206
-	/**
207
-	 * get recovery key
208
-	 *
209
-	 * @return string
210
-	 */
211
-	public function getRecoveryKey() {
212
-		return $this->keyStorage->getSystemUserKey($this->recoveryKeyId . '.publicKey', Encryption::ID);
213
-	}
214
-
215
-	/**
216
-	 * get recovery key ID
217
-	 *
218
-	 * @return string
219
-	 */
220
-	public function getRecoveryKeyId() {
221
-		return $this->recoveryKeyId;
222
-	}
223
-
224
-	/**
225
-	 * @param string $password
226
-	 * @return bool
227
-	 */
228
-	public function checkRecoveryPassword($password) {
229
-		$recoveryKey = $this->keyStorage->getSystemUserKey($this->recoveryKeyId . '.privateKey', Encryption::ID);
230
-		$decryptedRecoveryKey = $this->crypt->decryptPrivateKey($recoveryKey, $password);
231
-
232
-		if ($decryptedRecoveryKey) {
233
-			return true;
234
-		}
235
-		return false;
236
-	}
237
-
238
-	/**
239
-	 * @param string $uid
240
-	 * @param string $password
241
-	 * @param string $keyPair
242
-	 * @return bool
243
-	 */
244
-	public function storeKeyPair($uid, $password, $keyPair) {
245
-		// Save Public Key
246
-		$this->setPublicKey($uid, $keyPair['publicKey']);
247
-
248
-		$encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $password, $uid);
249
-
250
-		$header = $this->crypt->generateHeader();
251
-
252
-		if ($encryptedKey) {
253
-			$this->setPrivateKey($uid, $header . $encryptedKey);
254
-			return true;
255
-		}
256
-		return false;
257
-	}
258
-
259
-	/**
260
-	 * @param string $password
261
-	 * @param array $keyPair
262
-	 * @return bool
263
-	 */
264
-	public function setRecoveryKey($password, $keyPair) {
265
-		// Save Public Key
266
-		$this->keyStorage->setSystemUserKey($this->getRecoveryKeyId().
267
-			'.publicKey',
268
-			$keyPair['publicKey'],
269
-			Encryption::ID);
270
-
271
-		$encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $password);
272
-		$header = $this->crypt->generateHeader();
273
-
274
-		if ($encryptedKey) {
275
-			$this->setSystemPrivateKey($this->getRecoveryKeyId(), $header . $encryptedKey);
276
-			return true;
277
-		}
278
-		return false;
279
-	}
280
-
281
-	/**
282
-	 * @param $userId
283
-	 * @param $key
284
-	 * @return bool
285
-	 */
286
-	public function setPublicKey($userId, $key) {
287
-		return $this->keyStorage->setUserKey($userId, $this->publicKeyId, $key, Encryption::ID);
288
-	}
289
-
290
-	/**
291
-	 * @param $userId
292
-	 * @param string $key
293
-	 * @return bool
294
-	 */
295
-	public function setPrivateKey($userId, $key) {
296
-		return $this->keyStorage->setUserKey($userId,
297
-			$this->privateKeyId,
298
-			$key,
299
-			Encryption::ID);
300
-	}
301
-
302
-	/**
303
-	 * write file key to key storage
304
-	 *
305
-	 * @param string $path
306
-	 * @param string $key
307
-	 * @return boolean
308
-	 */
309
-	public function setFileKey($path, $key) {
310
-		return $this->keyStorage->setFileKey($path, $this->fileKeyId, $key, Encryption::ID);
311
-	}
312
-
313
-	/**
314
-	 * set all file keys (the file key and the corresponding share keys)
315
-	 *
316
-	 * @param string $path
317
-	 * @param array $keys
318
-	 */
319
-	public function setAllFileKeys($path, $keys) {
320
-		$this->setFileKey($path, $keys['data']);
321
-		foreach ($keys['keys'] as $uid => $keyFile) {
322
-			$this->setShareKey($path, $uid, $keyFile);
323
-		}
324
-	}
325
-
326
-	/**
327
-	 * write share key to the key storage
328
-	 *
329
-	 * @param string $path
330
-	 * @param string $uid
331
-	 * @param string $key
332
-	 * @return boolean
333
-	 */
334
-	public function setShareKey($path, $uid, $key) {
335
-		$keyId = $uid . '.' . $this->shareKeyId;
336
-		return $this->keyStorage->setFileKey($path, $keyId, $key, Encryption::ID);
337
-	}
338
-
339
-	/**
340
-	 * Decrypt private key and store it
341
-	 *
342
-	 * @param string $uid user id
343
-	 * @param string $passPhrase users password
344
-	 * @return boolean
345
-	 */
346
-	public function init($uid, $passPhrase) {
347
-
348
-		$this->session->setStatus(Session::INIT_EXECUTED);
349
-
350
-		try {
351
-			if($this->util->isMasterKeyEnabled()) {
352
-				$uid = $this->getMasterKeyId();
353
-				$passPhrase = $this->getMasterKeyPassword();
354
-				$privateKey = $this->getSystemPrivateKey($uid);
355
-			} else {
356
-				$privateKey = $this->getPrivateKey($uid);
357
-			}
358
-			$privateKey = $this->crypt->decryptPrivateKey($privateKey, $passPhrase, $uid);
359
-		} catch (PrivateKeyMissingException $e) {
360
-			return false;
361
-		} catch (DecryptionFailedException $e) {
362
-			return false;
363
-		} catch (\Exception $e) {
364
-			$this->log->warning(
365
-				'Could not decrypt the private key from user "' . $uid . '"" during login. ' .
366
-				'Assume password change on the user back-end. Error message: '
367
-				. $e->getMessage()
368
-			);
369
-			return false;
370
-		}
371
-
372
-		if ($privateKey) {
373
-			$this->session->setPrivateKey($privateKey);
374
-			$this->session->setStatus(Session::INIT_SUCCESSFUL);
375
-			return true;
376
-		}
377
-
378
-		return false;
379
-	}
380
-
381
-	/**
382
-	 * @param $userId
383
-	 * @return string
384
-	 * @throws PrivateKeyMissingException
385
-	 */
386
-	public function getPrivateKey($userId) {
387
-		$privateKey = $this->keyStorage->getUserKey($userId,
388
-			$this->privateKeyId, Encryption::ID);
389
-
390
-		if (strlen($privateKey) !== 0) {
391
-			return $privateKey;
392
-		}
393
-		throw new PrivateKeyMissingException($userId);
394
-	}
395
-
396
-	/**
397
-	 * @param string $path
398
-	 * @param $uid
399
-	 * @return string
400
-	 */
401
-	public function getFileKey($path, $uid) {
402
-		$encryptedFileKey = $this->keyStorage->getFileKey($path, $this->fileKeyId, Encryption::ID);
403
-
404
-		if (empty($encryptedFileKey)) {
405
-			return '';
406
-		}
407
-
408
-		if ($this->util->isMasterKeyEnabled()) {
409
-			$uid = $this->getMasterKeyId();
410
-		}
411
-
412
-		if (is_null($uid)) {
413
-			$uid = $this->getPublicShareKeyId();
414
-			$shareKey = $this->getShareKey($path, $uid);
415
-			$privateKey = $this->keyStorage->getSystemUserKey($this->publicShareKeyId . '.privateKey', Encryption::ID);
416
-			$privateKey = $this->crypt->decryptPrivateKey($privateKey);
417
-		} else {
418
-			$shareKey = $this->getShareKey($path, $uid);
419
-			$privateKey = $this->session->getPrivateKey();
420
-		}
421
-
422
-		if ($encryptedFileKey && $shareKey && $privateKey) {
423
-			return $this->crypt->multiKeyDecrypt($encryptedFileKey,
424
-				$shareKey,
425
-				$privateKey);
426
-		}
427
-
428
-		return '';
429
-	}
430
-
431
-	/**
432
-	 * Get the current version of a file
433
-	 *
434
-	 * @param string $path
435
-	 * @param View $view
436
-	 * @return int
437
-	 */
438
-	public function getVersion($path, View $view) {
439
-		$fileInfo = $view->getFileInfo($path);
440
-		if($fileInfo === false) {
441
-			return 0;
442
-		}
443
-		return $fileInfo->getEncryptedVersion();
444
-	}
445
-
446
-	/**
447
-	 * Set the current version of a file
448
-	 *
449
-	 * @param string $path
450
-	 * @param int $version
451
-	 * @param View $view
452
-	 */
453
-	public function setVersion($path, $version, View $view) {
454
-		$fileInfo= $view->getFileInfo($path);
455
-
456
-		if($fileInfo !== false) {
457
-			$cache = $fileInfo->getStorage()->getCache();
458
-			$cache->update($fileInfo->getId(), ['encrypted' => $version, 'encryptedVersion' => $version]);
459
-		}
460
-	}
461
-
462
-	/**
463
-	 * get the encrypted file key
464
-	 *
465
-	 * @param string $path
466
-	 * @return string
467
-	 */
468
-	public function getEncryptedFileKey($path) {
469
-		$encryptedFileKey = $this->keyStorage->getFileKey($path,
470
-			$this->fileKeyId, Encryption::ID);
471
-
472
-		return $encryptedFileKey;
473
-	}
474
-
475
-	/**
476
-	 * delete share key
477
-	 *
478
-	 * @param string $path
479
-	 * @param string $keyId
480
-	 * @return boolean
481
-	 */
482
-	public function deleteShareKey($path, $keyId) {
483
-		return $this->keyStorage->deleteFileKey(
484
-			$path,
485
-			$keyId . '.' . $this->shareKeyId,
486
-			Encryption::ID);
487
-	}
488
-
489
-
490
-	/**
491
-	 * @param $path
492
-	 * @param $uid
493
-	 * @return mixed
494
-	 */
495
-	public function getShareKey($path, $uid) {
496
-		$keyId = $uid . '.' . $this->shareKeyId;
497
-		return $this->keyStorage->getFileKey($path, $keyId, Encryption::ID);
498
-	}
499
-
500
-	/**
501
-	 * check if user has a private and a public key
502
-	 *
503
-	 * @param string $userId
504
-	 * @return bool
505
-	 * @throws PrivateKeyMissingException
506
-	 * @throws PublicKeyMissingException
507
-	 */
508
-	public function userHasKeys($userId) {
509
-		$privateKey = $publicKey = true;
510
-		$exception = null;
511
-
512
-		try {
513
-			$this->getPrivateKey($userId);
514
-		} catch (PrivateKeyMissingException $e) {
515
-			$privateKey = false;
516
-			$exception = $e;
517
-		}
518
-		try {
519
-			$this->getPublicKey($userId);
520
-		} catch (PublicKeyMissingException $e) {
521
-			$publicKey = false;
522
-			$exception = $e;
523
-		}
524
-
525
-		if ($privateKey && $publicKey) {
526
-			return true;
527
-		} elseif (!$privateKey && !$publicKey) {
528
-			return false;
529
-		} else {
530
-			throw $exception;
531
-		}
532
-	}
533
-
534
-	/**
535
-	 * @param $userId
536
-	 * @return mixed
537
-	 * @throws PublicKeyMissingException
538
-	 */
539
-	public function getPublicKey($userId) {
540
-		$publicKey = $this->keyStorage->getUserKey($userId, $this->publicKeyId, Encryption::ID);
541
-
542
-		if (strlen($publicKey) !== 0) {
543
-			return $publicKey;
544
-		}
545
-		throw new PublicKeyMissingException($userId);
546
-	}
547
-
548
-	public function getPublicShareKeyId() {
549
-		return $this->publicShareKeyId;
550
-	}
551
-
552
-	/**
553
-	 * get public key for public link shares
554
-	 *
555
-	 * @return string
556
-	 */
557
-	public function getPublicShareKey() {
558
-		return $this->keyStorage->getSystemUserKey($this->publicShareKeyId . '.publicKey', Encryption::ID);
559
-	}
560
-
561
-	/**
562
-	 * @param string $purpose
563
-	 * @param string $uid
564
-	 */
565
-	public function backupUserKeys($purpose, $uid) {
566
-		$this->keyStorage->backupUserKeys(Encryption::ID, $purpose, $uid);
567
-	}
568
-
569
-	/**
570
-	 * creat a backup of the users private and public key and then  delete it
571
-	 *
572
-	 * @param string $uid
573
-	 */
574
-	public function deleteUserKeys($uid) {
575
-		$this->deletePublicKey($uid);
576
-		$this->deletePrivateKey($uid);
577
-	}
578
-
579
-	/**
580
-	 * @param $uid
581
-	 * @return bool
582
-	 */
583
-	public function deletePublicKey($uid) {
584
-		return $this->keyStorage->deleteUserKey($uid, $this->publicKeyId, Encryption::ID);
585
-	}
586
-
587
-	/**
588
-	 * @param string $uid
589
-	 * @return bool
590
-	 */
591
-	private function deletePrivateKey($uid) {
592
-		return $this->keyStorage->deleteUserKey($uid, $this->privateKeyId, Encryption::ID);
593
-	}
594
-
595
-	/**
596
-	 * @param string $path
597
-	 * @return bool
598
-	 */
599
-	public function deleteAllFileKeys($path) {
600
-		return $this->keyStorage->deleteAllFileKeys($path);
601
-	}
602
-
603
-	/**
604
-	 * @param array $userIds
605
-	 * @return array
606
-	 * @throws PublicKeyMissingException
607
-	 */
608
-	public function getPublicKeys(array $userIds) {
609
-		$keys = [];
610
-
611
-		foreach ($userIds as $userId) {
612
-			try {
613
-				$keys[$userId] = $this->getPublicKey($userId);
614
-			} catch (PublicKeyMissingException $e) {
615
-				continue;
616
-			}
617
-		}
618
-
619
-		return $keys;
620
-
621
-	}
622
-
623
-	/**
624
-	 * @param string $keyId
625
-	 * @return string returns openssl key
626
-	 */
627
-	public function getSystemPrivateKey($keyId) {
628
-		return $this->keyStorage->getSystemUserKey($keyId . '.' . $this->privateKeyId, Encryption::ID);
629
-	}
630
-
631
-	/**
632
-	 * @param string $keyId
633
-	 * @param string $key
634
-	 * @return string returns openssl key
635
-	 */
636
-	public function setSystemPrivateKey($keyId, $key) {
637
-		return $this->keyStorage->setSystemUserKey(
638
-			$keyId . '.' . $this->privateKeyId,
639
-			$key,
640
-			Encryption::ID);
641
-	}
642
-
643
-	/**
644
-	 * add system keys such as the public share key and the recovery key
645
-	 *
646
-	 * @param array $accessList
647
-	 * @param array $publicKeys
648
-	 * @param string $uid
649
-	 * @return array
650
-	 * @throws PublicKeyMissingException
651
-	 */
652
-	public function addSystemKeys(array $accessList, array $publicKeys, $uid) {
653
-		if (!empty($accessList['public'])) {
654
-			$publicShareKey = $this->getPublicShareKey();
655
-			if (empty($publicShareKey)) {
656
-				throw new PublicKeyMissingException($this->getPublicShareKeyId());
657
-			}
658
-			$publicKeys[$this->getPublicShareKeyId()] = $publicShareKey;
659
-		}
660
-
661
-		if ($this->recoveryKeyExists() &&
662
-			$this->util->isRecoveryEnabledForUser($uid)) {
663
-
664
-			$publicKeys[$this->getRecoveryKeyId()] = $this->getRecoveryKey();
665
-		}
666
-
667
-		return $publicKeys;
668
-	}
669
-
670
-	/**
671
-	 * get master key password
672
-	 *
673
-	 * @return string
674
-	 * @throws \Exception
675
-	 */
676
-	public function getMasterKeyPassword() {
677
-		$password = $this->config->getSystemValue('secret');
678
-		if (empty($password)){
679
-			throw new \Exception('Can not get secret from ownCloud instance');
680
-		}
681
-
682
-		return $password;
683
-	}
684
-
685
-	/**
686
-	 * return master key id
687
-	 *
688
-	 * @return string
689
-	 */
690
-	public function getMasterKeyId() {
691
-		return $this->masterKeyId;
692
-	}
693
-
694
-	/**
695
-	 * get public master key
696
-	 *
697
-	 * @return string
698
-	 */
699
-	public function getPublicMasterKey() {
700
-		return $this->keyStorage->getSystemUserKey($this->masterKeyId . '.publicKey', Encryption::ID);
701
-	}
41
+    /**
42
+     * @var Session
43
+     */
44
+    protected $session;
45
+    /**
46
+     * @var IStorage
47
+     */
48
+    private $keyStorage;
49
+    /**
50
+     * @var Crypt
51
+     */
52
+    private $crypt;
53
+    /**
54
+     * @var string
55
+     */
56
+    private $recoveryKeyId;
57
+    /**
58
+     * @var string
59
+     */
60
+    private $publicShareKeyId;
61
+    /**
62
+     * @var string
63
+     */
64
+    private $masterKeyId;
65
+    /**
66
+     * @var string UserID
67
+     */
68
+    private $keyId;
69
+    /**
70
+     * @var string
71
+     */
72
+    private $publicKeyId = 'publicKey';
73
+    /**
74
+     * @var string
75
+     */
76
+    private $privateKeyId = 'privateKey';
77
+
78
+    /**
79
+     * @var string
80
+     */
81
+    private $shareKeyId = 'shareKey';
82
+
83
+    /**
84
+     * @var string
85
+     */
86
+    private $fileKeyId = 'fileKey';
87
+    /**
88
+     * @var IConfig
89
+     */
90
+    private $config;
91
+    /**
92
+     * @var ILogger
93
+     */
94
+    private $log;
95
+    /**
96
+     * @var Util
97
+     */
98
+    private $util;
99
+
100
+    /**
101
+     * @param IStorage $keyStorage
102
+     * @param Crypt $crypt
103
+     * @param IConfig $config
104
+     * @param IUserSession $userSession
105
+     * @param Session $session
106
+     * @param ILogger $log
107
+     * @param Util $util
108
+     */
109
+    public function __construct(
110
+        IStorage $keyStorage,
111
+        Crypt $crypt,
112
+        IConfig $config,
113
+        IUserSession $userSession,
114
+        Session $session,
115
+        ILogger $log,
116
+        Util $util
117
+    ) {
118
+
119
+        $this->util = $util;
120
+        $this->session = $session;
121
+        $this->keyStorage = $keyStorage;
122
+        $this->crypt = $crypt;
123
+        $this->config = $config;
124
+        $this->log = $log;
125
+
126
+        $this->recoveryKeyId = $this->config->getAppValue('encryption',
127
+            'recoveryKeyId');
128
+        if (empty($this->recoveryKeyId)) {
129
+            $this->recoveryKeyId = 'recoveryKey_' . substr(md5(time()), 0, 8);
130
+            $this->config->setAppValue('encryption',
131
+                'recoveryKeyId',
132
+                $this->recoveryKeyId);
133
+        }
134
+
135
+        $this->publicShareKeyId = $this->config->getAppValue('encryption',
136
+            'publicShareKeyId');
137
+        if (empty($this->publicShareKeyId)) {
138
+            $this->publicShareKeyId = 'pubShare_' . substr(md5(time()), 0, 8);
139
+            $this->config->setAppValue('encryption', 'publicShareKeyId', $this->publicShareKeyId);
140
+        }
141
+
142
+        $this->masterKeyId = $this->config->getAppValue('encryption',
143
+            'masterKeyId');
144
+        if (empty($this->masterKeyId)) {
145
+            $this->masterKeyId = 'master_' . substr(md5(time()), 0, 8);
146
+            $this->config->setAppValue('encryption', 'masterKeyId', $this->masterKeyId);
147
+        }
148
+
149
+        $this->keyId = $userSession && $userSession->isLoggedIn() ? $userSession->getUser()->getUID() : false;
150
+        $this->log = $log;
151
+    }
152
+
153
+    /**
154
+     * check if key pair for public link shares exists, if not we create one
155
+     */
156
+    public function validateShareKey() {
157
+        $shareKey = $this->getPublicShareKey();
158
+        if (empty($shareKey)) {
159
+            $keyPair = $this->crypt->createKeyPair();
160
+
161
+            // Save public key
162
+            $this->keyStorage->setSystemUserKey(
163
+                $this->publicShareKeyId . '.publicKey', $keyPair['publicKey'],
164
+                Encryption::ID);
165
+
166
+            // Encrypt private key empty passphrase
167
+            $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], '');
168
+            $header = $this->crypt->generateHeader();
169
+            $this->setSystemPrivateKey($this->publicShareKeyId, $header . $encryptedKey);
170
+        }
171
+    }
172
+
173
+    /**
174
+     * check if a key pair for the master key exists, if not we create one
175
+     */
176
+    public function validateMasterKey() {
177
+
178
+        if ($this->util->isMasterKeyEnabled() === false) {
179
+            return;
180
+        }
181
+
182
+        $masterKey = $this->getPublicMasterKey();
183
+        if (empty($masterKey)) {
184
+            $keyPair = $this->crypt->createKeyPair();
185
+
186
+            // Save public key
187
+            $this->keyStorage->setSystemUserKey(
188
+                $this->masterKeyId . '.publicKey', $keyPair['publicKey'],
189
+                Encryption::ID);
190
+
191
+            // Encrypt private key with system password
192
+            $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $this->getMasterKeyPassword(), $this->masterKeyId);
193
+            $header = $this->crypt->generateHeader();
194
+            $this->setSystemPrivateKey($this->masterKeyId, $header . $encryptedKey);
195
+        }
196
+    }
197
+
198
+    /**
199
+     * @return bool
200
+     */
201
+    public function recoveryKeyExists() {
202
+        $key = $this->getRecoveryKey();
203
+        return (!empty($key));
204
+    }
205
+
206
+    /**
207
+     * get recovery key
208
+     *
209
+     * @return string
210
+     */
211
+    public function getRecoveryKey() {
212
+        return $this->keyStorage->getSystemUserKey($this->recoveryKeyId . '.publicKey', Encryption::ID);
213
+    }
214
+
215
+    /**
216
+     * get recovery key ID
217
+     *
218
+     * @return string
219
+     */
220
+    public function getRecoveryKeyId() {
221
+        return $this->recoveryKeyId;
222
+    }
223
+
224
+    /**
225
+     * @param string $password
226
+     * @return bool
227
+     */
228
+    public function checkRecoveryPassword($password) {
229
+        $recoveryKey = $this->keyStorage->getSystemUserKey($this->recoveryKeyId . '.privateKey', Encryption::ID);
230
+        $decryptedRecoveryKey = $this->crypt->decryptPrivateKey($recoveryKey, $password);
231
+
232
+        if ($decryptedRecoveryKey) {
233
+            return true;
234
+        }
235
+        return false;
236
+    }
237
+
238
+    /**
239
+     * @param string $uid
240
+     * @param string $password
241
+     * @param string $keyPair
242
+     * @return bool
243
+     */
244
+    public function storeKeyPair($uid, $password, $keyPair) {
245
+        // Save Public Key
246
+        $this->setPublicKey($uid, $keyPair['publicKey']);
247
+
248
+        $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $password, $uid);
249
+
250
+        $header = $this->crypt->generateHeader();
251
+
252
+        if ($encryptedKey) {
253
+            $this->setPrivateKey($uid, $header . $encryptedKey);
254
+            return true;
255
+        }
256
+        return false;
257
+    }
258
+
259
+    /**
260
+     * @param string $password
261
+     * @param array $keyPair
262
+     * @return bool
263
+     */
264
+    public function setRecoveryKey($password, $keyPair) {
265
+        // Save Public Key
266
+        $this->keyStorage->setSystemUserKey($this->getRecoveryKeyId().
267
+            '.publicKey',
268
+            $keyPair['publicKey'],
269
+            Encryption::ID);
270
+
271
+        $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $password);
272
+        $header = $this->crypt->generateHeader();
273
+
274
+        if ($encryptedKey) {
275
+            $this->setSystemPrivateKey($this->getRecoveryKeyId(), $header . $encryptedKey);
276
+            return true;
277
+        }
278
+        return false;
279
+    }
280
+
281
+    /**
282
+     * @param $userId
283
+     * @param $key
284
+     * @return bool
285
+     */
286
+    public function setPublicKey($userId, $key) {
287
+        return $this->keyStorage->setUserKey($userId, $this->publicKeyId, $key, Encryption::ID);
288
+    }
289
+
290
+    /**
291
+     * @param $userId
292
+     * @param string $key
293
+     * @return bool
294
+     */
295
+    public function setPrivateKey($userId, $key) {
296
+        return $this->keyStorage->setUserKey($userId,
297
+            $this->privateKeyId,
298
+            $key,
299
+            Encryption::ID);
300
+    }
301
+
302
+    /**
303
+     * write file key to key storage
304
+     *
305
+     * @param string $path
306
+     * @param string $key
307
+     * @return boolean
308
+     */
309
+    public function setFileKey($path, $key) {
310
+        return $this->keyStorage->setFileKey($path, $this->fileKeyId, $key, Encryption::ID);
311
+    }
312
+
313
+    /**
314
+     * set all file keys (the file key and the corresponding share keys)
315
+     *
316
+     * @param string $path
317
+     * @param array $keys
318
+     */
319
+    public function setAllFileKeys($path, $keys) {
320
+        $this->setFileKey($path, $keys['data']);
321
+        foreach ($keys['keys'] as $uid => $keyFile) {
322
+            $this->setShareKey($path, $uid, $keyFile);
323
+        }
324
+    }
325
+
326
+    /**
327
+     * write share key to the key storage
328
+     *
329
+     * @param string $path
330
+     * @param string $uid
331
+     * @param string $key
332
+     * @return boolean
333
+     */
334
+    public function setShareKey($path, $uid, $key) {
335
+        $keyId = $uid . '.' . $this->shareKeyId;
336
+        return $this->keyStorage->setFileKey($path, $keyId, $key, Encryption::ID);
337
+    }
338
+
339
+    /**
340
+     * Decrypt private key and store it
341
+     *
342
+     * @param string $uid user id
343
+     * @param string $passPhrase users password
344
+     * @return boolean
345
+     */
346
+    public function init($uid, $passPhrase) {
347
+
348
+        $this->session->setStatus(Session::INIT_EXECUTED);
349
+
350
+        try {
351
+            if($this->util->isMasterKeyEnabled()) {
352
+                $uid = $this->getMasterKeyId();
353
+                $passPhrase = $this->getMasterKeyPassword();
354
+                $privateKey = $this->getSystemPrivateKey($uid);
355
+            } else {
356
+                $privateKey = $this->getPrivateKey($uid);
357
+            }
358
+            $privateKey = $this->crypt->decryptPrivateKey($privateKey, $passPhrase, $uid);
359
+        } catch (PrivateKeyMissingException $e) {
360
+            return false;
361
+        } catch (DecryptionFailedException $e) {
362
+            return false;
363
+        } catch (\Exception $e) {
364
+            $this->log->warning(
365
+                'Could not decrypt the private key from user "' . $uid . '"" during login. ' .
366
+                'Assume password change on the user back-end. Error message: '
367
+                . $e->getMessage()
368
+            );
369
+            return false;
370
+        }
371
+
372
+        if ($privateKey) {
373
+            $this->session->setPrivateKey($privateKey);
374
+            $this->session->setStatus(Session::INIT_SUCCESSFUL);
375
+            return true;
376
+        }
377
+
378
+        return false;
379
+    }
380
+
381
+    /**
382
+     * @param $userId
383
+     * @return string
384
+     * @throws PrivateKeyMissingException
385
+     */
386
+    public function getPrivateKey($userId) {
387
+        $privateKey = $this->keyStorage->getUserKey($userId,
388
+            $this->privateKeyId, Encryption::ID);
389
+
390
+        if (strlen($privateKey) !== 0) {
391
+            return $privateKey;
392
+        }
393
+        throw new PrivateKeyMissingException($userId);
394
+    }
395
+
396
+    /**
397
+     * @param string $path
398
+     * @param $uid
399
+     * @return string
400
+     */
401
+    public function getFileKey($path, $uid) {
402
+        $encryptedFileKey = $this->keyStorage->getFileKey($path, $this->fileKeyId, Encryption::ID);
403
+
404
+        if (empty($encryptedFileKey)) {
405
+            return '';
406
+        }
407
+
408
+        if ($this->util->isMasterKeyEnabled()) {
409
+            $uid = $this->getMasterKeyId();
410
+        }
411
+
412
+        if (is_null($uid)) {
413
+            $uid = $this->getPublicShareKeyId();
414
+            $shareKey = $this->getShareKey($path, $uid);
415
+            $privateKey = $this->keyStorage->getSystemUserKey($this->publicShareKeyId . '.privateKey', Encryption::ID);
416
+            $privateKey = $this->crypt->decryptPrivateKey($privateKey);
417
+        } else {
418
+            $shareKey = $this->getShareKey($path, $uid);
419
+            $privateKey = $this->session->getPrivateKey();
420
+        }
421
+
422
+        if ($encryptedFileKey && $shareKey && $privateKey) {
423
+            return $this->crypt->multiKeyDecrypt($encryptedFileKey,
424
+                $shareKey,
425
+                $privateKey);
426
+        }
427
+
428
+        return '';
429
+    }
430
+
431
+    /**
432
+     * Get the current version of a file
433
+     *
434
+     * @param string $path
435
+     * @param View $view
436
+     * @return int
437
+     */
438
+    public function getVersion($path, View $view) {
439
+        $fileInfo = $view->getFileInfo($path);
440
+        if($fileInfo === false) {
441
+            return 0;
442
+        }
443
+        return $fileInfo->getEncryptedVersion();
444
+    }
445
+
446
+    /**
447
+     * Set the current version of a file
448
+     *
449
+     * @param string $path
450
+     * @param int $version
451
+     * @param View $view
452
+     */
453
+    public function setVersion($path, $version, View $view) {
454
+        $fileInfo= $view->getFileInfo($path);
455
+
456
+        if($fileInfo !== false) {
457
+            $cache = $fileInfo->getStorage()->getCache();
458
+            $cache->update($fileInfo->getId(), ['encrypted' => $version, 'encryptedVersion' => $version]);
459
+        }
460
+    }
461
+
462
+    /**
463
+     * get the encrypted file key
464
+     *
465
+     * @param string $path
466
+     * @return string
467
+     */
468
+    public function getEncryptedFileKey($path) {
469
+        $encryptedFileKey = $this->keyStorage->getFileKey($path,
470
+            $this->fileKeyId, Encryption::ID);
471
+
472
+        return $encryptedFileKey;
473
+    }
474
+
475
+    /**
476
+     * delete share key
477
+     *
478
+     * @param string $path
479
+     * @param string $keyId
480
+     * @return boolean
481
+     */
482
+    public function deleteShareKey($path, $keyId) {
483
+        return $this->keyStorage->deleteFileKey(
484
+            $path,
485
+            $keyId . '.' . $this->shareKeyId,
486
+            Encryption::ID);
487
+    }
488
+
489
+
490
+    /**
491
+     * @param $path
492
+     * @param $uid
493
+     * @return mixed
494
+     */
495
+    public function getShareKey($path, $uid) {
496
+        $keyId = $uid . '.' . $this->shareKeyId;
497
+        return $this->keyStorage->getFileKey($path, $keyId, Encryption::ID);
498
+    }
499
+
500
+    /**
501
+     * check if user has a private and a public key
502
+     *
503
+     * @param string $userId
504
+     * @return bool
505
+     * @throws PrivateKeyMissingException
506
+     * @throws PublicKeyMissingException
507
+     */
508
+    public function userHasKeys($userId) {
509
+        $privateKey = $publicKey = true;
510
+        $exception = null;
511
+
512
+        try {
513
+            $this->getPrivateKey($userId);
514
+        } catch (PrivateKeyMissingException $e) {
515
+            $privateKey = false;
516
+            $exception = $e;
517
+        }
518
+        try {
519
+            $this->getPublicKey($userId);
520
+        } catch (PublicKeyMissingException $e) {
521
+            $publicKey = false;
522
+            $exception = $e;
523
+        }
524
+
525
+        if ($privateKey && $publicKey) {
526
+            return true;
527
+        } elseif (!$privateKey && !$publicKey) {
528
+            return false;
529
+        } else {
530
+            throw $exception;
531
+        }
532
+    }
533
+
534
+    /**
535
+     * @param $userId
536
+     * @return mixed
537
+     * @throws PublicKeyMissingException
538
+     */
539
+    public function getPublicKey($userId) {
540
+        $publicKey = $this->keyStorage->getUserKey($userId, $this->publicKeyId, Encryption::ID);
541
+
542
+        if (strlen($publicKey) !== 0) {
543
+            return $publicKey;
544
+        }
545
+        throw new PublicKeyMissingException($userId);
546
+    }
547
+
548
+    public function getPublicShareKeyId() {
549
+        return $this->publicShareKeyId;
550
+    }
551
+
552
+    /**
553
+     * get public key for public link shares
554
+     *
555
+     * @return string
556
+     */
557
+    public function getPublicShareKey() {
558
+        return $this->keyStorage->getSystemUserKey($this->publicShareKeyId . '.publicKey', Encryption::ID);
559
+    }
560
+
561
+    /**
562
+     * @param string $purpose
563
+     * @param string $uid
564
+     */
565
+    public function backupUserKeys($purpose, $uid) {
566
+        $this->keyStorage->backupUserKeys(Encryption::ID, $purpose, $uid);
567
+    }
568
+
569
+    /**
570
+     * creat a backup of the users private and public key and then  delete it
571
+     *
572
+     * @param string $uid
573
+     */
574
+    public function deleteUserKeys($uid) {
575
+        $this->deletePublicKey($uid);
576
+        $this->deletePrivateKey($uid);
577
+    }
578
+
579
+    /**
580
+     * @param $uid
581
+     * @return bool
582
+     */
583
+    public function deletePublicKey($uid) {
584
+        return $this->keyStorage->deleteUserKey($uid, $this->publicKeyId, Encryption::ID);
585
+    }
586
+
587
+    /**
588
+     * @param string $uid
589
+     * @return bool
590
+     */
591
+    private function deletePrivateKey($uid) {
592
+        return $this->keyStorage->deleteUserKey($uid, $this->privateKeyId, Encryption::ID);
593
+    }
594
+
595
+    /**
596
+     * @param string $path
597
+     * @return bool
598
+     */
599
+    public function deleteAllFileKeys($path) {
600
+        return $this->keyStorage->deleteAllFileKeys($path);
601
+    }
602
+
603
+    /**
604
+     * @param array $userIds
605
+     * @return array
606
+     * @throws PublicKeyMissingException
607
+     */
608
+    public function getPublicKeys(array $userIds) {
609
+        $keys = [];
610
+
611
+        foreach ($userIds as $userId) {
612
+            try {
613
+                $keys[$userId] = $this->getPublicKey($userId);
614
+            } catch (PublicKeyMissingException $e) {
615
+                continue;
616
+            }
617
+        }
618
+
619
+        return $keys;
620
+
621
+    }
622
+
623
+    /**
624
+     * @param string $keyId
625
+     * @return string returns openssl key
626
+     */
627
+    public function getSystemPrivateKey($keyId) {
628
+        return $this->keyStorage->getSystemUserKey($keyId . '.' . $this->privateKeyId, Encryption::ID);
629
+    }
630
+
631
+    /**
632
+     * @param string $keyId
633
+     * @param string $key
634
+     * @return string returns openssl key
635
+     */
636
+    public function setSystemPrivateKey($keyId, $key) {
637
+        return $this->keyStorage->setSystemUserKey(
638
+            $keyId . '.' . $this->privateKeyId,
639
+            $key,
640
+            Encryption::ID);
641
+    }
642
+
643
+    /**
644
+     * add system keys such as the public share key and the recovery key
645
+     *
646
+     * @param array $accessList
647
+     * @param array $publicKeys
648
+     * @param string $uid
649
+     * @return array
650
+     * @throws PublicKeyMissingException
651
+     */
652
+    public function addSystemKeys(array $accessList, array $publicKeys, $uid) {
653
+        if (!empty($accessList['public'])) {
654
+            $publicShareKey = $this->getPublicShareKey();
655
+            if (empty($publicShareKey)) {
656
+                throw new PublicKeyMissingException($this->getPublicShareKeyId());
657
+            }
658
+            $publicKeys[$this->getPublicShareKeyId()] = $publicShareKey;
659
+        }
660
+
661
+        if ($this->recoveryKeyExists() &&
662
+            $this->util->isRecoveryEnabledForUser($uid)) {
663
+
664
+            $publicKeys[$this->getRecoveryKeyId()] = $this->getRecoveryKey();
665
+        }
666
+
667
+        return $publicKeys;
668
+    }
669
+
670
+    /**
671
+     * get master key password
672
+     *
673
+     * @return string
674
+     * @throws \Exception
675
+     */
676
+    public function getMasterKeyPassword() {
677
+        $password = $this->config->getSystemValue('secret');
678
+        if (empty($password)){
679
+            throw new \Exception('Can not get secret from ownCloud instance');
680
+        }
681
+
682
+        return $password;
683
+    }
684
+
685
+    /**
686
+     * return master key id
687
+     *
688
+     * @return string
689
+     */
690
+    public function getMasterKeyId() {
691
+        return $this->masterKeyId;
692
+    }
693
+
694
+    /**
695
+     * get public master key
696
+     *
697
+     * @return string
698
+     */
699
+    public function getPublicMasterKey() {
700
+        return $this->keyStorage->getSystemUserKey($this->masterKeyId . '.publicKey', Encryption::ID);
701
+    }
702 702
 }
Please login to merge, or discard this patch.
Spacing   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
 		$this->recoveryKeyId = $this->config->getAppValue('encryption',
127 127
 			'recoveryKeyId');
128 128
 		if (empty($this->recoveryKeyId)) {
129
-			$this->recoveryKeyId = 'recoveryKey_' . substr(md5(time()), 0, 8);
129
+			$this->recoveryKeyId = 'recoveryKey_'.substr(md5(time()), 0, 8);
130 130
 			$this->config->setAppValue('encryption',
131 131
 				'recoveryKeyId',
132 132
 				$this->recoveryKeyId);
@@ -135,14 +135,14 @@  discard block
 block discarded – undo
135 135
 		$this->publicShareKeyId = $this->config->getAppValue('encryption',
136 136
 			'publicShareKeyId');
137 137
 		if (empty($this->publicShareKeyId)) {
138
-			$this->publicShareKeyId = 'pubShare_' . substr(md5(time()), 0, 8);
138
+			$this->publicShareKeyId = 'pubShare_'.substr(md5(time()), 0, 8);
139 139
 			$this->config->setAppValue('encryption', 'publicShareKeyId', $this->publicShareKeyId);
140 140
 		}
141 141
 
142 142
 		$this->masterKeyId = $this->config->getAppValue('encryption',
143 143
 			'masterKeyId');
144 144
 		if (empty($this->masterKeyId)) {
145
-			$this->masterKeyId = 'master_' . substr(md5(time()), 0, 8);
145
+			$this->masterKeyId = 'master_'.substr(md5(time()), 0, 8);
146 146
 			$this->config->setAppValue('encryption', 'masterKeyId', $this->masterKeyId);
147 147
 		}
148 148
 
@@ -160,13 +160,13 @@  discard block
 block discarded – undo
160 160
 
161 161
 			// Save public key
162 162
 			$this->keyStorage->setSystemUserKey(
163
-				$this->publicShareKeyId . '.publicKey', $keyPair['publicKey'],
163
+				$this->publicShareKeyId.'.publicKey', $keyPair['publicKey'],
164 164
 				Encryption::ID);
165 165
 
166 166
 			// Encrypt private key empty passphrase
167 167
 			$encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], '');
168 168
 			$header = $this->crypt->generateHeader();
169
-			$this->setSystemPrivateKey($this->publicShareKeyId, $header . $encryptedKey);
169
+			$this->setSystemPrivateKey($this->publicShareKeyId, $header.$encryptedKey);
170 170
 		}
171 171
 	}
172 172
 
@@ -185,13 +185,13 @@  discard block
 block discarded – undo
185 185
 
186 186
 			// Save public key
187 187
 			$this->keyStorage->setSystemUserKey(
188
-				$this->masterKeyId . '.publicKey', $keyPair['publicKey'],
188
+				$this->masterKeyId.'.publicKey', $keyPair['publicKey'],
189 189
 				Encryption::ID);
190 190
 
191 191
 			// Encrypt private key with system password
192 192
 			$encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $this->getMasterKeyPassword(), $this->masterKeyId);
193 193
 			$header = $this->crypt->generateHeader();
194
-			$this->setSystemPrivateKey($this->masterKeyId, $header . $encryptedKey);
194
+			$this->setSystemPrivateKey($this->masterKeyId, $header.$encryptedKey);
195 195
 		}
196 196
 	}
197 197
 
@@ -209,7 +209,7 @@  discard block
 block discarded – undo
209 209
 	 * @return string
210 210
 	 */
211 211
 	public function getRecoveryKey() {
212
-		return $this->keyStorage->getSystemUserKey($this->recoveryKeyId . '.publicKey', Encryption::ID);
212
+		return $this->keyStorage->getSystemUserKey($this->recoveryKeyId.'.publicKey', Encryption::ID);
213 213
 	}
214 214
 
215 215
 	/**
@@ -226,7 +226,7 @@  discard block
 block discarded – undo
226 226
 	 * @return bool
227 227
 	 */
228 228
 	public function checkRecoveryPassword($password) {
229
-		$recoveryKey = $this->keyStorage->getSystemUserKey($this->recoveryKeyId . '.privateKey', Encryption::ID);
229
+		$recoveryKey = $this->keyStorage->getSystemUserKey($this->recoveryKeyId.'.privateKey', Encryption::ID);
230 230
 		$decryptedRecoveryKey = $this->crypt->decryptPrivateKey($recoveryKey, $password);
231 231
 
232 232
 		if ($decryptedRecoveryKey) {
@@ -250,7 +250,7 @@  discard block
 block discarded – undo
250 250
 		$header = $this->crypt->generateHeader();
251 251
 
252 252
 		if ($encryptedKey) {
253
-			$this->setPrivateKey($uid, $header . $encryptedKey);
253
+			$this->setPrivateKey($uid, $header.$encryptedKey);
254 254
 			return true;
255 255
 		}
256 256
 		return false;
@@ -272,7 +272,7 @@  discard block
 block discarded – undo
272 272
 		$header = $this->crypt->generateHeader();
273 273
 
274 274
 		if ($encryptedKey) {
275
-			$this->setSystemPrivateKey($this->getRecoveryKeyId(), $header . $encryptedKey);
275
+			$this->setSystemPrivateKey($this->getRecoveryKeyId(), $header.$encryptedKey);
276 276
 			return true;
277 277
 		}
278 278
 		return false;
@@ -332,7 +332,7 @@  discard block
 block discarded – undo
332 332
 	 * @return boolean
333 333
 	 */
334 334
 	public function setShareKey($path, $uid, $key) {
335
-		$keyId = $uid . '.' . $this->shareKeyId;
335
+		$keyId = $uid.'.'.$this->shareKeyId;
336 336
 		return $this->keyStorage->setFileKey($path, $keyId, $key, Encryption::ID);
337 337
 	}
338 338
 
@@ -348,7 +348,7 @@  discard block
 block discarded – undo
348 348
 		$this->session->setStatus(Session::INIT_EXECUTED);
349 349
 
350 350
 		try {
351
-			if($this->util->isMasterKeyEnabled()) {
351
+			if ($this->util->isMasterKeyEnabled()) {
352 352
 				$uid = $this->getMasterKeyId();
353 353
 				$passPhrase = $this->getMasterKeyPassword();
354 354
 				$privateKey = $this->getSystemPrivateKey($uid);
@@ -362,7 +362,7 @@  discard block
 block discarded – undo
362 362
 			return false;
363 363
 		} catch (\Exception $e) {
364 364
 			$this->log->warning(
365
-				'Could not decrypt the private key from user "' . $uid . '"" during login. ' .
365
+				'Could not decrypt the private key from user "'.$uid.'"" during login. '.
366 366
 				'Assume password change on the user back-end. Error message: '
367 367
 				. $e->getMessage()
368 368
 			);
@@ -412,7 +412,7 @@  discard block
 block discarded – undo
412 412
 		if (is_null($uid)) {
413 413
 			$uid = $this->getPublicShareKeyId();
414 414
 			$shareKey = $this->getShareKey($path, $uid);
415
-			$privateKey = $this->keyStorage->getSystemUserKey($this->publicShareKeyId . '.privateKey', Encryption::ID);
415
+			$privateKey = $this->keyStorage->getSystemUserKey($this->publicShareKeyId.'.privateKey', Encryption::ID);
416 416
 			$privateKey = $this->crypt->decryptPrivateKey($privateKey);
417 417
 		} else {
418 418
 			$shareKey = $this->getShareKey($path, $uid);
@@ -437,7 +437,7 @@  discard block
 block discarded – undo
437 437
 	 */
438 438
 	public function getVersion($path, View $view) {
439 439
 		$fileInfo = $view->getFileInfo($path);
440
-		if($fileInfo === false) {
440
+		if ($fileInfo === false) {
441 441
 			return 0;
442 442
 		}
443 443
 		return $fileInfo->getEncryptedVersion();
@@ -451,9 +451,9 @@  discard block
 block discarded – undo
451 451
 	 * @param View $view
452 452
 	 */
453 453
 	public function setVersion($path, $version, View $view) {
454
-		$fileInfo= $view->getFileInfo($path);
454
+		$fileInfo = $view->getFileInfo($path);
455 455
 
456
-		if($fileInfo !== false) {
456
+		if ($fileInfo !== false) {
457 457
 			$cache = $fileInfo->getStorage()->getCache();
458 458
 			$cache->update($fileInfo->getId(), ['encrypted' => $version, 'encryptedVersion' => $version]);
459 459
 		}
@@ -482,7 +482,7 @@  discard block
 block discarded – undo
482 482
 	public function deleteShareKey($path, $keyId) {
483 483
 		return $this->keyStorage->deleteFileKey(
484 484
 			$path,
485
-			$keyId . '.' . $this->shareKeyId,
485
+			$keyId.'.'.$this->shareKeyId,
486 486
 			Encryption::ID);
487 487
 	}
488 488
 
@@ -493,7 +493,7 @@  discard block
 block discarded – undo
493 493
 	 * @return mixed
494 494
 	 */
495 495
 	public function getShareKey($path, $uid) {
496
-		$keyId = $uid . '.' . $this->shareKeyId;
496
+		$keyId = $uid.'.'.$this->shareKeyId;
497 497
 		return $this->keyStorage->getFileKey($path, $keyId, Encryption::ID);
498 498
 	}
499 499
 
@@ -555,7 +555,7 @@  discard block
 block discarded – undo
555 555
 	 * @return string
556 556
 	 */
557 557
 	public function getPublicShareKey() {
558
-		return $this->keyStorage->getSystemUserKey($this->publicShareKeyId . '.publicKey', Encryption::ID);
558
+		return $this->keyStorage->getSystemUserKey($this->publicShareKeyId.'.publicKey', Encryption::ID);
559 559
 	}
560 560
 
561 561
 	/**
@@ -625,7 +625,7 @@  discard block
 block discarded – undo
625 625
 	 * @return string returns openssl key
626 626
 	 */
627 627
 	public function getSystemPrivateKey($keyId) {
628
-		return $this->keyStorage->getSystemUserKey($keyId . '.' . $this->privateKeyId, Encryption::ID);
628
+		return $this->keyStorage->getSystemUserKey($keyId.'.'.$this->privateKeyId, Encryption::ID);
629 629
 	}
630 630
 
631 631
 	/**
@@ -635,7 +635,7 @@  discard block
 block discarded – undo
635 635
 	 */
636 636
 	public function setSystemPrivateKey($keyId, $key) {
637 637
 		return $this->keyStorage->setSystemUserKey(
638
-			$keyId . '.' . $this->privateKeyId,
638
+			$keyId.'.'.$this->privateKeyId,
639 639
 			$key,
640 640
 			Encryption::ID);
641 641
 	}
@@ -675,7 +675,7 @@  discard block
 block discarded – undo
675 675
 	 */
676 676
 	public function getMasterKeyPassword() {
677 677
 		$password = $this->config->getSystemValue('secret');
678
-		if (empty($password)){
678
+		if (empty($password)) {
679 679
 			throw new \Exception('Can not get secret from ownCloud instance');
680 680
 		}
681 681
 
@@ -697,6 +697,6 @@  discard block
 block discarded – undo
697 697
 	 * @return string
698 698
 	 */
699 699
 	public function getPublicMasterKey() {
700
-		return $this->keyStorage->getSystemUserKey($this->masterKeyId . '.publicKey', Encryption::ID);
700
+		return $this->keyStorage->getSystemUserKey($this->masterKeyId.'.publicKey', Encryption::ID);
701 701
 	}
702 702
 }
Please login to merge, or discard this patch.