Completed
Push — stable10 ( 0bd063...d606d3 )
by Morris
58s
created
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.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -95,15 +95,15 @@  discard block
 block discarded – undo
95 95
 			$tags = $this->tagManager->getTagsByIds([$tagId]);
96 96
 			$tag = current($tags);
97 97
 			if (!$this->tagManager->canUserSeeTag($tag, $this->user)) {
98
-				throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
98
+				throw new PreconditionFailed('Tag with id '.$tagId.' does not exist, cannot assign');
99 99
 			}
100 100
 			if (!$this->tagManager->canUserAssignTag($tag, $this->user)) {
101
-				throw new Forbidden('No permission to assign tag ' . $tagId);
101
+				throw new Forbidden('No permission to assign tag '.$tagId);
102 102
 			}
103 103
 
104 104
 			$this->tagMapper->assignTags($this->objectId, $this->objectType, $tagId);
105 105
 		} catch (TagNotFoundException $e) {
106
-			throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
106
+			throw new PreconditionFailed('Tag with id '.$tagId.' does not exist, cannot assign');
107 107
 		}
108 108
 	}
109 109
 
@@ -120,11 +120,11 @@  discard block
 block discarded – undo
120 120
 					return $this->makeNode($tag);
121 121
 				}
122 122
 			}
123
-			throw new NotFound('Tag with id ' . $tagId . ' not present for object ' . $this->objectId);
123
+			throw new NotFound('Tag with id '.$tagId.' not present for object '.$this->objectId);
124 124
 		} catch (\InvalidArgumentException $e) {
125 125
 			throw new BadRequest('Invalid tag id', 0, $e);
126 126
 		} catch (TagNotFoundException $e) {
127
-			throw new NotFound('Tag with id ' . $tagId . ' not found', 0, $e);
127
+			throw new NotFound('Tag with id '.$tagId.' not found', 0, $e);
128 128
 		}
129 129
 	}
130 130
 
Please login to merge, or discard this patch.
Indentation   +165 added lines, -165 removed lines patch added patch discarded remove patch
@@ -39,169 +39,169 @@
 block discarded – undo
39 39
  */
