Passed
Push — master ( 30e999...85099f )
by Joas
12:49 queued 11s
created
lib/private/Collaboration/Collaborators/MailPlugin.php 1 patch
Indentation   +202 added lines, -202 removed lines patch added patch discarded remove patch
@@ -40,208 +40,208 @@
 block discarded – undo
40 40
 use OCP\Share\IShare;
41 41
 
42 42
 class MailPlugin implements ISearchPlugin {
43
-	protected $shareeEnumeration;
44
-	protected $shareWithGroupOnly;
45
-
46
-	/** @var IManager */
47
-	private $contactsManager;
48
-	/** @var ICloudIdManager */
49
-	private $cloudIdManager;
50
-	/** @var IConfig */
51
-	private $config;
52
-
53
-	/** @var IGroupManager */
54
-	private $groupManager;
55
-
56
-	/** @var IUserSession */
57
-	private $userSession;
58
-
59
-	public function __construct(IManager $contactsManager, ICloudIdManager $cloudIdManager, IConfig $config, IGroupManager $groupManager, IUserSession $userSession) {
60
-		$this->contactsManager = $contactsManager;
61
-		$this->cloudIdManager = $cloudIdManager;
62
-		$this->config = $config;
63
-		$this->groupManager = $groupManager;
64
-		$this->userSession = $userSession;
65
-
66
-		$this->shareeEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
67
-		$this->shareWithGroupOnly = $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
68
-		$this->shareeEnumerationInGroupOnly = $this->shareeEnumeration && $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes';
69
-	}
70
-
71
-	/**
72
-	 * @param $search
73
-	 * @param $limit
74
-	 * @param $offset
75
-	 * @param ISearchResult $searchResult
76
-	 * @return bool
77
-	 * @since 13.0.0
78
-	 */
79
-	public function search($search, $limit, $offset, ISearchResult $searchResult) {
80
-		$result = $userResults = ['wide' => [], 'exact' => []];
81
-		$userType = new SearchResultType('users');
82
-		$emailType = new SearchResultType('emails');
83
-
84
-		// Search in contacts
85
-		$addressBookContacts = $this->contactsManager->search($search, ['EMAIL', 'FN'], ['limit' => $limit, 'offset' => $offset]);
86
-		$lowerSearch = strtolower($search);
87
-		foreach ($addressBookContacts as $contact) {
88
-			if (isset($contact['EMAIL'])) {
89
-				$emailAddresses = $contact['EMAIL'];
90
-				if (\is_string($emailAddresses)) {
91
-					$emailAddresses = [$emailAddresses];
92
-				}
93
-				foreach ($emailAddresses as $type => $emailAddress) {
94
-					$displayName = $emailAddress;
95
-					$emailAddressType = null;
96
-					if (\is_array($emailAddress)) {
97
-						$emailAddressData = $emailAddress;
98
-						$emailAddress = $emailAddressData['value'];
99
-						$emailAddressType = $emailAddressData['type'];
100
-					}
101
-					if (isset($contact['FN'])) {
102
-						$displayName = $contact['FN'] . ' (' . $emailAddress . ')';
103
-					}
104
-					$exactEmailMatch = strtolower($emailAddress) === $lowerSearch;
105
-
106
-					if (isset($contact['isLocalSystemBook'])) {
107
-						if ($this->shareWithGroupOnly) {
108
-							/*
43
+    protected $shareeEnumeration;
44
+    protected $shareWithGroupOnly;
45
+
46
+    /** @var IManager */
47
+    private $contactsManager;
48
+    /** @var ICloudIdManager */
49
+    private $cloudIdManager;
50
+    /** @var IConfig */
51
+    private $config;
52
+
53
+    /** @var IGroupManager */
54
+    private $groupManager;
55
+
56
+    /** @var IUserSession */
57
+    private $userSession;
58
+
59
+    public function __construct(IManager $contactsManager, ICloudIdManager $cloudIdManager, IConfig $config, IGroupManager $groupManager, IUserSession $userSession) {
60
+        $this->contactsManager = $contactsManager;
61
+        $this->cloudIdManager = $cloudIdManager;
62
+        $this->config = $config;
63
+        $this->groupManager = $groupManager;
64
+        $this->userSession = $userSession;
65
+
66
+        $this->shareeEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
67
+        $this->shareWithGroupOnly = $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
68
+        $this->shareeEnumerationInGroupOnly = $this->shareeEnumeration && $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes';
69
+    }
70
+
71
+    /**
72
+     * @param $search
73
+     * @param $limit
74
+     * @param $offset
75
+     * @param ISearchResult $searchResult
76
+     * @return bool
77
+     * @since 13.0.0
78
+     */
79
+    public function search($search, $limit, $offset, ISearchResult $searchResult) {
80
+        $result = $userResults = ['wide' => [], 'exact' => []];
81
+        $userType = new SearchResultType('users');
82
+        $emailType = new SearchResultType('emails');
83
+
84
+        // Search in contacts
85
+        $addressBookContacts = $this->contactsManager->search($search, ['EMAIL', 'FN'], ['limit' => $limit, 'offset' => $offset]);
86
+        $lowerSearch = strtolower($search);
87
+        foreach ($addressBookContacts as $contact) {
88
+            if (isset($contact['EMAIL'])) {
89
+                $emailAddresses = $contact['EMAIL'];
90
+                if (\is_string($emailAddresses)) {
91
+                    $emailAddresses = [$emailAddresses];
92
+                }
93
+                foreach ($emailAddresses as $type => $emailAddress) {
94
+                    $displayName = $emailAddress;
95
+                    $emailAddressType = null;
96
+                    if (\is_array($emailAddress)) {
97
+                        $emailAddressData = $emailAddress;
98
+                        $emailAddress = $emailAddressData['value'];
99
+                        $emailAddressType = $emailAddressData['type'];
100
+                    }
101
+                    if (isset($contact['FN'])) {
102
+                        $displayName = $contact['FN'] . ' (' . $emailAddress . ')';
103
+                    }
104
+                    $exactEmailMatch = strtolower($emailAddress) === $lowerSearch;
105
+
106
+                    if (isset($contact['isLocalSystemBook'])) {
107
+                        if ($this->shareWithGroupOnly) {
108
+                            /*
109 109
 							 * Check if the user may share with the user associated with the e-mail of the just found contact
110 110
 							 */
111
-							$userGroups = $this->groupManager->getUserGroupIds($this->userSession->getUser());
112
-							$found = false;
113
-							foreach ($userGroups as $userGroup) {
114
-								if ($this->groupManager->isInGroup($contact['UID'], $userGroup)) {
115
-									$found = true;
116
-									break;
117
-								}
118
-							}
119
-							if (!$found) {
120
-								continue;
121
-							}
122
-						}
123
-						if ($exactEmailMatch) {
124
-							try {
125
-								$cloud = $this->cloudIdManager->resolveCloudId($contact['CLOUD'][0]);
126
-							} catch (\InvalidArgumentException $e) {
127
-								continue;
128
-							}
129
-
130
-							if (!$this->isCurrentUser($cloud) && !$searchResult->hasResult($userType, $cloud->getUser())) {
131
-								$singleResult = [[
132
-									'label' => $displayName,
133
-									'uuid' => $contact['UID'],
134
-									'name' => $contact['FN'],
135
-									'value' => [
136
-										'shareType' => IShare::TYPE_USER,
137
-										'shareWith' => $cloud->getUser(),
138
-									],
139
-								]];
140
-								$searchResult->addResultSet($userType, [], $singleResult);
141
-								$searchResult->markExactIdMatch($emailType);
142
-							}
143
-							return false;
144
-						}
145
-
146
-						if ($this->shareeEnumeration) {
147
-							try {
148
-								$cloud = $this->cloudIdManager->resolveCloudId($contact['CLOUD'][0]);
149
-							} catch (\InvalidArgumentException $e) {
150
-								continue;
151
-							}
152
-
153
-							$addToWide = !$this->shareeEnumerationInGroupOnly;
154
-							if ($this->shareeEnumerationInGroupOnly) {
155
-								$addToWide = false;
156
-								$userGroups = $this->groupManager->getUserGroupIds($this->userSession->getUser());
157
-								foreach ($userGroups as $userGroup) {
158
-									if ($this->groupManager->isInGroup($contact['UID'], $userGroup)) {
159
-										$addToWide = true;
160
-										break;
161
-									}
162
-								}
163
-							}
164
-							if ($addToWide && !$this->isCurrentUser($cloud) && !$searchResult->hasResult($userType, $cloud->getUser())) {
165
-								$userResults['wide'][] = [
166
-									'label' => $displayName,
167
-									'uuid' => $contact['UID'],
168
-									'name' => $contact['FN'],
169
-									'value' => [
170
-										'shareType' => IShare::TYPE_USER,
171
-										'shareWith' => $cloud->getUser(),
172
-									],
173
-								];
174
-								continue;
175
-							}
176
-						}
177
-						continue;
178
-					}
179
-
180
-					if ($exactEmailMatch
181
-						|| isset($contact['FN']) && strtolower($contact['FN']) === $lowerSearch) {
182
-						if ($exactEmailMatch) {
183
-							$searchResult->markExactIdMatch($emailType);
184
-						}
185
-						$result['exact'][] = [
186
-							'label' => $displayName,
187
-							'uuid' => $contact['UID'],
188
-							'name' => $contact['FN'],
189
-							'type' => $emailAddressType ?? '',
190
-							'value' => [
191
-								'shareType' => IShare::TYPE_EMAIL,
192
-								'shareWith' => $emailAddress,
193
-							],
194
-						];
195
-					} else {
196
-						$result['wide'][] = [
197
-							'label' => $displayName,
198
-							'uuid' => $contact['UID'],
199
-							'name' => $contact['FN'],
200
-							'type' => $emailAddressType ?? '',
201
-							'value' => [
202
-								'shareType' => IShare::TYPE_EMAIL,
203
-								'shareWith' => $emailAddress,
204
-							],
205
-						];
206
-					}
207
-				}
208
-			}
209
-		}
210
-
211
-		$reachedEnd = true;
212
-		if (!$this->shareeEnumeration) {
213
-			$result['wide'] = [];
214
-			$userResults['wide'] = [];
215
-		} else {
216
-			$reachedEnd = (count($result['wide']) < $offset + $limit) &&
217
-				(count($userResults['wide']) < $offset + $limit);
218
-
219
-			$result['wide'] = array_slice($result['wide'], $offset, $limit);
220
-			$userResults['wide'] = array_slice($userResults['wide'], $offset, $limit);
221
-		}
222
-
223
-
224
-		if (!$searchResult->hasExactIdMatch($emailType) && filter_var($search, FILTER_VALIDATE_EMAIL)) {
225
-			$result['exact'][] = [
226
-				'label' => $search,
227
-				'uuid' => $search,
228
-				'value' => [
229
-					'shareType' => IShare::TYPE_EMAIL,
230
-					'shareWith' => $search,
231
-				],
232
-			];
233
-		}
234
-
235
-		if (!empty($userResults['wide'])) {
236
-			$searchResult->addResultSet($userType, $userResults['wide'], []);
237
-		}
238
-		$searchResult->addResultSet($emailType, $result['wide'], $result['exact']);
239
-
240
-		return !$reachedEnd;
241
-	}
242
-
243
-	public function isCurrentUser(ICloudId $cloud): bool {
244
-		$currentUser = $this->userSession->getUser();
245
-		return $currentUser instanceof IUser ? $currentUser->getUID() === $cloud->getUser() : false;
246
-	}
111
+                            $userGroups = $this->groupManager->getUserGroupIds($this->userSession->getUser());
112
+                            $found = false;
113
+                            foreach ($userGroups as $userGroup) {
114
+                                if ($this->groupManager->isInGroup($contact['UID'], $userGroup)) {
115
+                                    $found = true;
116
+                                    break;
117
+                                }
118
+                            }
119
+                            if (!$found) {
120
+                                continue;
121
+                            }
122
+                        }
123
+                        if ($exactEmailMatch) {
124
+                            try {
125
+                                $cloud = $this->cloudIdManager->resolveCloudId($contact['CLOUD'][0]);
126
+                            } catch (\InvalidArgumentException $e) {
127
+                                continue;
128
+                            }
129
+
130
+                            if (!$this->isCurrentUser($cloud) && !$searchResult->hasResult($userType, $cloud->getUser())) {
131
+                                $singleResult = [[
132
+                                    'label' => $displayName,
133
+                                    'uuid' => $contact['UID'],
134
+                                    'name' => $contact['FN'],
135
+                                    'value' => [
136
+                                        'shareType' => IShare::TYPE_USER,
137
+                                        'shareWith' => $cloud->getUser(),
138
+                                    ],
139
+                                ]];
140
+                                $searchResult->addResultSet($userType, [], $singleResult);
141
+                                $searchResult->markExactIdMatch($emailType);
142
+                            }
143
+                            return false;
144
+                        }
145
+
146
+                        if ($this->shareeEnumeration) {
147
+                            try {
148
+                                $cloud = $this->cloudIdManager->resolveCloudId($contact['CLOUD'][0]);
149
+                            } catch (\InvalidArgumentException $e) {
150
+                                continue;
151
+                            }
152
+
153
+                            $addToWide = !$this->shareeEnumerationInGroupOnly;
154
+                            if ($this->shareeEnumerationInGroupOnly) {
155
+                                $addToWide = false;
156
+                                $userGroups = $this->groupManager->getUserGroupIds($this->userSession->getUser());
157
+                                foreach ($userGroups as $userGroup) {
158
+                                    if ($this->groupManager->isInGroup($contact['UID'], $userGroup)) {
159
+                                        $addToWide = true;
160
+                                        break;
161
+                                    }
162
+                                }
163
+                            }
164
+                            if ($addToWide && !$this->isCurrentUser($cloud) && !$searchResult->hasResult($userType, $cloud->getUser())) {
165
+                                $userResults['wide'][] = [
166
+                                    'label' => $displayName,
167
+                                    'uuid' => $contact['UID'],
168
+                                    'name' => $contact['FN'],
169
+                                    'value' => [
170
+                                        'shareType' => IShare::TYPE_USER,
171
+                                        'shareWith' => $cloud->getUser(),
172
+                                    ],
173
+                                ];
174
+                                continue;
175
+                            }
176
+                        }
177
+                        continue;
178
+                    }
179
+
180
+                    if ($exactEmailMatch
181
+                        || isset($contact['FN']) && strtolower($contact['FN']) === $lowerSearch) {
182
+                        if ($exactEmailMatch) {
183
+                            $searchResult->markExactIdMatch($emailType);
184
+                        }
185
+                        $result['exact'][] = [
186
+                            'label' => $displayName,
187
+                            'uuid' => $contact['UID'],
188
+                            'name' => $contact['FN'],
189
+                            'type' => $emailAddressType ?? '',
190
+                            'value' => [
191
+                                'shareType' => IShare::TYPE_EMAIL,
192
+                                'shareWith' => $emailAddress,
193
+                            ],
194
+                        ];
195
+                    } else {
196
+                        $result['wide'][] = [
197
+                            'label' => $displayName,
198
+                            'uuid' => $contact['UID'],
199
+                            'name' => $contact['FN'],
200
+                            'type' => $emailAddressType ?? '',
201
+                            'value' => [
202
+                                'shareType' => IShare::TYPE_EMAIL,
203
+                                'shareWith' => $emailAddress,
204
+                            ],
205
+                        ];
206
+                    }
207
+                }
208
+            }
209
+        }
210
+
211
+        $reachedEnd = true;
212
+        if (!$this->shareeEnumeration) {
213
+            $result['wide'] = [];
214
+            $userResults['wide'] = [];
215
+        } else {
216
+            $reachedEnd = (count($result['wide']) < $offset + $limit) &&
217
+                (count($userResults['wide']) < $offset + $limit);
218
+
219
+            $result['wide'] = array_slice($result['wide'], $offset, $limit);
220
+            $userResults['wide'] = array_slice($userResults['wide'], $offset, $limit);
221
+        }
222
+
223
+
224
+        if (!$searchResult->hasExactIdMatch($emailType) && filter_var($search, FILTER_VALIDATE_EMAIL)) {
225
+            $result['exact'][] = [
226
+                'label' => $search,
227
+                'uuid' => $search,
228
+                'value' => [
229
+                    'shareType' => IShare::TYPE_EMAIL,
230
+                    'shareWith' => $search,
231
+                ],
232
+            ];
233
+        }
234
+
235
+        if (!empty($userResults['wide'])) {
236
+            $searchResult->addResultSet($userType, $userResults['wide'], []);
237
+        }
238
+        $searchResult->addResultSet($emailType, $result['wide'], $result['exact']);
239
+
240
+        return !$reachedEnd;
241
+    }
242
+
243
+    public function isCurrentUser(ICloudId $cloud): bool {
244
+        $currentUser = $this->userSession->getUser();
245
+        return $currentUser instanceof IUser ? $currentUser->getUID() === $cloud->getUser() : false;
246
+    }
247 247
 }