40 40
 class SystemTagsObjectMappingCollection implements ICollection {
41 41
 
42
-	/**
43
-	 * @var string
44
-	 */
45
-	private $objectId;
46
-
47
-	/**
48
-	 * @var string
49
-	 */
50
-	private $objectType;
51
-
52
-	/**
53
-	 * @var ISystemTagManager
54
-	 */
55
-	private $tagManager;
56
-
57
-	/**
58
-	 * @var ISystemTagObjectMapper
59
-	 */
60
-	private $tagMapper;
61
-
62
-	/**
63
-	 * User
64
-	 *
65
-	 * @var IUser
66
-	 */
67
-	private $user;
68
-
69
-
70
-	/**
71
-	 * Constructor
72
-	 *
73
-	 * @param string $objectId object id
74
-	 * @param string $objectType object type
75
-	 * @param IUser $user user
76
-	 * @param ISystemTagManager $tagManager tag manager
77
-	 * @param ISystemTagObjectMapper $tagMapper tag mapper
78
-	 */
79
-	public function __construct(
80
-		$objectId,
81
-		$objectType,
82
-		IUser $user,
83
-		ISystemTagManager $tagManager,
84
-		ISystemTagObjectMapper $tagMapper
85
-	) {
86
-		$this->tagManager = $tagManager;
87
-		$this->tagMapper = $tagMapper;
88
-		$this->objectId = $objectId;
89
-		$this->objectType = $objectType;
90
-		$this->user = $user;
91
-	}
92
-
93
-	function createFile($tagId, $data = null) {
94
-		try {
95
-			$tags = $this->tagManager->getTagsByIds([$tagId]);
96
-			$tag = current($tags);
97
-			if (!$this->tagManager->canUserSeeTag($tag, $this->user)) {
98
-				throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
99
-			}
100
-			if (!$this->tagManager->canUserAssignTag($tag, $this->user)) {
101
-				throw new Forbidden('No permission to assign tag ' . $tagId);
102
-			}
103
-
104
-			$this->tagMapper->assignTags($this->objectId, $this->objectType, $tagId);
105
-		} catch (TagNotFoundException $e) {
106
-			throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
107
-		}
108
-	}
109
-
110
-	function createDirectory($name) {
111
-		throw new Forbidden('Permission denied to create collections');
112
-	}
113
-
114
-	function getChild($tagId) {
115
-		try {
116
-			if ($this->tagMapper->haveTag([$this->objectId], $this->objectType, $tagId, true)) {
117
-				$tag = $this->tagManager->getTagsByIds([$tagId]);
118
-				$tag = current($tag);
119
-				if ($this->tagManager->canUserSeeTag($tag, $this->user)) {
120
-					return $this->makeNode($tag);
121
-				}
122
-			}
123
-			throw new NotFound('Tag with id ' . $tagId . ' not present for object ' . $this->objectId);
124
-		} catch (\InvalidArgumentException $e) {
125
-			throw new BadRequest('Invalid tag id', 0, $e);
126
-		} catch (TagNotFoundException $e) {
127
-			throw new NotFound('Tag with id ' . $tagId . ' not found', 0, $e);
128
-		}
129
-	}
130
-
131
-	function getChildren() {
132
-		$tagIds = current($this->tagMapper->getTagIdsForObjects([$this->objectId], $this->objectType));
133
-		if (empty($tagIds)) {
134
-			return [];
135
-		}
136
-		$tags = $this->tagManager->getTagsByIds($tagIds);
137
-
138
-		// filter out non-visible tags
139
-		$tags = array_filter($tags, function($tag) {
140
-			return $this->tagManager->canUserSeeTag($tag, $this->user);
141
-		});
142
-
143
-		return array_values(array_map(function($tag) {
144
-			return $this->makeNode($tag);
145
-		}, $tags));
146
-	}
147
-
148
-	function childExists($tagId) {
149
-		try {
150
-			$result = ($this->tagMapper->haveTag([$this->objectId], $this->objectType, $tagId, true));
151
-
152
-			if ($result) {
153
-				$tags = $this->tagManager->getTagsByIds([$tagId]);
154
-				$tag = current($tags);
155
-				if (!$this->tagManager->canUserSeeTag($tag, $this->user)) {
156
-					return false;
157
-				}
158
-			}
159
-
160
-			return $result;
161
-		} catch (\InvalidArgumentException $e) {
162
-			throw new BadRequest('Invalid tag id', 0, $e);
163
-		} catch (TagNotFoundException $e) {
164
-			return false;
165
-		}
166
-	}
167
-
168
-	function delete() {
169
-		throw new Forbidden('Permission denied to delete this collection');
170
-	}
171
-
172
-	function getName() {
173
-		return $this->objectId;
174
-	}
175
-
176
-	function setName($name) {
177
-		throw new Forbidden('Permission denied to rename this collection');
178
-	}
179
-
180
-	/**
181
-	 * Returns the last modification time, as a unix timestamp
182
-	 *
183
-	 * @return int
184
-	 */
185
-	function getLastModified() {
186
-		return null;
187
-	}
188
-
189
-	/**
190
-	 * Create a sabre node for the mapping of the 
191
-	 * given system tag to the collection's object
192
-	 *
193
-	 * @param ISystemTag $tag
194
-	 *
195
-	 * @return SystemTagNode
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 SystemTagNode
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.
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.
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.
Indentation   +215 added lines, -215 removed lines patch added patch discarded remove patch
@@ -35,220 +35,220 @@
 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
-	/**
54
-	 * @param string $path
55
-	 * @param string $mode
56
-	 * @param int $options
57
-	 * @param string &$opened_path
58
-	 * @return bool
59
-	 */
60
-	public function stream_open($path, $mode, $options, &$opened_path) {
61
-		$this->loadContext('assembly');
62
-
63
-		// sort the nodes
64
-		$nodes = $this->nodes;
65
-		// http://stackoverflow.com/a/10985500
66
-		@usort($nodes, function(IFile $a, IFile $b) {
67
-			return strcmp($a->getName(), $b->getName());
68
-		});
69
-		$this->nodes = $nodes;
70
-
71
-		// build additional information
72
-		$this->sortedNodes = [];
73
-		$start = 0;
74
-		foreach($this->nodes as $node) {
75
-			$size = $node->getSize();
76
-			$name = $node->getName();
77
-			$this->sortedNodes[$name] = ['node' => $node, 'start' => $start, 'end' => $start + $size];
78
-			$start += $size;
79
-			$this->size = $start;
80
-		}
81
-		return true;
82
-	}
83
-
84
-	/**
85
-	 * @param string $offset
86
-	 * @param int $whence
87
-	 * @return bool
88
-	 */
89
-	public function stream_seek($offset, $whence = SEEK_SET) {
90
-		return false;
91
-	}
92
-
93
-	/**
94
-	 * @return int
95
-	 */
96
-	public function stream_tell() {
97
-		return $this->pos;
98
-	}
99
-
100
-	/**
101
-	 * @param int $count
102
-	 * @return string
103
-	 */
104
-	public function stream_read($count) {
105
-
106
-		list($node, $posInNode) = $this->getNodeForPosition($this->pos);
107
-		if (is_null($node)) {
108
-			return null;
109
-		}
110
-		$stream = $this->getStream($node);
111
-
112
-		fseek($stream, $posInNode);
113
-		$data = fread($stream, $count);
114
-		$read = strlen($data);
115
-
116
-		// update position
117
-		$this->pos += $read;
118
-		return $data;
119
-	}
120
-
121
-	/**
122
-	 * @param string $data
123
-	 * @return int
124
-	 */
125
-	public function stream_write($data) {
126
-		return false;
127
-	}
128
-
129
-	/**
130
-	 * @param int $option
131
-	 * @param int $arg1
132
-	 * @param int $arg2
133
-	 * @return bool
134
-	 */
135
-	public function stream_set_option($option, $arg1, $arg2) {
136
-		return false;
137
-	}
138
-
139
-	/**
140
-	 * @param int $size
141
-	 * @return bool
142
-	 */
143
-	public function stream_truncate($size) {
144
-		return false;
145
-	}
146
-
147
-	/**
148
-	 * @return array
149
-	 */
150
-	public function stream_stat() {
151
-		return [];
152
-	}
153
-
154
-	/**
155
-	 * @param int $operation
156
-	 * @return bool
157
-	 */
158
-	public function stream_lock($operation) {
159
-		return false;
160
-	}
161
-
162
-	/**
163
-	 * @return bool
164
-	 */
165
-	public function stream_flush() {
166
-		return false;
167
-	}
168
-
169
-	/**
170
-	 * @return bool
171
-	 */
172
-	public function stream_eof() {
173
-		return $this->pos >= $this->size;
174
-	}
175
-
176
-	/**
177
-	 * @return bool
178
-	 */
179
-	public function stream_close() {
180
-		return true;
181
-	}
182
-
183
-
184
-	/**
185
-	 * Load the source from the stream context and return the context options
186
-	 *
187
-	 * @param string $name
188
-	 * @return array
189
-	 * @throws \Exception
190
-	 */
191
-	protected function loadContext($name) {
192
-		$context = stream_context_get_options($this->context);
193
-		if (isset($context[$name])) {
194
-			$context = $context[$name];
195
-		} else {
196
-			throw new \BadMethodCallException('Invalid context, "' . $name . '" options not set');
197
-		}
198
-		if (isset($context['nodes']) and is_array($context['nodes'])) {
199
-			$this->nodes = $context['nodes'];
200
-		} else {
201
-			throw new \BadMethodCallException('Invalid context, nodes not set');
202
-		}
203
-		return $context;
204
-	}
205
-
206
-	/**
207
-	 * @param IFile[] $nodes
208
-	 * @return resource
209
-	 *
210
-	 * @throws \BadMethodCallException
211
-	 */
212
-	public static function wrap(array $nodes) {
213
-		$context = stream_context_create([
214
-			'assembly' => [
215
-				'nodes' => $nodes]
216
-		]);
217
-		stream_wrapper_register('assembly', '\OCA\DAV\Upload\AssemblyStream');
218
-		try {
219
-			$wrapped = fopen('assembly://', 'r', null, $context);
220
-		} catch (\BadMethodCallException $e) {
221
-			stream_wrapper_unregister('assembly');
222
-			throw $e;
223
-		}
224
-		stream_wrapper_unregister('assembly');
225
-		return $wrapped;
226
-	}
227
-
228
-	/**
229
-	 * @param $pos
230
-	 * @return IFile | null
231
-	 */
232
-	private function getNodeForPosition($pos) {
233
-		foreach($this->sortedNodes as $node) {
234
-			if ($pos >= $node['start'] && $pos < $node['end']) {
235
-				return [$node['node'], $pos - $node['start']];
236
-			}
237
-		}
238
-		return null;
239
-	}
240
-
241
-	/**
242
-	 * @param IFile $node
243
-	 * @return resource
244
-	 */
245
-	private function getStream(IFile $node) {
246
-		$data = $node->get();
247
-		if (is_resource($data)) {
248
-			return $data;
249
-		}
250
-
251
-		return fopen('data://text/plain,' . $data,'r');
252
-	}
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
+    /**
54
+     * @param string $path
55
+     * @param string $mode
56
+     * @param int $options
57
+     * @param string &$opened_path
58
+     * @return bool
59
+     */
60
+    public function stream_open($path, $mode, $options, &$opened_path) {
61
+        $this->loadContext('assembly');
62
+
63
+        // sort the nodes
64
+        $nodes = $this->nodes;
65
+        // http://stackoverflow.com/a/10985500
66
+        @usort($nodes, function(IFile $a, IFile $b) {
67
+            return strcmp($a->getName(), $b->getName());
68
+        });
69
+        $this->nodes = $nodes;
70
+
71
+        // build additional information
72
+        $this->sortedNodes = [];
73
+        $start = 0;
74
+        foreach($this->nodes as $node) {
75
+            $size = $node->getSize();
76
+            $name = $node->getName();
77
+            $this->sortedNodes[$name] = ['node' => $node, 'start' => $start, 'end' => $start + $size];
78
+            $start += $size;
79
+            $this->size = $start;
80
+        }
81
+        return true;
82
+    }
83
+
84
+    /**
85
+     * @param string $offset
86
+     * @param int $whence
87
+     * @return bool
88
+     */
89
+    public function stream_seek($offset, $whence = SEEK_SET) {
90
+        return false;
91
+    }
92
+
93
+    /**
94
+     * @return int
95
+     */
96
+    public function stream_tell() {
97
+        return $this->pos;
98
+    }
99
+
100
+    /**
101
+     * @param int $count
102
+     * @return string
103
+     */
104
+    public function stream_read($count) {
105
+
106
+        list($node, $posInNode) = $this->getNodeForPosition($this->pos);
107
+        if (is_null($node)) {
108
+            return null;
109
+        }
110
+        $stream = $this->getStream($node);
111
+
112
+        fseek($stream, $posInNode);
113
+        $data = fread($stream, $count);
114
+        $read = strlen($data);
115
+
116
+        // update position
117
+        $this->pos += $read;
118
+        return $data;
119
+    }
120
+
121
+    /**
122
+     * @param string $data
123
+     * @return int
124
+     */
125
+    public function stream_write($data) {
126
+        return false;
127
+    }
128
+
129
+    /**
130
+     * @param int $option
131
+     * @param int $arg1
132
+     * @param int $arg2
133
+     * @return bool
134
+     */
135
+    public function stream_set_option($option, $arg1, $arg2) {
136
+        return false;
137
+    }
138
+
139
+    /**
140
+     * @param int $size
141
+     * @return bool
142
+     */
143
+    public function stream_truncate($size) {
144
+        return false;
145
+    }
146
+
147
+    /**
148
+     * @return array
149
+     */
150
+    public function stream_stat() {
151
+        return [];
152
+    }
153
+
154
+    /**
155
+     * @param int $operation
156
+     * @return bool
157
+     */
158
+    public function stream_lock($operation) {
159
+        return false;
160
+    }
161
+
162
+    /**
163
+     * @return bool
164
+     */
165
+    public function stream_flush() {
166
+        return false;
167
+    }
168
+
169
+    /**
170
+     * @return bool
171
+     */
172
+    public function stream_eof() {
173
+        return $this->pos >= $this->size;
174
+    }
175
+
176
+    /**
177
+     * @return bool
178
+     */
179
+    public function stream_close() {
180
+        return true;
181
+    }
182
+
183
+
184
+    /**
185
+     * Load the source from the stream context and return the context options
186
+     *
187
+     * @param string $name
188
+     * @return array
189
+     * @throws \Exception
190
+     */
191
+    protected function loadContext($name) {
192
+        $context = stream_context_get_options($this->context);
193
+        if (isset($context[$name])) {
194
+            $context = $context[$name];
195
+        } else {
196
+            throw new \BadMethodCallException('Invalid context, "' . $name . '" options not set');
197
+        }
198
+        if (isset($context['nodes']) and is_array($context['nodes'])) {
199
+            $this->nodes = $context['nodes'];
200
+        } else {
201
+            throw new \BadMethodCallException('Invalid context, nodes not set');
202
+        }
203
+        return $context;
204
+    }
205
+
206
+    /**
207
+     * @param IFile[] $nodes
208
+     * @return resource
209
+     *
210
+     * @throws \BadMethodCallException
211
+     */
212
+    public static function wrap(array $nodes) {
213
+        $context = stream_context_create([
214
+            'assembly' => [
215
+                'nodes' => $nodes]
216
+        ]);
217
+        stream_wrapper_register('assembly', '\OCA\DAV\Upload\AssemblyStream');
218
+        try {
219
+            $wrapped = fopen('assembly://', 'r', null, $context);
220
+        } catch (\BadMethodCallException $e) {
221
+            stream_wrapper_unregister('assembly');
222
+            throw $e;
223
+        }
224
+        stream_wrapper_unregister('assembly');
225
+        return $wrapped;
226
+    }
227
+
228
+    /**
229
+     * @param $pos
230
+     * @return IFile | null
231
+     */
232
+    private function getNodeForPosition($pos) {
233
+        foreach($this->sortedNodes as $node) {
234
+            if ($pos >= $node['start'] && $pos < $node['end']) {
235
+                return [$node['node'], $pos - $node['start']];
236
+            }
237
+        }
238
+        return null;
239
+    }
240
+
241
+    /**
242
+     * @param IFile $node
243
+     * @return resource
244
+     */
245
+    private function getStream(IFile $node) {
246
+        $data = $node->get();
247
+        if (is_resource($data)) {
248
+            return $data;
249
+        }
250
+
251
+        return fopen('data://text/plain,' . $data,'r');
252
+    }
253 253
 
254 254
 }
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   +518 added lines, -518 removed lines patch added patch discarded remove patch
@@ -43,522 +43,522 @@
 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->decryptAllModeActivated()) {
181
-			$encryptedFileKey = $this->keyManager->getEncryptedFileKey($this->path);
182
-			$shareKey = $this->keyManager->getShareKey($this->path, $this->session->getDecryptAllUid());
183
-			$this->fileKey = $this->crypt->multiKeyDecrypt($encryptedFileKey,
184
-				$shareKey,
185
-				$this->session->getDecryptAllKey());
186
-		} else {
187
-			$this->fileKey = $this->keyManager->getFileKey($this->path, $this->user);
188
-		}
189
-
190
-		// always use the version from the original file, also part files
191
-		// need to have a correct version number if they get moved over to the
192
-		// final location
193
-		$this->version = (int)$this->keyManager->getVersion($this->stripPartFileExtension($path), new View());
194
-
195
-		if (
196
-			$mode === 'w'
197
-			|| $mode === 'w+'
198
-			|| $mode === 'wb'
199
-			|| $mode === 'wb+'
200
-		) {
201
-			$this->isWriteOperation = true;
202
-			if (empty($this->fileKey)) {
203
-				$this->fileKey = $this->crypt->generateFileKey();
204
-			}
205
-		} else {
206
-			// if we read a part file we need to increase the version by 1
207
-			// because the version number was also increased by writing
208
-			// the part file
209
-			if(Scanner::isPartialFile($path)) {
210
-				$this->version = $this->version + 1;
211
-			}
212
-		}
213
-
214
-		if ($this->isWriteOperation) {
215
-			$this->cipher = $this->crypt->getCipher();
216
-		} elseif (isset($header['cipher'])) {
217
-			$this->cipher = $header['cipher'];
218
-		} else {
219
-			// if we read a file without a header we fall-back to the legacy cipher
220
-			// which was used in <=oC6
221
-			$this->cipher = $this->crypt->getLegacyCipher();
222
-		}
223
-
224
-		return array('cipher' => $this->cipher, 'signed' => 'true');
225
-	}
226
-
227
-	/**
228
-	 * last chunk received. This is the place where you can perform some final
229
-	 * operation and return some remaining data if something is left in your
230
-	 * buffer.
231
-	 *
232
-	 * @param string $path to the file
233
-	 * @param int $position
234
-	 * @return string remained data which should be written to the file in case
235
-	 *                of a write operation
236
-	 * @throws PublicKeyMissingException
237
-	 * @throws \Exception
238
-	 * @throws \OCA\Encryption\Exceptions\MultiKeyEncryptException
239
-	 */
240
-	public function end($path, $position = 0) {
241
-		$result = '';
242
-		if ($this->isWriteOperation) {
243
-			$this->keyManager->setVersion($path, $this->version + 1, new View());
244
-			// in case of a part file we remember the new signature versions
245
-			// the version will be set later on update.
246
-			// This way we make sure that other apps listening to the pre-hooks
247
-			// still get the old version which should be the correct value for them
248
-			if (Scanner::isPartialFile($path)) {
249
-				self::$rememberVersion[$this->stripPartFileExtension($path)] = $this->version + 1;
250
-			}
251
-			if (!empty($this->writeCache)) {
252
-				$result = $this->crypt->symmetricEncryptFileContent($this->writeCache, $this->fileKey, $this->version + 1, $position);
253
-				$this->writeCache = '';
254
-			}
255
-			$publicKeys = array();
256
-			if ($this->useMasterPassword === true) {
257
-				$publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey();
258
-			} else {
259
-				foreach ($this->accessList['users'] as $uid) {
260
-					try {
261
-						$publicKeys[$uid] = $this->keyManager->getPublicKey($uid);
262
-					} catch (PublicKeyMissingException $e) {
263
-						$this->logger->warning(
264
-							'no public key found for user "{uid}", user will not be able to read the file',
265
-							['app' => 'encryption', 'uid' => $uid]
266
-						);
267
-						// if the public key of the owner is missing we should fail
268
-						if ($uid === $this->user) {
269
-							throw $e;
270
-						}
271
-					}
272
-				}
273
-			}
274
-
275
-			$publicKeys = $this->keyManager->addSystemKeys($this->accessList, $publicKeys, $this->user);
276
-			$encryptedKeyfiles = $this->crypt->multiKeyEncrypt($this->fileKey, $publicKeys);
277
-			$this->keyManager->setAllFileKeys($this->path, $encryptedKeyfiles);
278
-		}
279
-		return $result;
280
-	}
281
-
282
-	/**
283
-	 * encrypt data
284
-	 *
285
-	 * @param string $data you want to encrypt
286
-	 * @param int $position
287
-	 * @return string encrypted data
288
-	 */
289
-	public function encrypt($data, $position = 0) {
290
-		// If extra data is left over from the last round, make sure it
291
-		// is integrated into the next block
292
-		if ($this->writeCache) {
293
-
294
-			// Concat writeCache to start of $data
295
-			$data = $this->writeCache . $data;
296
-
297
-			// Clear the write cache, ready for reuse - it has been
298
-			// flushed and its old contents processed
299
-			$this->writeCache = '';
300
-
301
-		}
302
-
303
-		$encrypted = '';
304
-		// While there still remains some data to be processed & written
305
-		while (strlen($data) > 0) {
306
-
307
-			// Remaining length for this iteration, not of the
308
-			// entire file (may be greater than 8192 bytes)
309
-			$remainingLength = strlen($data);
310
-
311
-			// If data remaining to be written is less than the
312
-			// size of 1 6126 byte block
313
-			if ($remainingLength < $this->unencryptedBlockSizeSigned) {
314
-
315
-				// Set writeCache to contents of $data
316
-				// The writeCache will be carried over to the
317
-				// next write round, and added to the start of
318
-				// $data to ensure that written blocks are
319
-				// always the correct length. If there is still
320
-				// data in writeCache after the writing round
321
-				// has finished, then the data will be written
322
-				// to disk by $this->flush().
323
-				$this->writeCache = $data;
324
-
325
-				// Clear $data ready for next round
326
-				$data = '';
327
-
328
-			} else {
329
-
330
-				// Read the chunk from the start of $data
331
-				$chunk = substr($data, 0, $this->unencryptedBlockSizeSigned);
332
-
333
-				$encrypted .= $this->crypt->symmetricEncryptFileContent($chunk, $this->fileKey, $this->version + 1, $position);
334
-
335
-				// Remove the chunk we just processed from
336
-				// $data, leaving only unprocessed data in $data
337
-				// var, for handling on the next round
338
-				$data = substr($data, $this->unencryptedBlockSizeSigned);
339
-
340
-			}
341
-
342
-		}
343
-
344
-		return $encrypted;
345
-	}
346
-
347
-	/**
348
-	 * decrypt data
349
-	 *
350
-	 * @param string $data you want to decrypt
351
-	 * @param int $position
352
-	 * @return string decrypted data
353
-	 * @throws DecryptionFailedException
354
-	 */
355
-	public function decrypt($data, $position = 0) {
356
-		if (empty($this->fileKey)) {
357
-			$msg = 'Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.';
358
-			$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.');
359
-			$this->logger->error($msg);
360
-
361
-			throw new DecryptionFailedException($msg, $hint);
362
-		}
363
-
364
-		return $this->crypt->symmetricDecryptFileContent($data, $this->fileKey, $this->cipher, $this->version, $position);
365
-	}
366
-
367
-	/**
368
-	 * update encrypted file, e.g. give additional users access to the file
369
-	 *
370
-	 * @param string $path path to the file which should be updated
371
-	 * @param string $uid of the user who performs the operation
372
-	 * @param array $accessList who has access to the file contains the key 'users' and 'public'
373
-	 * @return boolean
374
-	 */
375
-	public function update($path, $uid, array $accessList) {
376
-
377
-		if (empty($accessList)) {
378
-			if (isset(self::$rememberVersion[$path])) {
379
-				$this->keyManager->setVersion($path, self::$rememberVersion[$path], new View());
380
-				unset(self::$rememberVersion[$path]);
381
-			}
382
-			return;
383
-		}
384
-
385
-		$fileKey = $this->keyManager->getFileKey($path, $uid);
386
-
387
-		if (!empty($fileKey)) {
388
-
389
-			$publicKeys = array();
390
-			if ($this->useMasterPassword === true) {
391
-				$publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey();
392
-			} else {
393
-				foreach ($accessList['users'] as $user) {
394
-					try {
395
-						$publicKeys[$user] = $this->keyManager->getPublicKey($user);
396
-					} catch (PublicKeyMissingException $e) {
397
-						$this->logger->warning('Could not encrypt file for ' . $user . ': ' . $e->getMessage());
398
-					}
399
-				}
400
-			}
401
-
402
-			$publicKeys = $this->keyManager->addSystemKeys($accessList, $publicKeys, $uid);
403
-
404
-			$encryptedFileKey = $this->crypt->multiKeyEncrypt($fileKey, $publicKeys);
405
-
406
-			$this->keyManager->deleteAllFileKeys($path);
407
-
408
-			$this->keyManager->setAllFileKeys($path, $encryptedFileKey);
409
-
410
-		} else {
411
-			$this->logger->debug('no file key found, we assume that the file "{file}" is not encrypted',
412
-				array('file' => $path, 'app' => 'encryption'));
413
-
414
-			return false;
415
-		}
416
-
417
-		return true;
418
-	}
419
-
420
-	/**
421
-	 * should the file be encrypted or not
422
-	 *
423
-	 * @param string $path
424
-	 * @return boolean
425
-	 */
426
-	public function shouldEncrypt($path) {
427
-		if ($this->util->shouldEncryptHomeStorage() === false) {
428
-			$storage = $this->util->getStorage($path);
429
-			if ($storage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
430
-				return false;
431
-			}
432
-		}
433
-		$parts = explode('/', $path);
434
-		if (count($parts) < 4) {
435
-			return false;
436
-		}
437
-
438
-		if ($parts[2] == 'files') {
439
-			return true;
440
-		}
441
-		if ($parts[2] == 'files_versions') {
442
-			return true;
443
-		}
444
-		if ($parts[2] == 'files_trashbin') {
445
-			return true;
446
-		}
447
-
448
-		return false;
449
-	}
450
-
451
-	/**
452
-	 * get size of the unencrypted payload per block.
453
-	 * ownCloud read/write files with a block size of 8192 byte
454
-	 *
455
-	 * @param bool $signed
456
-	 * @return int
457
-	 */
458
-	public function getUnencryptedBlockSize($signed = false) {
459
-		if ($signed === false) {
460
-			return $this->unencryptedBlockSize;
461
-		}
462
-
463
-		return $this->unencryptedBlockSizeSigned;
464
-	}
465
-
466
-	/**
467
-	 * check if the encryption module is able to read the file,
468
-	 * e.g. if all encryption keys exists
469
-	 *
470
-	 * @param string $path
471
-	 * @param string $uid user for whom we want to check if he can read the file
472
-	 * @return bool
473
-	 * @throws DecryptionFailedException
474
-	 */
475
-	public function isReadable($path, $uid) {
476
-		$fileKey = $this->keyManager->getFileKey($path, $uid);
477
-		if (empty($fileKey)) {
478
-			$owner = $this->util->getOwner($path);
479
-			if ($owner !== $uid) {
480
-				// if it is a shared file we throw a exception with a useful
481
-				// error message because in this case it means that the file was
482
-				// shared with the user at a point where the user didn't had a
483
-				// valid private/public key
484
-				$msg = 'Encryption module "' . $this->getDisplayName() .
485
-					'" is not able to read ' . $path;
486
-				$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.');
487
-				$this->logger->warning($msg);
488
-				throw new DecryptionFailedException($msg, $hint);
489
-			}
490
-			return false;
491
-		}
492
-
493
-		return true;
494
-	}
495
-
496
-	/**
497
-	 * Initial encryption of all files
498
-	 *
499
-	 * @param InputInterface $input
500
-	 * @param OutputInterface $output write some status information to the terminal during encryption
501
-	 */
502
-	public function encryptAll(InputInterface $input, OutputInterface $output) {
503
-		$this->encryptAll->encryptAll($input, $output);
504
-	}
505
-
506
-	/**
507
-	 * prepare module to perform decrypt all operation
508
-	 *
509
-	 * @param InputInterface $input
510
-	 * @param OutputInterface $output
511
-	 * @param string $user
512
-	 * @return bool
513
-	 */
514
-	public function prepareDecryptAll(InputInterface $input, OutputInterface $output, $user = '') {
515
-		return $this->decryptAll->prepare($input, $output, $user);
516
-	}
517
-
518
-
519
-	/**
520
-	 * @param string $path
521
-	 * @return string
522
-	 */
523
-	protected function getPathToRealFile($path) {
524
-		$realPath = $path;
525
-		$parts = explode('/', $path);
526
-		if ($parts[2] === 'files_versions') {
527
-			$realPath = '/' . $parts[1] . '/files/' . implode('/', array_slice($parts, 3));
528
-			$length = strrpos($realPath, '.');
529
-			$realPath = substr($realPath, 0, $length);
530
-		}
531
-
532
-		return $realPath;
533
-	}
534
-
535
-	/**
536
-	 * remove .part file extension and the ocTransferId from the file to get the
537
-	 * original file name
538
-	 *
539
-	 * @param string $path
540
-	 * @return string
541
-	 */
542
-	protected function stripPartFileExtension($path) {
543
-		if (pathinfo($path, PATHINFO_EXTENSION) === 'part') {
544
-			$pos = strrpos($path, '.', -6);
545
-			$path = substr($path, 0, $pos);
546
-		}
547
-
548
-		return $path;
549
-	}
550
-
551
-	/**
552
-	 * Check if the module is ready to be used by that specific user.
553
-	 * In case a module is not ready - because e.g. key pairs have not been generated
554
-	 * upon login this method can return false before any operation starts and might
555
-	 * cause issues during operations.
556
-	 *
557
-	 * @param string $user
558
-	 * @return boolean
559
-	 * @since 9.1.0
560
-	 */
561
-	public function isReadyForUser($user) {
562
-		return $this->keyManager->userHasKeys($user);
563
-	}
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->decryptAllModeActivated()) {
181
+            $encryptedFileKey = $this->keyManager->getEncryptedFileKey($this->path);
182
+            $shareKey = $this->keyManager->getShareKey($this->path, $this->session->getDecryptAllUid());
183
+            $this->fileKey = $this->crypt->multiKeyDecrypt($encryptedFileKey,
184
+                $shareKey,
185
+                $this->session->getDecryptAllKey());
186
+        } else {
187
+            $this->fileKey = $this->keyManager->getFileKey($this->path, $this->user);
188
+        }
189
+
190
+        // always use the version from the original file, also part files
191
+        // need to have a correct version number if they get moved over to the
192
+        // final location
193
+        $this->version = (int)$this->keyManager->getVersion($this->stripPartFileExtension($path), new View());
194
+
195
+        if (
196
+            $mode === 'w'
197
+            || $mode === 'w+'
198
+            || $mode === 'wb'
199
+            || $mode === 'wb+'
200
+        ) {
201
+            $this->isWriteOperation = true;
202
+            if (empty($this->fileKey)) {
203
+                $this->fileKey = $this->crypt->generateFileKey();
204
+            }
205
+        } else {
206
+            // if we read a part file we need to increase the version by 1
207
+            // because the version number was also increased by writing
208
+            // the part file
209
+            if(Scanner::isPartialFile($path)) {
210
+                $this->version = $this->version + 1;
211
+            }
212
+        }
213
+
214
+        if ($this->isWriteOperation) {
215
+            $this->cipher = $this->crypt->getCipher();
216
+        } elseif (isset($header['cipher'])) {
217
+            $this->cipher = $header['cipher'];
218
+        } else {
219
+            // if we read a file without a header we fall-back to the legacy cipher
220
+            // which was used in <=oC6
221
+            $this->cipher = $this->crypt->getLegacyCipher();
222
+        }
223
+
224
+        return array('cipher' => $this->cipher, 'signed' => 'true');
225
+    }
226
+
227
+    /**
228
+     * last chunk received. This is the place where you can perform some final
229
+     * operation and return some remaining data if something is left in your
230
+     * buffer.
231
+     *
232
+     * @param string $path to the file
233
+     * @param int $position
234
+     * @return string remained data which should be written to the file in case
235
+     *                of a write operation
236
+     * @throws PublicKeyMissingException
237
+     * @throws \Exception
238
+     * @throws \OCA\Encryption\Exceptions\MultiKeyEncryptException
239
+     */
240
+    public function end($path, $position = 0) {
241
+        $result = '';
242
+        if ($this->isWriteOperation) {
243
+            $this->keyManager->setVersion($path, $this->version + 1, new View());
244
+            // in case of a part file we remember the new signature versions
245
+            // the version will be set later on update.
246
+            // This way we make sure that other apps listening to the pre-hooks
247
+            // still get the old version which should be the correct value for them
248
+            if (Scanner::isPartialFile($path)) {
249
+                self::$rememberVersion[$this->stripPartFileExtension($path)] = $this->version + 1;
250
+            }
251
+            if (!empty($this->writeCache)) {
252
+                $result = $this->crypt->symmetricEncryptFileContent($this->writeCache, $this->fileKey, $this->version + 1, $position);
253
+                $this->writeCache = '';
254
+            }
255
+            $publicKeys = array();
256
+            if ($this->useMasterPassword === true) {
257
+                $publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey();
258
+            } else {
259
+                foreach ($this->accessList['users'] as $uid) {
260
+                    try {
261
+                        $publicKeys[$uid] = $this->keyManager->getPublicKey($uid);
262
+                    } catch (PublicKeyMissingException $e) {
263
+                        $this->logger->warning(
264
+                            'no public key found for user "{uid}", user will not be able to read the file',
265
+                            ['app' => 'encryption', 'uid' => $uid]
266
+                        );
267
+                        // if the public key of the owner is missing we should fail
268
+                        if ($uid === $this->user) {
269
+                            throw $e;
270
+                        }
271
+                    }
272
+                }
273
+            }
274
+
275
+            $publicKeys = $this->keyManager->addSystemKeys($this->accessList, $publicKeys, $this->user);
276
+            $encryptedKeyfiles = $this->crypt->multiKeyEncrypt($this->fileKey, $publicKeys);
277
+            $this->keyManager->setAllFileKeys($this->path, $encryptedKeyfiles);
278
+        }
279
+        return $result;
280
+    }
281
+
282
+    /**
283
+     * encrypt data
284
+     *
285
+     * @param string $data you want to encrypt
286
+     * @param int $position
287
+     * @return string encrypted data
288
+     */
289
+    public function encrypt($data, $position = 0) {
290
+        // If extra data is left over from the last round, make sure it
291
+        // is integrated into the next block
292
+        if ($this->writeCache) {
293
+
294
+            // Concat writeCache to start of $data
295
+            $data = $this->writeCache . $data;
296
+
297
+            // Clear the write cache, ready for reuse - it has been
298
+            // flushed and its old contents processed
299
+            $this->writeCache = '';
300
+
301
+        }
302
+
303
+        $encrypted = '';
304
+        // While there still remains some data to be processed & written
305
+        while (strlen($data) > 0) {
306
+
307
+            // Remaining length for this iteration, not of the
308
+            // entire file (may be greater than 8192 bytes)
309
+            $remainingLength = strlen($data);
310
+
311
+            // If data remaining to be written is less than the
312
+            // size of 1 6126 byte block
313
+            if ($remainingLength < $this->unencryptedBlockSizeSigned) {
314
+
315
+                // Set writeCache to contents of $data
316
+                // The writeCache will be carried over to the
317
+                // next write round, and added to the start of
318
+                // $data to ensure that written blocks are
319
+                // always the correct length. If there is still
320
+                // data in writeCache after the writing round
321
+                // has finished, then the data will be written
322
+                // to disk by $this->flush().
323
+                $this->writeCache = $data;
324
+
325
+                // Clear $data ready for next round
326
+                $data = '';
327
+
328
+            } else {
329
+
330
+                // Read the chunk from the start of $data
331
+                $chunk = substr($data, 0, $this->unencryptedBlockSizeSigned);
332
+
333
+                $encrypted .= $this->crypt->symmetricEncryptFileContent($chunk, $this->fileKey, $this->version + 1, $position);
334
+
335
+                // Remove the chunk we just processed from
336
+                // $data, leaving only unprocessed data in $data
337
+                // var, for handling on the next round
338
+                $data = substr($data, $this->unencryptedBlockSizeSigned);
339
+
340
+            }
341
+
342
+        }
343
+
344
+        return $encrypted;
345
+    }
346
+
347
+    /**
348
+     * decrypt data
349
+     *
350
+     * @param string $data you want to decrypt
351
+     * @param int $position
352
+     * @return string decrypted data
353
+     * @throws DecryptionFailedException
354
+     */
355
+    public function decrypt($data, $position = 0) {
356
+        if (empty($this->fileKey)) {
357
+            $msg = 'Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.';
358
+            $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.');
359
+            $this->logger->error($msg);
360
+
361
+            throw new DecryptionFailedException($msg, $hint);
362
+        }
363
+
364
+        return $this->crypt->symmetricDecryptFileContent($data, $this->fileKey, $this->cipher, $this->version, $position);
365
+    }
366
+
367
+    /**
368
+     * update encrypted file, e.g. give additional users access to the file
369
+     *
370
+     * @param string $path path to the file which should be updated
371
+     * @param string $uid of the user who performs the operation
372
+     * @param array $accessList who has access to the file contains the key 'users' and 'public'
373
+     * @return boolean
374
+     */
375
+    public function update($path, $uid, array $accessList) {
376
+
377
+        if (empty($accessList)) {
378
+            if (isset(self::$rememberVersion[$path])) {
379
+                $this->keyManager->setVersion($path, self::$rememberVersion[$path], new View());
380
+                unset(self::$rememberVersion[$path]);
381
+            }
382
+            return;
383
+        }
384
+
385
+        $fileKey = $this->keyManager->getFileKey($path, $uid);
386
+
387
+        if (!empty($fileKey)) {
388
+
389
+            $publicKeys = array();
390
+            if ($this->useMasterPassword === true) {
391
+                $publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey();
392
+            } else {
393
+                foreach ($accessList['users'] as $user) {
394
+                    try {
395
+                        $publicKeys[$user] = $this->keyManager->getPublicKey($user);
396
+                    } catch (PublicKeyMissingException $e) {
397
+                        $this->logger->warning('Could not encrypt file for ' . $user . ': ' . $e->getMessage());
398
+                    }
399
+                }
400
+            }
401
+
402
+            $publicKeys = $this->keyManager->addSystemKeys($accessList, $publicKeys, $uid);
403
+
404
+            $encryptedFileKey = $this->crypt->multiKeyEncrypt($fileKey, $publicKeys);
405
+
406
+            $this->keyManager->deleteAllFileKeys($path);
407
+
408
+            $this->keyManager->setAllFileKeys($path, $encryptedFileKey);
409
+
410
+        } else {
411
+            $this->logger->debug('no file key found, we assume that the file "{file}" is not encrypted',
412
+                array('file' => $path, 'app' => 'encryption'));
413
+
414
+            return false;
415
+        }
416
+
417
+        return true;
418
+    }
419
+
420
+    /**
421
+     * should the file be encrypted or not
422
+     *
423
+     * @param string $path
424
+     * @return boolean
425
+     */
426
+    public function shouldEncrypt($path) {
427
+        if ($this->util->shouldEncryptHomeStorage() === false) {
428
+            $storage = $this->util->getStorage($path);
429
+            if ($storage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
430
+                return false;
431
+            }
432
+        }
433
+        $parts = explode('/', $path);
434
+        if (count($parts) < 4) {
435
+            return false;
436
+        }
437
+
438
+        if ($parts[2] == 'files') {
439
+            return true;
440
+        }
441
+        if ($parts[2] == 'files_versions') {
442
+            return true;
443
+        }
444
+        if ($parts[2] == 'files_trashbin') {
445
+            return true;
446
+        }
447
+
448
+        return false;
449
+    }
450
+
451
+    /**
452
+     * get size of the unencrypted payload per block.
453
+     * ownCloud read/write files with a block size of 8192 byte
454
+     *
455
+     * @param bool $signed
456
+     * @return int
457
+     */
458
+    public function getUnencryptedBlockSize($signed = false) {
459
+        if ($signed === false) {
460
+            return $this->unencryptedBlockSize;
461
+        }
462
+
463
+        return $this->unencryptedBlockSizeSigned;
464
+    }
465
+
466
+    /**
467
+     * check if the encryption module is able to read the file,
468
+     * e.g. if all encryption keys exists
469
+     *
470
+     * @param string $path
471
+     * @param string $uid user for whom we want to check if he can read the file
472
+     * @return bool
473
+     * @throws DecryptionFailedException
474
+     */
475
+    public function isReadable($path, $uid) {
476
+        $fileKey = $this->keyManager->getFileKey($path, $uid);
477
+        if (empty($fileKey)) {
478
+            $owner = $this->util->getOwner($path);
479
+            if ($owner !== $uid) {
480
+                // if it is a shared file we throw a exception with a useful
481
+                // error message because in this case it means that the file was
482
+                // shared with the user at a point where the user didn't had a
483
+                // valid private/public key
484
+                $msg = 'Encryption module "' . $this->getDisplayName() .
485
+                    '" is not able to read ' . $path;
486
+                $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.');
487
+                $this->logger->warning($msg);
488
+                throw new DecryptionFailedException($msg, $hint);
489
+            }
490
+            return false;
491
+        }
492
+
493
+        return true;
494
+    }
495
+
496
+    /**
497
+     * Initial encryption of all files
498
+     *
499
+     * @param InputInterface $input
500
+     * @param OutputInterface $output write some status information to the terminal during encryption
501
+     */
502
+    public function encryptAll(InputInterface $input, OutputInterface $output) {
503
+        $this->encryptAll->encryptAll($input, $output);
504
+    }
505
+
506
+    /**
507
+     * prepare module to perform decrypt all operation
508
+     *
509
+     * @param InputInterface $input
510
+     * @param OutputInterface $output
511
+     * @param string $user
512
+     * @return bool
513
+     */
514
+    public function prepareDecryptAll(InputInterface $input, OutputInterface $output, $user = '') {
515
+        return $this->decryptAll->prepare($input, $output, $user);
516
+    }
517
+
518
+
519
+    /**
520
+     * @param string $path
521
+     * @return string
522
+     */
523
+    protected function getPathToRealFile($path) {
524
+        $realPath = $path;
525
+        $parts = explode('/', $path);
526
+        if ($parts[2] === 'files_versions') {
527
+            $realPath = '/' . $parts[1] . '/files/' . implode('/', array_slice($parts, 3));
528
+            $length = strrpos($realPath, '.');
529
+            $realPath = substr($realPath, 0, $length);
530
+        }
531
+
532
+        return $realPath;
533
+    }
534
+
535
+    /**
536
+     * remove .part file extension and the ocTransferId from the file to get the
537
+     * original file name
538
+     *
539
+     * @param string $path
540
+     * @return string
541
+     */
542
+    protected function stripPartFileExtension($path) {
543
+        if (pathinfo($path, PATHINFO_EXTENSION) === 'part') {
544
+            $pos = strrpos($path, '.', -6);
545
+            $path = substr($path, 0, $pos);
546
+        }
547
+
548
+        return $path;
549
+    }
550
+
551
+    /**
552
+     * Check if the module is ready to be used by that specific user.
553
+     * In case a module is not ready - because e.g. key pairs have not been generated
554
+     * upon login this method can return false before any operation starts and might
555
+     * cause issues during operations.
556
+     *
557
+     * @param string $user
558
+     * @return boolean
559
+     * @since 9.1.0
560
+     */
561
+    public function isReadyForUser($user) {
562
+        return $this->keyManager->userHasKeys($user);
563
+    }
564 564
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -190,7 +190,7 @@  discard block
 block discarded – undo