Please login to merge, or discard this patch.
lib/private/Collaboration/Collaborators/UserPlugin.php 1 patch
Indentation   +147 added lines, -147 removed lines patch added patch discarded remove patch
@@ -40,151 +40,151 @@
 block discarded – undo
40 40
 use OCP\Share\IShare;
41 41
 
42 42
 class UserPlugin implements ISearchPlugin {
43
-	/* @var bool */
44
-	protected $shareWithGroupOnly;
45
-	protected $shareeEnumeration;
46
-	protected $shareeEnumerationInGroupOnly;
47
-
48
-	/** @var IConfig */
49
-	private $config;
50
-	/** @var IGroupManager */
51
-	private $groupManager;
52
-	/** @var IUserSession */
53
-	private $userSession;
54
-	/** @var IUserManager */
55
-	private $userManager;
56
-
57
-	public function __construct(IConfig $config, IUserManager $userManager, IGroupManager $groupManager, IUserSession $userSession) {
58
-		$this->config = $config;
59
-
60
-		$this->groupManager = $groupManager;
61
-		$this->userSession = $userSession;
62
-		$this->userManager = $userManager;
63
-
64
-		$this->shareWithGroupOnly = $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
65
-		$this->shareeEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
66
-		$this->shareeEnumerationInGroupOnly = $this->shareeEnumeration && $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes';
67
-	}
68
-
69
-	public function search($search, $limit, $offset, ISearchResult $searchResult) {
70
-		$result = ['wide' => [], 'exact' => []];
71
-		$users = [];
72
-		$hasMoreResults = false;
73
-
74
-		$currentUserGroups = $this->groupManager->getUserGroupIds($this->userSession->getUser());
75
-		if ($this->shareWithGroupOnly) {
76
-			// Search in all the groups this user is part of
77
-			foreach ($currentUserGroups as $userGroupId) {
78
-				$usersInGroup = $this->groupManager->displayNamesInGroup($userGroupId, $search, $limit, $offset);
79
-				foreach ($usersInGroup as $userId => $displayName) {
80
-					$userId = (string) $userId;
81
-					$users[$userId] = $this->userManager->get($userId);
82
-				}
83
-			}
84
-		} else {
85
-			// Search in all users
86
-			$usersTmp = $this->userManager->searchDisplayName($search, $limit, $offset);
87
-			foreach ($usersTmp as $user) {
88
-				if ($user->isEnabled()) { // Don't keep deactivated users
89
-					$users[$user->getUID()] = $user;
90
-				}
91
-			}
92
-		}
93
-
94
-		$this->takeOutCurrentUser($users);
95
-
96
-		if (!$this->shareeEnumeration || count($users) < $limit) {
97
-			$hasMoreResults = true;
98
-		}
99
-
100
-		$foundUserById = false;
101
-		$lowerSearch = strtolower($search);
102
-		foreach ($users as $uid => $user) {
103
-			$userDisplayName = $user->getDisplayName();
104
-			$userEmail = $user->getEMailAddress();
105
-			$uid = (string) $uid;
106
-			if (
107
-				strtolower($uid) === $lowerSearch ||
108
-				strtolower($userDisplayName) === $lowerSearch ||
109
-				strtolower($userEmail) === $lowerSearch
110
-			) {
111
-				if (strtolower($uid) === $lowerSearch) {
112
-					$foundUserById = true;
113
-				}
114
-				$result['exact'][] = [
115
-					'label' => $userDisplayName,
116
-					'value' => [
117
-						'shareType' => IShare::TYPE_USER,
118
-						'shareWith' => $uid,
119
-					],
120
-				];
121
-			} else {
122
-				$addToWideResults = false;
123
-				if ($this->shareeEnumeration && !$this->shareeEnumerationInGroupOnly) {
124
-					$addToWideResults = true;
125
-				}
126
-
127
-				if ($this->shareeEnumerationInGroupOnly) {
128
-					$commonGroups = array_intersect($currentUserGroups, $this->groupManager->getUserGroupIds($user));
129
-					if (!empty($commonGroups)) {
130
-						$addToWideResults = true;
131
-					}
132
-				}
133
-
134
-				if ($addToWideResults) {
135
-					$result['wide'][] = [
136
-						'label' => $userDisplayName,
137
-						'value' => [
138
-							'shareType' => IShare::TYPE_USER,
139
-							'shareWith' => $uid,
140
-						],
141
-					];
142
-				}
143
-			}
144
-		}
145
-
146
-		if ($offset === 0 && !$foundUserById) {
147
-			// On page one we try if the search result has a direct hit on the
148
-			// user id and if so, we add that to the exact match list
149
-			$user = $this->userManager->get($search);
150
-			if ($user instanceof IUser) {
151
-				$addUser = true;
152
-
153
-				if ($this->shareWithGroupOnly) {
154
-					// Only add, if we have a common group
155
-					$commonGroups = array_intersect($currentUserGroups, $this->groupManager->getUserGroupIds($user));
156
-					$addUser = !empty($commonGroups);
157
-				}
158
-
159
-				if ($addUser) {
160
-					$result['exact'][] = [
161
-						'label' => $user->getDisplayName(),
162
-						'value' => [
163
-							'shareType' => IShare::TYPE_USER,
164
-							'shareWith' => $user->getUID(),
165
-						],
166
-					];
167
-				}
168
-			}
169
-		}
170
-
171
-
172
-
173
-		$type = new SearchResultType('users');
174
-		$searchResult->addResultSet($type, $result['wide'], $result['exact']);
175
-		if (count($result['exact'])) {
176
-			$searchResult->markExactIdMatch($type);
177
-		}
178
-
179
-		return $hasMoreResults;
180
-	}
181
-
182
-	public function takeOutCurrentUser(array &$users) {
183
-		$currentUser = $this->userSession->getUser();
184
-		if (!is_null($currentUser)) {
185
-			if (isset($users[$currentUser->getUID()])) {
186
-				unset($users[$currentUser->getUID()]);
187
-			}
188
-		}
189
-	}
43
+    /* @var bool */
44
+    protected $shareWithGroupOnly;
45
+    protected $shareeEnumeration;
46
+    protected $shareeEnumerationInGroupOnly;
47
+
48
+    /** @var IConfig */
49
+    private $config;
50
+    /** @var IGroupManager */
51
+    private $groupManager;
52
+    /** @var IUserSession */
53
+    private $userSession;
54
+    /** @var IUserManager */
55
+    private $userManager;
56
+
57
+    public function __construct(IConfig $config, IUserManager $userManager, IGroupManager $groupManager, IUserSession $userSession) {
58
+        $this->config = $config;
59
+
60
+        $this->groupManager = $groupManager;
61
+        $this->userSession = $userSession;
62
+        $this->userManager = $userManager;
63
+
64
+        $this->shareWithGroupOnly = $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
65
+        $this->shareeEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
66
+        $this->shareeEnumerationInGroupOnly = $this->shareeEnumeration && $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes';
67
+    }
68
+
69
+    public function search($search, $limit, $offset, ISearchResult $searchResult) {
70
+        $result = ['wide' => [], 'exact' => []];
71
+        $users = [];
72
+        $hasMoreResults = false;
73
+
74
+        $currentUserGroups = $this->groupManager->getUserGroupIds($this->userSession->getUser());
75
+        if ($this->shareWithGroupOnly) {
76
+            // Search in all the groups this user is part of
77
+            foreach ($currentUserGroups as $userGroupId) {
78
+                $usersInGroup = $this->groupManager->displayNamesInGroup($userGroupId, $search, $limit, $offset);
79
+                foreach ($usersInGroup as $userId => $displayName) {
80
+                    $userId = (string) $userId;
81
+                    $users[$userId] = $this->userManager->get($userId);
82
+                }
83
+            }
84
+        } else {
85
+            // Search in all users
86
+            $usersTmp = $this->userManager->searchDisplayName($search, $limit, $offset);
87
+            foreach ($usersTmp as $user) {
88
+                if ($user->isEnabled()) { // Don't keep deactivated users
89
+                    $users[$user->getUID()] = $user;
90
+                }
91
+            }
92
+        }
93
+
94
+        $this->takeOutCurrentUser($users);
95
+
96
+        if (!$this->shareeEnumeration || count($users) < $limit) {
97
+            $hasMoreResults = true;
98
+        }
99
+
100
+        $foundUserById = false;
101
+        $lowerSearch = strtolower($search);
102
+        foreach ($users as $uid => $user) {
103
+            $userDisplayName = $user->getDisplayName();
104
+            $userEmail = $user->getEMailAddress();
105
+            $uid = (string) $uid;
106
+            if (
107
+                strtolower($uid) === $lowerSearch ||
108
+                strtolower($userDisplayName) === $lowerSearch ||
109
+                strtolower($userEmail) === $lowerSearch
110
+            ) {
111
+                if (strtolower($uid) === $lowerSearch) {
112
+                    $foundUserById = true;
113
+                }
114
+                $result['exact'][] = [
115
+                    'label' => $userDisplayName,
116
+                    'value' => [
117
+                        'shareType' => IShare::TYPE_USER,
118
+                        'shareWith' => $uid,
119
+                    ],
120
+                ];
121
+            } else {
122
+                $addToWideResults = false;
123
+                if ($this->shareeEnumeration && !$this->shareeEnumerationInGroupOnly) {
124
+                    $addToWideResults = true;
125
+                }
126
+
127
+                if ($this->shareeEnumerationInGroupOnly) {
128
+                    $commonGroups = array_intersect($currentUserGroups, $this->groupManager->getUserGroupIds($user));
129
+                    if (!empty($commonGroups)) {
130
+                        $addToWideResults = true;
131
+                    }
132
+                }
133
+
134
+                if ($addToWideResults) {
135
+                    $result['wide'][] = [
136
+                        'label' => $userDisplayName,
137
+                        'value' => [
138
+                            'shareType' => IShare::TYPE_USER,
139
+                            'shareWith' => $uid,
140
+                        ],
141
+                    ];
142
+                }
143
+            }
144
+        }
145
+
146
+        if ($offset === 0 && !$foundUserById) {
147
+            // On page one we try if the search result has a direct hit on the
148
+            // user id and if so, we add that to the exact match list
149
+            $user = $this->userManager->get($search);
150
+            if ($user instanceof IUser) {
151
+                $addUser = true;
152
+
153
+                if ($this->shareWithGroupOnly) {
154
+                    // Only add, if we have a common group
155
+                    $commonGroups = array_intersect($currentUserGroups, $this->groupManager->getUserGroupIds($user));
156
+                    $addUser = !empty($commonGroups);
157
+                }
158
+
159
+                if ($addUser) {
160
+                    $result['exact'][] = [
161
+                        'label' => $user->getDisplayName(),
162
+                        'value' => [
163
+                            'shareType' => IShare::TYPE_USER,
164
+                            'shareWith' => $user->getUID(),
165
+                        ],
166
+                    ];
167
+                }
168
+            }
169
+        }
170
+
171
+
172
+
173
+        $type = new SearchResultType('users');
174
+        $searchResult->addResultSet($type, $result['wide'], $result['exact']);
175
+        if (count($result['exact'])) {
176
+            $searchResult->markExactIdMatch($type);
177
+        }
178
+
179
+        return $hasMoreResults;
180
+    }
181
+
182
+    public function takeOutCurrentUser(array &$users) {
183
+        $currentUser = $this->userSession->getUser();
184
+        if (!is_null($currentUser)) {
185
+            if (isset($users[$currentUser->getUID()])) {
186
+                unset($users[$currentUser->getUID()]);
187
+            }
188
+        }
189
+    }
190 190
 }
Please login to merge, or discard this patch.
lib/private/Collaboration/Collaborators/RemoteGroupPlugin.php 1 patch
Indentation   +51 added lines, -51 removed lines patch added patch discarded remove patch
@@ -33,62 +33,62 @@
 block discarded – undo
33 33
 use OCP\Share\IShare;
34 34
 
35 35
 class RemoteGroupPlugin implements ISearchPlugin {
36
-	protected $shareeEnumeration;
36
+    protected $shareeEnumeration;
37 37
 
38
-	/** @var ICloudIdManager */
39
-	private $cloudIdManager;
40
-	/** @var bool */
41
-	private $enabled = false;
38
+    /** @var ICloudIdManager */
39
+    private $cloudIdManager;
40
+    /** @var bool */
41
+    private $enabled = false;
42 42
 
43
-	public function __construct(ICloudFederationProviderManager $cloudFederationProviderManager, ICloudIdManager $cloudIdManager) {
44
-		try {
45
-			$fileSharingProvider = $cloudFederationProviderManager->getCloudFederationProvider('file');
46
-			$supportedShareTypes = $fileSharingProvider->getSupportedShareTypes();
47
-			if (in_array('group', $supportedShareTypes)) {
48
-				$this->enabled = true;
49
-			}
50
-		} catch (\Exception $e) {
51
-			// do nothing, just don't enable federated group shares
52
-		}
53
-		$this->cloudIdManager = $cloudIdManager;
54
-	}
43
+    public function __construct(ICloudFederationProviderManager $cloudFederationProviderManager, ICloudIdManager $cloudIdManager) {
44
+        try {
45
+            $fileSharingProvider = $cloudFederationProviderManager->getCloudFederationProvider('file');
46
+            $supportedShareTypes = $fileSharingProvider->getSupportedShareTypes();
47
+            if (in_array('group', $supportedShareTypes)) {
48
+                $this->enabled = true;
49
+            }
50
+        } catch (\Exception $e) {
51
+            // do nothing, just don't enable federated group shares
52
+        }
53
+        $this->cloudIdManager = $cloudIdManager;
54
+    }
55 55
 
56
-	public function search($search, $limit, $offset, ISearchResult $searchResult) {
57
-		$result = ['wide' => [], 'exact' => []];
58
-		$resultType = new SearchResultType('remote_groups');
56
+    public function search($search, $limit, $offset, ISearchResult $searchResult) {
57
+        $result = ['wide' => [], 'exact' => []];
58
+        $resultType = new SearchResultType('remote_groups');
59 59
 
60
-		if ($this->enabled && $this->cloudIdManager->isValidCloudId($search) && $offset === 0) {
61
-			list($remoteGroup, $serverUrl) = $this->splitGroupRemote($search);
62
-			$result['exact'][] = [
63
-				'label' => $remoteGroup . " ($serverUrl)",
64
-				'guid' => $remoteGroup,
65
-				'name' => $remoteGroup,
66
-				'value' => [
67
-					'shareType' => IShare::TYPE_REMOTE_GROUP,
68
-					'shareWith' => $search,
69
-					'server' => $serverUrl,
70
-				],
71
-			];
72
-		}
60
+        if ($this->enabled && $this->cloudIdManager->isValidCloudId($search) && $offset === 0) {
61
+            list($remoteGroup, $serverUrl) = $this->splitGroupRemote($search);
62
+            $result['exact'][] = [
63
+                'label' => $remoteGroup . " ($serverUrl)",
64
+                'guid' => $remoteGroup,
65
+                'name' => $remoteGroup,
66
+                'value' => [
67
+                    'shareType' => IShare::TYPE_REMOTE_GROUP,
68
+                    'shareWith' => $search,
69
+                    'server' => $serverUrl,
70
+                ],
71
+            ];
72
+        }
73 73
 
74
-		$searchResult->addResultSet($resultType, $result['wide'], $result['exact']);
74
+        $searchResult->addResultSet($resultType, $result['wide'], $result['exact']);
75 75
 
76
-		return true;
77
-	}
76
+        return true;
77
+    }
78 78
 
79
-	/**
80
-	 * split group and remote from federated cloud id
81
-	 *
82
-	 * @param string $address federated share address
83
-	 * @return array [user, remoteURL]
84
-	 * @throws \InvalidArgumentException
85
-	 */
86
-	public function splitGroupRemote($address) {
87
-		try {
88
-			$cloudId = $this->cloudIdManager->resolveCloudId($address);
89
-			return [$cloudId->getUser(), $cloudId->getRemote()];
90
-		} catch (\InvalidArgumentException $e) {
91
-			throw new \InvalidArgumentException('Invalid Federated Cloud ID', 0, $e);
92
-		}
93
-	}
79
+    /**
80
+     * split group and remote from federated cloud id
81
+     *
82
+     * @param string $address federated share address
83
+     * @return array [user, remoteURL]
84
+     * @throws \InvalidArgumentException
85
+     */
86
+    public function splitGroupRemote($address) {
87
+        try {
88
+            $cloudId = $this->cloudIdManager->resolveCloudId($address);
89
+            return [$cloudId->getUser(), $cloudId->getRemote()];
90
+        } catch (\InvalidArgumentException $e) {
91
+            throw new \InvalidArgumentException('Invalid Federated Cloud ID', 0, $e);
92
+        }
93
+    }
94 94
 }