190 190
 		// always use the version from the original file, also part files
191 191
 		// need to have a correct version number if they get moved over to the
192 192
 		// final location
193
-		$this->version = (int)$this->keyManager->getVersion($this->stripPartFileExtension($path), new View());
193
+		$this->version = (int) $this->keyManager->getVersion($this->stripPartFileExtension($path), new View());
194 194
 
195 195
 		if (
196 196
 			$mode === 'w'
@@ -206,7 +206,7 @@  discard block
 block discarded – undo
206 206
 			// if we read a part file we need to increase the version by 1
207 207
 			// because the version number was also increased by writing
208 208
 			// the part file
209
-			if(Scanner::isPartialFile($path)) {
209
+			if (Scanner::isPartialFile($path)) {
210 210
 				$this->version = $this->version + 1;
211 211
 			}
212 212
 		}
@@ -292,7 +292,7 @@  discard block
 block discarded – undo
292 292
 		if ($this->writeCache) {
293 293
 
294 294
 			// Concat writeCache to start of $data
295
-			$data = $this->writeCache . $data;
295
+			$data = $this->writeCache.$data;
296 296
 
297 297
 			// Clear the write cache, ready for reuse - it has been
298 298
 			// flushed and its old contents processed
@@ -394,7 +394,7 @@  discard block
 block discarded – undo
394 394
 					try {
395 395
 						$publicKeys[$user] = $this->keyManager->getPublicKey($user);
396 396
 					} catch (PublicKeyMissingException $e) {
397
-						$this->logger->warning('Could not encrypt file for ' . $user . ': ' . $e->getMessage());
397
+						$this->logger->warning('Could not encrypt file for '.$user.': '.$e->getMessage());
398 398
 					}
399 399
 				}
400 400
 			}
@@ -481,8 +481,8 @@  discard block
 block discarded – undo
481 481
 				// error message because in this case it means that the file was
482 482
 				// shared with the user at a point where the user didn't had a
483 483
 				// valid private/public key
484
-				$msg = 'Encryption module "' . $this->getDisplayName() .
485
-					'" is not able to read ' . $path;
484
+				$msg = 'Encryption module "'.$this->getDisplayName().
485
+					'" is not able to read '.$path;
486 486
 				$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.');
487 487
 				$this->logger->warning($msg);
488 488
 				throw new DecryptionFailedException($msg, $hint);
@@ -524,7 +524,7 @@  discard block
 block discarded – undo
524 524
 		$realPath = $path;
525 525
 		$parts = explode('/', $path);
526 526
 		if ($parts[2] === 'files_versions') {
527
-			$realPath = '/' . $parts[1] . '/files/' . implode('/', array_slice($parts, 3));
527
+			$realPath = '/'.$parts[1].'/files/'.implode('/', array_slice($parts, 3));
528 528
 			$length = strrpos($realPath, '.');
529 529
 			$realPath = substr($realPath, 0, $length);
530 530
 		}
Please login to merge, or discard this patch.
apps/encryption/lib/KeyManager.php 4 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.
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -32,7 +32,6 @@
 block discarded – undo
32 32
 use OCA\Encryption\Crypto\Crypt;
33 33
 use OCP\Encryption\Keys\IStorage;
34 34
 use OCP\IConfig;
35
-use OCP\IDBConnection;
36 35
 use OCP\ILogger;
37 36
 use OCP\IUserSession;
38 37
 
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.
Indentation   +662 added lines, -662 removed lines patch added patch discarded remove patch
@@ -39,667 +39,667 @@
 block discarded – undo
39 39
 
40 40
 class KeyManager {
41 41
 
42
-	/**
43
-	 * @var Session
44
-	 */
45
-	protected $session;
46
-	/**
47
-	 * @var IStorage
48
-	 */
49
-	private $keyStorage;
50
-	/**
51
-	 * @var Crypt
52
-	 */
53
-	private $crypt;
54
-	/**
55
-	 * @var string
56
-	 */
57
-	private $recoveryKeyId;
58
-	/**
59
-	 * @var string
60
-	 */
61
-	private $publicShareKeyId;
62
-	/**
63
-	 * @var string
64
-	 */
65
-	private $masterKeyId;
66
-	/**
67
-	 * @var string UserID
68
-	 */
69
-	private $keyId;
70
-	/**
71
-	 * @var string
72
-	 */
73
-	private $publicKeyId = 'publicKey';
74
-	/**
75
-	 * @var string
76
-	 */
77
-	private $privateKeyId = 'privateKey';
78
-
79
-	/**
80
-	 * @var string
81
-	 */
82
-	private $shareKeyId = 'shareKey';
83
-
84
-	/**
85
-	 * @var string
86
-	 */
87
-	private $fileKeyId = 'fileKey';
88
-	/**
89
-	 * @var IConfig
90
-	 */
91
-	private $config;
92
-	/**
93
-	 * @var ILogger
94
-	 */
95
-	private $log;
96
-	/**
97
-	 * @var Util
98
-	 */
99
-	private $util;
100
-
101
-	/**
102
-	 * @param IStorage $keyStorage
103
-	 * @param Crypt $crypt
104
-	 * @param IConfig $config
105
-	 * @param IUserSession $userSession
106
-	 * @param Session $session
107
-	 * @param ILogger $log
108
-	 * @param Util $util
109
-	 */
110
-	public function __construct(
111
-		IStorage $keyStorage,
112
-		Crypt $crypt,
113
-		IConfig $config,
114
-		IUserSession $userSession,
115
-		Session $session,
116
-		ILogger $log,
117
-		Util $util
118
-	) {
119
-
120
-		$this->util = $util;
121
-		$this->session = $session;
122
-		$this->keyStorage = $keyStorage;
123
-		$this->crypt = $crypt;
124
-		$this->config = $config;
125
-		$this->log = $log;
126
-
127
-		$this->recoveryKeyId = $this->config->getAppValue('encryption',
128
-			'recoveryKeyId');
129
-		if (empty($this->recoveryKeyId)) {
130
-			$this->recoveryKeyId = 'recoveryKey_' . substr(md5(time()), 0, 8);
131
-			$this->config->setAppValue('encryption',
132
-				'recoveryKeyId',
133
-				$this->recoveryKeyId);
134
-		}
135
-
136
-		$this->publicShareKeyId = $this->config->getAppValue('encryption',
137
-			'publicShareKeyId');
138
-		if (empty($this->publicShareKeyId)) {
139
-			$this->publicShareKeyId = 'pubShare_' . substr(md5(time()), 0, 8);
140
-			$this->config->setAppValue('encryption', 'publicShareKeyId', $this->publicShareKeyId);
141
-		}
142
-
143
-		$this->masterKeyId = $this->config->getAppValue('encryption',
144
-			'masterKeyId');
145
-		if (empty($this->masterKeyId)) {
146
-			$this->masterKeyId = 'master_' . substr(md5(time()), 0, 8);
147
-			$this->config->setAppValue('encryption', 'masterKeyId', $this->masterKeyId);
148
-		}
149
-
150
-		$this->keyId = $userSession && $userSession->isLoggedIn() ? $userSession->getUser()->getUID() : false;
151
-		$this->log = $log;
152
-	}
153
-
154
-	/**
155
-	 * check if key pair for public link shares exists, if not we create one
156
-	 */
157
-	public function validateShareKey() {
158
-		$shareKey = $this->getPublicShareKey();
159
-		if (empty($shareKey)) {
160
-			$keyPair = $this->crypt->createKeyPair();
161
-
162
-			// Save public key
163
-			$this->keyStorage->setSystemUserKey(
164
-				$this->publicShareKeyId . '.publicKey', $keyPair['publicKey'],
165
-				Encryption::ID);
166
-
167
-			// Encrypt private key empty passphrase
168
-			$encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], '');
169
-			$header = $this->crypt->generateHeader();
170
-			$this->setSystemPrivateKey($this->publicShareKeyId, $header . $encryptedKey);
171
-		}
172
-	}
173
-
174
-	/**
175
-	 * check if a key pair for the master key exists, if not we create one
176
-	 */
177
-	public function validateMasterKey() {
178
-
179
-		if ($this->util->isMasterKeyEnabled() === false) {
180
-			return;
181
-		}
182
-
183
-		$masterKey = $this->getPublicMasterKey();
184
-		if (empty($masterKey)) {
185
-			$keyPair = $this->crypt->createKeyPair();
186
-
187
-			// Save public key
188
-			$this->keyStorage->setSystemUserKey(
189
-				$this->masterKeyId . '.publicKey', $keyPair['publicKey'],
190
-				Encryption::ID);
191
-
192
-			// Encrypt private key with system password
193
-			$encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $this->getMasterKeyPassword(), $this->masterKeyId);
194
-			$header = $this->crypt->generateHeader();
195
-			$this->setSystemPrivateKey($this->masterKeyId, $header . $encryptedKey);
196
-		}
197
-	}
198
-
199
-	/**
200
-	 * @return bool
201
-	 */
202
-	public function recoveryKeyExists() {
203
-		$key = $this->getRecoveryKey();
204
-		return (!empty($key));
205
-	}
206
-
207
-	/**
208
-	 * get recovery key
209
-	 *
210
-	 * @return string
211
-	 */
212
-	public function getRecoveryKey() {
213
-		return $this->keyStorage->getSystemUserKey($this->recoveryKeyId . '.publicKey', Encryption::ID);
214
-	}
215
-
216
-	/**
217
-	 * get recovery key ID
218
-	 *
219
-	 * @return string
220
-	 */
221
-	public function getRecoveryKeyId() {
222
-		return $this->recoveryKeyId;
223
-	}
224
-
225
-	/**
226
-	 * @param string $password
227
-	 * @return bool
228
-	 */
229
-	public function checkRecoveryPassword($password) {
230
-		$recoveryKey = $this->keyStorage->getSystemUserKey($this->recoveryKeyId . '.privateKey', Encryption::ID);
231
-		$decryptedRecoveryKey = $this->crypt->decryptPrivateKey($recoveryKey, $password);
232
-
233
-		if ($decryptedRecoveryKey) {
234
-			return true;
235
-		}
236
-		return false;
237
-	}
238
-
239
-	/**
240
-	 * @param string $uid
241
-	 * @param string $password
242
-	 * @param string $keyPair
243
-	 * @return bool
244
-	 */
245
-	public function storeKeyPair($uid, $password, $keyPair) {
246
-		// Save Public Key
247
-		$this->setPublicKey($uid, $keyPair['publicKey']);
248
-
249
-		$encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $password, $uid);
250
-
251
-		$header = $this->crypt->generateHeader();
252
-
253
-		if ($encryptedKey) {
254
-			$this->setPrivateKey($uid, $header . $encryptedKey);
255
-			return true;
256
-		}
257
-		return false;
258
-	}
259
-
260
-	/**
261
-	 * @param string $password
262
-	 * @param array $keyPair
263
-	 * @return bool
264
-	 */
265
-	public function setRecoveryKey($password, $keyPair) {
266
-		// Save Public Key
267
-		$this->keyStorage->setSystemUserKey($this->getRecoveryKeyId().
268
-			'.publicKey',
269
-			$keyPair['publicKey'],
270
-			Encryption::ID);
271
-
272
-		$encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $password);
273
-		$header = $this->crypt->generateHeader();
274
-
275
-		if ($encryptedKey) {
276
-			$this->setSystemPrivateKey($this->getRecoveryKeyId(), $header . $encryptedKey);
277
-			return true;
278
-		}
279
-		return false;
280
-	}
281
-
282
-	/**
283
-	 * @param $userId
284
-	 * @param $key
285
-	 * @return bool
286
-	 */
287
-	public function setPublicKey($userId, $key) {
288
-		return $this->keyStorage->setUserKey($userId, $this->publicKeyId, $key, Encryption::ID);
289
-	}
290
-
291
-	/**
292
-	 * @param $userId
293
-	 * @param string $key
294
-	 * @return bool
295
-	 */
296
-	public function setPrivateKey($userId, $key) {
297
-		return $this->keyStorage->setUserKey($userId,
298
-			$this->privateKeyId,
299
-			$key,
300
-			Encryption::ID);
301
-	}
302
-
303
-	/**
304
-	 * write file key to key storage
305
-	 *
306
-	 * @param string $path
307
-	 * @param string $key
308
-	 * @return boolean
309
-	 */
310
-	public function setFileKey($path, $key) {
311
-		return $this->keyStorage->setFileKey($path, $this->fileKeyId, $key, Encryption::ID);
312
-	}
313
-
314
-	/**
315
-	 * set all file keys (the file key and the corresponding share keys)
316
-	 *
317
-	 * @param string $path
318
-	 * @param array $keys
319
-	 */
320
-	public function setAllFileKeys($path, $keys) {
321
-		$this->setFileKey($path, $keys['data']);
322
-		foreach ($keys['keys'] as $uid => $keyFile) {
323
-			$this->setShareKey($path, $uid, $keyFile);
324
-		}
325
-	}
326
-
327
-	/**
328
-	 * write share key to the key storage
329
-	 *
330
-	 * @param string $path
331
-	 * @param string $uid
332
-	 * @param string $key
333
-	 * @return boolean
334
-	 */
335
-	public function setShareKey($path, $uid, $key) {
336
-		$keyId = $uid . '.' . $this->shareKeyId;
337
-		return $this->keyStorage->setFileKey($path, $keyId, $key, Encryption::ID);
338
-	}
339
-
340
-	/**
341
-	 * Decrypt private key and store it
342
-	 *
343
-	 * @param string $uid user id
344
-	 * @param string $passPhrase users password
345
-	 * @return boolean
346
-	 */
347
-	public function init($uid, $passPhrase) {
348
-
349
-		$this->session->setStatus(Session::INIT_EXECUTED);
350
-
351
-		try {
352
-			if($this->util->isMasterKeyEnabled()) {
353
-				$uid = $this->getMasterKeyId();
354
-				$passPhrase = $this->getMasterKeyPassword();
355
-				$privateKey = $this->getSystemPrivateKey($uid);
356
-			} else {
357
-				$privateKey = $this->getPrivateKey($uid);
358
-			}
359
-			$privateKey = $this->crypt->decryptPrivateKey($privateKey, $passPhrase, $uid);
360
-		} catch (PrivateKeyMissingException $e) {
361
-			return false;
362
-		} catch (DecryptionFailedException $e) {
363
-			return false;
364
-		} catch (\Exception $e) {
365
-			$this->log->warning(
366
-				'Could not decrypt the private key from user "' . $uid . '"" during login. ' .
367
-				'Assume password change on the user back-end. Error message: '
368
-				. $e->getMessage()
369
-			);
370
-			return false;
371
-		}
372
-
373
-		if ($privateKey) {
374
-			$this->session->setPrivateKey($privateKey);
375
-			$this->session->setStatus(Session::INIT_SUCCESSFUL);
376
-			return true;
377
-		}
378
-
379
-		return false;
380
-	}
381
-
382
-	/**
383
-	 * @param $userId
384
-	 * @return string
385
-	 * @throws PrivateKeyMissingException
386
-	 */
387
-	public function getPrivateKey($userId) {
388
-		$privateKey = $this->keyStorage->getUserKey($userId,
389
-			$this->privateKeyId, Encryption::ID);
390
-
391
-		if (strlen($privateKey) !== 0) {
392
-			return $privateKey;
393
-		}
394
-		throw new PrivateKeyMissingException($userId);
395
-	}
396
-
397
-	/**
398
-	 * @param string $path
399
-	 * @param $uid
400
-	 * @return string
401
-	 */
402
-	public function getFileKey($path, $uid) {
403
-		$encryptedFileKey = $this->keyStorage->getFileKey($path, $this->fileKeyId, Encryption::ID);
404
-
405
-		if (empty($encryptedFileKey)) {
406
-			return '';
407
-		}
408
-
409
-		if ($this->util->isMasterKeyEnabled()) {
410
-			$uid = $this->getMasterKeyId();
411
-		}
412
-
413
-		if (is_null($uid)) {
414
-			$uid = $this->getPublicShareKeyId();
415
-			$shareKey = $this->getShareKey($path, $uid);
416
-			$privateKey = $this->keyStorage->getSystemUserKey($this->publicShareKeyId . '.privateKey', Encryption::ID);
417
-			$privateKey = $this->crypt->decryptPrivateKey($privateKey);
418
-		} else {
419
-			$shareKey = $this->getShareKey($path, $uid);
420
-			$privateKey = $this->session->getPrivateKey();
421
-		}
422
-
423
-		if ($encryptedFileKey && $shareKey && $privateKey) {
424
-			return $this->crypt->multiKeyDecrypt($encryptedFileKey,
425
-				$shareKey,
426
-				$privateKey);
427
-		}
428
-
429
-		return '';
430
-	}
431
-
432
-	/**
433
-	 * Get the current version of a file
434
-	 *
435
-	 * @param string $path
436
-	 * @param View $view
437
-	 * @return int
438
-	 */
439
-	public function getVersion($path, View $view) {
440
-		$fileInfo = $view->getFileInfo($path);
441
-		if($fileInfo === false) {
442
-			return 0;
443
-		}
444
-		return $fileInfo->getEncryptedVersion();
445
-	}
446
-
447
-	/**
448
-	 * Set the current version of a file
449
-	 *
450
-	 * @param string $path
451
-	 * @param int $version
452
-	 * @param View $view
453
-	 */
454
-	public function setVersion($path, $version, View $view) {
455
-		$fileInfo= $view->getFileInfo($path);
456
-
457
-		if($fileInfo !== false) {
458
-			$cache = $fileInfo->getStorage()->getCache();
459
-			$cache->update($fileInfo->getId(), ['encrypted' => $version, 'encryptedVersion' => $version]);
460
-		}
461
-	}
462
-
463
-	/**
464
-	 * get the encrypted file key
465
-	 *
466
-	 * @param string $path
467
-	 * @return string
468
-	 */
469
-	public function getEncryptedFileKey($path) {
470
-		$encryptedFileKey = $this->keyStorage->getFileKey($path,
471
-			$this->fileKeyId, Encryption::ID);
472
-
473
-		return $encryptedFileKey;
474
-	}
475
-
476
-	/**
477
-	 * delete share key
478
-	 *
479
-	 * @param string $path
480
-	 * @param string $keyId
481
-	 * @return boolean
482
-	 */
483
-	public function deleteShareKey($path, $keyId) {
484
-		return $this->keyStorage->deleteFileKey(
485
-			$path,
486
-			$keyId . '.' . $this->shareKeyId,
487
-			Encryption::ID);
488
-	}
489
-
490
-
491
-	/**
492
-	 * @param $path
493
-	 * @param $uid
494
-	 * @return mixed
495
-	 */
496
-	public function getShareKey($path, $uid) {
497
-		$keyId = $uid . '.' . $this->shareKeyId;
498
-		return $this->keyStorage->getFileKey($path, $keyId, Encryption::ID);
499
-	}
500
-
501
-	/**
502
-	 * check if user has a private and a public key
503
-	 *
504
-	 * @param string $userId
505
-	 * @return bool
506
-	 * @throws PrivateKeyMissingException
507
-	 * @throws PublicKeyMissingException
508
-	 */
509
-	public function userHasKeys($userId) {
510
-		$privateKey = $publicKey = true;
511
-		$exception = null;
512
-
513
-		try {
514
-			$this->getPrivateKey($userId);
515
-		} catch (PrivateKeyMissingException $e) {
516
-			$privateKey = false;
517
-			$exception = $e;
518
-		}
519
-		try {
520
-			$this->getPublicKey($userId);
521
-		} catch (PublicKeyMissingException $e) {
522
-			$publicKey = false;
523
-			$exception = $e;
524
-		}
525
-
526
-		if ($privateKey && $publicKey) {
527
-			return true;
528
-		} elseif (!$privateKey && !$publicKey) {
529
-			return false;
530
-		} else {
531
-			throw $exception;
532
-		}
533
-	}
534
-
535
-	/**
536
-	 * @param $userId
537
-	 * @return mixed
538
-	 * @throws PublicKeyMissingException
539
-	 */
540
-	public function getPublicKey($userId) {
541
-		$publicKey = $this->keyStorage->getUserKey($userId, $this->publicKeyId, Encryption::ID);
542
-
543
-		if (strlen($publicKey) !== 0) {
544
-			return $publicKey;
545
-		}
546
-		throw new PublicKeyMissingException($userId);
547
-	}
548
-
549
-	public function getPublicShareKeyId() {
550
-		return $this->publicShareKeyId;
551
-	}
552
-
553
-	/**
554
-	 * get public key for public link shares
555
-	 *
556
-	 * @return string
557
-	 */
558
-	public function getPublicShareKey() {
559
-		return $this->keyStorage->getSystemUserKey($this->publicShareKeyId . '.publicKey', Encryption::ID);
560
-	}
561
-
562
-	/**
563
-	 * @param string $purpose
564
-	 * @param bool $timestamp
565
-	 * @param bool $includeUserKeys
566
-	 */
567
-	public function backupAllKeys($purpose, $timestamp = true, $includeUserKeys = true) {
42
+    /**
43
+     * @var Session
44
+     */
45
+    protected $session;
46
+    /**
47
+     * @var IStorage
48
+     */
49
+    private $keyStorage;
50
+    /**
51
+     * @var Crypt
52
+     */
53
+    private $crypt;
54
+    /**
55
+     * @var string
56
+     */
57
+    private $recoveryKeyId;
58
+    /**
59
+     * @var string
60
+     */
61
+    private $publicShareKeyId;
62
+    /**
63
+     * @var string
64
+     */
65
+    private $masterKeyId;
66
+    /**
67
+     * @var string UserID
68
+     */
69
+    private $keyId;
70
+    /**
71
+     * @var string
72
+     */
73
+    private $publicKeyId = 'publicKey';
74
+    /**
75
+     * @var string
76
+     */
77
+    private $privateKeyId = 'privateKey';
78
+
79
+    /**
80
+     * @var string
81
+     */
82
+    private $shareKeyId = 'shareKey';
83
+
84
+    /**
85
+     * @var string
86
+     */
87
+    private $fileKeyId = 'fileKey';
88
+    /**
89
+     * @var IConfig
90
+     */
91
+    private $config;
92
+    /**
93
+     * @var ILogger
94
+     */
95
+    private $log;
96
+    /**
97
+     * @var Util
98
+     */
99
+    private $util;
100
+
101
+    /**
102
+     * @param IStorage $keyStorage
103
+     * @param Crypt $crypt
104
+     * @param IConfig $config
105
+     * @param IUserSession $userSession
106
+     * @param Session $session
107
+     * @param ILogger $log
108
+     * @param Util $util
109
+     */
110
+    public function __construct(
111
+        IStorage $keyStorage,
112
+        Crypt $crypt,
113
+        IConfig $config,
114
+        IUserSession $userSession,
115
+        Session $session,
116
+        ILogger $log,
117
+        Util $util
118
+    ) {
119
+
120
+        $this->util = $util;
121
+        $this->session = $session;
122
+        $this->keyStorage = $keyStorage;
123
+        $this->crypt = $crypt;
124
+        $this->config = $config;
125
+        $this->log = $log;
126
+
127
+        $this->recoveryKeyId = $this->config->getAppValue('encryption',
128
+            'recoveryKeyId');
129
+        if (empty($this->recoveryKeyId)) {
130
+            $this->recoveryKeyId = 'recoveryKey_' . substr(md5(time()), 0, 8);
131
+            $this->config->setAppValue('encryption',
132
+                'recoveryKeyId',
133
+                $this->recoveryKeyId);
134
+        }
135
+
136
+        $this->publicShareKeyId = $this->config->getAppValue('encryption',
137
+            'publicShareKeyId');
138
+        if (empty($this->publicShareKeyId)) {
139
+            $this->publicShareKeyId = 'pubShare_' . substr(md5(time()), 0, 8);
140
+            $this->config->setAppValue('encryption', 'publicShareKeyId', $this->publicShareKeyId);
141
+        }
142
+
143
+        $this->masterKeyId = $this->config->getAppValue('encryption',
144
+            'masterKeyId');
145
+        if (empty($this->masterKeyId)) {
146
+            $this->masterKeyId = 'master_' . substr(md5(time()), 0, 8);
147
+            $this->config->setAppValue('encryption', 'masterKeyId', $this->masterKeyId);
148
+        }
149
+
150
+        $this->keyId = $userSession && $userSession->isLoggedIn() ? $userSession->getUser()->getUID() : false;
151
+        $this->log = $log;
152
+    }
153
+
154
+    /**
155
+     * check if key pair for public link shares exists, if not we create one
156
+     */
157
+    public function validateShareKey() {
158
+        $shareKey = $this->getPublicShareKey();
159
+        if (empty($shareKey)) {
160
+            $keyPair = $this->crypt->createKeyPair();
161
+
162
+            // Save public key
163
+            $this->keyStorage->setSystemUserKey(
164
+                $this->publicShareKeyId . '.publicKey', $keyPair['publicKey'],
165
+                Encryption::ID);
166
+
167
+            // Encrypt private key empty passphrase
168
+            $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], '');
169
+            $header = $this->crypt->generateHeader();
170
+            $this->setSystemPrivateKey($this->publicShareKeyId, $header . $encryptedKey);
171
+        }
172
+    }
173
+
174
+    /**
175
+     * check if a key pair for the master key exists, if not we create one
176
+     */
177
+    public function validateMasterKey() {
178
+
179
+        if ($this->util->isMasterKeyEnabled() === false) {
180
+            return;
181
+        }
182
+
183
+        $masterKey = $this->getPublicMasterKey();
184
+        if (empty($masterKey)) {
185
+            $keyPair = $this->crypt->createKeyPair();
186
+
187
+            // Save public key
188
+            $this->keyStorage->setSystemUserKey(
189
+                $this->masterKeyId . '.publicKey', $keyPair['publicKey'],
190
+                Encryption::ID);
191
+
192
+            // Encrypt private key with system password
193
+            $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $this->getMasterKeyPassword(), $this->masterKeyId);
194
+            $header = $this->crypt->generateHeader();
195
+            $this->setSystemPrivateKey($this->masterKeyId, $header . $encryptedKey);
196
+        }
197
+    }
198
+
199
+    /**
200
+     * @return bool
201
+     */
202
+    public function recoveryKeyExists() {
203
+        $key = $this->getRecoveryKey();
204
+        return (!empty($key));
205
+    }
206
+
207
+    /**
208
+     * get recovery key
209
+     *
210
+     * @return string
211
+     */
212
+    public function getRecoveryKey() {
213
+        return $this->keyStorage->getSystemUserKey($this->recoveryKeyId . '.publicKey', Encryption::ID);
214
+    }
215
+
216
+    /**
217
+     * get recovery key ID
218
+     *
219
+     * @return string
220
+     */
221
+    public function getRecoveryKeyId() {
222
+        return $this->recoveryKeyId;
223
+    }
224
+
225
+    /**
226
+     * @param string $password
227
+     * @return bool
228
+     */
229
+    public function checkRecoveryPassword($password) {
230
+        $recoveryKey = $this->keyStorage->getSystemUserKey($this->recoveryKeyId . '.privateKey', Encryption::ID);
231
+        $decryptedRecoveryKey = $this->crypt->decryptPrivateKey($recoveryKey, $password);
232
+
233
+        if ($decryptedRecoveryKey) {
234
+            return true;
235
+        }
236
+        return false;
237
+    }
238
+
239
+    /**
240
+     * @param string $uid
241
+     * @param string $password
242
+     * @param string $keyPair
243
+     * @return bool
244
+     */
245
+    public function storeKeyPair($uid, $password, $keyPair) {
246
+        // Save Public Key
247
+        $this->setPublicKey($uid, $keyPair['publicKey']);
248
+
249
+        $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $password, $uid);
250
+
251
+        $header = $this->crypt->generateHeader();
252
+
253
+        if ($encryptedKey) {
254
+            $this->setPrivateKey($uid, $header . $encryptedKey);
255
+            return true;
256
+        }
257
+        return false;
258
+    }
259
+
260
+    /**
261
+     * @param string $password
262
+     * @param array $keyPair
263
+     * @return bool
264
+     */
265
+    public function setRecoveryKey($password, $keyPair) {
266
+        // Save Public Key
267
+        $this->keyStorage->setSystemUserKey($this->getRecoveryKeyId().
268
+            '.publicKey',
269
+            $keyPair['publicKey'],
270
+            Encryption::ID);
271
+
272
+        $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $password);
273
+        $header = $this->crypt->generateHeader();
274
+
275
+        if ($encryptedKey) {
276
+            $this->setSystemPrivateKey($this->getRecoveryKeyId(), $header . $encryptedKey);
277
+            return true;
278
+        }
279
+        return false;
280
+    }
281
+
282
+    /**
283
+     * @param $userId
284
+     * @param $key
285
+     * @return bool
286
+     */
287
+    public function setPublicKey($userId, $key) {
288
+        return $this->keyStorage->setUserKey($userId, $this->publicKeyId, $key, Encryption::ID);
289
+    }
290
+
291
+    /**
292
+     * @param $userId
293
+     * @param string $key
294
+     * @return bool
295
+     */
296
+    public function setPrivateKey($userId, $key) {
297
+        return $this->keyStorage->setUserKey($userId,
298
+            $this->privateKeyId,
299
+            $key,
300
+            Encryption::ID);
301
+    }
302
+
303
+    /**
304
+     * write file key to key storage
305
+     *
306
+     * @param string $path
307
+     * @param string $key
308
+     * @return boolean
309
+     */
310
+    public function setFileKey($path, $key) {
311
+        return $this->keyStorage->setFileKey($path, $this->fileKeyId, $key, Encryption::ID);
312
+    }
313
+
314
+    /**
315
+     * set all file keys (the file key and the corresponding share keys)
316
+     *
317
+     * @param string $path
318
+     * @param array $keys
319
+     */
320
+    public function setAllFileKeys($path, $keys) {
321
+        $this->setFileKey($path, $keys['data']);
322
+        foreach ($keys['keys'] as $uid => $keyFile) {
323
+            $this->setShareKey($path, $uid, $keyFile);
324
+        }
325
+    }
326
+
327
+    /**
328
+     * write share key to the key storage
329
+     *
330
+     * @param string $path
331
+     * @param string $uid
332
+     * @param string $key
333
+     * @return boolean
334
+     */
335
+    public function setShareKey($path, $uid, $key) {
336
+        $keyId = $uid . '.' . $this->shareKeyId;
337
+        return $this->keyStorage->setFileKey($path, $keyId, $key, Encryption::ID);
338
+    }
339
+
340
+    /**
341
+     * Decrypt private key and store it
342
+     *
343
+     * @param string $uid user id
344
+     * @param string $passPhrase users password
345
+     * @return boolean
346
+     */
347
+    public function init($uid, $passPhrase) {
348
+
349
+        $this->session->setStatus(Session::INIT_EXECUTED);
350
+
351
+        try {
352
+            if($this->util->isMasterKeyEnabled()) {
353
+                $uid = $this->getMasterKeyId();
354
+                $passPhrase = $this->getMasterKeyPassword();
355
+                $privateKey = $this->getSystemPrivateKey($uid);
356
+            } else {
357
+                $privateKey = $this->getPrivateKey($uid);
358
+            }
359
+            $privateKey = $this->crypt->decryptPrivateKey($privateKey, $passPhrase, $uid);
360
+        } catch (PrivateKeyMissingException $e) {
361
+            return false;
362
+        } catch (DecryptionFailedException $e) {
363
+            return false;
364
+        } catch (\Exception $e) {
365
+            $this->log->warning(
366
+                'Could not decrypt the private key from user "' . $uid . '"" during login. ' .
367
+                'Assume password change on the user back-end. Error message: '
368
+                . $e->getMessage()
369
+            );
370
+            return false;
371
+        }
372
+
373
+        if ($privateKey) {
374
+            $this->session->setPrivateKey($privateKey);
375
+            $this->session->setStatus(Session::INIT_SUCCESSFUL);
376
+            return true;
377
+        }
378
+
379
+        return false;
380
+    }
381
+
382
+    /**
383
+     * @param $userId
384
+     * @return string
385
+     * @throws PrivateKeyMissingException
386
+     */
387
+    public function getPrivateKey($userId) {
388
+        $privateKey = $this->keyStorage->getUserKey($userId,
389
+            $this->privateKeyId, Encryption::ID);
390
+
391
+        if (strlen($privateKey) !== 0) {
392
+            return $privateKey;
393
+        }
394
+        throw new PrivateKeyMissingException($userId);
395
+    }
396
+
397
+    /**
398
+     * @param string $path
399
+     * @param $uid
400
+     * @return string
401
+     */
402
+    public function getFileKey($path, $uid) {
403
+        $encryptedFileKey = $this->keyStorage->getFileKey($path, $this->fileKeyId, Encryption::ID);
404
+
405
+        if (empty($encryptedFileKey)) {
406
+            return '';
407
+        }
408
+
409
+        if ($this->util->isMasterKeyEnabled()) {
410
+            $uid = $this->getMasterKeyId();
411
+        }
412
+
413
+        if (is_null($uid)) {
414
+            $uid = $this->getPublicShareKeyId();
415
+            $shareKey = $this->getShareKey($path, $uid);
416
+            $privateKey = $this->keyStorage->getSystemUserKey($this->publicShareKeyId . '.privateKey', Encryption::ID);
417
+            $privateKey = $this->crypt->decryptPrivateKey($privateKey);
418
+        } else {
419
+            $shareKey = $this->getShareKey($path, $uid);
420
+            $privateKey = $this->session->getPrivateKey();
421
+        }
422
+
423
+        if ($encryptedFileKey && $shareKey && $privateKey) {
424
+            return $this->crypt->multiKeyDecrypt($encryptedFileKey,
425
+                $shareKey,
426
+                $privateKey);
427
+        }
428
+
429
+        return '';
430
+    }
431
+
432
+    /**
433
+     * Get the current version of a file
434
+     *
435
+     * @param string $path
436
+     * @param View $view
437
+     * @return int
438
+     */
439
+    public function getVersion($path, View $view) {
440
+        $fileInfo = $view->getFileInfo($path);
441
+        if($fileInfo === false) {
442
+            return 0;
443
+        }
444
+        return $fileInfo->getEncryptedVersion();
445
+    }
446
+
447
+    /**
448
+     * Set the current version of a file
449
+     *
450
+     * @param string $path
451
+     * @param int $version
452
+     * @param View $view
453
+     */
454
+    public function setVersion($path, $version, View $view) {
455
+        $fileInfo= $view->getFileInfo($path);
456
+
457
+        if($fileInfo !== false) {
458
+            $cache = $fileInfo->getStorage()->getCache();
459
+            $cache->update($fileInfo->getId(), ['encrypted' => $version, 'encryptedVersion' => $version]);
460
+        }
461
+    }
462
+
463
+    /**
464
+     * get the encrypted file key
465
+     *
466
+     * @param string $path
467
+     * @return string
468
+     */
469
+    public function getEncryptedFileKey($path) {
470
+        $encryptedFileKey = $this->keyStorage->getFileKey($path,
471
+            $this->fileKeyId, Encryption::ID);
472
+
473
+        return $encryptedFileKey;
474
+    }
475
+
476
+    /**
477
+     * delete share key
478
+     *
479
+     * @param string $path
480
+     * @param string $keyId
481
+     * @return boolean
482
+     */
483
+    public function deleteShareKey($path, $keyId) {
484
+        return $this->keyStorage->deleteFileKey(
485
+            $path,
486
+            $keyId . '.' . $this->shareKeyId,
487
+            Encryption::ID);
488
+    }
489
+
490
+
491
+    /**
492
+     * @param $path
493
+     * @param $uid
494
+     * @return mixed
495
+     */
496
+    public function getShareKey($path, $uid) {
497
+        $keyId = $uid . '.' . $this->shareKeyId;
498
+        return $this->keyStorage->getFileKey($path, $keyId, Encryption::ID);
499
+    }
500
+
501
+    /**
502
+     * check if user has a private and a public key
503
+     *
504
+     * @param string $userId
505
+     * @return bool
506
+     * @throws PrivateKeyMissingException
507
+     * @throws PublicKeyMissingException
508
+     */
509
+    public function userHasKeys($userId) {
510
+        $privateKey = $publicKey = true;
511
+        $exception = null;
512
+
513
+        try {
514
+            $this->getPrivateKey($userId);
515
+        } catch (PrivateKeyMissingException $e) {
516
+            $privateKey = false;
517
+            $exception = $e;
518
+        }
519
+        try {
520
+            $this->getPublicKey($userId);
521
+        } catch (PublicKeyMissingException $e) {
522
+            $publicKey = false;
523
+            $exception = $e;
524
+        }
525
+
526
+        if ($privateKey && $publicKey) {
527
+            return true;
528
+        } elseif (!$privateKey && !$publicKey) {
529
+            return false;
530
+        } else {
531
+            throw $exception;
532
+        }
533
+    }
534
+
535
+    /**
536
+     * @param $userId
537
+     * @return mixed
538
+     * @throws PublicKeyMissingException
539
+     */
540
+    public function getPublicKey($userId) {
541
+        $publicKey = $this->keyStorage->getUserKey($userId, $this->publicKeyId, Encryption::ID);
542
+
543
+        if (strlen($publicKey) !== 0) {
544
+            return $publicKey;
545
+        }
546
+        throw new PublicKeyMissingException($userId);
547
+    }
548
+
549
+    public function getPublicShareKeyId() {
550
+        return $this->publicShareKeyId;
551
+    }
552
+
553
+    /**
554
+     * get public key for public link shares
555
+     *
556
+     * @return string
557
+     */
558
+    public function getPublicShareKey() {
559
+        return $this->keyStorage->getSystemUserKey($this->publicShareKeyId . '.publicKey', Encryption::ID);
560
+    }
561
+
562
+    /**
563
+     * @param string $purpose
564
+     * @param bool $timestamp
565
+     * @param bool $includeUserKeys
566
+     */
567
+    public function backupAllKeys($purpose, $timestamp = true, $includeUserKeys = true) {
568 568
 //		$backupDir = $this->keyStorage->;
569
-	}
570
-
571
-	/**
572
-	 * creat a backup of the users private and public key and then  delete it
573
-	 *
574
-	 * @param string $uid
575
-	 */
576
-	public function deleteUserKeys($uid) {
577
-		$this->backupAllKeys('password_reset');
578
-		$this->deletePublicKey($uid);
579
-		$this->deletePrivateKey($uid);
580
-	}
581
-
582
-	/**
583
-	 * @param $uid
584
-	 * @return bool
585
-	 */
586
-	public function deletePublicKey($uid) {
587
-		return $this->keyStorage->deleteUserKey($uid, $this->publicKeyId, Encryption::ID);
588
-	}
589
-
590
-	/**
591
-	 * @param string $uid
592
-	 * @return bool
593
-	 */
594
-	private function deletePrivateKey($uid) {
595
-		return $this->keyStorage->deleteUserKey($uid, $this->privateKeyId, Encryption::ID);
596
-	}
597
-
598
-	/**
599
-	 * @param string $path
600
-	 * @return bool
601
-	 */
602
-	public function deleteAllFileKeys($path) {
603
-		return $this->keyStorage->deleteAllFileKeys($path);
604
-	}
605
-
606
-	/**
607
-	 * @param array $userIds
608
-	 * @return array
609
-	 * @throws PublicKeyMissingException
610
-	 */
611
-	public function getPublicKeys(array $userIds) {
612
-		$keys = [];
613
-
614
-		foreach ($userIds as $userId) {
615
-			try {
616
-				$keys[$userId] = $this->getPublicKey($userId);
617
-			} catch (PublicKeyMissingException $e) {
618
-				continue;
619
-			}
620
-		}
621
-
622
-		return $keys;
623
-
624
-	}
625
-
626
-	/**
627
-	 * @param string $keyId
628
-	 * @return string returns openssl key
629
-	 */
630
-	public function getSystemPrivateKey($keyId) {
631
-		return $this->keyStorage->getSystemUserKey($keyId . '.' . $this->privateKeyId, Encryption::ID);
632
-	}
633
-
634
-	/**
635
-	 * @param string $keyId
636
-	 * @param string $key
637
-	 * @return string returns openssl key
638
-	 */
639
-	public function setSystemPrivateKey($keyId, $key) {
640
-		return $this->keyStorage->setSystemUserKey(
641
-			$keyId . '.' . $this->privateKeyId,
642
-			$key,
643
-			Encryption::ID);
644
-	}
645
-
646
-	/**
647
-	 * add system keys such as the public share key and the recovery key
648
-	 *
649
-	 * @param array $accessList
650
-	 * @param array $publicKeys
651
-	 * @param string $uid
652
-	 * @return array
653
-	 * @throws PublicKeyMissingException
654
-	 */
655
-	public function addSystemKeys(array $accessList, array $publicKeys, $uid) {
656
-		if (!empty($accessList['public'])) {
657
-			$publicShareKey = $this->getPublicShareKey();
658
-			if (empty($publicShareKey)) {
659
-				throw new PublicKeyMissingException($this->getPublicShareKeyId());
660
-			}
661
-			$publicKeys[$this->getPublicShareKeyId()] = $publicShareKey;
662
-		}
663
-
664
-		if ($this->recoveryKeyExists() &&
665
-			$this->util->isRecoveryEnabledForUser($uid)) {
666
-
667
-			$publicKeys[$this->getRecoveryKeyId()] = $this->getRecoveryKey();
668
-		}
669
-
670
-		return $publicKeys;
671
-	}
672
-
673
-	/**
674
-	 * get master key password
675
-	 *
676
-	 * @return string
677
-	 * @throws \Exception
678
-	 */
679
-	public function getMasterKeyPassword() {
680
-		$password = $this->config->getSystemValue('secret');
681
-		if (empty($password)){
682
-			throw new \Exception('Can not get secret from ownCloud instance');
683
-		}
684
-
685
-		return $password;
686
-	}
687
-
688
-	/**
689
-	 * return master key id
690
-	 *
691
-	 * @return string
692
-	 */
693
-	public function getMasterKeyId() {
694
-		return $this->masterKeyId;
695
-	}
696
-
697
-	/**
698
-	 * get public master key
699
-	 *
700
-	 * @return string
701
-	 */
702
-	public function getPublicMasterKey() {
703
-		return $this->keyStorage->getSystemUserKey($this->masterKeyId . '.publicKey', Encryption::ID);
704
-	}
569
+    }
570
+
571
+    /**
572
+     * creat a backup of the users private and public key and then  delete it
573
+     *
574
+     * @param string $uid
575
+     */
576
+    public function deleteUserKeys($uid) {
577
+        $this->backupAllKeys('password_reset');
578
+        $this->deletePublicKey($uid);
579
+        $this->deletePrivateKey($uid);
580
+    }
581
+
582
+    /**
583
+     * @param $uid
584
+     * @return bool
585
+     */
586
+    public function deletePublicKey($uid) {
587
+        return $this->keyStorage->deleteUserKey($uid, $this->publicKeyId, Encryption::ID);
588
+    }
589
+
590
+    /**
591
+     * @param string $uid
592
+     * @return bool
593
+     */
594
+    private function deletePrivateKey($uid) {
595
+        return $this->keyStorage->deleteUserKey($uid, $this->privateKeyId, Encryption::ID);
596
+    }
597
+
598
+    /**
599
+     * @param string $path
600
+     * @return bool
601
+     */
602
+    public function deleteAllFileKeys($path) {
603
+        return $this->keyStorage->deleteAllFileKeys($path);
604
+    }
605
+
606
+    /**
607
+     * @param array $userIds
608
+     * @return array
609
+     * @throws PublicKeyMissingException
610
+     */
611
+    public function getPublicKeys(array $userIds) {
612
+        $keys = [];
613
+
614
+        foreach ($userIds as $userId) {
615
+            try {
616
+                $keys[$userId] = $this->getPublicKey($userId);
617
+            } catch (PublicKeyMissingException $e) {
618
+                continue;
619
+            }
620
+        }
621
+
622
+        return $keys;
623
+
624
+    }
625
+
626
+    /**
627
+     * @param string $keyId
628
+     * @return string returns openssl key
629
+     */
630
+    public function getSystemPrivateKey($keyId) {
631
+        return $this->keyStorage->getSystemUserKey($keyId . '.' . $this->privateKeyId, Encryption::ID);
632
+    }
633
+
634
+    /**
635
+     * @param string $keyId
636
+     * @param string $key
637
+     * @return string returns openssl key
638
+     */
639
+    public function setSystemPrivateKey($keyId, $key) {
640
+        return $this->keyStorage->setSystemUserKey(
641
+            $keyId . '.' . $this->privateKeyId,
642
+            $key,
643
+            Encryption::ID);
644
+    }
645
+
646
+    /**
647
+     * add system keys such as the public share key and the recovery key
648
+     *
649
+     * @param array $accessList
650
+     * @param array $publicKeys
651
+     * @param string $uid
652
+     * @return array
653
+     * @throws PublicKeyMissingException
654
+     */
655
+    public function addSystemKeys(array $accessList, array $publicKeys, $uid) {
656
+        if (!empty($accessList['public'])) {
657
+            $publicShareKey = $this->getPublicShareKey();
658
+            if (empty($publicShareKey)) {
659
+                throw new PublicKeyMissingException($this->getPublicShareKeyId());
660
+            }
661
+            $publicKeys[$this->getPublicShareKeyId()] = $publicShareKey;
662
+        }
663
+
664
+        if ($this->recoveryKeyExists() &&
665
+            $this->util->isRecoveryEnabledForUser($uid)) {
666
+
667
+            $publicKeys[$this->getRecoveryKeyId()] = $this->getRecoveryKey();
668
+        }
669
+
670
+        return $publicKeys;
671
+    }
672
+
673
+    /**
674
+     * get master key password
675
+     *
676
+     * @return string
677
+     * @throws \Exception
678
+     */
679
+    public function getMasterKeyPassword() {
680
+        $password = $this->config->getSystemValue('secret');
681
+        if (empty($password)){
682
+            throw new \Exception('Can not get secret from ownCloud instance');
683
+        }
684
+
685
+        return $password;
686
+    }
687
+
688
+    /**
689
+     * return master key id
690
+     *
691
+     * @return string
692
+     */
693
+    public function getMasterKeyId() {
694
+        return $this->masterKeyId;
695
+    }
696
+
697
+    /**
698
+     * get public master key
699
+     *
700
+     * @return string
701
+     */
702
+    public function getPublicMasterKey() {
703
+        return $this->keyStorage->getSystemUserKey($this->masterKeyId . '.publicKey', Encryption::ID);
704
+    }
705 705
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/FederatedShareProvider.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -391,7 +391,7 @@  discard block
 block discarded – undo