Please login to merge, or discard this patch.
lib/private/Repair/OldGroupMembershipShares.php 1 patch
Indentation   +85 added lines, -85 removed lines patch added patch discarded remove patch
@@ -32,89 +32,89 @@
 block discarded – undo
32 32
 
33 33
 class OldGroupMembershipShares implements IRepairStep {
34 34
 
35
-	/** @var \OCP\IDBConnection */
36
-	protected $connection;
37
-
38
-	/** @var \OCP\IGroupManager */
39
-	protected $groupManager;
40
-
41
-	/**
42
-	 * @var array [gid => [uid => (bool)]]
43
-	 */
44
-	protected $memberships;
45
-
46
-	/**
47
-	 * @param IDBConnection $connection
48
-	 * @param IGroupManager $groupManager
49
-	 */
50
-	public function __construct(IDBConnection $connection, IGroupManager $groupManager) {
51
-		$this->connection = $connection;
52
-		$this->groupManager = $groupManager;
53
-	}
54
-
55
-	/**
56
-	 * Returns the step's name
57
-	 *
58
-	 * @return string
59
-	 */
60
-	public function getName() {
61
-		return 'Remove shares of old group memberships';
62
-	}
63
-
64
-	/**
65
-	 * Run repair step.
66
-	 * Must throw exception on error.
67
-	 *
68
-	 * @throws \Exception in case of failure
69
-	 * @suppress SqlInjectionChecker
70
-	 */
71
-	public function run(IOutput $output) {
72
-		$deletedEntries = 0;
73
-
74
-		$query = $this->connection->getQueryBuilder();
75
-		$query->select('s1.id')->selectAlias('s1.share_with', 'user')->selectAlias('s2.share_with', 'group')
76
-			->from('share', 's1')
77
-			->where($query->expr()->isNotNull('s1.parent'))
78
-				// \OC\Share\Constant::$shareTypeGroupUserUnique === 2
79
-				->andWhere($query->expr()->eq('s1.share_type', $query->expr()->literal(2)))
80
-				->andWhere($query->expr()->isNotNull('s2.id'))
81
-				->andWhere($query->expr()->eq('s2.share_type', $query->expr()->literal(IShare::TYPE_GROUP)))
82
-			->leftJoin('s1', 'share', 's2', $query->expr()->eq('s1.parent', 's2.id'));
83
-
84
-		$deleteQuery = $this->connection->getQueryBuilder();
85
-		$deleteQuery->delete('share')
86
-			->where($query->expr()->eq('id', $deleteQuery->createParameter('share')));
87
-
88
-		$result = $query->execute();
89
-		while ($row = $result->fetch()) {
90
-			if (!$this->isMember($row['group'], $row['user'])) {
91
-				$deletedEntries += $deleteQuery->setParameter('share', (int) $row['id'])
92
-					->execute();
93
-			}
94
-		}
95
-		$result->closeCursor();
96
-
97
-		if ($deletedEntries) {
98
-			$output->info('Removed ' . $deletedEntries . ' shares where user is not a member of the group anymore');
99
-		}
100
-	}
101
-
102
-	/**
103
-	 * @param string $gid
104
-	 * @param string $uid
105
-	 * @return bool
106
-	 */
107
-	protected function isMember($gid, $uid) {
108
-		if (isset($this->memberships[$gid][$uid])) {
109
-			return $this->memberships[$gid][$uid];
110
-		}
111
-
112
-		$isMember = $this->groupManager->isInGroup($uid, $gid);
113
-		if (!isset($this->memberships[$gid])) {
114
-			$this->memberships[$gid] = [];
115
-		}
116
-		$this->memberships[$gid][$uid] = $isMember;
117
-
118
-		return $isMember;
119
-	}
35
+    /** @var \OCP\IDBConnection */
36
+    protected $connection;
37
+
38
+    /** @var \OCP\IGroupManager */
39
+    protected $groupManager;
40
+
41
+    /**
42
+     * @var array [gid => [uid => (bool)]]
43
+     */
44
+    protected $memberships;
45
+
46
+    /**
47
+     * @param IDBConnection $connection
48
+     * @param IGroupManager $groupManager
49
+     */
50
+    public function __construct(IDBConnection $connection, IGroupManager $groupManager) {
51
+        $this->connection = $connection;
52
+        $this->groupManager = $groupManager;
53
+    }
54
+
55
+    /**
56
+     * Returns the step's name
57
+     *
58
+     * @return string
59
+     */
60
+    public function getName() {
61
+        return 'Remove shares of old group memberships';
62
+    }
63
+
64
+    /**
65
+     * Run repair step.
66
+     * Must throw exception on error.
67
+     *
68
+     * @throws \Exception in case of failure
69
+     * @suppress SqlInjectionChecker
70
+     */
71
+    public function run(IOutput $output) {
72
+        $deletedEntries = 0;
73
+
74
+        $query = $this->connection->getQueryBuilder();
75
+        $query->select('s1.id')->selectAlias('s1.share_with', 'user')->selectAlias('s2.share_with', 'group')
76
+            ->from('share', 's1')
77
+            ->where($query->expr()->isNotNull('s1.parent'))
78
+                // \OC\Share\Constant::$shareTypeGroupUserUnique === 2
79
+                ->andWhere($query->expr()->eq('s1.share_type', $query->expr()->literal(2)))
80
+                ->andWhere($query->expr()->isNotNull('s2.id'))
81
+                ->andWhere($query->expr()->eq('s2.share_type', $query->expr()->literal(IShare::TYPE_GROUP)))
82
+            ->leftJoin('s1', 'share', 's2', $query->expr()->eq('s1.parent', 's2.id'));
83
+
84
+        $deleteQuery = $this->connection->getQueryBuilder();
85
+        $deleteQuery->delete('share')
86
+            ->where($query->expr()->eq('id', $deleteQuery->createParameter('share')));
87
+
88
+        $result = $query->execute();
89
+        while ($row = $result->fetch()) {
90
+            if (!$this->isMember($row['group'], $row['user'])) {
91
+                $deletedEntries += $deleteQuery->setParameter('share', (int) $row['id'])
92
+                    ->execute();
93
+            }
94
+        }
95
+        $result->closeCursor();
96
+
97
+        if ($deletedEntries) {
98
+            $output->info('Removed ' . $deletedEntries . ' shares where user is not a member of the group anymore');
99
+        }
100
+    }
101
+
102
+    /**
103
+     * @param string $gid
104
+     * @param string $uid
105
+     * @return bool
106
+     */
107
+    protected function isMember($gid, $uid) {
108
+        if (isset($this->memberships[$gid][$uid])) {
109
+            return $this->memberships[$gid][$uid];
110
+        }
111
+
112
+        $isMember = $this->groupManager->isInGroup($uid, $gid);
113
+        if (!isset($this->memberships[$gid])) {
114
+            $this->memberships[$gid] = [];
115
+        }
116
+        $this->memberships[$gid][$uid] = $isMember;
117
+
118
+        return $isMember;
119
+    }
120 120
 }
Please login to merge, or discard this patch.
apps/admin_audit/lib/Actions/Sharing.php 1 patch
Indentation   +279 added lines, -279 removed lines patch added patch discarded remove patch
@@ -38,288 +38,288 @@
 block discarded – undo
38 38
  * @package OCA\AdminAudit\Actions
39 39
  */