391 391
 	/**
392 392
 	 * store remote ID in federated reShare table
393 393
 	 *
394
-	 * @param $shareId
394
+	 * @param integer $shareId
395 395
 	 * @param $remoteId
396 396
 	 */
397 397
 	public function storeRemoteId($shareId, $remoteId) {
@@ -729,7 +729,7 @@  discard block
 block discarded – undo
729 729
 	/**
730 730
 	 * get database row of a give share
731 731
 	 *
732
-	 * @param $id
732
+	 * @param integer $id
733 733
 	 * @return array
734 734
 	 * @throws ShareNotFound
735 735
 	 */
Please login to merge, or discard this patch.
Indentation   +836 added lines, -836 removed lines patch added patch discarded remove patch
@@ -47,850 +47,850 @@
 block discarded – undo
47 47
  */
48 48
 class FederatedShareProvider implements IShareProvider {
49 49
 
50
-	const SHARE_TYPE_REMOTE = 6;
51
-
52
-	/** @var IDBConnection */
53
-	private $dbConnection;
54
-
55
-	/** @var AddressHandler */
56
-	private $addressHandler;
57
-
58
-	/** @var Notifications */
59
-	private $notifications;
60
-
61
-	/** @var TokenHandler */
62
-	private $tokenHandler;
63
-
64
-	/** @var IL10N */
65
-	private $l;
66
-
67
-	/** @var ILogger */
68
-	private $logger;
69
-
70
-	/** @var IRootFolder */
71
-	private $rootFolder;
72
-
73
-	/** @var IConfig */
74
-	private $config;
75
-
76
-	/** @var string */
77
-	private $externalShareTable = 'share_external';
78
-
79
-	/** @var IUserManager */
80
-	private $userManager;
81
-
82
-	/**
83
-	 * DefaultShareProvider constructor.
84
-	 *
85
-	 * @param IDBConnection $connection
86
-	 * @param AddressHandler $addressHandler
87
-	 * @param Notifications $notifications
88
-	 * @param TokenHandler $tokenHandler
89
-	 * @param IL10N $l10n
90
-	 * @param ILogger $logger
91
-	 * @param IRootFolder $rootFolder
92
-	 * @param IConfig $config
93
-	 * @param IUserManager $userManager
94
-	 */
95
-	public function __construct(
96
-			IDBConnection $connection,
97
-			AddressHandler $addressHandler,
98
-			Notifications $notifications,
99
-			TokenHandler $tokenHandler,
100
-			IL10N $l10n,
101
-			ILogger $logger,
102
-			IRootFolder $rootFolder,
103
-			IConfig $config,
104
-			IUserManager $userManager
105
-	) {
106
-		$this->dbConnection = $connection;
107
-		$this->addressHandler = $addressHandler;
108
-		$this->notifications = $notifications;
109
-		$this->tokenHandler = $tokenHandler;
110
-		$this->l = $l10n;
111
-		$this->logger = $logger;
112
-		$this->rootFolder = $rootFolder;
113
-		$this->config = $config;
114
-		$this->userManager = $userManager;
115
-	}
116
-
117
-	/**
118
-	 * Return the identifier of this provider.
119
-	 *
120
-	 * @return string Containing only [a-zA-Z0-9]
121
-	 */
122
-	public function identifier() {
123
-		return 'ocFederatedSharing';
124
-	}
125
-
126
-	/**
127
-	 * Share a path
128
-	 *
129
-	 * @param IShare $share
130
-	 * @return IShare The share object
131
-	 * @throws ShareNotFound
132
-	 * @throws \Exception
133
-	 */
134
-	public function create(IShare $share) {
135
-
136
-		$shareWith = $share->getSharedWith();
137
-		$itemSource = $share->getNodeId();
138
-		$itemType = $share->getNodeType();
139
-		$permissions = $share->getPermissions();
140
-		$sharedBy = $share->getSharedBy();
141
-
142
-		/*
50
+    const SHARE_TYPE_REMOTE = 6;
51
+
52
+    /** @var IDBConnection */
53
+    private $dbConnection;
54
+
55
+    /** @var AddressHandler */
56
+    private $addressHandler;
57
+
58
+    /** @var Notifications */
59
+    private $notifications;
60
+
61
+    /** @var TokenHandler */
62
+    private $tokenHandler;
63
+
64
+    /** @var IL10N */
65
+    private $l;
66
+
67
+    /** @var ILogger */
68
+    private $logger;
69
+
70
+    /** @var IRootFolder */
71
+    private $rootFolder;
72
+
73
+    /** @var IConfig */
74
+    private $config;
75
+
76
+    /** @var string */
77
+    private $externalShareTable = 'share_external';
78
+
79
+    /** @var IUserManager */
80
+    private $userManager;
81
+
82
+    /**
83
+     * DefaultShareProvider constructor.
84
+     *
85
+     * @param IDBConnection $connection
86
+     * @param AddressHandler $addressHandler
87
+     * @param Notifications $notifications
88
+     * @param TokenHandler $tokenHandler
89
+     * @param IL10N $l10n
90
+     * @param ILogger $logger
91
+     * @param IRootFolder $rootFolder
92
+     * @param IConfig $config
93
+     * @param IUserManager $userManager
94
+     */
95
+    public function __construct(
96
+            IDBConnection $connection,
97
+            AddressHandler $addressHandler,
98
+            Notifications $notifications,
99
+            TokenHandler $tokenHandler,
100
+            IL10N $l10n,
101
+            ILogger $logger,
102
+            IRootFolder $rootFolder,
103
+            IConfig $config,
104
+            IUserManager $userManager
105
+    ) {
106
+        $this->dbConnection = $connection;
107
+        $this->addressHandler = $addressHandler;
108
+        $this->notifications = $notifications;
109
+        $this->tokenHandler = $tokenHandler;
110
+        $this->l = $l10n;
111
+        $this->logger = $logger;
112
+        $this->rootFolder = $rootFolder;
113
+        $this->config = $config;
114
+        $this->userManager = $userManager;
115
+    }
116
+
117
+    /**
118
+     * Return the identifier of this provider.
119
+     *
120
+     * @return string Containing only [a-zA-Z0-9]
121
+     */
122
+    public function identifier() {
123
+        return 'ocFederatedSharing';
124
+    }
125
+
126
+    /**
127
+     * Share a path
128
+     *
129
+     * @param IShare $share
130
+     * @return IShare The share object
131
+     * @throws ShareNotFound
132
+     * @throws \Exception
133
+     */
134
+    public function create(IShare $share) {
135
+
136
+        $shareWith = $share->getSharedWith();
137
+        $itemSource = $share->getNodeId();
138
+        $itemType = $share->getNodeType();
139
+        $permissions = $share->getPermissions();
140
+        $sharedBy = $share->getSharedBy();
141
+
142
+        /*
143 143
 		 * Check if file is not already shared with the remote user
144 144
 		 */
145
-		$alreadyShared = $this->getSharedWith($shareWith, self::SHARE_TYPE_REMOTE, $share->getNode(), 1, 0);
146
-		if (!empty($alreadyShared)) {
147
-			$message = 'Sharing %s failed, because this item is already shared with %s';
148
-			$message_t = $this->l->t('Sharing %s failed, because this item is already shared with %s', array($share->getNode()->getName(), $shareWith));
149
-			$this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
150
-			throw new \Exception($message_t);
151
-		}
152
-
153
-
154
-		// don't allow federated shares if source and target server are the same
155
-		list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
156
-		$currentServer = $this->addressHandler->generateRemoteURL();
157
-		$currentUser = $sharedBy;
158
-		if ($this->addressHandler->compareAddresses($user, $remote, $currentUser, $currentServer)) {
159
-			$message = 'Not allowed to create a federated share with the same user.';
160
-			$message_t = $this->l->t('Not allowed to create a federated share with the same user');
161
-			$this->logger->debug($message, ['app' => 'Federated File Sharing']);
162
-			throw new \Exception($message_t);
163
-		}
164
-
165
-		$share->setSharedWith($user . '@' . $remote);
166
-
167
-		try {
168
-			$remoteShare = $this->getShareFromExternalShareTable($share);
169
-		} catch (ShareNotFound $e) {
170
-			$remoteShare = null;
171
-		}
172
-
173
-		if ($remoteShare) {
174
-			try {
175
-				$uidOwner = $remoteShare['owner'] . '@' . $remoteShare['remote'];
176
-				$shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, 'tmp_token_' . time());
177
-				$share->setId($shareId);
178
-				list($token, $remoteId) = $this->askOwnerToReShare($shareWith, $share, $shareId);
179
-				// remote share was create successfully if we get a valid token as return
180
-				$send = is_string($token) && $token !== '';
181
-			} catch (\Exception $e) {
182
-				// fall back to old re-share behavior if the remote server
183
-				// doesn't support flat re-shares (was introduced with Nextcloud 9.1)
184
-				$this->removeShareFromTable($share);
185
-				$shareId = $this->createFederatedShare($share);
186
-			}
187
-			if ($send) {
188
-				$this->updateSuccessfulReshare($shareId, $token);
189
-				$this->storeRemoteId($shareId, $remoteId);
190
-			} else {
191
-				$this->removeShareFromTable($share);
192
-				$message_t = $this->l->t('File is already shared with %s', [$shareWith]);
193
-				throw new \Exception($message_t);
194
-			}
195
-
196
-		} else {
197
-			$shareId = $this->createFederatedShare($share);
198
-		}
199
-
200
-		$data = $this->getRawShare($shareId);
201
-		return $this->createShareObject($data);
202
-	}
203
-
204
-	/**
205
-	 * create federated share and inform the recipient
206
-	 *
207
-	 * @param IShare $share
208
-	 * @return int
209
-	 * @throws ShareNotFound
210
-	 * @throws \Exception
211
-	 */
212
-	protected function createFederatedShare(IShare $share) {
213
-		$token = $this->tokenHandler->generateToken();
214
-		$shareId = $this->addShareToDB(
215
-			$share->getNodeId(),
216
-			$share->getNodeType(),
217
-			$share->getSharedWith(),
218
-			$share->getSharedBy(),
219
-			$share->getShareOwner(),
220
-			$share->getPermissions(),
221
-			$token
222
-		);
223
-
224
-		try {
225
-			$sharedByFederatedId = $share->getSharedBy();
226
-			if ($this->userManager->userExists($sharedByFederatedId)) {
227
-				$sharedByFederatedId = $sharedByFederatedId . '@' . $this->addressHandler->generateRemoteURL();
228
-			}
229
-			$send = $this->notifications->sendRemoteShare(
230
-				$token,
231
-				$share->getSharedWith(),
232
-				$share->getNode()->getName(),
233
-				$shareId,
234
-				$share->getShareOwner(),
235
-				$share->getShareOwner() . '@' . $this->addressHandler->generateRemoteURL(),
236
-				$share->getSharedBy(),
237
-				$sharedByFederatedId
238
-			);
239
-
240
-			if ($send === false) {
241
-				$message_t = $this->l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable.',
242
-					[$share->getNode()->getName(), $share->getSharedWith()]);
243
-				throw new \Exception($message_t);
244
-			}
245
-		} catch (\Exception $e) {
246
-			$this->logger->error('Failed to notify remote server of federated share, removing share (' . $e->getMessage() . ')');
247
-			$this->removeShareFromTableById($shareId);
248
-			throw $e;
249
-		}
250
-
251
-		return $shareId;
252
-	}
253
-
254
-	/**
255
-	 * @param string $shareWith
256
-	 * @param IShare $share
257
-	 * @param string $shareId internal share Id
258
-	 * @return array
259
-	 * @throws \Exception
260
-	 */
261
-	protected function askOwnerToReShare($shareWith, IShare $share, $shareId) {
262
-
263
-		$remoteShare = $this->getShareFromExternalShareTable($share);
264
-		$token = $remoteShare['share_token'];
265
-		$remoteId = $remoteShare['remote_id'];
266
-		$remote = $remoteShare['remote'];
267
-
268
-		list($token, $remoteId) = $this->notifications->requestReShare(
269
-			$token,
270
-			$remoteId,
271
-			$shareId,
272
-			$remote,
273
-			$shareWith,
274
-			$share->getPermissions()
275
-		);
276
-
277
-		return [$token, $remoteId];
278
-	}
279
-
280
-	/**
281
-	 * get federated share from the share_external table but exclude mounted link shares
282
-	 *
283
-	 * @param IShare $share
284
-	 * @return array
285
-	 * @throws ShareNotFound
286
-	 */
287
-	protected function getShareFromExternalShareTable(IShare $share) {
288
-		$query = $this->dbConnection->getQueryBuilder();
289
-		$query->select('*')->from($this->externalShareTable)
290
-			->where($query->expr()->eq('user', $query->createNamedParameter($share->getShareOwner())))
291
-			->andWhere($query->expr()->eq('mountpoint', $query->createNamedParameter($share->getTarget())));
292
-		$result = $query->execute()->fetchAll();
293
-
294
-		if (isset($result[0]) && (int)$result[0]['remote_id'] > 0) {
295
-			return $result[0];
296
-		}
297
-
298
-		throw new ShareNotFound('share not found in share_external table');
299
-	}
300
-
301
-	/**
302
-	 * add share to the database and return the ID
303
-	 *
304
-	 * @param int $itemSource
305
-	 * @param string $itemType
306
-	 * @param string $shareWith
307
-	 * @param string $sharedBy
308
-	 * @param string $uidOwner
309
-	 * @param int $permissions
310
-	 * @param string $token
311
-	 * @return int
312
-	 */
313
-	private function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token) {
314
-		$qb = $this->dbConnection->getQueryBuilder();
315
-		$qb->insert('share')
316
-			->setValue('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE))
317
-			->setValue('item_type', $qb->createNamedParameter($itemType))
318
-			->setValue('item_source', $qb->createNamedParameter($itemSource))
319
-			->setValue('file_source', $qb->createNamedParameter($itemSource))
320
-			->setValue('share_with', $qb->createNamedParameter($shareWith))
321
-			->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
322
-			->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
323
-			->setValue('permissions', $qb->createNamedParameter($permissions))
324
-			->setValue('token', $qb->createNamedParameter($token))
325
-			->setValue('stime', $qb->createNamedParameter(time()));
326
-
327
-		/*
145
+        $alreadyShared = $this->getSharedWith($shareWith, self::SHARE_TYPE_REMOTE, $share->getNode(), 1, 0);
146
+        if (!empty($alreadyShared)) {
147
+            $message = 'Sharing %s failed, because this item is already shared with %s';
148
+            $message_t = $this->l->t('Sharing %s failed, because this item is already shared with %s', array($share->getNode()->getName(), $shareWith));
149
+            $this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
150
+            throw new \Exception($message_t);
151
+        }
152
+
153
+
154
+        // don't allow federated shares if source and target server are the same
155
+        list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
156
+        $currentServer = $this->addressHandler->generateRemoteURL();
157
+        $currentUser = $sharedBy;
158
+        if ($this->addressHandler->compareAddresses($user, $remote, $currentUser, $currentServer)) {
159
+            $message = 'Not allowed to create a federated share with the same user.';
160
+            $message_t = $this->l->t('Not allowed to create a federated share with the same user');
161
+            $this->logger->debug($message, ['app' => 'Federated File Sharing']);
162
+            throw new \Exception($message_t);
163
+        }
164
+
165
+        $share->setSharedWith($user . '@' . $remote);
166
+
167
+        try {
168
+            $remoteShare = $this->getShareFromExternalShareTable($share);
169
+        } catch (ShareNotFound $e) {
170
+            $remoteShare = null;
171
+        }
172
+
173
+        if ($remoteShare) {
174
+            try {
175
+                $uidOwner = $remoteShare['owner'] . '@' . $remoteShare['remote'];
176
+                $shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, 'tmp_token_' . time());
177
+                $share->setId($shareId);
178
+                list($token, $remoteId) = $this->askOwnerToReShare($shareWith, $share, $shareId);
179
+                // remote share was create successfully if we get a valid token as return
180
+                $send = is_string($token) && $token !== '';
181
+            } catch (\Exception $e) {
182
+                // fall back to old re-share behavior if the remote server
183
+                // doesn't support flat re-shares (was introduced with Nextcloud 9.1)
184
+                $this->removeShareFromTable($share);
185
+                $shareId = $this->createFederatedShare($share);
186
+            }
187
+            if ($send) {
188
+                $this->updateSuccessfulReshare($shareId, $token);
189
+                $this->storeRemoteId($shareId, $remoteId);
190
+            } else {
191
+                $this->removeShareFromTable($share);
192
+                $message_t = $this->l->t('File is already shared with %s', [$shareWith]);
193
+                throw new \Exception($message_t);
194
+            }
195
+
196
+        } else {
197
+            $shareId = $this->createFederatedShare($share);
198
+        }
199
+
200
+        $data = $this->getRawShare($shareId);
201
+        return $this->createShareObject($data);
202
+    }
203
+
204
+    /**
205
+     * create federated share and inform the recipient
206
+     *
207
+     * @param IShare $share
208
+     * @return int
209
+     * @throws ShareNotFound
210
+     * @throws \Exception
211
+     */
212
+    protected function createFederatedShare(IShare $share) {
213
+        $token = $this->tokenHandler->generateToken();
214
+        $shareId = $this->addShareToDB(
215
+            $share->getNodeId(),
216
+            $share->getNodeType(),
217
+            $share->getSharedWith(),
218
+            $share->getSharedBy(),
219
+            $share->getShareOwner(),
220
+            $share->getPermissions(),
221
+            $token
222
+        );
223
+
224
+        try {
225
+            $sharedByFederatedId = $share->getSharedBy();
226
+            if ($this->userManager->userExists($sharedByFederatedId)) {
227
+                $sharedByFederatedId = $sharedByFederatedId . '@' . $this->addressHandler->generateRemoteURL();
228
+            }
229
+            $send = $this->notifications->sendRemoteShare(
230
+                $token,
231
+                $share->getSharedWith(),
232
+                $share->getNode()->getName(),
233
+                $shareId,
234
+                $share->getShareOwner(),
235
+                $share->getShareOwner() . '@' . $this->addressHandler->generateRemoteURL(),
236
+                $share->getSharedBy(),
237
+                $sharedByFederatedId
238
+            );
239
+
240
+            if ($send === false) {
241
+                $message_t = $this->l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable.',
242
+                    [$share->getNode()->getName(), $share->getSharedWith()]);
243
+                throw new \Exception($message_t);
244
+            }
245
+        } catch (\Exception $e) {
246
+            $this->logger->error('Failed to notify remote server of federated share, removing share (' . $e->getMessage() . ')');
247
+            $this->removeShareFromTableById($shareId);
248
+            throw $e;
249
+        }
250
+
251
+        return $shareId;
252
+    }
253
+
254
+    /**
255
+     * @param string $shareWith
256
+     * @param IShare $share
257
+     * @param string $shareId internal share Id
258
+     * @return array
259
+     * @throws \Exception
260
+     */
261
+    protected function askOwnerToReShare($shareWith, IShare $share, $shareId) {
262
+
263
+        $remoteShare = $this->getShareFromExternalShareTable($share);
264
+        $token = $remoteShare['share_token'];
265
+        $remoteId = $remoteShare['remote_id'];
266
+        $remote = $remoteShare['remote'];
267
+
268
+        list($token, $remoteId) = $this->notifications->requestReShare(
269
+            $token,
270
+            $remoteId,
271
+            $shareId,
272
+            $remote,
273
+            $shareWith,
274
+            $share->getPermissions()
275
+        );
276
+
277
+        return [$token, $remoteId];
278
+    }
279
+
280
+    /**
281
+     * get federated share from the share_external table but exclude mounted link shares
282
+     *
283
+     * @param IShare $share
284
+     * @return array
285
+     * @throws ShareNotFound
286
+     */
287
+    protected function getShareFromExternalShareTable(IShare $share) {
288
+        $query = $this->dbConnection->getQueryBuilder();
289
+        $query->select('*')->from($this->externalShareTable)
290
+            ->where($query->expr()->eq('user', $query->createNamedParameter($share->getShareOwner())))
291
+            ->andWhere($query->expr()->eq('mountpoint', $query->createNamedParameter($share->getTarget())));
292
+        $result = $query->execute()->fetchAll();
293
+
294
+        if (isset($result[0]) && (int)$result[0]['remote_id'] > 0) {
295
+            return $result[0];
296
+        }
297
+
298
+        throw new ShareNotFound('share not found in share_external table');
299
+    }
300
+
301
+    /**
302
+     * add share to the database and return the ID
303
+     *
304
+     * @param int $itemSource
305
+     * @param string $itemType
306
+     * @param string $shareWith
307
+     * @param string $sharedBy
308
+     * @param string $uidOwner
309
+     * @param int $permissions
310
+     * @param string $token
311
+     * @return int
312
+     */
313
+    private function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token) {
314
+        $qb = $this->dbConnection->getQueryBuilder();
315
+        $qb->insert('share')
316
+            ->setValue('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE))
317
+            ->setValue('item_type', $qb->createNamedParameter($itemType))
318
+            ->setValue('item_source', $qb->createNamedParameter($itemSource))
319
+            ->setValue('file_source', $qb->createNamedParameter($itemSource))
320
+            ->setValue('share_with', $qb->createNamedParameter($shareWith))
321
+            ->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
322
+            ->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
323
+            ->setValue('permissions', $qb->createNamedParameter($permissions))
324
+            ->setValue('token', $qb->createNamedParameter($token))
325
+            ->setValue('stime', $qb->createNamedParameter(time()));
326
+
327
+        /*
328 328
 		 * Added to fix https://github.com/owncloud/core/issues/22215
329 329
 		 * Can be removed once we get rid of ajax/share.php
330 330
 		 */
331
-		$qb->setValue('file_target', $qb->createNamedParameter(''));
332
-
333
-		$qb->execute();
334
-		$id = $qb->getLastInsertId();
335
-
336
-		return (int)$id;
337
-	}
338
-
339
-	/**
340
-	 * Update a share
341
-	 *
342
-	 * @param IShare $share
343
-	 * @return IShare The share object
344
-	 */
345
-	public function update(IShare $share) {
346
-		/*
331
+        $qb->setValue('file_target', $qb->createNamedParameter(''));
332
+
333
+        $qb->execute();
334
+        $id = $qb->getLastInsertId();
335
+
336
+        return (int)$id;
337
+    }
338
+
339
+    /**
340
+     * Update a share
341
+     *
342
+     * @param IShare $share
343
+     * @return IShare The share object
344
+     */
345
+    public function update(IShare $share) {
346
+        /*
347 347
 		 * We allow updating the permissions of federated shares
348 348
 		 */
349
-		$qb = $this->dbConnection->getQueryBuilder();
350
-			$qb->update('share')
351
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
352
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
353
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
354
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
355
-				->execute();
356
-
357
-		// send the updated permission to the owner/initiator, if they are not the same
358
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
359
-			$this->sendPermissionUpdate($share);
360
-		}
361
-
362
-		return $share;
363
-	}
364
-
365
-	/**
366
-	 * send the updated permission to the owner/initiator, if they are not the same
367
-	 *
368
-	 * @param IShare $share
369
-	 * @throws ShareNotFound
370
-	 * @throws \OC\HintException
371
-	 */
372
-	protected function sendPermissionUpdate(IShare $share) {
373
-		$remoteId = $this->getRemoteId($share);
374
-		// if the local user is the owner we send the permission change to the initiator
375
-		if ($this->userManager->userExists($share->getShareOwner())) {
376
-			list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
377
-		} else { // ... if not we send the permission change to the owner
378
-			list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
379
-		}
380
-		$this->notifications->sendPermissionChange($remote, $remoteId, $share->getToken(), $share->getPermissions());
381
-	}
382
-
383
-
384
-	/**
385
-	 * update successful reShare with the correct token
386
-	 *
387
-	 * @param int $shareId
388
-	 * @param string $token
389
-	 */
390
-	protected function updateSuccessfulReShare($shareId, $token) {
391
-		$query = $this->dbConnection->getQueryBuilder();
392
-		$query->update('share')
393
-			->where($query->expr()->eq('id', $query->createNamedParameter($shareId)))
394
-			->set('token', $query->createNamedParameter($token))
395
-			->execute();
396
-	}
397
-
398
-	/**
399
-	 * store remote ID in federated reShare table
400
-	 *
401
-	 * @param $shareId
402
-	 * @param $remoteId
403
-	 */
404
-	public function storeRemoteId($shareId, $remoteId) {
405
-		$query = $this->dbConnection->getQueryBuilder();
406
-		$query->insert('federated_reshares')
407
-			->values(
408
-				[
409
-					'share_id' =>  $query->createNamedParameter($shareId),
410
-					'remote_id' => $query->createNamedParameter($remoteId),
411
-				]
412
-			);
413
-		$query->execute();
414
-	}
415
-
416
-	/**
417
-	 * get share ID on remote server for federated re-shares
418
-	 *
419
-	 * @param IShare $share
420
-	 * @return int
421
-	 * @throws ShareNotFound
422
-	 */
423
-	public function getRemoteId(IShare $share) {
424
-		$query = $this->dbConnection->getQueryBuilder();
425
-		$query->select('remote_id')->from('federated_reshares')
426
-			->where($query->expr()->eq('share_id', $query->createNamedParameter((int)$share->getId())));
427
-		$data = $query->execute()->fetch();
428
-
429
-		if (!is_array($data) || !isset($data['remote_id'])) {
430
-			throw new ShareNotFound();
431
-		}
432
-
433
-		return (int)$data['remote_id'];
434
-	}
435
-
436
-	/**
437
-	 * @inheritdoc
438
-	 */
439
-	public function move(IShare $share, $recipient) {
440
-		/*
349
+        $qb = $this->dbConnection->getQueryBuilder();
350
+            $qb->update('share')
351
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
352
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
353
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
354
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
355
+                ->execute();
356
+
357
+        // send the updated permission to the owner/initiator, if they are not the same
358
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
359
+            $this->sendPermissionUpdate($share);
360
+        }
361
+
362
+        return $share;
363
+    }
364
+
365
+    /**
366
+     * send the updated permission to the owner/initiator, if they are not the same
367
+     *
368
+     * @param IShare $share
369
+     * @throws ShareNotFound
370
+     * @throws \OC\HintException
371
+     */
372
+    protected function sendPermissionUpdate(IShare $share) {
373
+        $remoteId = $this->getRemoteId($share);
374
+        // if the local user is the owner we send the permission change to the initiator
375
+        if ($this->userManager->userExists($share->getShareOwner())) {
376
+            list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
377
+        } else { // ... if not we send the permission change to the owner
378
+            list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
379
+        }
380
+        $this->notifications->sendPermissionChange($remote, $remoteId, $share->getToken(), $share->getPermissions());
381
+    }
382
+
383
+
384
+    /**
385
+     * update successful reShare with the correct token
386
+     *
387
+     * @param int $shareId
388
+     * @param string $token
389
+     */
390
+    protected function updateSuccessfulReShare($shareId, $token) {
391
+        $query = $this->dbConnection->getQueryBuilder();
392
+        $query->update('share')
393
+            ->where($query->expr()->eq('id', $query->createNamedParameter($shareId)))
394
+            ->set('token', $query->createNamedParameter($token))
395
+            ->execute();
396
+    }
397
+
398
+    /**
399
+     * store remote ID in federated reShare table
400
+     *
401
+     * @param $shareId
402
+     * @param $remoteId
403
+     */
404
+    public function storeRemoteId($shareId, $remoteId) {
405
+        $query = $this->dbConnection->getQueryBuilder();
406
+        $query->insert('federated_reshares')
407
+            ->values(
408
+                [
409
+                    'share_id' =>  $query->createNamedParameter($shareId),
410
+                    'remote_id' => $query->createNamedParameter($remoteId),
411
+                ]
412
+            );
413
+        $query->execute();
414
+    }
415
+
416
+    /**
417
+     * get share ID on remote server for federated re-shares
418
+     *
419
+     * @param IShare $share
420
+     * @return int
421
+     * @throws ShareNotFound
422
+     */
423
+    public function getRemoteId(IShare $share) {
424
+        $query = $this->dbConnection->getQueryBuilder();
425
+        $query->select('remote_id')->from('federated_reshares')
426
+            ->where($query->expr()->eq('share_id', $query->createNamedParameter((int)$share->getId())));
427
+        $data = $query->execute()->fetch();
428
+
429
+        if (!is_array($data) || !isset($data['remote_id'])) {
430
+            throw new ShareNotFound();
431
+        }
432
+
433
+        return (int)$data['remote_id'];
434
+    }
435
+
436
+    /**
437
+     * @inheritdoc
438
+     */
439
+    public function move(IShare $share, $recipient) {
440
+        /*
441 441
 		 * This function does nothing yet as it is just for outgoing
442 442
 		 * federated shares.
443 443
 		 */
444
-		return $share;
445
-	}
446
-
447
-	/**
448
-	 * Get all children of this share
449
-	 *
450
-	 * @param IShare $parent
451
-	 * @return IShare[]
452
-	 */
453
-	public function getChildren(IShare $parent) {
454
-		$children = [];
455
-
456
-		$qb = $this->dbConnection->getQueryBuilder();
457
-		$qb->select('*')
458
-			->from('share')
459
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
460
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
461
-			->orderBy('id');
462
-
463
-		$cursor = $qb->execute();
464
-		while($data = $cursor->fetch()) {
465
-			$children[] = $this->createShareObject($data);
466
-		}
467
-		$cursor->closeCursor();
468
-
469
-		return $children;
470
-	}
471
-
472
-	/**
473
-	 * Delete a share (owner unShares the file)
474
-	 *
475
-	 * @param IShare $share
476
-	 */
477
-	public function delete(IShare $share) {
478
-
479
-		list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedWith());
480
-
481
-		$isOwner = false;
482
-
483
-		$this->removeShareFromTable($share);
484
-
485
-		// if the local user is the owner we can send the unShare request directly...
486
-		if ($this->userManager->userExists($share->getShareOwner())) {
487
-			$this->notifications->sendRemoteUnShare($remote, $share->getId(), $share->getToken());
488
-			$this->revokeShare($share, true);
489
-			$isOwner = true;
490
-		} else { // ... if not we need to correct ID for the unShare request
491
-			$remoteId = $this->getRemoteId($share);
492
-			$this->notifications->sendRemoteUnShare($remote, $remoteId, $share->getToken());
493
-			$this->revokeShare($share, false);
494
-		}
495
-
496
-		// send revoke notification to the other user, if initiator and owner are not the same user
497
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
498
-			$remoteId = $this->getRemoteId($share);
499
-			if ($isOwner) {
500
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
501
-			} else {
502
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
503
-			}
504
-			$this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
505
-		}
506
-	}
507
-
508
-	/**
509
-	 * in case of a re-share we need to send the other use (initiator or owner)
510
-	 * a message that the file was unshared
511
-	 *
512
-	 * @param IShare $share
513
-	 * @param bool $isOwner the user can either be the owner or the user who re-sahred it
514
-	 * @throws ShareNotFound
515
-	 * @throws \OC\HintException
516
-	 */
517
-	protected function revokeShare($share, $isOwner) {
518
-		// also send a unShare request to the initiator, if this is a different user than the owner
519
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
520
-			if ($isOwner) {
521
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
522
-			} else {
523
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
524
-			}
525
-			$remoteId = $this->getRemoteId($share);
526
-			$this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
527
-		}
528
-	}
529
-
530
-	/**
531
-	 * remove share from table
532
-	 *
533
-	 * @param IShare $share
534
-	 */
535
-	public function removeShareFromTable(IShare $share) {
536
-		$this->removeShareFromTableById($share->getId());
537
-	}
538
-
539
-	/**
540
-	 * remove share from table
541
-	 *
542
-	 * @param string $shareId
543
-	 */
544
-	private function removeShareFromTableById($shareId) {
545
-		$qb = $this->dbConnection->getQueryBuilder();
546
-		$qb->delete('share')
547
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
548
-		$qb->execute();
549
-
550
-		$qb->delete('federated_reshares')
551
-			->where($qb->expr()->eq('share_id', $qb->createNamedParameter($shareId)));
552
-		$qb->execute();
553
-	}
554
-
555
-	/**
556
-	 * @inheritdoc
557
-	 */
558
-	public function deleteFromSelf(IShare $share, $recipient) {
559
-		// nothing to do here. Technically deleteFromSelf in the context of federated
560
-		// shares is a umount of a external storage. This is handled here
561
-		// apps/files_sharing/lib/external/manager.php
562
-		// TODO move this code over to this app
563
-		return;
564
-	}
565
-
566
-	/**
567
-	 * @inheritdoc
568
-	 */
569
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
570
-		$qb = $this->dbConnection->getQueryBuilder();
571
-		$qb->select('*')
572
-			->from('share');
573
-
574
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
575
-
576
-		/**
577
-		 * Reshares for this user are shares where they are the owner.
578
-		 */
579
-		if ($reshares === false) {
580
-			//Special case for old shares created via the web UI
581
-			$or1 = $qb->expr()->andX(
582
-				$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
583
-				$qb->expr()->isNull('uid_initiator')
584
-			);
585
-
586
-			$qb->andWhere(
587
-				$qb->expr()->orX(
588
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
589
-					$or1
590
-				)
591
-			);
592
-		} else {
593
-			$qb->andWhere(
594
-				$qb->expr()->orX(
595
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
596
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
597
-				)
598
-			);
599
-		}
600
-
601
-		if ($node !== null) {
602
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
603
-		}
604
-
605
-		if ($limit !== -1) {
606
-			$qb->setMaxResults($limit);
607
-		}
608
-
609
-		$qb->setFirstResult($offset);
610
-		$qb->orderBy('id');
611
-
612
-		$cursor = $qb->execute();
613
-		$shares = [];
614
-		while($data = $cursor->fetch()) {
615
-			$shares[] = $this->createShareObject($data);
616
-		}
617
-		$cursor->closeCursor();
618
-
619
-		return $shares;
620
-	}
621
-
622
-	/**
623
-	 * @inheritdoc
624
-	 */
625
-	public function getShareById($id, $recipientId = null) {
626
-		$qb = $this->dbConnection->getQueryBuilder();
627
-
628
-		$qb->select('*')
629
-			->from('share')
630
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
631
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
632
-
633
-		$cursor = $qb->execute();
634
-		$data = $cursor->fetch();
635
-		$cursor->closeCursor();
636
-
637
-		if ($data === false) {
638
-			throw new ShareNotFound();
639
-		}
640
-
641
-		try {
642
-			$share = $this->createShareObject($data);
643
-		} catch (InvalidShare $e) {
644
-			throw new ShareNotFound();
645
-		}
646
-
647
-		return $share;
648
-	}
649
-
650
-	/**
651
-	 * Get shares for a given path
652
-	 *
653
-	 * @param \OCP\Files\Node $path
654
-	 * @return IShare[]
655
-	 */
656
-	public function getSharesByPath(Node $path) {
657
-		$qb = $this->dbConnection->getQueryBuilder();
658
-
659
-		$cursor = $qb->select('*')
660
-			->from('share')
661
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
662
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
663
-			->execute();
664
-
665
-		$shares = [];
666
-		while($data = $cursor->fetch()) {
667
-			$shares[] = $this->createShareObject($data);
668
-		}
669
-		$cursor->closeCursor();
670
-
671
-		return $shares;
672
-	}
673
-
674
-	/**
675
-	 * @inheritdoc
676
-	 */
677
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
678
-		/** @var IShare[] $shares */
679
-		$shares = [];
680
-
681
-		//Get shares directly with this user
682
-		$qb = $this->dbConnection->getQueryBuilder();
683
-		$qb->select('*')
684
-			->from('share');
685
-
686
-		// Order by id
687
-		$qb->orderBy('id');
688
-
689
-		// Set limit and offset
690
-		if ($limit !== -1) {
691
-			$qb->setMaxResults($limit);
692
-		}
693
-		$qb->setFirstResult($offset);
694
-
695
-		$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
696
-		$qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
697
-
698
-		// Filter by node if provided
699
-		if ($node !== null) {
700
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
701
-		}
702
-
703
-		$cursor = $qb->execute();
704
-
705
-		while($data = $cursor->fetch()) {
706
-			$shares[] = $this->createShareObject($data);
707
-		}
708
-		$cursor->closeCursor();
709
-
710
-
711
-		return $shares;
712
-	}
713
-
714
-	/**
715
-	 * Get a share by token
716
-	 *
717
-	 * @param string $token
718
-	 * @return IShare
719
-	 * @throws ShareNotFound
720
-	 */
721
-	public function getShareByToken($token) {
722
-		$qb = $this->dbConnection->getQueryBuilder();
723
-
724
-		$cursor = $qb->select('*')
725
-			->from('share')
726
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
727
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
728
-			->execute();
729
-
730
-		$data = $cursor->fetch();
731
-
732
-		if ($data === false) {
733
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
734
-		}
735
-
736
-		try {
737
-			$share = $this->createShareObject($data);
738
-		} catch (InvalidShare $e) {
739
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
740
-		}
741
-
742
-		return $share;
743
-	}
744
-
745
-	/**
746
-	 * get database row of a give share
747
-	 *
748
-	 * @param $id
749
-	 * @return array
750
-	 * @throws ShareNotFound
751
-	 */
752
-	private function getRawShare($id) {
753
-
754
-		// Now fetch the inserted share and create a complete share object
755
-		$qb = $this->dbConnection->getQueryBuilder();
756
-		$qb->select('*')
757
-			->from('share')
758
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
759
-
760
-		$cursor = $qb->execute();
761
-		$data = $cursor->fetch();
762
-		$cursor->closeCursor();
763
-
764
-		if ($data === false) {
765
-			throw new ShareNotFound;
766
-		}
767
-
768
-		return $data;
769
-	}
770
-
771
-	/**
772
-	 * Create a share object from an database row
773
-	 *
774
-	 * @param array $data
775
-	 * @return IShare
776
-	 * @throws InvalidShare
777
-	 * @throws ShareNotFound
778
-	 */
779
-	private function createShareObject($data) {
780
-
781
-		$share = new Share($this->rootFolder, $this->userManager);
782
-		$share->setId((int)$data['id'])
783
-			->setShareType((int)$data['share_type'])
784
-			->setPermissions((int)$data['permissions'])
785
-			->setTarget($data['file_target'])
786
-			->setMailSend((bool)$data['mail_send'])
787
-			->setToken($data['token']);
788
-
789
-		$shareTime = new \DateTime();
790
-		$shareTime->setTimestamp((int)$data['stime']);
791
-		$share->setShareTime($shareTime);
792
-		$share->setSharedWith($data['share_with']);
793
-
794
-		if ($data['uid_initiator'] !== null) {
795
-			$share->setShareOwner($data['uid_owner']);
796
-			$share->setSharedBy($data['uid_initiator']);
797
-		} else {
798
-			//OLD SHARE
799
-			$share->setSharedBy($data['uid_owner']);
800
-			$path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
801
-
802
-			$owner = $path->getOwner();
803
-			$share->setShareOwner($owner->getUID());
804
-		}
805
-
806
-		$share->setNodeId((int)$data['file_source']);
807
-		$share->setNodeType($data['item_type']);
808
-
809
-		$share->setProviderId($this->identifier());
810
-
811
-		return $share;
812
-	}
813
-
814
-	/**
815
-	 * Get the node with file $id for $user
816
-	 *
817
-	 * @param string $userId
818
-	 * @param int $id
819
-	 * @return \OCP\Files\File|\OCP\Files\Folder
820
-	 * @throws InvalidShare
821
-	 */
822
-	private function getNode($userId, $id) {
823
-		try {
824
-			$userFolder = $this->rootFolder->getUserFolder($userId);
825
-		} catch (NotFoundException $e) {
826
-			throw new InvalidShare();
827
-		}
828
-
829
-		$nodes = $userFolder->getById($id);
830
-
831
-		if (empty($nodes)) {
832
-			throw new InvalidShare();
833
-		}
834
-
835
-		return $nodes[0];
836
-	}
837
-
838
-	/**
839
-	 * A user is deleted from the system
840
-	 * So clean up the relevant shares.
841
-	 *
842
-	 * @param string $uid
843
-	 * @param int $shareType
844
-	 */
845
-	public function userDeleted($uid, $shareType) {
846
-		//TODO: probabaly a good idea to send unshare info to remote servers
847
-
848
-		$qb = $this->dbConnection->getQueryBuilder();
849
-
850
-		$qb->delete('share')
851
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE)))
852
-			->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
853
-			->execute();
854
-	}
855
-
856
-	/**
857
-	 * This provider does not handle groups
858
-	 *
859
-	 * @param string $gid
860
-	 */
861
-	public function groupDeleted($gid) {
862
-		// We don't handle groups here
863
-		return;
864
-	}
865
-
866
-	/**
867
-	 * This provider does not handle groups
868
-	 *
869
-	 * @param string $uid
870
-	 * @param string $gid
871
-	 */
872
-	public function userDeletedFromGroup($uid, $gid) {
873
-		// We don't handle groups here
874
-		return;
875
-	}
876
-
877
-	/**
878
-	 * check if users from other Nextcloud instances are allowed to mount public links share by this instance
879
-	 *
880
-	 * @return bool
881
-	 */
882
-	public function isOutgoingServer2serverShareEnabled() {
883
-		$result = $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes');
884
-		return ($result === 'yes') ? true : false;
885
-	}
886
-
887
-	/**
888
-	 * check if users are allowed to mount public links from other ownClouds
889
-	 *
890
-	 * @return bool
891
-	 */
892
-	public function isIncomingServer2serverShareEnabled() {
893
-		$result = $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes');
894
-		return ($result === 'yes') ? true : false;
895
-	}
444
+        return $share;
445
+    }
446
+
447
+    /**
448
+     * Get all children of this share
449
+     *
450
+     * @param IShare $parent
451
+     * @return IShare[]
452
+     */
453
+    public function getChildren(IShare $parent) {
454
+        $children = [];
455
+
456
+        $qb = $this->dbConnection->getQueryBuilder();
457
+        $qb->select('*')
458
+            ->from('share')
459
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
460
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
461
+            ->orderBy('id');
462
+
463
+        $cursor = $qb->execute();
464
+        while($data = $cursor->fetch()) {
465
+            $children[] = $this->createShareObject($data);
466
+        }
467
+        $cursor->closeCursor();
468
+
469
+        return $children;
470
+    }
471
+
472
+    /**
473
+     * Delete a share (owner unShares the file)
474
+     *
475
+     * @param IShare $share
476
+     */
477
+    public function delete(IShare $share) {
478
+
479
+        list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedWith());
480
+
481
+        $isOwner = false;
482
+
483
+        $this->removeShareFromTable($share);
484
+
485
+        // if the local user is the owner we can send the unShare request directly...
486
+        if ($this->userManager->userExists($share->getShareOwner())) {
487
+            $this->notifications->sendRemoteUnShare($remote, $share->getId(), $share->getToken());
488
+            $this->revokeShare($share, true);
489
+            $isOwner = true;
490
+        } else { // ... if not we need to correct ID for the unShare request
491
+            $remoteId = $this->getRemoteId($share);
492
+            $this->notifications->sendRemoteUnShare($remote, $remoteId, $share->getToken());
493
+            $this->revokeShare($share, false);
494
+        }
495
+
496
+        // send revoke notification to the other user, if initiator and owner are not the same user
497
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
498
+            $remoteId = $this->getRemoteId($share);
499
+            if ($isOwner) {
500
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
501
+            } else {
502
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
503
+            }
504
+            $this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
505
+        }
506
+    }
507
+
508
+    /**
509
+     * in case of a re-share we need to send the other use (initiator or owner)
510
+     * a message that the file was unshared
511
+     *
512
+     * @param IShare $share
513
+     * @param bool $isOwner the user can either be the owner or the user who re-sahred it
514
+     * @throws ShareNotFound
515
+     * @throws \OC\HintException
516
+     */
517
+    protected function revokeShare($share, $isOwner) {
518
+        // also send a unShare request to the initiator, if this is a different user than the owner
519
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
520
+            if ($isOwner) {
521
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
522
+            } else {
523
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
524
+            }
525
+            $remoteId = $this->getRemoteId($share);
526
+            $this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
527
+        }
528
+    }
529
+
530
+    /**
531
+     * remove share from table
532
+     *
533
+     * @param IShare $share
534
+     */
535
+    public function removeShareFromTable(IShare $share) {
536
+        $this->removeShareFromTableById($share->getId());
537
+    }
538
+
539
+    /**
540
+     * remove share from table
541
+     *
542
+     * @param string $shareId
543
+     */
544
+    private function removeShareFromTableById($shareId) {
545
+        $qb = $this->dbConnection->getQueryBuilder();
546
+        $qb->delete('share')
547
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
548
+        $qb->execute();
549
+
550
+        $qb->delete('federated_reshares')
551
+            ->where($qb->expr()->eq('share_id', $qb->createNamedParameter($shareId)));
552
+        $qb->execute();
553
+    }
554
+
555
+    /**
556
+     * @inheritdoc
557
+     */
558
+    public function deleteFromSelf(IShare $share, $recipient) {
559
+        // nothing to do here. Technically deleteFromSelf in the context of federated
560
+        // shares is a umount of a external storage. This is handled here
561
+        // apps/files_sharing/lib/external/manager.php
562
+        // TODO move this code over to this app
563
+        return;
564
+    }
565
+
566
+    /**
567
+     * @inheritdoc
568
+     */
569
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
570
+        $qb = $this->dbConnection->getQueryBuilder();
571
+        $qb->select('*')
572
+            ->from('share');
573
+
574
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
575
+
576
+        /**
577
+         * Reshares for this user are shares where they are the owner.
578
+         */
579
+        if ($reshares === false) {
580
+            //Special case for old shares created via the web UI
581
+            $or1 = $qb->expr()->andX(
582
+                $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
583
+                $qb->expr()->isNull('uid_initiator')
584
+            );
585
+
586
+            $qb->andWhere(
587
+                $qb->expr()->orX(
588
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
589
+                    $or1
590
+                )
591
+            );
592
+        } else {
593
+            $qb->andWhere(
594
+                $qb->expr()->orX(
595
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
596
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
597
+                )
598
+            );
599
+        }
600
+
601
+        if ($node !== null) {
602
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
603
+        }
604
+
605
+        if ($limit !== -1) {
606
+            $qb->setMaxResults($limit);
607
+        }
608
+
609
+        $qb->setFirstResult($offset);
610
+        $qb->orderBy('id');
611
+
612
+        $cursor = $qb->execute();
613
+        $shares = [];
614
+        while($data = $cursor->fetch()) {
615
+            $shares[] = $this->createShareObject($data);
616
+        }
617
+        $cursor->closeCursor();
618
+
619
+        return $shares;
620
+    }
621
+
622
+    /**
623
+     * @inheritdoc
624
+     */
625
+    public function getShareById($id, $recipientId = null) {
626
+        $qb = $this->dbConnection->getQueryBuilder();
627
+
628
+        $qb->select('*')
629
+            ->from('share')
630
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
631
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
632
+
633
+        $cursor = $qb->execute();
634
+        $data = $cursor->fetch();
635
+        $cursor->closeCursor();
636
+
637
+        if ($data === false) {
638
+            throw new ShareNotFound();
639
+        }
640
+
641
+        try {
642
+            $share = $this->createShareObject($data);
643
+        } catch (InvalidShare $e) {
644
+            throw new ShareNotFound();
645
+        }
646
+
647
+        return $share;
648
+    }
649
+
650
+    /**
651
+     * Get shares for a given path
652
+     *
653
+     * @param \OCP\Files\Node $path
654
+     * @return IShare[]
655
+     */
656
+    public function getSharesByPath(Node $path) {
657
+        $qb = $this->dbConnection->getQueryBuilder();
658
+
659
+        $cursor = $qb->select('*')
660
+            ->from('share')
661
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
662
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
663
+            ->execute();
664
+
665
+        $shares = [];
666
+        while($data = $cursor->fetch()) {
667
+            $shares[] = $this->createShareObject($data);
668
+        }
669
+        $cursor->closeCursor();
670
+
671
+        return $shares;
672
+    }
673
+
674
+    /**
675
+     * @inheritdoc
676
+     */
677
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
678
+        /** @var IShare[] $shares */
679
+        $shares = [];
680
+
681
+        //Get shares directly with this user
682
+        $qb = $this->dbConnection->getQueryBuilder();
683
+        $qb->select('*')
684
+            ->from('share');
685
+
686
+        // Order by id
687
+        $qb->orderBy('id');
688
+
689
+        // Set limit and offset
690
+        if ($limit !== -1) {
691
+            $qb->setMaxResults($limit);
692
+        }
693
+        $qb->setFirstResult($offset);
694
+
695
+        $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
696
+        $qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
697
+
698
+        // Filter by node if provided
699
+        if ($node !== null) {
700
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
701
+        }
702
+
703
+        $cursor = $qb->execute();
704
+
705
+        while($data = $cursor->fetch()) {
706
+            $shares[] = $this->createShareObject($data);
707
+        }
708
+        $cursor->closeCursor();
709
+
710
+
711
+        return $shares;
712
+    }
713
+
714
+    /**
715
+     * Get a share by token
716
+     *
717
+     * @param string $token
718
+     * @return IShare
719
+     * @throws ShareNotFound
720
+     */
721
+    public function getShareByToken($token) {
722
+        $qb = $this->dbConnection->getQueryBuilder();
723
+
724
+        $cursor = $qb->select('*')
725
+            ->from('share')
726
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
727
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
728
+            ->execute();
729
+
730
+        $data = $cursor->fetch();
731
+
732
+        if ($data === false) {
733
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
734
+        }
735
+
736
+        try {
737
+            $share = $this->createShareObject($data);
738
+        } catch (InvalidShare $e) {
739
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
740
+        }
741
+
742
+        return $share;
743
+    }
744
+
745
+    /**
746
+     * get database row of a give share
747
+     *
748
+     * @param $id
749
+     * @return array
750
+     * @throws ShareNotFound
751
+     */
752
+    private function getRawShare($id) {
753
+
754
+        // Now fetch the inserted share and create a complete share object
755
+        $qb = $this->dbConnection->getQueryBuilder();
756
+        $qb->select('*')
757
+            ->from('share')
758
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
759
+
760
+        $cursor = $qb->execute();
761
+        $data = $cursor->fetch();
762
+        $cursor->closeCursor();
763
+
764
+        if ($data === false) {
765
+            throw new ShareNotFound;
766
+        }
767
+
768
+        return $data;
769
+    }
770
+
771
+    /**
772
+     * Create a share object from an database row
773
+     *
774
+     * @param array $data
775
+     * @return IShare
776
+     * @throws InvalidShare
777
+     * @throws ShareNotFound
778
+     */
779
+    private function createShareObject($data) {
780
+
781
+        $share = new Share($this->rootFolder, $this->userManager);
782
+        $share->setId((int)$data['id'])
783
+            ->setShareType((int)$data['share_type'])
784
+            ->setPermissions((int)$data['permissions'])
785
+            ->setTarget($data['file_target'])
786
+            ->setMailSend((bool)$data['mail_send'])
787
+            ->setToken($data['token']);
788
+
789
+        $shareTime = new \DateTime();
790
+        $shareTime->setTimestamp((int)$data['stime']);
791
+        $share->setShareTime($shareTime);
792
+        $share->setSharedWith($data['share_with']);
793
+
794
+        if ($data['uid_initiator'] !== null) {
795
+            $share->setShareOwner($data['uid_owner']);
796
+            $share->setSharedBy($data['uid_initiator']);
797
+        } else {
798
+            //OLD SHARE
799
+            $share->setSharedBy($data['uid_owner']);
800
+            $path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
801
+
802
+            $owner = $path->getOwner();
803
+            $share->setShareOwner($owner->getUID());
804
+        }
805
+
806
+        $share->setNodeId((int)$data['file_source']);
807
+        $share->setNodeType($data['item_type']);
808
+
809
+        $share->setProviderId($this->identifier());
810
+
811
+        return $share;
812
+    }
813
+
814
+    /**
815
+     * Get the node with file $id for $user
816
+     *
817
+     * @param string $userId
818
+     * @param int $id
819
+     * @return \OCP\Files\File|\OCP\Files\Folder
820
+     * @throws InvalidShare
821
+     */
822
+    private function getNode($userId, $id) {
823
+        try {
824
+            $userFolder = $this->rootFolder->getUserFolder($userId);
825
+        } catch (NotFoundException $e) {
826
+            throw new InvalidShare();
827
+        }
828
+
829
+        $nodes = $userFolder->getById($id);
830
+
831
+        if (empty($nodes)) {
832
+            throw new InvalidShare();
833
+        }
834
+
835
+        return $nodes[0];
836
+    }
837
+
838
+    /**
839
+     * A user is deleted from the system
840
+     * So clean up the relevant shares.
841
+     *
842
+     * @param string $uid
843
+     * @param int $shareType
844
+     */
845
+    public function userDeleted($uid, $shareType) {
846
+        //TODO: probabaly a good idea to send unshare info to remote servers
847
+
848
+        $qb = $this->dbConnection->getQueryBuilder();
849
+
850
+        $qb->delete('share')
851
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE)))
852
+            ->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
853
+            ->execute();
854
+    }
855
+
856
+    /**
857
+     * This provider does not handle groups
858
+     *
859
+     * @param string $gid
860
+     */
861
+    public function groupDeleted($gid) {
862
+        // We don't handle groups here
863
+        return;
864
+    }
865
+
866
+    /**
867
+     * This provider does not handle groups
868
+     *
869
+     * @param string $uid
870
+     * @param string $gid
871
+     */
872
+    public function userDeletedFromGroup($uid, $gid) {
873
+        // We don't handle groups here
874
+        return;
875
+    }
876
+
877
+    /**
878
+     * check if users from other Nextcloud instances are allowed to mount public links share by this instance
879
+     *
880
+     * @return bool
881
+     */
882
+    public function isOutgoingServer2serverShareEnabled() {
883
+        $result = $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes');
884
+        return ($result === 'yes') ? true : false;
885
+    }
886
+
887
+    /**
888
+     * check if users are allowed to mount public links from other ownClouds
889
+     *
890
+     * @return bool
891
+     */
892
+    public function isIncomingServer2serverShareEnabled() {
893
+        $result = $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes');
894
+        return ($result === 'yes') ? true : false;
895
+    }
896 896
 }
Please login to merge, or discard this patch.
Spacing   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -162,7 +162,7 @@  discard block
 block discarded – undo
162 162
 			throw new \Exception($message_t);
163 163
 		}
164 164
 
165
-		$share->setSharedWith($user . '@' . $remote);
165
+		$share->setSharedWith($user.'@'.$remote);
166 166
 
167 167
 		try {
168 168
 			$remoteShare = $this->getShareFromExternalShareTable($share);
@@ -172,8 +172,8 @@  discard block
 block discarded – undo
172 172
 
173 173
 		if ($remoteShare) {
174 174
 			try {
175
-				$uidOwner = $remoteShare['owner'] . '@' . $remoteShare['remote'];
176
-				$shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, 'tmp_token_' . time());
175
+				$uidOwner = $remoteShare['owner'].'@'.$remoteShare['remote'];
176
+				$shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, 'tmp_token_'.time());
177 177
 				$share->setId($shareId);
178 178
 				list($token, $remoteId) = $this->askOwnerToReShare($shareWith, $share, $shareId);
179 179
 				// remote share was create successfully if we get a valid token as return
@@ -224,7 +224,7 @@  discard block
 block discarded – undo
224 224
 		try {
225 225
 			$sharedByFederatedId = $share->getSharedBy();
226 226
 			if ($this->userManager->userExists($sharedByFederatedId)) {
227
-				$sharedByFederatedId = $sharedByFederatedId . '@' . $this->addressHandler->generateRemoteURL();
227
+				$sharedByFederatedId = $sharedByFederatedId.'@'.$this->addressHandler->generateRemoteURL();
228 228
 			}
229 229
 			$send = $this->notifications->sendRemoteShare(
230 230
 				$token,
@@ -232,7 +232,7 @@  discard block
 block discarded – undo
232 232
 				$share->getNode()->getName(),
233 233
 				$shareId,
234 234
 				$share->getShareOwner(),
235
-				$share->getShareOwner() . '@' . $this->addressHandler->generateRemoteURL(),
235
+				$share->getShareOwner().'@'.$this->addressHandler->generateRemoteURL(),
236 236
 				$share->getSharedBy(),
237 237
 				$sharedByFederatedId
238 238
 			);
@@ -243,7 +243,7 @@  discard block
 block discarded – undo
243 243
 				throw new \Exception($message_t);
244 244
 			}
245 245
 		} catch (\Exception $e) {
246
-			$this->logger->error('Failed to notify remote server of federated share, removing share (' . $e->getMessage() . ')');
246
+			$this->logger->error('Failed to notify remote server of federated share, removing share ('.$e->getMessage().')');
247 247
 			$this->removeShareFromTableById($shareId);
248 248
 			throw $e;
249 249
 		}