40 40
 class Sharing extends Action {
41
-	/**
42
-	 * Logs sharing of data
43
-	 *
44
-	 * @param array $params
45
-	 */
46
-	public function shared(array $params) {
47
-		if ($params['shareType'] === IShare::TYPE_LINK) {
48
-			$this->log(
49
-				'The %s "%s" with ID "%s" has been shared via link with permissions "%s" (Share ID: %s)',
50
-				$params,
51
-				[
52
-					'itemType',
53
-					'itemTarget',
54
-					'itemSource',
55
-					'permissions',
56
-					'id',
57
-				]
58
-			);
59
-		} elseif ($params['shareType'] === IShare::TYPE_USER) {
60
-			$this->log(
61
-				'The %s "%s" with ID "%s" has been shared to the user "%s" with permissions "%s"  (Share ID: %s)',
62
-				$params,
63
-				[
64
-					'itemType',
65
-					'itemTarget',
66
-					'itemSource',
67
-					'shareWith',
68
-					'permissions',
69
-					'id',
70
-				]
71
-			);
72
-		} elseif ($params['shareType'] === IShare::TYPE_GROUP) {
73
-			$this->log(
74
-				'The %s "%s" with ID "%s" has been shared to the group "%s" with permissions "%s"  (Share ID: %s)',
75
-				$params,
76
-				[
77
-					'itemType',
78
-					'itemTarget',
79
-					'itemSource',
80
-					'shareWith',
81
-					'permissions',
82
-					'id',
83
-				]
84
-			);
85
-		} elseif ($params['shareType'] === IShare::TYPE_ROOM) {
86
-			$this->log(
87
-				'The %s "%s" with ID "%s" has been shared to the room "%s" with permissions "%s" (Share ID: %s)',
88
-				$params,
89
-				[
90
-					'itemType',
91
-					'itemTarget',
92
-					'itemSource',
93
-					'shareWith',
94
-					'permissions',
95
-					'id',
96
-				]
97
-			);
98
-		} elseif ($params['shareType'] === IShare::TYPE_EMAIL) {
99
-			$this->log(
100
-				'The %s "%s" with ID "%s" has been shared to the email recipient "%s" with permissions "%s" (Share ID: %s)',
101
-				$params,
102
-				[
103
-					'itemType',
104
-					'itemTarget',
105
-					'itemSource',
106
-					'shareWith',
107
-					'permissions',
108
-					'id',
109
-				]
110
-			);
111
-		} elseif ($params['shareType'] === IShare::TYPE_CIRCLE) {
112
-			$this->log(
113
-				'The %s "%s" with ID "%s" has been shared to the circle "%s" with permissions "%s" (Share ID: %s)',
114
-				$params,
115
-				[
116
-					'itemType',
117
-					'itemTarget',
118
-					'itemSource',
119
-					'shareWith',
120
-					'permissions',
121
-					'id',
122
-				]
123
-			);
124
-		} elseif ($params['shareType'] === IShare::TYPE_REMOTE) {
125
-			$this->log(
126
-				'The %s "%s" with ID "%s" has been shared to the remote user "%s" with permissions "%s" (Share ID: %s)',
127
-				$params,
128
-				[
129
-					'itemType',
130
-					'itemTarget',
131
-					'itemSource',
132
-					'shareWith',
133
-					'permissions',
134
-					'id',
135
-				]
136
-			);
137
-		} elseif ($params['shareType'] === IShare::TYPE_REMOTE_GROUP) {
138
-			$this->log(
139
-				'The %s "%s" with ID "%s" has been shared to the remote group "%s" with permissions "%s" (Share ID: %s)',
140
-				$params,
141
-				[
142
-					'itemType',
143
-					'itemTarget',
144
-					'itemSource',
145
-					'shareWith',
146
-					'permissions',
147
-					'id',
148
-				]
149
-			);
150
-		}
151
-	}
41
+    /**
42
+     * Logs sharing of data
43
+     *
44
+     * @param array $params
45
+     */
46
+    public function shared(array $params) {
47
+        if ($params['shareType'] === IShare::TYPE_LINK) {
48
+            $this->log(
49
+                'The %s "%s" with ID "%s" has been shared via link with permissions "%s" (Share ID: %s)',
50
+                $params,
51
+                [
52
+                    'itemType',
53
+                    'itemTarget',
54
+                    'itemSource',
55
+                    'permissions',
56
+                    'id',
57
+                ]
58
+            );
59
+        } elseif ($params['shareType'] === IShare::TYPE_USER) {
60
+            $this->log(
61
+                'The %s "%s" with ID "%s" has been shared to the user "%s" with permissions "%s"  (Share ID: %s)',
62
+                $params,
63
+                [
64
+                    'itemType',
65
+                    'itemTarget',
66
+                    'itemSource',
67
+                    'shareWith',
68
+                    'permissions',
69
+                    'id',
70
+                ]
71
+            );
72
+        } elseif ($params['shareType'] === IShare::TYPE_GROUP) {
73
+            $this->log(
74
+                'The %s "%s" with ID "%s" has been shared to the group "%s" with permissions "%s"  (Share ID: %s)',
75
+                $params,
76
+                [
77
+                    'itemType',
78
+                    'itemTarget',
79
+                    'itemSource',
80
+                    'shareWith',
81
+                    'permissions',
82
+                    'id',
83
+                ]
84
+            );
85
+        } elseif ($params['shareType'] === IShare::TYPE_ROOM) {
86
+            $this->log(
87
+                'The %s "%s" with ID "%s" has been shared to the room "%s" with permissions "%s" (Share ID: %s)',
88
+                $params,
89
+                [
90
+                    'itemType',
91
+                    'itemTarget',
92
+                    'itemSource',
93
+                    'shareWith',
94
+                    'permissions',
95
+                    'id',
96
+                ]
97
+            );
98
+        } elseif ($params['shareType'] === IShare::TYPE_EMAIL) {
99
+            $this->log(
100
+                'The %s "%s" with ID "%s" has been shared to the email recipient "%s" with permissions "%s" (Share ID: %s)',
101
+                $params,
102
+                [
103
+                    'itemType',
104
+                    'itemTarget',
105
+                    'itemSource',
106
+                    'shareWith',
107
+                    'permissions',
108
+                    'id',
109
+                ]
110
+            );
111
+        } elseif ($params['shareType'] === IShare::TYPE_CIRCLE) {
112
+            $this->log(
113
+                'The %s "%s" with ID "%s" has been shared to the circle "%s" with permissions "%s" (Share ID: %s)',
114
+                $params,
115
+                [
116
+                    'itemType',
117
+                    'itemTarget',
118
+                    'itemSource',
119
+                    'shareWith',
120
+                    'permissions',
121
+                    'id',
122
+                ]
123
+            );
124
+        } elseif ($params['shareType'] === IShare::TYPE_REMOTE) {
125
+            $this->log(
126
+                'The %s "%s" with ID "%s" has been shared to the remote user "%s" with permissions "%s" (Share ID: %s)',
127
+                $params,
128
+                [
129
+                    'itemType',
130
+                    'itemTarget',
131
+                    'itemSource',
132
+                    'shareWith',
133
+                    'permissions',
134
+                    'id',
135
+                ]
136
+            );
137
+        } elseif ($params['shareType'] === IShare::TYPE_REMOTE_GROUP) {
138
+            $this->log(
139
+                'The %s "%s" with ID "%s" has been shared to the remote group "%s" with permissions "%s" (Share ID: %s)',
140
+                $params,
141
+                [
142
+                    'itemType',
143
+                    'itemTarget',
144
+                    'itemSource',
145
+                    'shareWith',
146
+                    'permissions',
147
+                    'id',
148
+                ]
149
+            );
150
+        }
151
+    }
152 152
 
153
-	/**
154
-	 * Logs unsharing of data
155
-	 *
156
-	 * @param array $params
157
-	 */
158
-	public function unshare(array $params) {
159
-		if ($params['shareType'] === IShare::TYPE_LINK) {
160
-			$this->log(
161
-				'The %s "%s" with ID "%s" has been unshared (Share ID: %s)',
162
-				$params,
163
-				[
164
-					'itemType',
165
-					'fileTarget',
166
-					'itemSource',
167
-					'id',
168
-				]
169
-			);
170
-		} elseif ($params['shareType'] === IShare::TYPE_USER) {
171
-			$this->log(
172
-				'The %s "%s" with ID "%s" has been unshared from the user "%s" (Share ID: %s)',
173
-				$params,
174
-				[
175
-					'itemType',
176
-					'fileTarget',
177
-					'itemSource',
178
-					'shareWith',
179
-					'id',
180
-				]
181
-			);
182
-		} elseif ($params['shareType'] === IShare::TYPE_GROUP) {
183
-			$this->log(
184
-				'The %s "%s" with ID "%s" has been unshared from the group "%s" (Share ID: %s)',
185
-				$params,
186
-				[
187
-					'itemType',
188
-					'fileTarget',
189
-					'itemSource',
190
-					'shareWith',
191
-					'id',
192
-				]
193
-			);
194
-		} elseif ($params['shareType'] === IShare::TYPE_ROOM) {
195
-			$this->log(
196
-				'The %s "%s" with ID "%s" has been unshared from the room "%s" (Share ID: %s)',
197
-				$params,
198
-				[
199
-					'itemType',
200
-					'fileTarget',
201
-					'itemSource',
202
-					'shareWith',
203
-					'id',
204
-				]
205
-			);
206
-		} elseif ($params['shareType'] === IShare::TYPE_EMAIL) {
207
-			$this->log(
208
-				'The %s "%s" with ID "%s" has been unshared from the email recipient "%s" (Share ID: %s)',
209
-				$params,
210
-				[
211
-					'itemType',
212
-					'fileTarget',
213
-					'itemSource',
214
-					'shareWith',
215
-					'id',
216
-				]
217
-			);
218
-		} elseif ($params['shareType'] === IShare::TYPE_CIRCLE) {
219
-			$this->log(
220
-				'The %s "%s" with ID "%s" has been unshared from the circle "%s" (Share ID: %s)',
221
-				$params,
222
-				[
223
-					'itemType',
224
-					'fileTarget',
225
-					'itemSource',
226
-					'shareWith',
227
-					'id',
228
-				]
229
-			);
230
-		} elseif ($params['shareType'] === IShare::TYPE_REMOTE) {
231
-			$this->log(
232
-				'The %s "%s" with ID "%s" has been unshared from the remote user "%s" (Share ID: %s)',
233
-				$params,
234
-				[
235
-					'itemType',
236
-					'fileTarget',
237
-					'itemSource',
238
-					'shareWith',
239
-					'id',
240
-				]
241
-			);
242
-		} elseif ($params['shareType'] === IShare::TYPE_REMOTE_GROUP) {
243
-			$this->log(
244
-				'The %s "%s" with ID "%s" has been unshared from the remote group "%s" (Share ID: %s)',
245
-				$params,
246
-				[
247
-					'itemType',
248
-					'fileTarget',
249
-					'itemSource',
250
-					'shareWith',
251
-					'id',
252
-				]
253
-			);
254
-		}
255
-	}
153
+    /**
154
+     * Logs unsharing of data
155
+     *
156
+     * @param array $params
157
+     */
158
+    public function unshare(array $params) {
159
+        if ($params['shareType'] === IShare::TYPE_LINK) {
160
+            $this->log(
161
+                'The %s "%s" with ID "%s" has been unshared (Share ID: %s)',
162
+                $params,
163
+                [
164
+                    'itemType',
165
+                    'fileTarget',
166
+                    'itemSource',
167
+                    'id',
168
+                ]
169
+            );
170
+        } elseif ($params['shareType'] === IShare::TYPE_USER) {
171
+            $this->log(
172
+                'The %s "%s" with ID "%s" has been unshared from the user "%s" (Share ID: %s)',
173
+                $params,
174
+                [
175
+                    'itemType',
176
+                    'fileTarget',
177
+                    'itemSource',
178
+                    'shareWith',
179
+                    'id',
180
+                ]
181
+            );
182
+        } elseif ($params['shareType'] === IShare::TYPE_GROUP) {
183
+            $this->log(
184
+                'The %s "%s" with ID "%s" has been unshared from the group "%s" (Share ID: %s)',
185
+                $params,
186
+                [
187
+                    'itemType',
188
+                    'fileTarget',
189
+                    'itemSource',
190
+                    'shareWith',
191
+                    'id',
192
+                ]
193
+            );
194
+        } elseif ($params['shareType'] === IShare::TYPE_ROOM) {
195
+            $this->log(
196
+                'The %s "%s" with ID "%s" has been unshared from the room "%s" (Share ID: %s)',
197
+                $params,
198
+                [
199
+                    'itemType',
200
+                    'fileTarget',
201
+                    'itemSource',
202
+                    'shareWith',
203
+                    'id',
204
+                ]
205
+            );
206
+        } elseif ($params['shareType'] === IShare::TYPE_EMAIL) {
207
+            $this->log(
208
+                'The %s "%s" with ID "%s" has been unshared from the email recipient "%s" (Share ID: %s)',
209
+                $params,
210
+                [
211
+                    'itemType',
212
+                    'fileTarget',
213
+                    'itemSource',
214
+                    'shareWith',
215
+                    'id',
216
+                ]
217
+            );
218
+        } elseif ($params['shareType'] === IShare::TYPE_CIRCLE) {
219
+            $this->log(
220
+                'The %s "%s" with ID "%s" has been unshared from the circle "%s" (Share ID: %s)',
221
+                $params,
222
+                [
223
+                    'itemType',
224
+                    'fileTarget',
225
+                    'itemSource',
226
+                    'shareWith',
227
+                    'id',
228
+                ]
229
+            );
230
+        } elseif ($params['shareType'] === IShare::TYPE_REMOTE) {
231
+            $this->log(
232
+                'The %s "%s" with ID "%s" has been unshared from the remote user "%s" (Share ID: %s)',
233
+                $params,
234
+                [
235
+                    'itemType',
236
+                    'fileTarget',
237
+                    'itemSource',
238
+                    'shareWith',
239
+                    'id',
240
+                ]
241
+            );
242
+        } elseif ($params['shareType'] === IShare::TYPE_REMOTE_GROUP) {
243
+            $this->log(
244
+                'The %s "%s" with ID "%s" has been unshared from the remote group "%s" (Share ID: %s)',
245
+                $params,
246
+                [
247
+                    'itemType',
248
+                    'fileTarget',
249
+                    'itemSource',
250
+                    'shareWith',
251
+                    'id',
252
+                ]
253
+            );
254
+        }
255
+    }
256 256
 
257
-	/**
258
-	 * Logs the updating of permission changes for shares
259
-	 *
260
-	 * @param array $params
261
-	 */
262
-	public function updatePermissions(array $params) {
263
-		$this->log(
264
-			'The permissions of the shared %s "%s" with ID "%s" have been changed to "%s"',
265
-			$params,
266
-			[
267
-				'itemType',
268
-				'path',
269
-				'itemSource',
270
-				'permissions',
271
-			]
272
-		);
273
-	}
257
+    /**
258
+     * Logs the updating of permission changes for shares
259
+     *
260
+     * @param array $params
261
+     */
262
+    public function updatePermissions(array $params) {
263
+        $this->log(
264
+            'The permissions of the shared %s "%s" with ID "%s" have been changed to "%s"',
265
+            $params,
266
+            [
267
+                'itemType',
268
+                'path',
269
+                'itemSource',
270
+                'permissions',
271
+            ]
272
+        );
273
+    }
274 274
 
275
-	/**
276
-	 * Logs the password changes for a share
277
-	 *
278
-	 * @param array $params
279
-	 */
280
-	public function updatePassword(array $params) {
281
-		$this->log(
282
-			'The password of the publicly shared %s "%s" with ID "%s" has been changed',
283
-			$params,
284
-			[
285
-				'itemType',
286
-				'token',
287
-				'itemSource',
288
-			]
289
-		);
290
-	}
275
+    /**
276
+     * Logs the password changes for a share
277
+     *
278
+     * @param array $params
279
+     */
280
+    public function updatePassword(array $params) {
281
+        $this->log(
282
+            'The password of the publicly shared %s "%s" with ID "%s" has been changed',
283
+            $params,
284
+            [
285
+                'itemType',
286
+                'token',
287
+                'itemSource',
288
+            ]
289
+        );
290
+    }
291 291
 
292
-	/**
293
-	 * Logs the expiration date changes for a share
294
-	 *
295
-	 * @param array $params
296
-	 */
297
-	public function updateExpirationDate(array $params) {
298
-		$this->log(
299
-			'The expiration date of the publicly shared %s with ID "%s" has been changed to "%s"',
300
-			$params,
301
-			[
302
-				'itemType',
303
-				'itemSource',
304
-				'date',
305
-			]
306
-		);
307
-	}
292
+    /**
293
+     * Logs the expiration date changes for a share
294
+     *
295
+     * @param array $params
296
+     */
297
+    public function updateExpirationDate(array $params) {
298
+        $this->log(
299
+            'The expiration date of the publicly shared %s with ID "%s" has been changed to "%s"',
300
+            $params,
301
+            [
302
+                'itemType',
303
+                'itemSource',
304
+                'date',
305
+            ]
306
+        );
307
+    }
308 308
 
309
-	/**
310
-	 * Logs access of shared files
311
-	 *
312
-	 * @param array $params
313
-	 */
314
-	public function shareAccessed(array $params) {
315
-		$this->log(
316
-			'The shared %s with the token "%s" by "%s" has been accessed.',
317
-			$params,
318
-			[
319
-				'itemType',
320
-				'token',
321
-				'uidOwner',
322
-			]
323
-		);
324
-	}
309
+    /**
310
+     * Logs access of shared files
311
+     *
312
+     * @param array $params
313
+     */
314
+    public function shareAccessed(array $params) {
315
+        $this->log(
316
+            'The shared %s with the token "%s" by "%s" has been accessed.',
317
+            $params,
318
+            [
319
+                'itemType',
320
+                'token',
321
+                'uidOwner',
322
+            ]
323
+        );
324
+    }
325 325
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/ExpireSharesJob.php 1 patch
Indentation   +37 added lines, -37 removed lines patch added patch discarded remove patch
@@ -32,47 +32,47 @@
 block discarded – undo
32 32
  */
33 33
 class ExpireSharesJob extends TimedJob {
34 34
 
35
-	/**
36
-	 * sets the correct interval for this timed job
37
-	 */
38
-	public function __construct() {
39
-		// Run once a day
40
-		$this->setInterval(24 * 60 * 60);
41
-	}
35
+    /**
36
+     * sets the correct interval for this timed job
37
+     */
38
+    public function __construct() {
39
+        // Run once a day
40
+        $this->setInterval(24 * 60 * 60);
41
+    }
42 42
 
43
-	/**
44
-	 * Makes the background job do its work
45
-	 *
46
-	 * @param array $argument unused argument
47
-	 */
48
-	public function run($argument) {
49
-		$connection = \OC::$server->getDatabaseConnection();
43
+    /**
44
+     * Makes the background job do its work
45
+     *
46
+     * @param array $argument unused argument
47
+     */
48
+    public function run($argument) {
49
+        $connection = \OC::$server->getDatabaseConnection();
50 50
 
51
-		//Current time
52
-		$now = new \DateTime();
53
-		$now = $now->format('Y-m-d H:i:s');
51
+        //Current time
52
+        $now = new \DateTime();
53
+        $now = $now->format('Y-m-d H:i:s');
54 54
 
55
-		/*
55
+        /*
56 56
 		 * Expire file link shares only (for now)
57 57
 		 */
58
-		$qb = $connection->getQueryBuilder();
59
-		$qb->select('id', 'file_source', 'uid_owner', 'item_type')
60
-			->from('share')
61
-			->where(
62
-				$qb->expr()->andX(
63
-					$qb->expr()->eq('share_type', $qb->expr()->literal(IShare::TYPE_LINK)),
64
-					$qb->expr()->lte('expiration', $qb->expr()->literal($now)),
65
-					$qb->expr()->orX(
66
-						$qb->expr()->eq('item_type', $qb->expr()->literal('file')),
67
-						$qb->expr()->eq('item_type', $qb->expr()->literal('folder'))
68
-					)
69
-				)
70
-			);
58
+        $qb = $connection->getQueryBuilder();
59
+        $qb->select('id', 'file_source', 'uid_owner', 'item_type')
60
+            ->from('share')
61
+            ->where(
62
+                $qb->expr()->andX(
63
+                    $qb->expr()->eq('share_type', $qb->expr()->literal(IShare::TYPE_LINK)),
64
+                    $qb->expr()->lte('expiration', $qb->expr()->literal($now)),
65
+                    $qb->expr()->orX(
66
+                        $qb->expr()->eq('item_type', $qb->expr()->literal('file')),
67
+                        $qb->expr()->eq('item_type', $qb->expr()->literal('folder'))
68
+                    )
69
+                )
70
+            );
71 71
 
72
-		$shares = $qb->execute();
73
-		while ($share = $shares->fetch()) {
74
-			\OC\Share\Share::unshare($share['item_type'], $share['file_source'], IShare::TYPE_LINK, null, $share['uid_owner']);
75
-		}
76
-		$shares->closeCursor();
77
-	}
72
+        $shares = $qb->execute();
73
+        while ($share = $shares->fetch()) {
74
+            \OC\Share\Share::unshare($share['item_type'], $share['file_source'], IShare::TYPE_LINK, null, $share['uid_owner']);
75
+        }
76
+        $shares->closeCursor();
77
+    }
78 78
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/MountProvider.php 1 patch
Indentation   +200 added lines, -200 removed lines patch added patch discarded remove patch
@@ -40,204 +40,204 @@
 block discarded – undo
40 40
 use OCP\Share\IShare;
41 41
 
42 42
 class MountProvider implements IMountProvider {
43
-	/**
44
-	 * @var \OCP\IConfig
45
-	 */
46
-	protected $config;
47
-
48
-	/**
49
-	 * @var IManager
50
-	 */
51
-	protected $shareManager;
52
-
53
-	/**
54
-	 * @var ILogger
55
-	 */
56
-	protected $logger;
57
-
58
-	/**
59
-	 * @param \OCP\IConfig $config
60
-	 * @param IManager $shareManager
61
-	 * @param ILogger $logger
62
-	 */
63
-	public function __construct(IConfig $config, IManager $shareManager, ILogger $logger) {
64
-		$this->config = $config;
65
-		$this->shareManager = $shareManager;
66
-		$this->logger = $logger;
67
-	}
68
-
69
-
70
-	/**
71
-	 * Get all mountpoints applicable for the user and check for shares where we need to update the etags
72
-	 *
73
-	 * @param \OCP\IUser $user
74
-	 * @param \OCP\Files\Storage\IStorageFactory $storageFactory
75
-	 * @return \OCP\Files\Mount\IMountPoint[]
76
-	 */
77
-	public function getMountsForUser(IUser $user, IStorageFactory $storageFactory) {
78
-		$shares = $this->shareManager->getSharedWith($user->getUID(), IShare::TYPE_USER, null, -1);
79
-		$shares = array_merge($shares, $this->shareManager->getSharedWith($user->getUID(), IShare::TYPE_GROUP, null, -1));
80
-		$shares = array_merge($shares, $this->shareManager->getSharedWith($user->getUID(), IShare::TYPE_CIRCLE, null, -1));
81
-		$shares = array_merge($shares, $this->shareManager->getSharedWith($user->getUID(), IShare::TYPE_ROOM, null, -1));
82
-
83
-		// filter out excluded shares and group shares that includes self
84
-		$shares = array_filter($shares, function (\OCP\Share\IShare $share) use ($user) {
85
-			return $share->getPermissions() > 0 && $share->getShareOwner() !== $user->getUID();
86
-		});
87
-
88
-		$superShares = $this->buildSuperShares($shares, $user);
89
-
90
-		$mounts = [];
91
-		$view = new View('/' . $user->getUID() . '/files');
92
-		$ownerViews = [];
93
-		$sharingDisabledForUser = $this->shareManager->sharingDisabledForUser($user->getUID());
94
-		$foldersExistCache = new CappedMemoryCache();
95
-		foreach ($superShares as $share) {
96
-			try {
97
-				/** @var \OCP\Share\IShare $parentShare */
98
-				$parentShare = $share[0];
99
-
100
-				if ($parentShare->getStatus() !== IShare::STATUS_ACCEPTED &&
101
-					($parentShare->getShareType() === IShare::TYPE_GROUP ||
102
-						$parentShare->getShareType() === IShare::TYPE_USERGROUP ||
103
-						$parentShare->getShareType() === IShare::TYPE_USER)) {
104
-					continue;
105
-				}
106
-
107
-				$owner = $parentShare->getShareOwner();
108
-				if (!isset($ownerViews[$owner])) {
109
-					$ownerViews[$owner] = new View('/' . $parentShare->getShareOwner() . '/files');
110
-				}
111
-				$mount = new SharedMount(
112
-					'\OCA\Files_Sharing\SharedStorage',
113
-					$mounts,
114
-					[
115
-						'user' => $user->getUID(),
116
-						// parent share
117
-						'superShare' => $parentShare,
118
-						// children/component of the superShare
119
-						'groupedShares' => $share[1],
120
-						'ownerView' => $ownerViews[$owner],
121
-						'sharingDisabledForUser' => $sharingDisabledForUser
122
-					],
123
-					$storageFactory,
124
-					$view,
125
-					$foldersExistCache
126
-				);
127
-				$mounts[$mount->getMountPoint()] = $mount;
128
-			} catch (\Exception $e) {
129
-				$this->logger->logException($e);
130
-				$this->logger->error('Error while trying to create shared mount');
131
-			}
132
-		}
133
-
134
-		// array_filter removes the null values from the array
135
-		return array_values(array_filter($mounts));
136
-	}
137
-
138
-	/**
139
-	 * Groups shares by path (nodeId) and target path
140
-	 *
141
-	 * @param \OCP\Share\IShare[] $shares
142
-	 * @return \OCP\Share\IShare[][] array of grouped shares, each element in the
143
-	 * array is a group which itself is an array of shares
144
-	 */
145
-	private function groupShares(array $shares) {
146
-		$tmp = [];
147
-
148
-		foreach ($shares as $share) {
149
-			if (!isset($tmp[$share->getNodeId()])) {
150
-				$tmp[$share->getNodeId()] = [];
151
-			}
152
-			$tmp[$share->getNodeId()][] = $share;
153
-		}
154
-
155
-		$result = [];
156
-		// sort by stime, the super share will be based on the least recent share
157
-		foreach ($tmp as &$tmp2) {
158
-			@usort($tmp2, function ($a, $b) {
159
-				$aTime = $a->getShareTime()->getTimestamp();
160
-				$bTime = $b->getShareTime()->getTimestamp();
161
-				if ($aTime === $bTime) {
162
-					return $a->getId() < $b->getId() ? -1 : 1;
163
-				}
164
-				return $aTime < $bTime ? -1 : 1;
165
-			});
166
-			$result[] = $tmp2;
167
-		}
168
-
169
-		return array_values($result);
170
-	}
171
-
172
-	/**
173
-	 * Build super shares (virtual share) by grouping them by node id and target,
174
-	 * then for each group compute the super share and return it along with the matching
175
-	 * grouped shares. The most permissive permissions are used based on the permissions
176
-	 * of all shares within the group.
177
-	 *
178
-	 * @param \OCP\Share\IShare[] $allShares
179
-	 * @param \OCP\IUser $user user
180
-	 * @return array Tuple of [superShare, groupedShares]
181
-	 */
182
-	private function buildSuperShares(array $allShares, \OCP\IUser $user) {
183
-		$result = [];
184
-
185
-		$groupedShares = $this->groupShares($allShares);
186
-
187
-		/** @var \OCP\Share\IShare[] $shares */
188
-		foreach ($groupedShares as $shares) {
189
-			if (count($shares) === 0) {
190
-				continue;
191
-			}
192
-
193
-			$superShare = $this->shareManager->newShare();
194
-
195
-			// compute super share based on first entry of the group
196
-			$superShare->setId($shares[0]->getId())
197
-				->setShareOwner($shares[0]->getShareOwner())
198
-				->setNodeId($shares[0]->getNodeId())
199
-				->setShareType($shares[0]->getShareType())
200
-				->setTarget($shares[0]->getTarget());
201
-
202
-			// use most permissive permissions
203
-			$permissions = 0;
204
-			$status = IShare::STATUS_PENDING;
205
-			foreach ($shares as $share) {
206
-				$permissions |= $share->getPermissions();
207
-				$status = max($status, $share->getStatus());
208
-
209
-				if ($share->getTarget() !== $superShare->getTarget()) {
210
-					// adjust target, for database consistency
211
-					$share->setTarget($superShare->getTarget());
212
-					try {
213
-						$this->shareManager->moveShare($share, $user->getUID());
214
-					} catch (\InvalidArgumentException $e) {
215
-						// ignore as it is not important and we don't want to
216
-						// block FS setup
217
-
218
-						// the subsequent code anyway only uses the target of the
219
-						// super share
220
-
221
-						// such issue can usually happen when dealing with
222
-						// null groups which usually appear with group backend
223
-						// caching inconsistencies
224
-						$this->logger->debug(
225
-							'Could not adjust share target for share ' . $share->getId() . ' to make it consistent: ' . $e->getMessage(),
226
-							['app' => 'files_sharing']
227
-						);
228
-					}
229
-				}
230
-				if (!is_null($share->getNodeCacheEntry())) {
231
-					$superShare->setNodeCacheEntry($share->getNodeCacheEntry());
232
-				}
233
-			}
234
-
235
-			$superShare->setPermissions($permissions)
236
-				->setStatus($status);
237
-
238
-			$result[] = [$superShare, $shares];
239
-		}
240
-
241
-		return $result;
242
-	}
43
+    /**
44
+     * @var \OCP\IConfig
45
+     */
46
+    protected $config;
47
+
48
+    /**
49
+     * @var IManager
50
+     */
51
+    protected $shareManager;
52
+
53
+    /**
54
+     * @var ILogger
55
+     */
56
+    protected $logger;
57
+
58
+    /**
59
+     * @param \OCP\IConfig $config
60
+     * @param IManager $shareManager
61
+     * @param ILogger $logger
62
+     */
63
+    public function __construct(IConfig $config, IManager $shareManager, ILogger $logger) {
64
+        $this->config = $config;
65
+        $this->shareManager = $shareManager;
66
+        $this->logger = $logger;
67
+    }
68
+
69
+
70
+    /**
71
+     * Get all mountpoints applicable for the user and check for shares where we need to update the etags
72
+     *
73
+     * @param \OCP\IUser $user
74
+     * @param \OCP\Files\Storage\IStorageFactory $storageFactory
75
+     * @return \OCP\Files\Mount\IMountPoint[]
76
+     */
77
+    public function getMountsForUser(IUser $user, IStorageFactory $storageFactory) {
78
+        $shares = $this->shareManager->getSharedWith($user->getUID(), IShare::TYPE_USER, null, -1);
79
+        $shares = array_merge($shares, $this->shareManager->getSharedWith($user->getUID(), IShare::TYPE_GROUP, null, -1));
80
+        $shares = array_merge($shares, $this->shareManager->getSharedWith($user->getUID(), IShare::TYPE_CIRCLE, null, -1));
81
+        $shares = array_merge($shares, $this->shareManager->getSharedWith($user->getUID(), IShare::TYPE_ROOM, null, -1));
82
+
83
+        // filter out excluded shares and group shares that includes self
84
+        $shares = array_filter($shares, function (\OCP\Share\IShare $share) use ($user) {
85
+            return $share->getPermissions() > 0 && $share->getShareOwner() !== $user->getUID();
86
+        });
87
+
88
+        $superShares = $this->buildSuperShares($shares, $user);
89
+
90
+        $mounts = [];
91
+        $view = new View('/' . $user->getUID() . '/files');
92
+        $ownerViews = [];
93
+        $sharingDisabledForUser = $this->shareManager->sharingDisabledForUser($user->getUID());
94
+        $foldersExistCache = new CappedMemoryCache();
95
+        foreach ($superShares as $share) {
96
+            try {
97
+                /** @var \OCP\Share\IShare $parentShare */
98
+                $parentShare = $share[0];
99
+
100
+                if ($parentShare->getStatus() !== IShare::STATUS_ACCEPTED &&
101
+                    ($parentShare->getShareType() === IShare::TYPE_GROUP ||
102
+                        $parentShare->getShareType() === IShare::TYPE_USERGROUP ||
103
+                        $parentShare->getShareType() === IShare::TYPE_USER)) {
104
+                    continue;
105
+                }
106
+
107
+                $owner = $parentShare->getShareOwner();
108
+                if (!isset($ownerViews[$owner])) {
109
+                    $ownerViews[$owner] = new View('/' . $parentShare->getShareOwner() . '/files');
110
+                }
111
+                $mount = new SharedMount(
112
+                    '\OCA\Files_Sharing\SharedStorage',
113
+                    $mounts,
114
+                    [
115
+                        'user' => $user->getUID(),
116
+                        // parent share
117
+                        'superShare' => $parentShare,
118
+                        // children/component of the superShare
119
+                        'groupedShares' => $share[1],
120
+                        'ownerView' => $ownerViews[$owner],
121
+                        'sharingDisabledForUser' => $sharingDisabledForUser
122
+                    ],
123
+                    $storageFactory,
124
+                    $view,
125
+                    $foldersExistCache
126
+                );
127
+                $mounts[$mount->getMountPoint()] = $mount;
128
+            } catch (\Exception $e) {
129
+                $this->logger->logException($e);
130
+                $this->logger->error('Error while trying to create shared mount');
131
+            }
132
+        }
133
+
134
+        // array_filter removes the null values from the array
135
+        return array_values(array_filter($mounts));
136
+    }
137
+
138
+    /**
139
+     * Groups shares by path (nodeId) and target path
140
+     *
141
+     * @param \OCP\Share\IShare[] $shares
142
+     * @return \OCP\Share\IShare[][] array of grouped shares, each element in the
143
+     * array is a group which itself is an array of shares
144
+     */
145
+    private function groupShares(array $shares) {
146
+        $tmp = [];
147
+
148
+        foreach ($shares as $share) {
149
+            if (!isset($tmp[$share->getNodeId()])) {
150
+                $tmp[$share->getNodeId()] = [];
151
+            }
152
+            $tmp[$share->getNodeId()][] = $share;
153
+        }
154
+
155
+        $result = [];
156
+        // sort by stime, the super share will be based on the least recent share
157
+        foreach ($tmp as &$tmp2) {
158
+            @usort($tmp2, function ($a, $b) {
159
+                $aTime = $a->getShareTime()->getTimestamp();
160
+                $bTime = $b->getShareTime()->getTimestamp();
161
+                if ($aTime === $bTime) {
162
+                    return $a->getId() < $b->getId() ? -1 : 1;
163
+                }
164
+                return $aTime < $bTime ? -1 : 1;
165
+            });
166
+            $result[] = $tmp2;
167
+        }
168
+
169
+        return array_values($result);
170
+    }
171
+
172
+    /**
173
+     * Build super shares (virtual share) by grouping them by node id and target,
174
+     * then for each group compute the super share and return it along with the matching
175
+     * grouped shares. The most permissive permissions are used based on the permissions
176
+     * of all shares within the group.
177
+     *
178
+     * @param \OCP\Share\IShare[] $allShares
179
+     * @param \OCP\IUser $user user
180
+     * @return array Tuple of [superShare, groupedShares]
181
+     */
182
+    private function buildSuperShares(array $allShares, \OCP\IUser $user) {
183
+        $result = [];
184
+
185
+        $groupedShares = $this->groupShares($allShares);
186
+
187
+        /** @var \OCP\Share\IShare[] $shares */
188
+        foreach ($groupedShares as $shares) {
189
+            if (count($shares) === 0) {
190
+                continue;
191
+            }
192
+
193
+            $superShare = $this->shareManager->newShare();
194
+
195
+            // compute super share based on first entry of the group
196
+            $superShare->setId($shares[0]->getId())
197
+                ->setShareOwner($shares[0]->getShareOwner())
198
+                ->setNodeId($shares[0]->getNodeId())
199
+                ->setShareType($shares[0]->getShareType())
200
+                ->setTarget($shares[0]->getTarget());
201
+
202
+            // use most permissive permissions
203
+            $permissions = 0;
204
+            $status = IShare::STATUS_PENDING;
205
+            foreach ($shares as $share) {
206
+                $permissions |= $share->getPermissions();
207
+                $status = max($status, $share->getStatus());
208
+
209
+                if ($share->getTarget() !== $superShare->getTarget()) {
210
+                    // adjust target, for database consistency
211
+                    $share->setTarget($superShare->getTarget());
212
+                    try {
213
+                        $this->shareManager->moveShare($share, $user->getUID());
214
+                    } catch (\InvalidArgumentException $e) {
215
+                        // ignore as it is not important and we don't want to
216
+                        // block FS setup
217
+
218
+                        // the subsequent code anyway only uses the target of the
219
+                        // super share
220
+
221
+                        // such issue can usually happen when dealing with
222
+                        // null groups which usually appear with group backend
223
+                        // caching inconsistencies
224
+                        $this->logger->debug(
225
+                            'Could not adjust share target for share ' . $share->getId() . ' to make it consistent: ' . $e->getMessage(),
226
+                            ['app' => 'files_sharing']
227
+                        );
228
+                    }
229
+                }
230
+                if (!is_null($share->getNodeCacheEntry())) {
231
+                    $superShare->setNodeCacheEntry($share->getNodeCacheEntry());
232
+                }
233
+            }
234
+
235
+            $superShare->setPermissions($permissions)
236
+                ->setStatus($status);
237
+
238
+            $result[] = [$superShare, $shares];
239
+        }
240
+
241
+        return $result;
242
+    }
243 243
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/External/Manager.php 1 patch
Indentation   +555 added lines, -555 removed lines patch added patch discarded remove patch
@@ -48,600 +48,600 @@
 block discarded – undo
48 48
 use OCP\Share\IShare;
49 49
 
50 50
 class Manager {
51
-	public const STORAGE = '\OCA\Files_Sharing\External\Storage';
52
-
53
-	/**
54
-	 * @var string
55
-	 */
56
-	private $uid;
57
-
58
-	/**
59
-	 * @var IDBConnection
60
-	 */
61
-	private $connection;
62
-
63
-	/**
64
-	 * @var \OC\Files\Mount\Manager
65
-	 */
66
-	private $mountManager;
67
-
68
-	/**
69
-	 * @var IStorageFactory
70
-	 */
71
-	private $storageLoader;
72
-
73
-	/**
74
-	 * @var IClientService
75
-	 */
76
-	private $clientService;
77
-
78
-	/**
79
-	 * @var IManager
80
-	 */
81
-	private $notificationManager;
82
-
83
-	/**
84
-	 * @var IDiscoveryService
85
-	 */
86
-	private $discoveryService;
87
-
88
-	/** @var ICloudFederationProviderManager */
89
-	private $cloudFederationProviderManager;
90
-
91
-	/** @var ICloudFederationFactory */
92
-	private $cloudFederationFactory;
93
-
94
-	/** @var IGroupManager  */
95
-	private $groupManager;
96
-
97
-	/** @var IUserManager */
98
-	private $userManager;
99
-
100
-	/**
101
-	 * @param IDBConnection $connection
102
-	 * @param \OC\Files\Mount\Manager $mountManager
103
-	 * @param IStorageFactory $storageLoader
104
-	 * @param IClientService $clientService
105
-	 * @param IManager $notificationManager
106
-	 * @param IDiscoveryService $discoveryService
107
-	 * @param ICloudFederationProviderManager $cloudFederationProviderManager
108
-	 * @param ICloudFederationFactory $cloudFederationFactory
109
-	 * @param IGroupManager $groupManager
110
-	 * @param IUserManager $userManager
111
-	 * @param string $uid
112
-	 */
113
-	public function __construct(IDBConnection $connection,
114
-								\OC\Files\Mount\Manager $mountManager,
115
-								IStorageFactory $storageLoader,
116
-								IClientService $clientService,
117
-								IManager $notificationManager,
118
-								IDiscoveryService $discoveryService,
119
-								ICloudFederationProviderManager $cloudFederationProviderManager,
120
-								ICloudFederationFactory $cloudFederationFactory,
121
-								IGroupManager $groupManager,
122
-								IUserManager $userManager,
123
-								$uid) {
124
-		$this->connection = $connection;
125
-		$this->mountManager = $mountManager;
126
-		$this->storageLoader = $storageLoader;
127
-		$this->clientService = $clientService;
128
-		$this->uid = $uid;
129
-		$this->notificationManager = $notificationManager;
130
-		$this->discoveryService = $discoveryService;
131
-		$this->cloudFederationProviderManager = $cloudFederationProviderManager;
132
-		$this->cloudFederationFactory = $cloudFederationFactory;
133
-		$this->groupManager = $groupManager;
134
-		$this->userManager = $userManager;
135
-	}
136
-
137
-	/**
138
-	 * add new server-to-server share
139
-	 *
140
-	 * @param string $remote
141
-	 * @param string $token
142
-	 * @param string $password
143
-	 * @param string $name
144
-	 * @param string $owner
145
-	 * @param int $shareType
146
-	 * @param boolean $accepted
147
-	 * @param string $user
148
-	 * @param int $remoteId
149
-	 * @param int $parent
150
-	 * @return Mount|null
151
-	 * @throws \Doctrine\DBAL\DBALException
152
-	 */
153
-	public function addShare($remote, $token, $password, $name, $owner, $shareType, $accepted=false, $user = null, $remoteId = -1, $parent = -1) {
154
-		$user = $user ? $user : $this->uid;
155
-		$accepted = $accepted ? IShare::STATUS_ACCEPTED : IShare::STATUS_PENDING;
156
-		$name = Filesystem::normalizePath('/' . $name);
157
-
158
-		if ($accepted !== IShare::STATUS_ACCEPTED) {
159
-			// To avoid conflicts with the mount point generation later,
160
-			// we only use a temporary mount point name here. The real
161
-			// mount point name will be generated when accepting the share,
162
-			// using the original share item name.
163
-			$tmpMountPointName = '{{TemporaryMountPointName#' . $name . '}}';
164
-			$mountPoint = $tmpMountPointName;
165
-			$hash = md5($tmpMountPointName);
166
-			$data = [
167
-				'remote'		=> $remote,
168
-				'share_token'	=> $token,
169
-				'password'		=> $password,
170
-				'name'			=> $name,
171
-				'owner'			=> $owner,
172
-				'user'			=> $user,
173
-				'mountpoint'	=> $mountPoint,
174
-				'mountpoint_hash'	=> $hash,
175
-				'accepted'		=> $accepted,
176
-				'remote_id'		=> $remoteId,
177
-				'share_type'    => $shareType,
178
-			];
179
-
180
-			$i = 1;
181
-			while (!$this->connection->insertIfNotExist('*PREFIX*share_external', $data, ['user', 'mountpoint_hash'])) {
182
-				// The external share already exists for the user
183
-				$data['mountpoint'] = $tmpMountPointName . '-' . $i;
184
-				$data['mountpoint_hash'] = md5($data['mountpoint']);
185
-				$i++;
186
-			}
187
-			return null;
188
-		}
189
-
190
-		$mountPoint = Files::buildNotExistingFileName('/', $name);
191
-		$mountPoint = Filesystem::normalizePath('/' . $mountPoint);
192
-		$hash = md5($mountPoint);
193
-
194
-		$this->writeShareToDb($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType);
195
-
196
-		$options = [
197
-			'remote'	=> $remote,
198
-			'token'		=> $token,
199
-			'password'	=> $password,
200
-			'mountpoint'	=> $mountPoint,
201
-			'owner'		=> $owner
202
-		];
203
-		return $this->mountShare($options);
204
-	}
205
-
206
-	/**
207
-	 * write remote share to the database
208
-	 *
209
-	 * @param $remote
210
-	 * @param $token
211
-	 * @param $password
212
-	 * @param $name
213
-	 * @param $owner
214
-	 * @param $user
215
-	 * @param $mountPoint
216
-	 * @param $hash
217
-	 * @param $accepted
218
-	 * @param $remoteId
219
-	 * @param $parent
220
-	 * @param $shareType
221
-	 * @return bool
222
-	 */
223
-	private function writeShareToDb($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType) {
224
-		$query = $this->connection->prepare('
51
+    public const STORAGE = '\OCA\Files_Sharing\External\Storage';
52
+
53
+    /**
54
+     * @var string
55
+     */
56
+    private $uid;
57
+
58
+    /**
59
+     * @var IDBConnection
60
+     */
61
+    private $connection;
62
+
63
+    /**
64
+     * @var \OC\Files\Mount\Manager
65
+     */
66
+    private $mountManager;
67
+
68
+    /**
69
+     * @var IStorageFactory
70
+     */
71
+    private $storageLoader;
72
+
73
+    /**
74
+     * @var IClientService
75
+     */
76
+    private $clientService;
77
+
78
+    /**
79
+     * @var IManager
80
+     */
81
+    private $notificationManager;
82
+
83
+    /**
84
+     * @var IDiscoveryService
85
+     */
86
+    private $discoveryService;
87
+
88
+    /** @var ICloudFederationProviderManager */
89
+    private $cloudFederationProviderManager;
90
+
91
+    /** @var ICloudFederationFactory */
92
+    private $cloudFederationFactory;
93
+
94
+    /** @var IGroupManager  */
95
+    private $groupManager;
96
+
97
+    /** @var IUserManager */
98
+    private $userManager;
99
+
100
+    /**
101
+     * @param IDBConnection $connection
102
+     * @param \OC\Files\Mount\Manager $mountManager
103
+     * @param IStorageFactory $storageLoader
104
+     * @param IClientService $clientService
105
+     * @param IManager $notificationManager
106
+     * @param IDiscoveryService $discoveryService
107
+     * @param ICloudFederationProviderManager $cloudFederationProviderManager
108
+     * @param ICloudFederationFactory $cloudFederationFactory
109
+     * @param IGroupManager $groupManager
110
+     * @param IUserManager $userManager
111
+     * @param string $uid
112
+     */
113
+    public function __construct(IDBConnection $connection,
114
+                                \OC\Files\Mount\Manager $mountManager,
115
+                                IStorageFactory $storageLoader,
116
+                                IClientService $clientService,
117
+                                IManager $notificationManager,
118
+                                IDiscoveryService $discoveryService,
119
+                                ICloudFederationProviderManager $cloudFederationProviderManager,
120
+                                ICloudFederationFactory $cloudFederationFactory,
121
+                                IGroupManager $groupManager,
122
+                                IUserManager $userManager,
123
+                                $uid) {
124
+        $this->connection = $connection;
125
+        $this->mountManager = $mountManager;
126
+        $this->storageLoader = $storageLoader;
127
+        $this->clientService = $clientService;
128
+        $this->uid = $uid;
129
+        $this->notificationManager = $notificationManager;
130
+        $this->discoveryService = $discoveryService;
131
+        $this->cloudFederationProviderManager = $cloudFederationProviderManager;
132
+        $this->cloudFederationFactory = $cloudFederationFactory;
133
+        $this->groupManager = $groupManager;
134
+        $this->userManager = $userManager;
135
+    }
136
+
137
+    /**
138
+     * add new server-to-server share
139
+     *
140
+     * @param string $remote
141
+     * @param string $token
142
+     * @param string $password
143
+     * @param string $name
144
+     * @param string $owner
145
+     * @param int $shareType
146
+     * @param boolean $accepted
147
+     * @param string $user
148
+     * @param int $remoteId
149
+     * @param int $parent
150
+     * @return Mount|null
151
+     * @throws \Doctrine\DBAL\DBALException
152
+     */
153
+    public function addShare($remote, $token, $password, $name, $owner, $shareType, $accepted=false, $user = null, $remoteId = -1, $parent = -1) {
154
+        $user = $user ? $user : $this->uid;
155
+        $accepted = $accepted ? IShare::STATUS_ACCEPTED : IShare::STATUS_PENDING;
156
+        $name = Filesystem::normalizePath('/' . $name);
157
+
158
+        if ($accepted !== IShare::STATUS_ACCEPTED) {
159
+            // To avoid conflicts with the mount point generation later,
160
+            // we only use a temporary mount point name here. The real
161
+            // mount point name will be generated when accepting the share,
162
+            // using the original share item name.
163
+            $tmpMountPointName = '{{TemporaryMountPointName#' . $name . '}}';
164
+            $mountPoint = $tmpMountPointName;
165
+            $hash = md5($tmpMountPointName);
166
+            $data = [
167
+                'remote'		=> $remote,
168
+                'share_token'	=> $token,
169
+                'password'		=> $password,
170
+                'name'			=> $name,
171
+                'owner'			=> $owner,
172
+                'user'			=> $user,
173
+                'mountpoint'	=> $mountPoint,
174
+                'mountpoint_hash'	=> $hash,
175
+                'accepted'		=> $accepted,
176
+                'remote_id'		=> $remoteId,
177
+                'share_type'    => $shareType,
178
+            ];
179
+
180
+            $i = 1;
181
+            while (!$this->connection->insertIfNotExist('*PREFIX*share_external', $data, ['user', 'mountpoint_hash'])) {
182
+                // The external share already exists for the user
183
+                $data['mountpoint'] = $tmpMountPointName . '-' . $i;
184
+                $data['mountpoint_hash'] = md5($data['mountpoint']);
185
+                $i++;
186
+            }
187
+            return null;
188
+        }
189
+
190
+        $mountPoint = Files::buildNotExistingFileName('/', $name);
191
+        $mountPoint = Filesystem::normalizePath('/' . $mountPoint);
192
+        $hash = md5($mountPoint);
193
+
194
+        $this->writeShareToDb($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType);
195
+
196
+        $options = [
197
+            'remote'	=> $remote,
198
+            'token'		=> $token,
199
+            'password'	=> $password,
200
+            'mountpoint'	=> $mountPoint,
201
+            'owner'		=> $owner
202
+        ];
203
+        return $this->mountShare($options);
204
+    }
205
+
206
+    /**
207
+     * write remote share to the database
208
+     *
209
+     * @param $remote
210
+     * @param $token
211
+     * @param $password
212
+     * @param $name
213
+     * @param $owner
214
+     * @param $user
215
+     * @param $mountPoint
216
+     * @param $hash
217
+     * @param $accepted
218
+     * @param $remoteId
219
+     * @param $parent
220
+     * @param $shareType
221
+     * @return bool
222
+     */
223
+    private function writeShareToDb($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType) {
224
+        $query = $this->connection->prepare('
225 225
 				INSERT INTO `*PREFIX*share_external`
226 226
 					(`remote`, `share_token`, `password`, `name`, `owner`, `user`, `mountpoint`, `mountpoint_hash`, `accepted`, `remote_id`, `parent`, `share_type`)
227 227
 				VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
228 228
 			');
229
-		return $query->execute([$remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType]);
230
-	}
231
-
232
-	/**
233
-	 * get share
234
-	 *
235
-	 * @param int $id share id
236
-	 * @return mixed share of false
237
-	 */
238
-	public function getShare($id) {
239
-		$getShare = $this->connection->prepare('
229
+        return $query->execute([$remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType]);
230
+    }
231
+
232
+    /**
233
+     * get share
234
+     *
235
+     * @param int $id share id
236
+     * @return mixed share of false
237
+     */
238
+    public function getShare($id) {
239
+        $getShare = $this->connection->prepare('
240 240
 			SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`, `parent`, `share_type`, `password`, `mountpoint_hash`
241 241
 			FROM  `*PREFIX*share_external`
242 242
 			WHERE `id` = ?');
243
-		$result = $getShare->execute([$id]);
244
-
245
-		$share = $result ? $getShare->fetch() : [];
246
-
247
-		$validShare = is_array($share) && isset($share['share_type']) && isset($share['user']);
248
-
249
-		// check if the user is allowed to access it
250
-		if ($validShare && (int)$share['share_type'] === IShare::TYPE_USER && $share['user'] === $this->uid) {
251
-			return $share;
252
-		} elseif ($validShare && (int)$share['share_type'] === IShare::TYPE_GROUP) {
253
-			$user = $this->userManager->get($this->uid);
254
-			if ($this->groupManager->get($share['user'])->inGroup($user)) {
255
-				return $share;
256
-			}
257
-		}
258
-
259
-		return false;
260
-	}
261
-
262
-	/**
263
-	 * accept server-to-server share
264
-	 *
265
-	 * @param int $id
266
-	 * @return bool True if the share could be accepted, false otherwise
267
-	 */
268
-	public function acceptShare($id) {
269
-		$share = $this->getShare($id);
270
-		$result = false;
271
-
272
-		if ($share) {
273
-			\OC_Util::setupFS($this->uid);
274
-			$shareFolder = Helper::getShareFolder();
275
-			$mountPoint = Files::buildNotExistingFileName($shareFolder, $share['name']);
276
-			$mountPoint = Filesystem::normalizePath($mountPoint);
277
-			$hash = md5($mountPoint);
278
-			$userShareAccepted = false;
279
-
280
-			if ((int)$share['share_type'] === IShare::TYPE_USER) {
281
-				$acceptShare = $this->connection->prepare('
243
+        $result = $getShare->execute([$id]);
244
+
245
+        $share = $result ? $getShare->fetch() : [];
246
+
247
+        $validShare = is_array($share) && isset($share['share_type']) && isset($share['user']);
248
+
249
+        // check if the user is allowed to access it
250
+        if ($validShare && (int)$share['share_type'] === IShare::TYPE_USER && $share['user'] === $this->uid) {
251
+            return $share;
252
+        } elseif ($validShare && (int)$share['share_type'] === IShare::TYPE_GROUP) {
253
+            $user = $this->userManager->get($this->uid);
254
+            if ($this->groupManager->get($share['user'])->inGroup($user)) {
255
+                return $share;
256
+            }
257
+        }
258
+
259
+        return false;
260
+    }
261
+
262
+    /**
263
+     * accept server-to-server share
264
+     *
265
+     * @param int $id
266
+     * @return bool True if the share could be accepted, false otherwise
267
+     */
268
+    public function acceptShare($id) {
269
+        $share = $this->getShare($id);
270
+        $result = false;
271
+
272
+        if ($share) {
273
+            \OC_Util::setupFS($this->uid);
274
+            $shareFolder = Helper::getShareFolder();
275
+            $mountPoint = Files::buildNotExistingFileName($shareFolder, $share['name']);
276
+            $mountPoint = Filesystem::normalizePath($mountPoint);
277
+            $hash = md5($mountPoint);
278
+            $userShareAccepted = false;
279
+
280
+            if ((int)$share['share_type'] === IShare::TYPE_USER) {
281
+                $acceptShare = $this->connection->prepare('
282 282
 				UPDATE `*PREFIX*share_external`
283 283
 				SET `accepted` = ?,
284 284
 					`mountpoint` = ?,
285 285
 					`mountpoint_hash` = ?
286 286
 				WHERE `id` = ? AND `user` = ?');
287
-				$userShareAccepted = $acceptShare->execute([1, $mountPoint, $hash, $id, $this->uid]);
288
-			} else {
289
-				$result = $this->writeShareToDb(
290
-					$share['remote'],
291
-					$share['share_token'],
292
-					$share['password'],
293
-					$share['name'],
294
-					$share['owner'],
295
-					$this->uid,
296
-					$mountPoint, $hash, 1,
297
-					$share['remote_id'],
298
-					$id,
299
-					$share['share_type']);
300
-			}
301
-			if ($userShareAccepted === true) {
302
-				$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'accept');
303
-				\OC_Hook::emit(Share::class, 'federated_share_added', ['server' => $share['remote']]);
304
-				$result = true;
305
-			}
306
-		}
307
-
308
-		// Make sure the user has no notification for something that does not exist anymore.
309
-		$this->processNotification($id);
310
-
311
-		return $result;
312
-	}
313
-
314
-	/**
315
-	 * decline server-to-server share
316
-	 *
317
-	 * @param int $id
318
-	 * @return bool True if the share could be declined, false otherwise
319
-	 */
320
-	public function declineShare($id) {
321
-		$share = $this->getShare($id);
322
-		$result = false;
323
-
324
-		if ($share && (int)$share['share_type'] === IShare::TYPE_USER) {
325
-			$removeShare = $this->connection->prepare('
287
+                $userShareAccepted = $acceptShare->execute([1, $mountPoint, $hash, $id, $this->uid]);
288
+            } else {
289
+                $result = $this->writeShareToDb(
290
+                    $share['remote'],
291
+                    $share['share_token'],
292
+                    $share['password'],
293
+                    $share['name'],
294
+                    $share['owner'],
295
+                    $this->uid,
296
+                    $mountPoint, $hash, 1,
297
+                    $share['remote_id'],
298
+                    $id,
299
+                    $share['share_type']);
300
+            }
301
+            if ($userShareAccepted === true) {
302
+                $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'accept');
303
+                \OC_Hook::emit(Share::class, 'federated_share_added', ['server' => $share['remote']]);
304
+                $result = true;
305
+            }
306
+        }
307
+
308
+        // Make sure the user has no notification for something that does not exist anymore.
309
+        $this->processNotification($id);
310
+
311
+        return $result;
312
+    }
313
+
314
+    /**
315
+     * decline server-to-server share
316
+     *
317
+     * @param int $id
318
+     * @return bool True if the share could be declined, false otherwise
319
+     */
320
+    public function declineShare($id) {
321
+        $share = $this->getShare($id);
322
+        $result = false;
323
+
324
+        if ($share && (int)$share['share_type'] === IShare::TYPE_USER) {
325
+            $removeShare = $this->connection->prepare('
326 326
 				DELETE FROM `*PREFIX*share_external` WHERE `id` = ? AND `user` = ?');
327
-			$removeShare->execute([$id, $this->uid]);
328
-			$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
329
-
330
-			$this->processNotification($id);
331
-			$result = true;
332
-		} elseif ($share && (int)$share['share_type'] === IShare::TYPE_GROUP) {
333
-			$result = $this->writeShareToDb(
334
-				$share['remote'],
335
-				$share['share_token'],
336
-				$share['password'],
337
-				$share['name'],
338
-				$share['owner'],
339
-				$this->uid,
340
-				$share['mountpoint'],
341
-				$share['mountpoint_hash'],
342
-				0,
343
-				$share['remote_id'],
344
-				$id,
345
-				$share['share_type']);
346
-			$this->processNotification($id);
347
-		}
348
-
349
-		return $result;
350
-	}
351
-
352
-	/**
353
-	 * @param int $remoteShare
354
-	 */
355
-	public function processNotification($remoteShare) {
356
-		$filter = $this->notificationManager->createNotification();
357
-		$filter->setApp('files_sharing')
358
-			->setUser($this->uid)
359
-			->setObject('remote_share', (int) $remoteShare);
360
-		$this->notificationManager->markProcessed($filter);
361
-	}
362
-
363
-	/**
364
-	 * inform remote server whether server-to-server share was accepted/declined
365
-	 *
366
-	 * @param string $remote
367
-	 * @param string $token
368
-	 * @param int $remoteId Share id on the remote host
369
-	 * @param string $feedback
370
-	 * @return boolean
371
-	 */
372
-	private function sendFeedbackToRemote($remote, $token, $remoteId, $feedback) {
373
-		$result = $this->tryOCMEndPoint($remote, $token, $remoteId, $feedback);
374
-
375
-		if ($result === true) {
376
-			return true;
377
-		}
378
-
379
-		$federationEndpoints = $this->discoveryService->discover($remote, 'FEDERATED_SHARING');
380
-		$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
381
-
382
-		$url = rtrim($remote, '/') . $endpoint . '/' . $remoteId . '/' . $feedback . '?format=' . Share::RESPONSE_FORMAT;
383
-		$fields = ['token' => $token];
384
-
385
-		$client = $this->clientService->newClient();
386
-
387
-		try {
388
-			$response = $client->post(
389
-				$url,
390
-				[
391
-					'body' => $fields,
392
-					'connect_timeout' => 10,
393
-				]
394
-			);
395
-		} catch (\Exception $e) {
396
-			return false;
397
-		}
398
-
399
-		$status = json_decode($response->getBody(), true);
400
-
401
-		return ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
402
-	}
403
-
404
-	/**
405
-	 * try send accept message to ocm end-point
406
-	 *
407
-	 * @param string $remoteDomain
408
-	 * @param string $token
409
-	 * @param $remoteId id of the share
410
-	 * @param string $feedback
411
-	 * @return bool
412
-	 */
413
-	protected function tryOCMEndPoint($remoteDomain, $token, $remoteId, $feedback) {
414
-		switch ($feedback) {
415
-			case 'accept':
416
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
417
-				$notification->setMessage(
418
-					'SHARE_ACCEPTED',
419
-					'file',
420
-					$remoteId,
421
-					[
422
-						'sharedSecret' => $token,
423
-						'message' => 'Recipient accept the share'
424
-					]
425
-
426
-				);
427
-				return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
428
-			case 'decline':
429
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
430
-				$notification->setMessage(
431
-					'SHARE_DECLINED',
432
-					'file',
433
-					$remoteId,
434
-					[
435
-						'sharedSecret' => $token,
436
-						'message' => 'Recipient declined the share'
437
-					]
438
-
439
-				);
440
-				return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
441
-		}
442
-
443
-		return false;
444
-	}
445
-
446
-
447
-	/**
448
-	 * remove '/user/files' from the path and trailing slashes
449
-	 *
450
-	 * @param string $path
451
-	 * @return string
452
-	 */
453
-	protected function stripPath($path) {
454
-		$prefix = '/' . $this->uid . '/files';
455
-		return rtrim(substr($path, strlen($prefix)), '/');
456
-	}
457
-
458
-	public function getMount($data) {
459
-		$data['manager'] = $this;
460
-		$mountPoint = '/' . $this->uid . '/files' . $data['mountpoint'];
461
-		$data['mountpoint'] = $mountPoint;
462
-		$data['certificateManager'] = \OC::$server->getCertificateManager($this->uid);
463
-		return new Mount(self::STORAGE, $mountPoint, $data, $this, $this->storageLoader);
464
-	}
465
-
466
-	/**
467
-	 * @param array $data
468
-	 * @return Mount
469
-	 */
470
-	protected function mountShare($data) {
471
-		$mount = $this->getMount($data);
472
-		$this->mountManager->addMount($mount);
473
-		return $mount;
474
-	}
475
-
476
-	/**
477
-	 * @return \OC\Files\Mount\Manager
478
-	 */
479
-	public function getMountManager() {
480
-		return $this->mountManager;
481
-	}
482
-
483
-	/**
484
-	 * @param string $source
485
-	 * @param string $target
486
-	 * @return bool
487
-	 */
488
-	public function setMountPoint($source, $target) {
489
-		$source = $this->stripPath($source);
490
-		$target = $this->stripPath($target);
491
-		$sourceHash = md5($source);
492
-		$targetHash = md5($target);
493
-
494
-		$query = $this->connection->prepare('
327
+            $removeShare->execute([$id, $this->uid]);
328
+            $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
329
+
330
+            $this->processNotification($id);
331
+            $result = true;
332
+        } elseif ($share && (int)$share['share_type'] === IShare::TYPE_GROUP) {
333
+            $result = $this->writeShareToDb(
334
+                $share['remote'],
335
+                $share['share_token'],
336
+                $share['password'],
337
+                $share['name'],
338
+                $share['owner'],
339
+                $this->uid,
340
+                $share['mountpoint'],
341
+                $share['mountpoint_hash'],
342
+                0,
343
+                $share['remote_id'],
344
+                $id,
345
+                $share['share_type']);
346
+            $this->processNotification($id);
347
+        }
348
+
349
+        return $result;
350
+    }
351
+
352
+    /**
353
+     * @param int $remoteShare
354
+     */
355
+    public function processNotification($remoteShare) {
356
+        $filter = $this->notificationManager->createNotification();
357
+        $filter->setApp('files_sharing')
358
+            ->setUser($this->uid)
359
+            ->setObject('remote_share', (int) $remoteShare);
360
+        $this->notificationManager->markProcessed($filter);
361
+    }
362
+
363
+    /**
364
+     * inform remote server whether server-to-server share was accepted/declined
365
+     *
366
+     * @param string $remote
367
+     * @param string $token
368
+     * @param int $remoteId Share id on the remote host
369
+     * @param string $feedback
370
+     * @return boolean
371
+     */
372
+    private function sendFeedbackToRemote($remote, $token, $remoteId, $feedback) {
373
+        $result = $this->tryOCMEndPoint($remote, $token, $remoteId, $feedback);
374
+
375
+        if ($result === true) {
376
+            return true;
377
+        }
378
+
379
+        $federationEndpoints = $this->discoveryService->discover($remote, 'FEDERATED_SHARING');
380
+        $endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
381
+
382
+        $url = rtrim($remote, '/') . $endpoint . '/' . $remoteId . '/' . $feedback . '?format=' . Share::RESPONSE_FORMAT;
383
+        $fields = ['token' => $token];
384
+
385
+        $client = $this->clientService->newClient();
386
+
387
+        try {
388
+            $response = $client->post(
389
+                $url,
390
+                [
391
+                    'body' => $fields,
392
+                    'connect_timeout' => 10,
393
+                ]
394
+            );
395
+        } catch (\Exception $e) {
396
+            return false;
397
+        }
398
+
399
+        $status = json_decode($response->getBody(), true);
400
+
401
+        return ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
402
+    }
403
+
404
+    /**
405
+     * try send accept message to ocm end-point
406
+     *
407
+     * @param string $remoteDomain
408
+     * @param string $token
409
+     * @param $remoteId id of the share
410
+     * @param string $feedback
411
+     * @return bool
412
+     */
413
+    protected function tryOCMEndPoint($remoteDomain, $token, $remoteId, $feedback) {
414
+        switch ($feedback) {
415
+            case 'accept':
416
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
417
+                $notification->setMessage(
418
+                    'SHARE_ACCEPTED',
419
+                    'file',
420
+                    $remoteId,
421
+                    [
422
+                        'sharedSecret' => $token,
423
+                        'message' => 'Recipient accept the share'
424
+                    ]
425
+
426
+                );
427
+                return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
428
+            case 'decline':
429
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
430
+                $notification->setMessage(
431
+                    'SHARE_DECLINED',
432
+                    'file',
433
+                    $remoteId,
434
+                    [
435
+                        'sharedSecret' => $token,
436
+                        'message' => 'Recipient declined the share'
437
+                    ]
438
+
439
+                );
440
+                return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
441
+        }
442
+
443
+        return false;
444
+    }
445
+
446
+
447
+    /**
448
+     * remove '/user/files' from the path and trailing slashes
449
+     *
450
+     * @param string $path
451
+     * @return string
452
+     */
453
+    protected function stripPath($path) {
454
+        $prefix = '/' . $this->uid . '/files';
455
+        return rtrim(substr($path, strlen($prefix)), '/');
456
+    }
457
+
458
+    public function getMount($data) {
459
+        $data['manager'] = $this;
460
+        $mountPoint = '/' . $this->uid . '/files' . $data['mountpoint'];
461
+        $data['mountpoint'] = $mountPoint;
462
+        $data['certificateManager'] = \OC::$server->getCertificateManager($this->uid);
463
+        return new Mount(self::STORAGE, $mountPoint, $data, $this, $this->storageLoader);
464
+    }
465
+
466
+    /**
467
+     * @param array $data
468
+     * @return Mount
469
+     */
470
+    protected function mountShare($data) {
471
+        $mount = $this->getMount($data);
472
+        $this->mountManager->addMount($mount);
473
+        return $mount;
474
+    }
475
+
476
+    /**
477
+     * @return \OC\Files\Mount\Manager
478
+     */
479
+    public function getMountManager() {
480
+        return $this->mountManager;
481
+    }
482
+
483
+    /**
484
+     * @param string $source
485
+     * @param string $target
486
+     * @return bool
487
+     */
488
+    public function setMountPoint($source, $target) {
489
+        $source = $this->stripPath($source);
490
+        $target = $this->stripPath($target);
491
+        $sourceHash = md5($source);
492
+        $targetHash = md5($target);
493
+
494
+        $query = $this->connection->prepare('
495 495
 			UPDATE `*PREFIX*share_external`
496 496
 			SET `mountpoint` = ?, `mountpoint_hash` = ?
497 497
 			WHERE `mountpoint_hash` = ?
498 498
 			AND `user` = ?
499 499
 		');
500
-		$result = (bool)$query->execute([$target, $targetHash, $sourceHash, $this->uid]);
500
+        $result = (bool)$query->execute([$target, $targetHash, $sourceHash, $this->uid]);
501 501
 
502
-		return $result;
503
-	}
502
+        return $result;
503
+    }
504 504
 
505
-	public function removeShare($mountPoint) {
506
-		$mountPointObj = $this->mountManager->find($mountPoint);
507
-		$id = $mountPointObj->getStorage()->getCache()->getId('');
505
+    public function removeShare($mountPoint) {
506
+        $mountPointObj = $this->mountManager->find($mountPoint);
507
+        $id = $mountPointObj->getStorage()->getCache()->getId('');
508 508
 
509
-		$mountPoint = $this->stripPath($mountPoint);
510
-		$hash = md5($mountPoint);
509
+        $mountPoint = $this->stripPath($mountPoint);
510
+        $hash = md5($mountPoint);
511 511
 
512
-		$getShare = $this->connection->prepare('
512
+        $getShare = $this->connection->prepare('
513 513
 			SELECT `remote`, `share_token`, `remote_id`, `share_type`, `id`
514 514
 			FROM  `*PREFIX*share_external`
515 515
 			WHERE `mountpoint_hash` = ? AND `user` = ?');
516
-		$result = $getShare->execute([$hash, $this->uid]);
517
-
518
-		$share = $getShare->fetch();
519
-		$getShare->closeCursor();
520
-		if ($result && $share !== false && (int)$share['share_type'] === IShare::TYPE_USER) {
521
-			try {
522
-				$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
523
-			} catch (\Throwable $e) {
524
-				// if we fail to notify the remote (probably cause the remote is down)
525
-				// we still want the share to be gone to prevent undeletable remotes
526
-			}
527
-
528
-			$query = $this->connection->prepare('
516
+        $result = $getShare->execute([$hash, $this->uid]);
517
+
518
+        $share = $getShare->fetch();
519
+        $getShare->closeCursor();
520
+        if ($result && $share !== false && (int)$share['share_type'] === IShare::TYPE_USER) {
521
+            try {
522
+                $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
523
+            } catch (\Throwable $e) {
524
+                // if we fail to notify the remote (probably cause the remote is down)
525
+                // we still want the share to be gone to prevent undeletable remotes
526
+            }
527
+
528
+            $query = $this->connection->prepare('
529 529
 			DELETE FROM `*PREFIX*share_external`
530 530
 			WHERE `id` = ?
531 531
 			');
532
-			$result = (bool)$query->execute([(int)$share['id']]);
533
-		} elseif ($result && (int)$share['share_type'] === IShare::TYPE_GROUP) {
534
-			$query = $this->connection->prepare('
532
+            $result = (bool)$query->execute([(int)$share['id']]);
533
+        } elseif ($result && (int)$share['share_type'] === IShare::TYPE_GROUP) {
534
+            $query = $this->connection->prepare('
535 535
 				UPDATE `*PREFIX*share_external`
536 536
 				SET `accepted` = ?
537 537
 				WHERE `id` = ?');
538
-			$result = (bool)$query->execute([0, (int)$share['id']]);
539
-		}
540
-
541
-		if ($result) {
542
-			$this->removeReShares($id);
543
-		}
544
-
545
-		return $result;
546
-	}
547
-
548
-	/**
549
-	 * remove re-shares from share table and mapping in the federated_reshares table
550
-	 *
551
-	 * @param $mountPointId
552
-	 */
553
-	protected function removeReShares($mountPointId) {
554
-		$selectQuery = $this->connection->getQueryBuilder();
555
-		$query = $this->connection->getQueryBuilder();
556
-		$selectQuery->select('id')->from('share')
557
-			->where($selectQuery->expr()->eq('file_source', $query->createNamedParameter($mountPointId)));
558
-		$select = $selectQuery->getSQL();
559
-
560
-
561
-		$query->delete('federated_reshares')
562
-			->where($query->expr()->in('share_id', $query->createFunction('(' . $select . ')')));
563
-		$query->execute();
564
-
565
-		$deleteReShares = $this->connection->getQueryBuilder();
566
-		$deleteReShares->delete('share')
567
-			->where($deleteReShares->expr()->eq('file_source', $deleteReShares->createNamedParameter($mountPointId)));
568
-		$deleteReShares->execute();
569
-	}
570
-
571
-	/**
572
-	 * remove all shares for user $uid if the user was deleted
573
-	 *
574
-	 * @param string $uid
575
-	 * @return bool
576
-	 */
577
-	public function removeUserShares($uid) {
578
-		$getShare = $this->connection->prepare('
538
+            $result = (bool)$query->execute([0, (int)$share['id']]);
539
+        }
540
+
541
+        if ($result) {
542
+            $this->removeReShares($id);
543
+        }
544
+
545
+        return $result;
546
+    }
547
+
548
+    /**
549
+     * remove re-shares from share table and mapping in the federated_reshares table
550
+     *
551
+     * @param $mountPointId
552
+     */
553
+    protected function removeReShares($mountPointId) {
554
+        $selectQuery = $this->connection->getQueryBuilder();
555
+        $query = $this->connection->getQueryBuilder();
556
+        $selectQuery->select('id')->from('share')
557
+            ->where($selectQuery->expr()->eq('file_source', $query->createNamedParameter($mountPointId)));
558
+        $select = $selectQuery->getSQL();
559
+
560
+
561
+        $query->delete('federated_reshares')
562
+            ->where($query->expr()->in('share_id', $query->createFunction('(' . $select . ')')));
563
+        $query->execute();
564
+
565
+        $deleteReShares = $this->connection->getQueryBuilder();
566
+        $deleteReShares->delete('share')
567
+            ->where($deleteReShares->expr()->eq('file_source', $deleteReShares->createNamedParameter($mountPointId)));
568
+        $deleteReShares->execute();
569
+    }
570
+
571
+    /**
572
+     * remove all shares for user $uid if the user was deleted
573
+     *
574
+     * @param string $uid
575
+     * @return bool
576
+     */
577
+    public function removeUserShares($uid) {
578
+        $getShare = $this->connection->prepare('
579 579
 			SELECT `remote`, `share_token`, `remote_id`
580 580
 			FROM  `*PREFIX*share_external`
581 581
 			WHERE `user` = ?');
582
-		$result = $getShare->execute([$uid]);
582
+        $result = $getShare->execute([$uid]);
583 583
 
584
-		if ($result) {
585
-			$shares = $getShare->fetchAll();
586
-			foreach ($shares as $share) {
587
-				$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
588
-			}
589
-		}
584
+        if ($result) {
585
+            $shares = $getShare->fetchAll();
586
+            foreach ($shares as $share) {
587
+                $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
588
+            }
589
+        }
590 590
 
591
-		$query = $this->connection->prepare('
591
+        $query = $this->connection->prepare('
592 592
 			DELETE FROM `*PREFIX*share_external`
593 593
 			WHERE `user` = ?
594 594
 		');
595
-		return (bool)$query->execute([$uid]);
596
-	}
597
-
598
-	/**
599
-	 * return a list of shares which are not yet accepted by the user
600
-	 *
601
-	 * @return array list of open server-to-server shares
602
-	 */
603
-	public function getOpenShares() {
604
-		return $this->getShares(false);
605
-	}
606
-
607
-	/**
608
-	 * return a list of shares which are accepted by the user
609
-	 *
610
-	 * @return array list of accepted server-to-server shares
611
-	 */
612
-	public function getAcceptedShares() {
613
-		return $this->getShares(true);
614
-	}
615
-
616
-	/**
617
-	 * return a list of shares for the user
618
-	 *
619
-	 * @param bool|null $accepted True for accepted only,
620
-	 *                            false for not accepted,
621
-	 *                            null for all shares of the user
622
-	 * @return array list of open server-to-server shares
623
-	 */
624
-	private function getShares($accepted) {
625
-		$user = $this->userManager->get($this->uid);
626
-		$groups = $this->groupManager->getUserGroups($user);
627
-		$userGroups = [];
628
-		foreach ($groups as $group) {
629
-			$userGroups[] = $group->getGID();
630
-		}
631
-
632
-		$query = 'SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`
595
+        return (bool)$query->execute([$uid]);
596
+    }
597
+
598
+    /**
599
+     * return a list of shares which are not yet accepted by the user
600
+     *
601
+     * @return array list of open server-to-server shares
602
+     */
603
+    public function getOpenShares() {
604
+        return $this->getShares(false);
605
+    }
606
+
607
+    /**
608
+     * return a list of shares which are accepted by the user
609
+     *
610
+     * @return array list of accepted server-to-server shares
611
+     */
612
+    public function getAcceptedShares() {
613
+        return $this->getShares(true);
614
+    }
615
+
616
+    /**
617
+     * return a list of shares for the user
618
+     *
619
+     * @param bool|null $accepted True for accepted only,
620
+     *                            false for not accepted,
621
+     *                            null for all shares of the user
622
+     * @return array list of open server-to-server shares
623
+     */
624
+    private function getShares($accepted) {
625
+        $user = $this->userManager->get($this->uid);
626
+        $groups = $this->groupManager->getUserGroups($user);
627
+        $userGroups = [];
628
+        foreach ($groups as $group) {
629
+            $userGroups[] = $group->getGID();
630
+        }
631
+
632
+        $query = 'SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`
633 633
 		          FROM `*PREFIX*share_external`
634 634
 				  WHERE (`user` = ? OR `user` IN (?))';
635
-		$parameters = [$this->uid, implode(',',$userGroups)];
636
-		if (!is_null($accepted)) {
637
-			$query .= ' AND `accepted` = ?';
638
-			$parameters[] = (int) $accepted;
639
-		}
640
-		$query .= ' ORDER BY `id` ASC';
641
-
642
-		$shares = $this->connection->prepare($query);
643
-		$result = $shares->execute($parameters);
644
-
645
-		return $result ? $shares->fetchAll() : [];
646
-	}
635
+        $parameters = [$this->uid, implode(',',$userGroups)];
636
+        if (!is_null($accepted)) {
637
+            $query .= ' AND `accepted` = ?';
638
+            $parameters[] = (int) $accepted;
639
+        }
640
+        $query .= ' ORDER BY `id` ASC';
641
+
642
+        $shares = $this->connection->prepare($query);
643
+        $result = $shares->execute($parameters);
644
+
645
+        return $result ? $shares->fetchAll() : [];
646
+    }
647 647
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/Updater.php 1 patch
Indentation   +65 added lines, -65 removed lines patch added patch discarded remove patch
@@ -31,80 +31,80 @@
 block discarded – undo
31 31
 
32 32
 class Updater {
33 33
 
34
-	/**
35
-	 * @param array $params
36
-	 */
37
-	public static function renameHook($params) {
38
-		self::renameChildren($params['oldpath'], $params['newpath']);
39
-		self::moveShareToShare($params['newpath']);
40
-	}
34
+    /**
35
+     * @param array $params
36
+     */
37
+    public static function renameHook($params) {
38
+        self::renameChildren($params['oldpath'], $params['newpath']);
39
+        self::moveShareToShare($params['newpath']);
40
+    }
41 41
 
42
-	/**
43
-	 * Fix for https://github.com/owncloud/core/issues/20769
44
-	 *
45
-	 * The owner is allowed to move their files (if they are shared) into a receiving folder
46
-	 * In this case we need to update the parent of the moved share. Since they are
47
-	 * effectively handing over ownership of the file the rest of the code needs to know
48
-	 * they need to build up the reshare tree.
49
-	 *
50
-	 * @param string $path
51
-	 */
52
-	private static function moveShareToShare($path) {
53
-		$userFolder = \OC::$server->getUserFolder();
42
+    /**
43
+     * Fix for https://github.com/owncloud/core/issues/20769
44
+     *
45
+     * The owner is allowed to move their files (if they are shared) into a receiving folder
46
+     * In this case we need to update the parent of the moved share. Since they are
47
+     * effectively handing over ownership of the file the rest of the code needs to know
48
+     * they need to build up the reshare tree.
49
+     *
50
+     * @param string $path
51
+     */
52
+    private static function moveShareToShare($path) {
53
+        $userFolder = \OC::$server->getUserFolder();
54 54
 
55
-		// If the user folder can't be constructed (e.g. link share) just return.
56
-		if ($userFolder === null) {
57
-			return;
58
-		}
55
+        // If the user folder can't be constructed (e.g. link share) just return.
56
+        if ($userFolder === null) {
57
+            return;
58
+        }
59 59
 
60
-		$src = $userFolder->get($path);
60
+        $src = $userFolder->get($path);
61 61
 
62
-		$shareManager = \OC::$server->getShareManager();
62
+        $shareManager = \OC::$server->getShareManager();
63 63
 
64
-		$shares = $shareManager->getSharesBy($userFolder->getOwner()->getUID(), IShare::TYPE_USER, $src, false, -1);
65
-		$shares = array_merge($shares, $shareManager->getSharesBy($userFolder->getOwner()->getUID(), IShare::TYPE_GROUP, $src, false, -1));
66
-		$shares = array_merge($shares, $shareManager->getSharesBy($userFolder->getOwner()->getUID(), IShare::TYPE_ROOM, $src, false, -1));
64
+        $shares = $shareManager->getSharesBy($userFolder->getOwner()->getUID(), IShare::TYPE_USER, $src, false, -1);
65
+        $shares = array_merge($shares, $shareManager->getSharesBy($userFolder->getOwner()->getUID(), IShare::TYPE_GROUP, $src, false, -1));
66
+        $shares = array_merge($shares, $shareManager->getSharesBy($userFolder->getOwner()->getUID(), IShare::TYPE_ROOM, $src, false, -1));
67 67
 
68
-		// If the path we move is not a share we don't care
69
-		if (empty($shares)) {
70
-			return;
71
-		}
68
+        // If the path we move is not a share we don't care
69
+        if (empty($shares)) {
70
+            return;
71
+        }
72 72
 
73
-		// Check if the destination is inside a share
74
-		$mountManager = \OC::$server->getMountManager();
75
-		$dstMount = $mountManager->find($src->getPath());
76
-		if (!($dstMount instanceof \OCA\Files_Sharing\SharedMount)) {
77
-			return;
78
-		}
73
+        // Check if the destination is inside a share
74
+        $mountManager = \OC::$server->getMountManager();
75
+        $dstMount = $mountManager->find($src->getPath());
76
+        if (!($dstMount instanceof \OCA\Files_Sharing\SharedMount)) {
77
+            return;
78
+        }
79 79
 
80
-		$newOwner = $dstMount->getShare()->getShareOwner();
80
+        $newOwner = $dstMount->getShare()->getShareOwner();
81 81
 
82
-		//Ownership is moved over
83
-		foreach ($shares as $share) {
84
-			/** @var IShare $share */
85
-			$share->setShareOwner($newOwner);
86
-			$shareManager->updateShare($share);
87
-		}
88
-	}
82
+        //Ownership is moved over
83
+        foreach ($shares as $share) {
84
+            /** @var IShare $share */
85
+            $share->setShareOwner($newOwner);
86
+            $shareManager->updateShare($share);
87
+        }
88
+    }
89 89
 
90
-	/**
91
-	 * rename mount point from the children if the parent was renamed
92
-	 *
93
-	 * @param string $oldPath old path relative to data/user/files
94
-	 * @param string $newPath new path relative to data/user/files
95
-	 */
96
-	private static function renameChildren($oldPath, $newPath) {
97
-		$absNewPath =  \OC\Files\Filesystem::normalizePath('/' . \OCP\User::getUser() . '/files/' . $newPath);
98
-		$absOldPath =  \OC\Files\Filesystem::normalizePath('/' . \OCP\User::getUser() . '/files/' . $oldPath);
90
+    /**
91
+     * rename mount point from the children if the parent was renamed
92
+     *
93
+     * @param string $oldPath old path relative to data/user/files
94
+     * @param string $newPath new path relative to data/user/files
95
+     */
96
+    private static function renameChildren($oldPath, $newPath) {
97
+        $absNewPath =  \OC\Files\Filesystem::normalizePath('/' . \OCP\User::getUser() . '/files/' . $newPath);
98
+        $absOldPath =  \OC\Files\Filesystem::normalizePath('/' . \OCP\User::getUser() . '/files/' . $oldPath);
99 99
 
100
-		$mountManager = \OC\Files\Filesystem::getMountManager();
101
-		$mountedShares = $mountManager->findIn('/' . \OCP\User::getUser() . '/files/' . $oldPath);
102
-		foreach ($mountedShares as $mount) {
103
-			if ($mount->getStorage()->instanceOfStorage(ISharedStorage::class)) {
104
-				$mountPoint = $mount->getMountPoint();
105
-				$target = str_replace($absOldPath, $absNewPath, $mountPoint);
106
-				$mount->moveMount($target);
107
-			}
108
-		}
109
-	}
100
+        $mountManager = \OC\Files\Filesystem::getMountManager();
101
+        $mountedShares = $mountManager->findIn('/' . \OCP\User::getUser() . '/files/' . $oldPath);
102
+        foreach ($mountedShares as $mount) {
103
+            if ($mount->getStorage()->instanceOfStorage(ISharedStorage::class)) {
104
+                $mountPoint = $mount->getMountPoint();
105
+                $target = str_replace($absOldPath, $absNewPath, $mountPoint);
106
+                $mount->moveMount($target);
107
+            }
108
+        }
109
+    }
110 110
 }
Please login to merge, or discard this patch.