@@ -291,7 +291,7 @@  discard block
 block discarded – undo
291 291
 			->andWhere($query->expr()->eq('mountpoint', $query->createNamedParameter($share->getTarget())));
292 292
 		$result = $query->execute()->fetchAll();
293 293
 
294
-		if (isset($result[0]) && (int)$result[0]['remote_id'] > 0) {
294
+		if (isset($result[0]) && (int) $result[0]['remote_id'] > 0) {
295 295
 			return $result[0];
296 296
 		}
297 297
 
@@ -333,7 +333,7 @@  discard block
 block discarded – undo
333 333
 		$qb->execute();
334 334
 		$id = $qb->getLastInsertId();
335 335
 
336
-		return (int)$id;
336
+		return (int) $id;
337 337
 	}
338 338
 
339 339
 	/**
@@ -423,14 +423,14 @@  discard block
 block discarded – undo
423 423
 	public function getRemoteId(IShare $share) {
424 424
 		$query = $this->dbConnection->getQueryBuilder();
425 425
 		$query->select('remote_id')->from('federated_reshares')
426
-			->where($query->expr()->eq('share_id', $query->createNamedParameter((int)$share->getId())));
426
+			->where($query->expr()->eq('share_id', $query->createNamedParameter((int) $share->getId())));
427 427
 		$data = $query->execute()->fetch();
428 428
 
429 429
 		if (!is_array($data) || !isset($data['remote_id'])) {
430 430
 			throw new ShareNotFound();
431 431
 		}
432 432
 
433
-		return (int)$data['remote_id'];
433
+		return (int) $data['remote_id'];
434 434
 	}
435 435
 
436 436
 	/**
@@ -461,7 +461,7 @@  discard block
 block discarded – undo
461 461
 			->orderBy('id');
462 462
 
463 463
 		$cursor = $qb->execute();
464
-		while($data = $cursor->fetch()) {
464
+		while ($data = $cursor->fetch()) {
465 465
 			$children[] = $this->createShareObject($data);
466 466
 		}
467 467
 		$cursor->closeCursor();
@@ -611,7 +611,7 @@  discard block
 block discarded – undo
611 611
 
612 612
 		$cursor = $qb->execute();
613 613
 		$shares = [];
614
-		while($data = $cursor->fetch()) {
614
+		while ($data = $cursor->fetch()) {
615 615
 			$shares[] = $this->createShareObject($data);
616 616
 		}
617 617
 		$cursor->closeCursor();
@@ -663,7 +663,7 @@  discard block
 block discarded – undo
663 663
 			->execute();
664 664
 
665 665
 		$shares = [];
666
-		while($data = $cursor->fetch()) {
666
+		while ($data = $cursor->fetch()) {
667 667
 			$shares[] = $this->createShareObject($data);
668 668
 		}
669 669
 		$cursor->closeCursor();
@@ -702,7 +702,7 @@  discard block
 block discarded – undo
702 702
 
703 703
 		$cursor = $qb->execute();
704 704
 
705
-		while($data = $cursor->fetch()) {
705
+		while ($data = $cursor->fetch()) {
706 706
 			$shares[] = $this->createShareObject($data);
707 707
 		}
708 708
 		$cursor->closeCursor();
@@ -779,15 +779,15 @@  discard block
 block discarded – undo
779 779
 	private function createShareObject($data) {
780 780
 
781 781
 		$share = new Share($this->rootFolder, $this->userManager);
782
-		$share->setId((int)$data['id'])
783
-			->setShareType((int)$data['share_type'])
784
-			->setPermissions((int)$data['permissions'])
782
+		$share->setId((int) $data['id'])
783
+			->setShareType((int) $data['share_type'])
784
+			->setPermissions((int) $data['permissions'])
785 785
 			->setTarget($data['file_target'])
786
-			->setMailSend((bool)$data['mail_send'])
786
+			->setMailSend((bool) $data['mail_send'])
787 787
 			->setToken($data['token']);
788 788
 
789 789
 		$shareTime = new \DateTime();
790
-		$shareTime->setTimestamp((int)$data['stime']);
790
+		$shareTime->setTimestamp((int) $data['stime']);
791 791
 		$share->setShareTime($shareTime);
792 792
 		$share->setSharedWith($data['share_with']);
793 793
 
@@ -797,13 +797,13 @@  discard block
 block discarded – undo
797 797
 		} else {
798 798
 			//OLD SHARE
799 799
 			$share->setSharedBy($data['uid_owner']);
800
-			$path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
800
+			$path = $this->getNode($share->getSharedBy(), (int) $data['file_source']);
801 801
 
802 802
 			$owner = $path->getOwner();
803 803
 			$share->setShareOwner($owner->getUID());
804 804
 		}
805 805
 
806
-		$share->setNodeId((int)$data['file_source']);
806
+		$share->setNodeId((int) $data['file_source']);
807 807
 		$share->setNodeType($data['item_type']);
808 808
 
809 809
 		$share->setProviderId($this->identifier());
Please login to merge, or discard this patch.
apps/federation/lib/AppInfo/Application.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -30,7 +30,6 @@
 block discarded – undo
30 30
 use OCA\Federation\Hooks;
31 31
 use OCA\Federation\Middleware\AddServerMiddleware;
32 32
 use OCA\Federation\SyncFederationAddressBooks;
33
-use OCA\Federation\SyncJob;
34 33
 use OCA\Federation\TrustedServers;
35 34
 use OCP\API;
36 35
 use OCP\App;
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -82,7 +82,7 @@
 block discarded – undo
82 82
 			);
83 83
 		});
84 84
 
85
-		$container->registerService('SettingsController', function (IAppContainer $c) {
85
+		$container->registerService('SettingsController', function(IAppContainer $c) {
86 86
 			$server = $c->getServer();
87 87
 			return new SettingsController(
88 88
 				$c->getAppName(),
Please login to merge, or discard this patch.
Indentation   +129 added lines, -129 removed lines patch added patch discarded remove patch
@@ -42,134 +42,134 @@
 block discarded – undo
42 42
 
43 43
 class Application extends \OCP\AppFramework\App {
44 44
 
45
-	/**
46
-	 * @param array $urlParams
47
-	 */
48
-	public function __construct($urlParams = array()) {
49
-		parent::__construct('federation', $urlParams);
50
-		$this->registerService();
51
-		$this->registerMiddleware();
52
-	}
53
-
54
-	private function registerService() {
55
-		$container = $this->getContainer();
56
-
57
-		$container->registerService('addServerMiddleware', function(IAppContainer $c) {
58
-			return new AddServerMiddleware(
59
-				$c->getAppName(),
60
-				\OC::$server->getL10N($c->getAppName()),
61
-				\OC::$server->getLogger()
62
-			);
63
-		});
64
-
65
-		$container->registerService('DbHandler', function(IAppContainer $c) {
66
-			return new DbHandler(
67
-				\OC::$server->getDatabaseConnection(),
68
-				\OC::$server->getL10N($c->getAppName())
69
-			);
70
-		});
71
-
72
-		$container->registerService('TrustedServers', function(IAppContainer $c) {
73
-			$server = $c->getServer();
74
-			return new TrustedServers(
75
-				$c->query('DbHandler'),
76
-				$server->getHTTPClientService(),
77
-				$server->getLogger(),
78
-				$server->getJobList(),
79
-				$server->getSecureRandom(),
80
-				$server->getConfig(),
81
-				$server->getEventDispatcher()
82
-			);
83
-		});
84
-
85
-		$container->registerService('SettingsController', function (IAppContainer $c) {
86
-			$server = $c->getServer();
87
-			return new SettingsController(
88
-				$c->getAppName(),
89
-				$server->getRequest(),
90
-				$server->getL10N($c->getAppName()),
91
-				$c->query('TrustedServers')
92
-			);
93
-		});
94
-
95
-	}
96
-
97
-	private function registerMiddleware() {
98
-		$container = $this->getContainer();
99
-		$container->registerMiddleware('addServerMiddleware');
100
-	}
101
-
102
-	/**
103
-	 * register OCS API Calls
104
-	 */
105
-	public function registerOCSApi() {
106
-
107
-		$container = $this->getContainer();
108
-		$server = $container->getServer();
109
-
110
-		$auth = new OCSAuthAPI(
111
-			$server->getRequest(),
112
-			$server->getSecureRandom(),
113
-			$server->getJobList(),
114
-			$container->query('TrustedServers'),
115
-			$container->query('DbHandler'),
116
-			$server->getLogger()
117
-
118
-		);
119
-
120
-		API::register('get',
121
-			'/apps/federation/api/v1/shared-secret',
122
-			array($auth, 'getSharedSecret'),
123
-			'federation',
124
-			API::GUEST_AUTH
125
-		);
126
-
127
-		API::register('post',
128
-			'/apps/federation/api/v1/request-shared-secret',
129
-			array($auth, 'requestSharedSecret'),
130
-			'federation',
131
-			API::GUEST_AUTH
132
-		);
133
-
134
-	}
135
-
136
-	/**
137
-	 * listen to federated_share_added hooks to auto-add new servers to the
138
-	 * list of trusted servers.
139
-	 */
140
-	public function registerHooks() {
141
-
142
-		$container = $this->getContainer();
143
-		$hooksManager = new Hooks($container->query('TrustedServers'));
144
-
145
-		Util::connectHook(
146
-				'OCP\Share',
147
-				'federated_share_added',
148
-				$hooksManager,
149
-				'addServerHook'
150
-		);
151
-
152
-		$dispatcher = $this->getContainer()->getServer()->getEventDispatcher();
153
-		$dispatcher->addListener('OCA\DAV\Connector\Sabre::authInit', function($event) use($container) {
154
-			if ($event instanceof SabrePluginEvent) {
155
-				$authPlugin = $event->getServer()->getPlugin('auth');
156
-				if ($authPlugin instanceof Plugin) {
157
-					$h = new DbHandler($container->getServer()->getDatabaseConnection(),
158
-							$container->getServer()->getL10N('federation')
159
-					);
160
-					$authPlugin->addBackend(new FedAuth($h));
161
-				}
162
-			}
163
-		});
164
-	}
165
-
166
-	/**
167
-	 * @return SyncFederationAddressBooks
168
-	 */
169
-	public function getSyncService() {
170
-		$syncService = \OC::$server->query('CardDAVSyncService');
171
-		$dbHandler = $this->getContainer()->query('DbHandler');
172
-		return new SyncFederationAddressBooks($dbHandler, $syncService);
173
-	}
45
+    /**
46
+     * @param array $urlParams
47
+     */
48
+    public function __construct($urlParams = array()) {
49
+        parent::__construct('federation', $urlParams);
50
+        $this->registerService();
51
+        $this->registerMiddleware();
52
+    }
53
+
54
+    private function registerService() {
55
+        $container = $this->getContainer();
56
+
57
+        $container->registerService('addServerMiddleware', function(IAppContainer $c) {
58
+            return new AddServerMiddleware(
59
+                $c->getAppName(),
60
+                \OC::$server->getL10N($c->getAppName()),
61
+                \OC::$server->getLogger()
62
+            );
63
+        });
64
+
65
+        $container->registerService('DbHandler', function(IAppContainer $c) {
66
+            return new DbHandler(
67
+                \OC::$server->getDatabaseConnection(),
68
+                \OC::$server->getL10N($c->getAppName())
69
+            );
70
+        });
71
+
72
+        $container->registerService('TrustedServers', function(IAppContainer $c) {
73
+            $server = $c->getServer();
74
+            return new TrustedServers(
75
+                $c->query('DbHandler'),
76
+                $server->getHTTPClientService(),
77
+                $server->getLogger(),
78
+                $server->getJobList(),
79
+                $server->getSecureRandom(),
80
+                $server->getConfig(),
81
+                $server->getEventDispatcher()
82
+            );
83
+        });
84
+
85
+        $container->registerService('SettingsController', function (IAppContainer $c) {
86
+            $server = $c->getServer();
87
+            return new SettingsController(
88
+                $c->getAppName(),
89
+                $server->getRequest(),
90
+                $server->getL10N($c->getAppName()),
91
+                $c->query('TrustedServers')
92
+            );
93
+        });
94
+
95
+    }
96
+
97
+    private function registerMiddleware() {
98
+        $container = $this->getContainer();
99
+        $container->registerMiddleware('addServerMiddleware');
100
+    }
101
+
102
+    /**
103
+     * register OCS API Calls
104
+     */
105
+    public function registerOCSApi() {
106
+
107
+        $container = $this->getContainer();
108
+        $server = $container->getServer();
109
+
110
+        $auth = new OCSAuthAPI(
111
+            $server->getRequest(),
112
+            $server->getSecureRandom(),
113
+            $server->getJobList(),
114
+            $container->query('TrustedServers'),
115
+            $container->query('DbHandler'),
116
+            $server->getLogger()
117
+
118
+        );
119
+
120
+        API::register('get',
121
+            '/apps/federation/api/v1/shared-secret',
122
+            array($auth, 'getSharedSecret'),
123
+            'federation',
124
+            API::GUEST_AUTH
125
+        );
126
+
127
+        API::register('post',
128
+            '/apps/federation/api/v1/request-shared-secret',
129
+            array($auth, 'requestSharedSecret'),
130
+            'federation',
131
+            API::GUEST_AUTH
132
+        );
133
+
134
+    }
135
+
136
+    /**
137
+     * listen to federated_share_added hooks to auto-add new servers to the
138
+     * list of trusted servers.
139
+     */
140
+    public function registerHooks() {
141
+
142
+        $container = $this->getContainer();
143
+        $hooksManager = new Hooks($container->query('TrustedServers'));
144
+
145
+        Util::connectHook(
146
+                'OCP\Share',
147
+                'federated_share_added',
148
+                $hooksManager,
149
+                'addServerHook'
150
+        );
151
+
152
+        $dispatcher = $this->getContainer()->getServer()->getEventDispatcher();
153
+        $dispatcher->addListener('OCA\DAV\Connector\Sabre::authInit', function($event) use($container) {
154
+            if ($event instanceof SabrePluginEvent) {
155
+                $authPlugin = $event->getServer()->getPlugin('auth');
156
+                if ($authPlugin instanceof Plugin) {
157
+                    $h = new DbHandler($container->getServer()->getDatabaseConnection(),
158
+                            $container->getServer()->getL10N('federation')
159
+                    );
160
+                    $authPlugin->addBackend(new FedAuth($h));
161
+                }
162
+            }
163
+        });
164
+    }
165
+
166
+    /**
167
+     * @return SyncFederationAddressBooks
168
+     */
169
+    public function getSyncService() {
170
+        $syncService = \OC::$server->query('CardDAVSyncService');
171
+        $dbHandler = $this->getContainer()->query('DbHandler');
172
+        return new SyncFederationAddressBooks($dbHandler, $syncService);
173
+    }
174 174
 
175 175
 }
Please login to merge, or discard this patch.
apps/federation/lib/Command/SyncFederationAddressBooks.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -22,7 +22,6 @@
 block discarded – undo
22 22
  */
23 23
 namespace OCA\Federation\Command;
24 24
 
25
-use OCA\Federation\DbHandler;
26 25
 use Symfony\Component\Console\Command\Command;
27 26
 use Symfony\Component\Console\Helper\ProgressBar;
28 27
 use Symfony\Component\Console\Input\InputInterface;
Please login to merge, or discard this patch.
Indentation   +33 added lines, -33 removed lines patch added patch discarded remove patch
@@ -31,45 +31,45 @@
 block discarded – undo
31 31
 
32 32
 class SyncFederationAddressBooks extends Command {
33 33
 
34
-	/** @var \OCA\Federation\SyncFederationAddressBooks */
35
-	private $syncService;
34
+    /** @var \OCA\Federation\SyncFederationAddressBooks */
35
+    private $syncService;
36 36
 
37
-	/**
38
-	 * @param \OCA\Federation\SyncFederationAddressBooks $syncService
39
-	 */
40
-	function __construct(\OCA\Federation\SyncFederationAddressBooks $syncService) {
41
-		parent::__construct();
37
+    /**
38
+     * @param \OCA\Federation\SyncFederationAddressBooks $syncService
39
+     */
40
+    function __construct(\OCA\Federation\SyncFederationAddressBooks $syncService) {
41
+        parent::__construct();
42 42
 
43
-		$this->syncService = $syncService;
44
-	}
43
+        $this->syncService = $syncService;
44
+    }
45 45
 
46
-	protected function configure() {
47
-		$this
48
-			->setName('federation:sync-addressbooks')
49
-			->setDescription('Synchronizes addressbooks of all federated clouds');
50
-	}
46
+    protected function configure() {
47
+        $this
48
+            ->setName('federation:sync-addressbooks')
49
+            ->setDescription('Synchronizes addressbooks of all federated clouds');
50
+    }
51 51
 
52
-	/**
53
-	 * @param InputInterface $input
54
-	 * @param OutputInterface $output
55
-	 * @return int
56
-	 */
57
-	protected function execute(InputInterface $input, OutputInterface $output) {
52
+    /**
53
+     * @param InputInterface $input
54
+     * @param OutputInterface $output
55
+     * @return int
56
+     */
57
+    protected function execute(InputInterface $input, OutputInterface $output) {
58 58
 
59
-		$progress = new ProgressBar($output);
60
-		$progress->start();
61
-		$this->syncService->syncThemAll(function($url, $ex) use ($progress, $output) {
62
-			if ($ex instanceof \Exception) {
63
-				$output->writeln("Error while syncing $url : " . $ex->getMessage());
59
+        $progress = new ProgressBar($output);
60
+        $progress->start();
61
+        $this->syncService->syncThemAll(function($url, $ex) use ($progress, $output) {
62
+            if ($ex instanceof \Exception) {
63
+                $output->writeln("Error while syncing $url : " . $ex->getMessage());
64 64
 
65
-			} else {
66
-				$progress->advance();
67
-			}
68
-		});
65
+            } else {
66
+                $progress->advance();
67
+            }
68
+        });
69 69
 
70
-		$progress->finish();
71
-		$output->writeln('');
70
+        $progress->finish();
71
+        $output->writeln('');
72 72
 
73
-		return 0;
74
-	}
73
+        return 0;
74
+    }
75 75
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -60,7 +60,7 @@
 block discarded – undo
60 60
 		$progress->start();
61 61
 		$this->syncService->syncThemAll(function($url, $ex) use ($progress, $output) {
62 62
 			if ($ex instanceof \Exception) {
63
-				$output->writeln("Error while syncing $url : " . $ex->getMessage());
63
+				$output->writeln("Error while syncing $url : ".$ex->getMessage());
64 64
 
65 65
 			} else {
66 66
 				$progress->advance();
Please login to merge, or discard this patch.