Completed
Pull Request — master (#3869)
by Jan-Christoph
22:08
created
lib/private/Accounts/AccountManager.php 1 patch
Indentation   +283 added lines, -283 removed lines patch added patch discarded remove patch
@@ -39,288 +39,288 @@
 block discarded – undo
39 39
  */
40 40
 class AccountManager {
41 41
 
42
-	/** nobody can see my account details */
43
-	const VISIBILITY_PRIVATE = 'private';
44
-	/** only contacts, especially trusted servers can see my contact details */
45
-	const VISIBILITY_CONTACTS_ONLY = 'contacts';
46
-	/** every body ca see my contact detail, will be published to the lookup server */
47
-	const VISIBILITY_PUBLIC = 'public';
48
-
49
-	const PROPERTY_AVATAR = 'avatar';
50
-	const PROPERTY_DISPLAYNAME = 'displayname';
51
-	const PROPERTY_PHONE = 'phone';
52
-	const PROPERTY_EMAIL = 'email';
53
-	const PROPERTY_WEBSITE = 'website';
54
-	const PROPERTY_ADDRESS = 'address';
55
-	const PROPERTY_TWITTER = 'twitter';
56
-
57
-	const NOT_VERIFIED = '0';
58
-	const VERIFICATION_IN_PROGRESS = '1';
59
-	const VERIFIED = '2';
60
-
61
-	/** @var  IDBConnection database connection */
62
-	private $connection;
63
-
64
-	/** @var string table name */
65
-	private $table = 'accounts';
66
-
67
-	/** @var EventDispatcherInterface */
68
-	private $eventDispatcher;
69
-
70
-	/** @var IJobList */
71
-	private $jobList;
72
-
73
-	/**
74
-	 * AccountManager constructor.
75
-	 *
76
-	 * @param IDBConnection $connection
77
-	 * @param EventDispatcherInterface $eventDispatcher
78
-	 * @param IJobList $jobList
79
-	 */
80
-	public function __construct(IDBConnection $connection,
81
-								EventDispatcherInterface $eventDispatcher,
82
-								IJobList $jobList) {
83
-		$this->connection = $connection;
84
-		$this->eventDispatcher = $eventDispatcher;
85
-		$this->jobList = $jobList;
86
-	}
87
-
88
-	/**
89
-	 * update user record
90
-	 *
91
-	 * @param IUser $user
92
-	 * @param $data
93
-	 */
94
-	public function updateUser(IUser $user, $data) {
95
-		$userData = $this->getUser($user);
96
-		$updated = true;
97
-		if (empty($userData)) {
98
-			$this->insertNewUser($user, $data);
99
-		} elseif ($userData !== $data) {
100
-			$this->checkEmailVerification($userData, $data, $user);
101
-			$data = $this->updateVerifyStatus($userData, $data);
102
-			$this->updateExistingUser($user, $data);
103
-		} else {
104
-			// nothing needs to be done if new and old data set are the same
105
-			$updated = false;
106
-		}
107
-
108
-		if ($updated) {
109
-			$this->eventDispatcher->dispatch(
110
-				'OC\AccountManager::userUpdated',
111
-				new GenericEvent($user, $data)
112
-			);
113
-		}
114
-	}
115
-
116
-	/**
117
-	 * get stored data from a given user
118
-	 *
119
-	 * @param IUser $user
120
-	 * @return array
121
-	 */
122
-	public function getUser(IUser $user) {
123
-		$uid = $user->getUID();
124
-		$query = $this->connection->getQueryBuilder();
125
-		$query->select('data')->from($this->table)
126
-			->where($query->expr()->eq('uid', $query->createParameter('uid')))
127
-			->setParameter('uid', $uid);
128
-		$query->execute();
129
-		$result = $query->execute()->fetchAll();
130
-
131
-		if (empty($result)) {
132
-			$userData = $this->buildDefaultUserRecord($user);
133
-			$this->insertNewUser($user, $userData);
134
-			return $userData;
135
-		}
136
-
137
-		$userDataArray = json_decode($result[0]['data'], true);
138
-
139
-		$userDataArray = $this->addMissingDefaultValues($userDataArray);
140
-
141
-		return $userDataArray;
142
-	}
143
-
144
-	/**
145
-	 * check if we need to ask the server for email verification, if yes we create a cronjob
146
-	 *
147
-	 * @param $oldData
148
-	 * @param $newData
149
-	 * @param IUser $user
150
-	 */
151
-	protected function checkEmailVerification($oldData, $newData, IUser $user) {
152
-		if ($oldData[self::PROPERTY_EMAIL]['value'] !== $newData[self::PROPERTY_EMAIL]['value']) {
153
-			$this->jobList->add('OC\Settings\BackgroundJobs\VerifyUserData',
154
-				[
155
-					'verificationCode' => '',
156
-					'data' => $newData[self::PROPERTY_EMAIL]['value'],
157
-					'type' => self::PROPERTY_EMAIL,
158
-					'uid' => $user->getUID(),
159
-					'try' => 0,
160
-					'lastRun' => time()
161
-				]
162
-			);
163
-		}
164
-	}
165
-
166
-	/**
167
-	 * make sure that all expected data are set
168
-	 *
169
-	 * @param array $userData
170
-	 * @return array
171
-	 */
172
-	protected function addMissingDefaultValues(array $userData) {
173
-
174
-		foreach ($userData as $key => $value) {
175
-			if (!isset($userData[$key]['verified'])) {
176
-				$userData[$key]['verified'] = self::NOT_VERIFIED;
177
-			}
178
-		}
179
-
180
-		return $userData;
181
-	}
182
-
183
-	/**
184
-	 * reset verification status if personal data changed
185
-	 *
186
-	 * @param array $oldData
187
-	 * @param array $newData
188
-	 * @return array
189
-	 */
190
-	protected function updateVerifyStatus($oldData, $newData) {
191
-
192
-		// which account was already verified successfully?
193
-		$twitterVerified = isset($oldData[self::PROPERTY_TWITTER]['verified']) && $oldData[self::PROPERTY_TWITTER]['verified'] === self::VERIFIED;
194
-		$websiteVerified = isset($oldData[self::PROPERTY_WEBSITE]['verified']) && $oldData[self::PROPERTY_WEBSITE]['verified'] === self::VERIFIED;
195
-		$emailVerified = isset($oldData[self::PROPERTY_EMAIL]['verified']) && $oldData[self::PROPERTY_EMAIL]['verified'] === self::VERIFIED;
196
-
197
-		// keep old verification status if we don't have a new one
198
-		if(!isset($newData[self::PROPERTY_TWITTER]['verified'])) {
199
-			// keep old verification status if value didn't changed and an old value exists
200
-			$keepOldStatus = $newData[self::PROPERTY_TWITTER]['value'] === $oldData[self::PROPERTY_TWITTER]['value'] && isset($oldData[self::PROPERTY_TWITTER]['verified']);
201
-			$newData[self::PROPERTY_TWITTER]['verified'] = $keepOldStatus ? $oldData[self::PROPERTY_TWITTER]['verified'] : self::NOT_VERIFIED;
202
-		}
203
-
204
-		if(!isset($newData[self::PROPERTY_WEBSITE]['verified'])) {
205
-			// keep old verification status if value didn't changed and an old value exists
206
-			$keepOldStatus = $newData[self::PROPERTY_WEBSITE]['value'] === $oldData[self::PROPERTY_WEBSITE]['value'] && isset($oldData[self::PROPERTY_WEBSITE]['verified']);
207
-			$newData[self::PROPERTY_WEBSITE]['verified'] = $keepOldStatus ? $oldData[self::PROPERTY_WEBSITE]['verified'] : self::NOT_VERIFIED;
208
-		}
209
-
210
-		if(!isset($newData[self::PROPERTY_EMAIL]['verified'])) {
211
-			// keep old verification status if value didn't changed and an old value exists
212
-			$keepOldStatus = $newData[self::PROPERTY_EMAIL]['value'] === $oldData[self::PROPERTY_EMAIL]['value'] && isset($oldData[self::PROPERTY_EMAIL]['verified']);
213
-			$newData[self::PROPERTY_EMAIL]['verified'] = $keepOldStatus ? $oldData[self::PROPERTY_EMAIL]['verified'] : self::VERIFICATION_IN_PROGRESS;
214
-		}
215
-
216
-		// reset verification status if a value from a previously verified data was changed
217
-		if($twitterVerified &&
218
-			$oldData[self::PROPERTY_TWITTER]['value'] !== $newData[self::PROPERTY_TWITTER]['value']
219
-		) {
220
-			$newData[self::PROPERTY_TWITTER]['verified'] = self::NOT_VERIFIED;
221
-		}
222
-
223
-		if($websiteVerified &&
224
-			$oldData[self::PROPERTY_WEBSITE]['value'] !== $newData[self::PROPERTY_WEBSITE]['value']
225
-		) {
226
-			$newData[self::PROPERTY_WEBSITE]['verified'] = self::NOT_VERIFIED;
227
-		}
228
-
229
-		if($emailVerified &&
230
-			$oldData[self::PROPERTY_EMAIL]['value'] !== $newData[self::PROPERTY_EMAIL]['value']
231
-		) {
232
-			$newData[self::PROPERTY_EMAIL]['verified'] = self::NOT_VERIFIED;
233
-		}
234
-
235
-		return $newData;
236
-
237
-	}
238
-
239
-	/**
240
-	 * add new user to accounts table
241
-	 *
242
-	 * @param IUser $user
243
-	 * @param array $data
244
-	 */
245
-	protected function insertNewUser(IUser $user, $data) {
246
-		$uid = $user->getUID();
247
-		$jsonEncodedData = json_encode($data);
248
-		$query = $this->connection->getQueryBuilder();
249
-		$query->insert($this->table)
250
-			->values(
251
-				[
252
-					'uid' => $query->createNamedParameter($uid),
253
-					'data' => $query->createNamedParameter($jsonEncodedData),
254
-				]
255
-			)
256
-			->execute();
257
-	}
258
-
259
-	/**
260
-	 * update existing user in accounts table
261
-	 *
262
-	 * @param IUser $user
263
-	 * @param array $data
264
-	 */
265
-	protected function updateExistingUser(IUser $user, $data) {
266
-		$uid = $user->getUID();
267
-		$jsonEncodedData = json_encode($data);
268
-		$query = $this->connection->getQueryBuilder();
269
-		$query->update($this->table)
270
-			->set('data', $query->createNamedParameter($jsonEncodedData))
271
-			->where($query->expr()->eq('uid', $query->createNamedParameter($uid)))
272
-			->execute();
273
-	}
274
-
275
-	/**
276
-	 * build default user record in case not data set exists yet
277
-	 *
278
-	 * @param IUser $user
279
-	 * @return array
280
-	 */
281
-	protected function buildDefaultUserRecord(IUser $user) {
282
-		return [
283
-			self::PROPERTY_DISPLAYNAME =>
284
-				[
285
-					'value' => $user->getDisplayName(),
286
-					'scope' => self::VISIBILITY_CONTACTS_ONLY,
287
-					'verified' => self::NOT_VERIFIED,
288
-				],
289
-			self::PROPERTY_ADDRESS =>
290
-				[
291
-					'value' => '',
292
-					'scope' => self::VISIBILITY_PRIVATE,
293
-					'verified' => self::NOT_VERIFIED,
294
-				],
295
-			self::PROPERTY_WEBSITE =>
296
-				[
297
-					'value' => '',
298
-					'scope' => self::VISIBILITY_PRIVATE,
299
-					'verified' => self::NOT_VERIFIED,
300
-				],
301
-			self::PROPERTY_EMAIL =>
302
-				[
303
-					'value' => $user->getEMailAddress(),
304
-					'scope' => self::VISIBILITY_CONTACTS_ONLY,
305
-					'verified' => self::NOT_VERIFIED,
306
-				],
307
-			self::PROPERTY_AVATAR =>
308
-				[
309
-					'scope' => self::VISIBILITY_CONTACTS_ONLY
310
-				],
311
-			self::PROPERTY_PHONE =>
312
-				[
313
-					'value' => '',
314
-					'scope' => self::VISIBILITY_PRIVATE,
315
-					'verified' => self::NOT_VERIFIED,
316
-				],
317
-			self::PROPERTY_TWITTER =>
318
-				[
319
-					'value' => '',
320
-					'scope' => self::VISIBILITY_PRIVATE,
321
-					'verified' => self::NOT_VERIFIED,
322
-				],
323
-		];
324
-	}
42
+    /** nobody can see my account details */
43
+    const VISIBILITY_PRIVATE = 'private';
44
+    /** only contacts, especially trusted servers can see my contact details */
45
+    const VISIBILITY_CONTACTS_ONLY = 'contacts';
46
+    /** every body ca see my contact detail, will be published to the lookup server */
47
+    const VISIBILITY_PUBLIC = 'public';
48
+
49
+    const PROPERTY_AVATAR = 'avatar';
50
+    const PROPERTY_DISPLAYNAME = 'displayname';
51
+    const PROPERTY_PHONE = 'phone';
52
+    const PROPERTY_EMAIL = 'email';
53
+    const PROPERTY_WEBSITE = 'website';
54
+    const PROPERTY_ADDRESS = 'address';
55
+    const PROPERTY_TWITTER = 'twitter';
56
+
57
+    const NOT_VERIFIED = '0';
58
+    const VERIFICATION_IN_PROGRESS = '1';
59
+    const VERIFIED = '2';
60
+
61
+    /** @var  IDBConnection database connection */
62
+    private $connection;
63
+
64
+    /** @var string table name */
65
+    private $table = 'accounts';
66
+
67
+    /** @var EventDispatcherInterface */
68
+    private $eventDispatcher;
69
+
70
+    /** @var IJobList */
71
+    private $jobList;
72
+
73
+    /**
74
+     * AccountManager constructor.
75
+     *
76
+     * @param IDBConnection $connection
77
+     * @param EventDispatcherInterface $eventDispatcher
78
+     * @param IJobList $jobList
79
+     */
80
+    public function __construct(IDBConnection $connection,
81
+                                EventDispatcherInterface $eventDispatcher,
82
+                                IJobList $jobList) {
83
+        $this->connection = $connection;
84
+        $this->eventDispatcher = $eventDispatcher;
85
+        $this->jobList = $jobList;
86
+    }
87
+
88
+    /**
89
+     * update user record
90
+     *
91
+     * @param IUser $user
92
+     * @param $data
93
+     */
94
+    public function updateUser(IUser $user, $data) {
95
+        $userData = $this->getUser($user);
96
+        $updated = true;
97
+        if (empty($userData)) {
98
+            $this->insertNewUser($user, $data);
99
+        } elseif ($userData !== $data) {
100
+            $this->checkEmailVerification($userData, $data, $user);
101
+            $data = $this->updateVerifyStatus($userData, $data);
102
+            $this->updateExistingUser($user, $data);
103
+        } else {
104
+            // nothing needs to be done if new and old data set are the same
105
+            $updated = false;
106
+        }
107
+
108
+        if ($updated) {
109
+            $this->eventDispatcher->dispatch(
110
+                'OC\AccountManager::userUpdated',
111
+                new GenericEvent($user, $data)
112
+            );
113
+        }
114
+    }
115
+
116
+    /**
117
+     * get stored data from a given user
118
+     *
119
+     * @param IUser $user
120
+     * @return array
121
+     */
122
+    public function getUser(IUser $user) {
123
+        $uid = $user->getUID();
124
+        $query = $this->connection->getQueryBuilder();
125
+        $query->select('data')->from($this->table)
126
+            ->where($query->expr()->eq('uid', $query->createParameter('uid')))
127
+            ->setParameter('uid', $uid);
128
+        $query->execute();
129
+        $result = $query->execute()->fetchAll();
130
+
131
+        if (empty($result)) {
132
+            $userData = $this->buildDefaultUserRecord($user);
133
+            $this->insertNewUser($user, $userData);
134
+            return $userData;
135
+        }
136
+
137
+        $userDataArray = json_decode($result[0]['data'], true);
138
+
139
+        $userDataArray = $this->addMissingDefaultValues($userDataArray);
140
+
141
+        return $userDataArray;
142
+    }
143
+
144
+    /**
145
+     * check if we need to ask the server for email verification, if yes we create a cronjob
146
+     *
147
+     * @param $oldData
148
+     * @param $newData
149
+     * @param IUser $user
150
+     */
151
+    protected function checkEmailVerification($oldData, $newData, IUser $user) {
152
+        if ($oldData[self::PROPERTY_EMAIL]['value'] !== $newData[self::PROPERTY_EMAIL]['value']) {
153
+            $this->jobList->add('OC\Settings\BackgroundJobs\VerifyUserData',
154
+                [
155
+                    'verificationCode' => '',
156
+                    'data' => $newData[self::PROPERTY_EMAIL]['value'],
157
+                    'type' => self::PROPERTY_EMAIL,
158
+                    'uid' => $user->getUID(),
159
+                    'try' => 0,
160
+                    'lastRun' => time()
161
+                ]
162
+            );
163
+        }
164
+    }
165
+
166
+    /**
167
+     * make sure that all expected data are set
168
+     *
169
+     * @param array $userData
170
+     * @return array
171
+     */
172
+    protected function addMissingDefaultValues(array $userData) {
173
+
174
+        foreach ($userData as $key => $value) {
175
+            if (!isset($userData[$key]['verified'])) {
176
+                $userData[$key]['verified'] = self::NOT_VERIFIED;
177
+            }
178
+        }
179
+
180
+        return $userData;
181
+    }
182
+
183
+    /**
184
+     * reset verification status if personal data changed
185
+     *
186
+     * @param array $oldData
187
+     * @param array $newData
188
+     * @return array
189
+     */
190
+    protected function updateVerifyStatus($oldData, $newData) {
191
+
192
+        // which account was already verified successfully?
193
+        $twitterVerified = isset($oldData[self::PROPERTY_TWITTER]['verified']) && $oldData[self::PROPERTY_TWITTER]['verified'] === self::VERIFIED;
194
+        $websiteVerified = isset($oldData[self::PROPERTY_WEBSITE]['verified']) && $oldData[self::PROPERTY_WEBSITE]['verified'] === self::VERIFIED;
195
+        $emailVerified = isset($oldData[self::PROPERTY_EMAIL]['verified']) && $oldData[self::PROPERTY_EMAIL]['verified'] === self::VERIFIED;
196
+
197
+        // keep old verification status if we don't have a new one
198
+        if(!isset($newData[self::PROPERTY_TWITTER]['verified'])) {
199
+            // keep old verification status if value didn't changed and an old value exists
200
+            $keepOldStatus = $newData[self::PROPERTY_TWITTER]['value'] === $oldData[self::PROPERTY_TWITTER]['value'] && isset($oldData[self::PROPERTY_TWITTER]['verified']);
201
+            $newData[self::PROPERTY_TWITTER]['verified'] = $keepOldStatus ? $oldData[self::PROPERTY_TWITTER]['verified'] : self::NOT_VERIFIED;
202
+        }
203
+
204
+        if(!isset($newData[self::PROPERTY_WEBSITE]['verified'])) {
205
+            // keep old verification status if value didn't changed and an old value exists
206
+            $keepOldStatus = $newData[self::PROPERTY_WEBSITE]['value'] === $oldData[self::PROPERTY_WEBSITE]['value'] && isset($oldData[self::PROPERTY_WEBSITE]['verified']);
207
+            $newData[self::PROPERTY_WEBSITE]['verified'] = $keepOldStatus ? $oldData[self::PROPERTY_WEBSITE]['verified'] : self::NOT_VERIFIED;
208
+        }
209
+
210
+        if(!isset($newData[self::PROPERTY_EMAIL]['verified'])) {
211
+            // keep old verification status if value didn't changed and an old value exists
212
+            $keepOldStatus = $newData[self::PROPERTY_EMAIL]['value'] === $oldData[self::PROPERTY_EMAIL]['value'] && isset($oldData[self::PROPERTY_EMAIL]['verified']);
213
+            $newData[self::PROPERTY_EMAIL]['verified'] = $keepOldStatus ? $oldData[self::PROPERTY_EMAIL]['verified'] : self::VERIFICATION_IN_PROGRESS;
214
+        }
215
+
216
+        // reset verification status if a value from a previously verified data was changed
217
+        if($twitterVerified &&
218
+            $oldData[self::PROPERTY_TWITTER]['value'] !== $newData[self::PROPERTY_TWITTER]['value']
219
+        ) {
220
+            $newData[self::PROPERTY_TWITTER]['verified'] = self::NOT_VERIFIED;
221
+        }
222
+
223
+        if($websiteVerified &&
224
+            $oldData[self::PROPERTY_WEBSITE]['value'] !== $newData[self::PROPERTY_WEBSITE]['value']
225
+        ) {
226
+            $newData[self::PROPERTY_WEBSITE]['verified'] = self::NOT_VERIFIED;
227
+        }
228
+
229
+        if($emailVerified &&
230
+            $oldData[self::PROPERTY_EMAIL]['value'] !== $newData[self::PROPERTY_EMAIL]['value']
231
+        ) {
232
+            $newData[self::PROPERTY_EMAIL]['verified'] = self::NOT_VERIFIED;
233
+        }
234
+
235
+        return $newData;
236
+
237
+    }
238
+
239
+    /**
240
+     * add new user to accounts table
241
+     *
242
+     * @param IUser $user
243
+     * @param array $data
244
+     */
245
+    protected function insertNewUser(IUser $user, $data) {
246
+        $uid = $user->getUID();
247
+        $jsonEncodedData = json_encode($data);
248
+        $query = $this->connection->getQueryBuilder();
249
+        $query->insert($this->table)
250
+            ->values(
251
+                [
252
+                    'uid' => $query->createNamedParameter($uid),
253
+                    'data' => $query->createNamedParameter($jsonEncodedData),
254
+                ]
255
+            )
256
+            ->execute();
257
+    }
258
+
259
+    /**
260
+     * update existing user in accounts table
261
+     *
262
+     * @param IUser $user
263
+     * @param array $data
264
+     */
265
+    protected function updateExistingUser(IUser $user, $data) {
266
+        $uid = $user->getUID();
267
+        $jsonEncodedData = json_encode($data);
268
+        $query = $this->connection->getQueryBuilder();
269
+        $query->update($this->table)
270
+            ->set('data', $query->createNamedParameter($jsonEncodedData))
271
+            ->where($query->expr()->eq('uid', $query->createNamedParameter($uid)))
272
+            ->execute();
273
+    }
274
+
275
+    /**
276
+     * build default user record in case not data set exists yet
277
+     *
278
+     * @param IUser $user
279
+     * @return array
280
+     */
281
+    protected function buildDefaultUserRecord(IUser $user) {
282
+        return [
283
+            self::PROPERTY_DISPLAYNAME =>
284
+                [
285
+                    'value' => $user->getDisplayName(),
286
+                    'scope' => self::VISIBILITY_CONTACTS_ONLY,
287
+                    'verified' => self::NOT_VERIFIED,
288
+                ],
289
+            self::PROPERTY_ADDRESS =>
290
+                [
291
+                    'value' => '',
292
+                    'scope' => self::VISIBILITY_PRIVATE,
293
+                    'verified' => self::NOT_VERIFIED,
294
+                ],
295
+            self::PROPERTY_WEBSITE =>
296
+                [
297
+                    'value' => '',
298
+                    'scope' => self::VISIBILITY_PRIVATE,
299
+                    'verified' => self::NOT_VERIFIED,
300
+                ],
301
+            self::PROPERTY_EMAIL =>
302
+                [
303
+                    'value' => $user->getEMailAddress(),
304
+                    'scope' => self::VISIBILITY_CONTACTS_ONLY,
305
+                    'verified' => self::NOT_VERIFIED,
306
+                ],
307
+            self::PROPERTY_AVATAR =>
308
+                [
309
+                    'scope' => self::VISIBILITY_CONTACTS_ONLY
310
+                ],
311
+            self::PROPERTY_PHONE =>
312
+                [
313
+                    'value' => '',
314
+                    'scope' => self::VISIBILITY_PRIVATE,
315
+                    'verified' => self::NOT_VERIFIED,
316
+                ],
317
+            self::PROPERTY_TWITTER =>
318
+                [
319
+                    'value' => '',
320
+                    'scope' => self::VISIBILITY_PRIVATE,
321
+                    'verified' => self::NOT_VERIFIED,
322
+                ],
323
+        ];
324
+    }
325 325
 
326 326
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/Controller/ShareesAPIController.php 1 patch
Indentation   +670 added lines, -670 removed lines patch added patch discarded remove patch
@@ -43,674 +43,674 @@
 block discarded – undo
43 43
 
44 44
 class ShareesAPIController extends OCSController {
45 45
 
46
-	/** @var IGroupManager */
47
-	protected $groupManager;
48
-
49
-	/** @var IUserManager */
50
-	protected $userManager;
51
-
52
-	/** @var IManager */
53
-	protected $contactsManager;
54
-
55
-	/** @var IConfig */
56
-	protected $config;
57
-
58
-	/** @var IUserSession */
59
-	protected $userSession;
60
-
61
-	/** @var IURLGenerator */
62
-	protected $urlGenerator;
63
-
64
-	/** @var ILogger */
65
-	protected $logger;
66
-
67
-	/** @var \OCP\Share\IManager */
68
-	protected $shareManager;
69
-
70
-	/** @var IClientService */
71
-	protected $clientService;
72
-
73
-	/** @var ICloudIdManager  */
74
-	protected $cloudIdManager;
75
-
76
-	/** @var bool */
77
-	protected $shareWithGroupOnly = false;
78
-
79
-	/** @var bool */
80
-	protected $shareeEnumeration = true;
81
-
82
-	/** @var int */
83
-	protected $offset = 0;
84
-
85
-	/** @var int */
86
-	protected $limit = 10;
87
-
88
-	/** @var array */
89
-	protected $result = [
90
-		'exact' => [
91
-			'users' => [],
92
-			'groups' => [],
93
-			'remotes' => [],
94
-			'emails' => [],
95
-			'circles' => [],
96
-		],
97
-		'users' => [],
98
-		'groups' => [],
99
-		'remotes' => [],
100
-		'emails' => [],
101
-		'lookup' => [],
102
-		'circles' => [],
103
-	];
104
-
105
-	protected $reachedEndFor = [];
106
-
107
-	/**
108
-	 * @param string $appName
109
-	 * @param IRequest $request
110
-	 * @param IGroupManager $groupManager
111
-	 * @param IUserManager $userManager
112
-	 * @param IManager $contactsManager
113
-	 * @param IConfig $config
114
-	 * @param IUserSession $userSession
115
-	 * @param IURLGenerator $urlGenerator
116
-	 * @param ILogger $logger
117
-	 * @param \OCP\Share\IManager $shareManager
118
-	 * @param IClientService $clientService
119
-	 * @param ICloudIdManager $cloudIdManager
120
-	 */
121
-	public function __construct($appName,
122
-								IRequest $request,
123
-								IGroupManager $groupManager,
124
-								IUserManager $userManager,
125
-								IManager $contactsManager,
126
-								IConfig $config,
127
-								IUserSession $userSession,
128
-								IURLGenerator $urlGenerator,
129
-								ILogger $logger,
130
-								\OCP\Share\IManager $shareManager,
131
-								IClientService $clientService,
132
-								ICloudIdManager $cloudIdManager
133
-	) {
134
-		parent::__construct($appName, $request);
135
-
136
-		$this->groupManager = $groupManager;
137
-		$this->userManager = $userManager;
138
-		$this->contactsManager = $contactsManager;
139
-		$this->config = $config;
140
-		$this->userSession = $userSession;
141
-		$this->urlGenerator = $urlGenerator;
142
-		$this->logger = $logger;
143
-		$this->shareManager = $shareManager;
144
-		$this->clientService = $clientService;
145
-		$this->cloudIdManager = $cloudIdManager;
146
-	}
147
-
148
-	/**
149
-	 * @param string $search
150
-	 */
151
-	protected function getUsers($search) {
152
-		$this->result['users'] = $this->result['exact']['users'] = $users = [];
153
-
154
-		$userGroups = [];
155
-		if ($this->shareWithGroupOnly) {
156
-			// Search in all the groups this user is part of
157
-			$userGroups = $this->groupManager->getUserGroupIds($this->userSession->getUser());
158
-			foreach ($userGroups as $userGroup) {
159
-				$usersTmp = $this->groupManager->displayNamesInGroup($userGroup, $search, $this->limit, $this->offset);
160
-				foreach ($usersTmp as $uid => $userDisplayName) {
161
-					$users[$uid] = $userDisplayName;
162
-				}
163
-			}
164
-		} else {
165
-			// Search in all users
166
-			$usersTmp = $this->userManager->searchDisplayName($search, $this->limit, $this->offset);
167
-
168
-			foreach ($usersTmp as $user) {
169
-				$users[$user->getUID()] = $user->getDisplayName();
170
-			}
171
-		}
172
-
173
-		if (!$this->shareeEnumeration || sizeof($users) < $this->limit) {
174
-			$this->reachedEndFor[] = 'users';
175
-		}
176
-
177
-		$foundUserById = false;
178
-		$lowerSearch = strtolower($search);
179
-		foreach ($users as $uid => $userDisplayName) {
180
-			if (strtolower($uid) === $lowerSearch || strtolower($userDisplayName) === $lowerSearch) {
181
-				if (strtolower($uid) === $lowerSearch) {
182
-					$foundUserById = true;
183
-				}
184
-				$this->result['exact']['users'][] = [
185
-					'label' => $userDisplayName,
186
-					'value' => [
187
-						'shareType' => Share::SHARE_TYPE_USER,
188
-						'shareWith' => $uid,
189
-					],
190
-				];
191
-			} else {
192
-				$this->result['users'][] = [
193
-					'label' => $userDisplayName,
194
-					'value' => [
195
-						'shareType' => Share::SHARE_TYPE_USER,
196
-						'shareWith' => $uid,
197
-					],
198
-				];
199
-			}
200
-		}
201
-
202
-		if ($this->offset === 0 && !$foundUserById) {
203
-			// On page one we try if the search result has a direct hit on the
204
-			// user id and if so, we add that to the exact match list
205
-			$user = $this->userManager->get($search);
206
-			if ($user instanceof IUser) {
207
-				$addUser = true;
208
-
209
-				if ($this->shareWithGroupOnly) {
210
-					// Only add, if we have a common group
211
-					$commonGroups = array_intersect($userGroups, $this->groupManager->getUserGroupIds($user));
212
-					$addUser = !empty($commonGroups);
213
-				}
214
-
215
-				if ($addUser) {
216
-					array_push($this->result['exact']['users'], [
217
-						'label' => $user->getDisplayName(),
218
-						'value' => [
219
-							'shareType' => Share::SHARE_TYPE_USER,
220
-							'shareWith' => $user->getUID(),
221
-						],
222
-					]);
223
-				}
224
-			}
225
-		}
226
-
227
-		if (!$this->shareeEnumeration) {
228
-			$this->result['users'] = [];
229
-		}
230
-	}
231
-
232
-	/**
233
-	 * @param string $search
234
-	 */
235
-	protected function getGroups($search) {
236
-		$this->result['groups'] = $this->result['exact']['groups'] = [];
237
-
238
-		$groups = $this->groupManager->search($search, $this->limit, $this->offset);
239
-		$groupIds = array_map(function (IGroup $group) { return $group->getGID(); }, $groups);
240
-
241
-		if (!$this->shareeEnumeration || sizeof($groups) < $this->limit) {
242
-			$this->reachedEndFor[] = 'groups';
243
-		}
244
-
245
-		$userGroups =  [];
246
-		if (!empty($groups) && $this->shareWithGroupOnly) {
247
-			// Intersect all the groups that match with the groups this user is a member of
248
-			$userGroups = $this->groupManager->getUserGroups($this->userSession->getUser());
249
-			$userGroups = array_map(function (IGroup $group) { return $group->getGID(); }, $userGroups);
250
-			$groupIds = array_intersect($groupIds, $userGroups);
251
-		}
252
-
253
-		$lowerSearch = strtolower($search);
254
-		foreach ($groups as $group) {
255
-			// FIXME: use a more efficient approach
256
-			$gid = $group->getGID();
257
-			if (!in_array($gid, $groupIds)) {
258
-				continue;
259
-			}
260
-			if (strtolower($gid) === $lowerSearch || strtolower($group->getDisplayName()) === $lowerSearch) {
261
-				$this->result['exact']['groups'][] = [
262
-					'label' => $group->getDisplayName(),
263
-					'value' => [
264
-						'shareType' => Share::SHARE_TYPE_GROUP,
265
-						'shareWith' => $gid,
266
-					],
267
-				];
268
-			} else {
269
-				$this->result['groups'][] = [
270
-					'label' => $group->getDisplayName(),
271
-					'value' => [
272
-						'shareType' => Share::SHARE_TYPE_GROUP,
273
-						'shareWith' => $gid,
274
-					],
275
-				];
276
-			}
277
-		}
278
-
279
-		if ($this->offset === 0 && empty($this->result['exact']['groups'])) {
280
-			// On page one we try if the search result has a direct hit on the
281
-			// user id and if so, we add that to the exact match list
282
-			$group = $this->groupManager->get($search);
283
-			if ($group instanceof IGroup && (!$this->shareWithGroupOnly || in_array($group->getGID(), $userGroups))) {
284
-				array_push($this->result['exact']['groups'], [
285
-					'label' => $group->getDisplayName(),
286
-					'value' => [
287
-						'shareType' => Share::SHARE_TYPE_GROUP,
288
-						'shareWith' => $group->getGID(),
289
-					],
290
-				]);
291
-			}
292
-		}
293
-
294
-		if (!$this->shareeEnumeration) {
295
-			$this->result['groups'] = [];
296
-		}
297
-	}
298
-
299
-
300
-	/**
301
-	 * @param string $search
302
-	 */
303
-	protected function getCircles($search) {
304
-		$this->result['circles'] = $this->result['exact']['circles'] = [];
305
-
306
-		$result = \OCA\Circles\Api\Sharees::search($search, $this->limit, $this->offset);
307
-		if (array_key_exists('circles', $result['exact'])) {
308
-			$this->result['exact']['circles'] = $result['exact']['circles'];
309
-		}
310
-		if (array_key_exists('circles', $result)) {
311
-			$this->result['circles'] = $result['circles'];
312
-		}
313
-	}
314
-
315
-
316
-	/**
317
-	 * @param string $search
318
-	 * @return array
319
-	 */
320
-	protected function getRemote($search) {
321
-		$result = ['results' => [], 'exact' => []];
322
-
323
-		// Search in contacts
324
-		//@todo Pagination missing
325
-		$addressBookContacts = $this->contactsManager->search($search, ['CLOUD', 'FN']);
326
-		$result['exactIdMatch'] = false;
327
-		foreach ($addressBookContacts as $contact) {
328
-			if (isset($contact['isLocalSystemBook'])) {
329
-				continue;
330
-			}
331
-			if (isset($contact['CLOUD'])) {
332
-				$cloudIds = $contact['CLOUD'];
333
-				if (!is_array($cloudIds)) {
334
-					$cloudIds = [$cloudIds];
335
-				}
336
-				$lowerSearch = strtolower($search);
337
-				foreach ($cloudIds as $cloudId) {
338
-					list(, $serverUrl) = $this->splitUserRemote($cloudId);
339
-					if (strtolower($contact['FN']) === $lowerSearch || strtolower($cloudId) === $lowerSearch) {
340
-						if (strtolower($cloudId) === $lowerSearch) {
341
-							$result['exactIdMatch'] = true;
342
-						}
343
-						$result['exact'][] = [
344
-							'label' => $contact['FN'] . " ($cloudId)",
345
-							'value' => [
346
-								'shareType' => Share::SHARE_TYPE_REMOTE,
347
-								'shareWith' => $cloudId,
348
-								'server' => $serverUrl,
349
-							],
350
-						];
351
-					} else {
352
-						$result['results'][] = [
353
-							'label' => $contact['FN'] . " ($cloudId)",
354
-							'value' => [
355
-								'shareType' => Share::SHARE_TYPE_REMOTE,
356
-								'shareWith' => $cloudId,
357
-								'server' => $serverUrl,
358
-							],
359
-						];
360
-					}
361
-				}
362
-			}
363
-		}
364
-
365
-		if (!$this->shareeEnumeration) {
366
-			$result['results'] = [];
367
-		}
368
-
369
-		if (!$result['exactIdMatch'] && $this->cloudIdManager->isValidCloudId($search) && $this->offset === 0) {
370
-			$result['exact'][] = [
371
-				'label' => $search,
372
-				'value' => [
373
-					'shareType' => Share::SHARE_TYPE_REMOTE,
374
-					'shareWith' => $search,
375
-				],
376
-			];
377
-		}
378
-
379
-		$this->reachedEndFor[] = 'remotes';
380
-
381
-		return $result;
382
-	}
383
-
384
-	/**
385
-	 * split user and remote from federated cloud id
386
-	 *
387
-	 * @param string $address federated share address
388
-	 * @return array [user, remoteURL]
389
-	 * @throws \Exception
390
-	 */
391
-	public function splitUserRemote($address) {
392
-		try {
393
-			$cloudId = $this->cloudIdManager->resolveCloudId($address);
394
-			return [$cloudId->getUser(), $cloudId->getRemote()];
395
-		} catch (\InvalidArgumentException $e) {
396
-			throw new \Exception('Invalid Federated Cloud ID', 0, $e);
397
-		}
398
-	}
399
-
400
-	/**
401
-	 * Strips away a potential file names and trailing slashes:
402
-	 * - http://localhost
403
-	 * - http://localhost/
404
-	 * - http://localhost/index.php
405
-	 * - http://localhost/index.php/s/{shareToken}
406
-	 *
407
-	 * all return: http://localhost
408
-	 *
409
-	 * @param string $remote
410
-	 * @return string
411
-	 */
412
-	protected function fixRemoteURL($remote) {
413
-		$remote = str_replace('\\', '/', $remote);
414
-		if ($fileNamePosition = strpos($remote, '/index.php')) {
415
-			$remote = substr($remote, 0, $fileNamePosition);
416
-		}
417
-		$remote = rtrim($remote, '/');
418
-
419
-		return $remote;
420
-	}
421
-
422
-	/**
423
-	 * @NoAdminRequired
424
-	 *
425
-	 * @param string $search
426
-	 * @param string $itemType
427
-	 * @param int $page
428
-	 * @param int $perPage
429
-	 * @param int|int[] $shareType
430
-	 * @param bool $lookup
431
-	 * @return DataResponse
432
-	 * @throws OCSBadRequestException
433
-	 */
434
-	public function search($search = '', $itemType = null, $page = 1, $perPage = 200, $shareType = null, $lookup = true) {
435
-
436
-		// only search for string larger than a given threshold
437
-		$threshold = (int)$this->config->getSystemValue('sharing.minSearchStringLength', 0);
438
-		if (strlen($search) < $threshold) {
439
-			return new DataResponse($this->result);
440
-		}
441
-
442
-		// never return more than the max. number of results configured in the config.php
443
-		$maxResults = (int)$this->config->getSystemValue('sharing.maxAutocompleteResults', 0);
444
-		if ($maxResults > 0) {
445
-			$perPage = min($perPage, $maxResults);
446
-		}
447
-		if ($perPage <= 0) {
448
-			throw new OCSBadRequestException('Invalid perPage argument');
449
-		}
450
-		if ($page <= 0) {
451
-			throw new OCSBadRequestException('Invalid page');
452
-		}
453
-
454
-		$shareTypes = [
455
-			Share::SHARE_TYPE_USER,
456
-		];
457
-
458
-		if ($itemType === 'file' || $itemType === 'folder') {
459
-			if ($this->shareManager->allowGroupSharing()) {
460
-				$shareTypes[] = Share::SHARE_TYPE_GROUP;
461
-			}
462
-
463
-			if ($this->isRemoteSharingAllowed($itemType)) {
464
-				$shareTypes[] = Share::SHARE_TYPE_REMOTE;
465
-			}
466
-
467
-			if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_EMAIL)) {
468
-				$shareTypes[] = Share::SHARE_TYPE_EMAIL;
469
-			}
470
-		} else {
471
-			$shareTypes[] = Share::SHARE_TYPE_GROUP;
472
-			$shareTypes[] = Share::SHARE_TYPE_EMAIL;
473
-		}
474
-
475
-		if (\OCP\App::isEnabled('circles')) {
476
-			$shareTypes[] = Share::SHARE_TYPE_CIRCLE;
477
-		}
478
-
479
-		if (isset($_GET['shareType']) && is_array($_GET['shareType'])) {
480
-			$shareTypes = array_intersect($shareTypes, $_GET['shareType']);
481
-			sort($shareTypes);
482
-		} else if (is_numeric($shareType)) {
483
-			$shareTypes = array_intersect($shareTypes, [(int) $shareType]);
484
-			sort($shareTypes);
485
-		}
486
-
487
-		$this->shareWithGroupOnly = $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
488
-		$this->shareeEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
489
-		$this->limit = (int) $perPage;
490
-		$this->offset = $perPage * ($page - 1);
491
-
492
-		return $this->searchSharees($search, $itemType, $shareTypes, $page, $perPage, $lookup);
493
-	}
494
-
495
-	/**
496
-	 * Method to get out the static call for better testing
497
-	 *
498
-	 * @param string $itemType
499
-	 * @return bool
500
-	 */
501
-	protected function isRemoteSharingAllowed($itemType) {
502
-		try {
503
-			$backend = Share::getBackend($itemType);
504
-			return $backend->isShareTypeAllowed(Share::SHARE_TYPE_REMOTE);
505
-		} catch (\Exception $e) {
506
-			return false;
507
-		}
508
-	}
509
-
510
-	/**
511
-	 * Testable search function that does not need globals
512
-	 *
513
-	 * @param string $search
514
-	 * @param string $itemType
515
-	 * @param array $shareTypes
516
-	 * @param int $page
517
-	 * @param int $perPage
518
-	 * @param bool $lookup
519
-	 * @return DataResponse
520
-	 * @throws OCSBadRequestException
521
-	 */
522
-	protected function searchSharees($search, $itemType, array $shareTypes, $page, $perPage, $lookup) {
523
-		// Verify arguments
524
-		if ($itemType === null) {
525
-			throw new OCSBadRequestException('Missing itemType');
526
-		}
527
-
528
-		// Get users
529
-		if (in_array(Share::SHARE_TYPE_USER, $shareTypes)) {
530
-			$this->getUsers($search);
531
-		}
532
-
533
-		// Get groups
534
-		if (in_array(Share::SHARE_TYPE_GROUP, $shareTypes)) {
535
-			$this->getGroups($search);
536
-		}
537
-
538
-		// Get circles
539
-		if (in_array(Share::SHARE_TYPE_CIRCLE, $shareTypes)) {
540
-			$this->getCircles($search);
541
-		}
542
-
543
-
544
-		// Get remote
545
-		$remoteResults = ['results' => [], 'exact' => [], 'exactIdMatch' => false];
546
-		if (in_array(Share::SHARE_TYPE_REMOTE, $shareTypes)) {
547
-			$remoteResults = $this->getRemote($search);
548
-		}
549
-
550
-		// Get emails
551
-		$mailResults = ['results' => [], 'exact' => [], 'exactIdMatch' => false];
552
-		if (in_array(Share::SHARE_TYPE_EMAIL, $shareTypes)) {
553
-			$mailResults = $this->getEmail($search);
554
-		}
555
-
556
-		// Get from lookup server
557
-		if ($lookup) {
558
-			$this->getLookup($search);
559
-		}
560
-
561
-		// if we have a exact match, either for the federated cloud id or for the
562
-		// email address we only return the exact match. It is highly unlikely
563
-		// that the exact same email address and federated cloud id exists
564
-		if ($mailResults['exactIdMatch'] && !$remoteResults['exactIdMatch']) {
565
-			$this->result['emails'] = $mailResults['results'];
566
-			$this->result['exact']['emails'] = $mailResults['exact'];
567
-		} else if (!$mailResults['exactIdMatch'] && $remoteResults['exactIdMatch']) {
568
-			$this->result['remotes'] = $remoteResults['results'];
569
-			$this->result['exact']['remotes'] = $remoteResults['exact'];
570
-		} else {
571
-			$this->result['remotes'] = $remoteResults['results'];
572
-			$this->result['exact']['remotes'] = $remoteResults['exact'];
573
-			$this->result['emails'] = $mailResults['results'];
574
-			$this->result['exact']['emails'] = $mailResults['exact'];
575
-		}
576
-
577
-		$response = new DataResponse($this->result);
578
-
579
-		if (sizeof($this->reachedEndFor) < 3) {
580
-			$response->addHeader('Link', $this->getPaginationLink($page, [
581
-				'search' => $search,
582
-				'itemType' => $itemType,
583
-				'shareType' => $shareTypes,
584
-				'perPage' => $perPage,
585
-			]));
586
-		}
587
-
588
-		return $response;
589
-	}
590
-
591
-	/**
592
-	 * @param string $search
593
-	 * @return array
594
-	 */
595
-	protected function getEmail($search) {
596
-		$result = ['results' => [], 'exact' => []];
597
-
598
-		// Search in contacts
599
-		//@todo Pagination missing
600
-		$addressBookContacts = $this->contactsManager->search($search, ['EMAIL', 'FN']);
601
-		$result['exactIdMatch'] = false;
602
-		foreach ($addressBookContacts as $contact) {
603
-			if (isset($contact['isLocalSystemBook'])) {
604
-				continue;
605
-			}
606
-			if (isset($contact['EMAIL'])) {
607
-				$emailAddresses = $contact['EMAIL'];
608
-				if (!is_array($emailAddresses)) {
609
-					$emailAddresses = [$emailAddresses];
610
-				}
611
-				foreach ($emailAddresses as $emailAddress) {
612
-					if (strtolower($contact['FN']) === strtolower($search) || strtolower($emailAddress) === strtolower($search)) {
613
-						if (strtolower($emailAddress) === strtolower($search)) {
614
-							$result['exactIdMatch'] = true;
615
-						}
616
-						$result['exact'][] = [
617
-							'label' => $contact['FN'] . " ($emailAddress)",
618
-							'value' => [
619
-								'shareType' => Share::SHARE_TYPE_EMAIL,
620
-								'shareWith' => $emailAddress,
621
-							],
622
-						];
623
-					} else {
624
-						$result['results'][] = [
625
-							'label' => $contact['FN'] . " ($emailAddress)",
626
-							'value' => [
627
-								'shareType' => Share::SHARE_TYPE_EMAIL,
628
-								'shareWith' => $emailAddress,
629
-							],
630
-						];
631
-					}
632
-				}
633
-			}
634
-		}
635
-
636
-		if (!$this->shareeEnumeration) {
637
-			$result['results'] = [];
638
-		}
639
-
640
-		if (!$result['exactIdMatch'] && filter_var($search, FILTER_VALIDATE_EMAIL)) {
641
-			$result['exact'][] = [
642
-				'label' => $search,
643
-				'value' => [
644
-					'shareType' => Share::SHARE_TYPE_EMAIL,
645
-					'shareWith' => $search,
646
-				],
647
-			];
648
-		}
649
-
650
-		$this->reachedEndFor[] = 'emails';
651
-
652
-		return $result;
653
-	}
654
-
655
-	protected function getLookup($search) {
656
-		$isEnabled = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no');
657
-		$lookupServerUrl = $this->config->getSystemValue('lookup_server', 'https://lookup.nextcloud.com');
658
-		$lookupServerUrl = rtrim($lookupServerUrl, '/');
659
-		$result = [];
660
-
661
-		if($isEnabled === 'yes') {
662
-			try {
663
-				$client = $this->clientService->newClient();
664
-				$response = $client->get(
665
-					$lookupServerUrl . '/users?search=' . urlencode($search),
666
-					[
667
-						'timeout' => 10,
668
-						'connect_timeout' => 3,
669
-					]
670
-				);
671
-
672
-				$body = json_decode($response->getBody(), true);
673
-
674
-				$result = [];
675
-				foreach ($body as $lookup) {
676
-					$result[] = [
677
-						'label' => $lookup['federationId'],
678
-						'value' => [
679
-							'shareType' => Share::SHARE_TYPE_REMOTE,
680
-							'shareWith' => $lookup['federationId'],
681
-						],
682
-						'extra' => $lookup,
683
-					];
684
-				}
685
-			} catch (\Exception $e) {}
686
-		}
687
-
688
-		$this->result['lookup'] = $result;
689
-	}
690
-
691
-	/**
692
-	 * Generates a bunch of pagination links for the current page
693
-	 *
694
-	 * @param int $page Current page
695
-	 * @param array $params Parameters for the URL
696
-	 * @return string
697
-	 */
698
-	protected function getPaginationLink($page, array $params) {
699
-		if ($this->isV2()) {
700
-			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v2.php/apps/files_sharing/api/v1/sharees') . '?';
701
-		} else {
702
-			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/sharees') . '?';
703
-		}
704
-		$params['page'] = $page + 1;
705
-		$link = '<' . $url . http_build_query($params) . '>; rel="next"';
706
-
707
-		return $link;
708
-	}
709
-
710
-	/**
711
-	 * @return bool
712
-	 */
713
-	protected function isV2() {
714
-		return $this->request->getScriptName() === '/ocs/v2.php';
715
-	}
46
+    /** @var IGroupManager */
47
+    protected $groupManager;
48
+
49
+    /** @var IUserManager */
50
+    protected $userManager;
51
+
52
+    /** @var IManager */
53
+    protected $contactsManager;
54
+
55
+    /** @var IConfig */
56
+    protected $config;
57
+
58
+    /** @var IUserSession */
59
+    protected $userSession;
60
+
61
+    /** @var IURLGenerator */
62
+    protected $urlGenerator;
63
+
64
+    /** @var ILogger */
65
+    protected $logger;
66
+
67
+    /** @var \OCP\Share\IManager */
68
+    protected $shareManager;
69
+
70
+    /** @var IClientService */
71
+    protected $clientService;
72
+
73
+    /** @var ICloudIdManager  */
74
+    protected $cloudIdManager;
75
+
76
+    /** @var bool */
77
+    protected $shareWithGroupOnly = false;
78
+
79
+    /** @var bool */
80
+    protected $shareeEnumeration = true;
81
+
82
+    /** @var int */
83
+    protected $offset = 0;
84
+
85
+    /** @var int */
86
+    protected $limit = 10;
87
+
88
+    /** @var array */
89
+    protected $result = [
90
+        'exact' => [
91
+            'users' => [],
92
+            'groups' => [],
93
+            'remotes' => [],
94
+            'emails' => [],
95
+            'circles' => [],
96
+        ],
97
+        'users' => [],
98
+        'groups' => [],
99
+        'remotes' => [],
100
+        'emails' => [],
101
+        'lookup' => [],
102
+        'circles' => [],
103
+    ];
104
+
105
+    protected $reachedEndFor = [];
106
+
107
+    /**
108
+     * @param string $appName
109
+     * @param IRequest $request
110
+     * @param IGroupManager $groupManager
111
+     * @param IUserManager $userManager
112
+     * @param IManager $contactsManager
113
+     * @param IConfig $config
114
+     * @param IUserSession $userSession
115
+     * @param IURLGenerator $urlGenerator
116
+     * @param ILogger $logger
117
+     * @param \OCP\Share\IManager $shareManager
118
+     * @param IClientService $clientService
119
+     * @param ICloudIdManager $cloudIdManager
120
+     */
121
+    public function __construct($appName,
122
+                                IRequest $request,
123
+                                IGroupManager $groupManager,
124
+                                IUserManager $userManager,
125
+                                IManager $contactsManager,
126
+                                IConfig $config,
127
+                                IUserSession $userSession,
128
+                                IURLGenerator $urlGenerator,
129
+                                ILogger $logger,
130
+                                \OCP\Share\IManager $shareManager,
131
+                                IClientService $clientService,
132
+                                ICloudIdManager $cloudIdManager
133
+    ) {
134
+        parent::__construct($appName, $request);
135
+
136
+        $this->groupManager = $groupManager;
137
+        $this->userManager = $userManager;
138
+        $this->contactsManager = $contactsManager;
139
+        $this->config = $config;
140
+        $this->userSession = $userSession;
141
+        $this->urlGenerator = $urlGenerator;
142
+        $this->logger = $logger;
143
+        $this->shareManager = $shareManager;
144
+        $this->clientService = $clientService;
145
+        $this->cloudIdManager = $cloudIdManager;
146
+    }
147
+
148
+    /**
149
+     * @param string $search
150
+     */
151
+    protected function getUsers($search) {
152
+        $this->result['users'] = $this->result['exact']['users'] = $users = [];
153
+
154
+        $userGroups = [];
155
+        if ($this->shareWithGroupOnly) {
156
+            // Search in all the groups this user is part of
157
+            $userGroups = $this->groupManager->getUserGroupIds($this->userSession->getUser());
158
+            foreach ($userGroups as $userGroup) {
159
+                $usersTmp = $this->groupManager->displayNamesInGroup($userGroup, $search, $this->limit, $this->offset);
160
+                foreach ($usersTmp as $uid => $userDisplayName) {
161
+                    $users[$uid] = $userDisplayName;
162
+                }
163
+            }
164
+        } else {
165
+            // Search in all users
166
+            $usersTmp = $this->userManager->searchDisplayName($search, $this->limit, $this->offset);
167
+
168
+            foreach ($usersTmp as $user) {
169
+                $users[$user->getUID()] = $user->getDisplayName();
170
+            }
171
+        }
172
+
173
+        if (!$this->shareeEnumeration || sizeof($users) < $this->limit) {
174
+            $this->reachedEndFor[] = 'users';
175
+        }
176
+
177
+        $foundUserById = false;
178
+        $lowerSearch = strtolower($search);
179
+        foreach ($users as $uid => $userDisplayName) {
180
+            if (strtolower($uid) === $lowerSearch || strtolower($userDisplayName) === $lowerSearch) {
181
+                if (strtolower($uid) === $lowerSearch) {
182
+                    $foundUserById = true;
183
+                }
184
+                $this->result['exact']['users'][] = [
185
+                    'label' => $userDisplayName,
186
+                    'value' => [
187
+                        'shareType' => Share::SHARE_TYPE_USER,
188
+                        'shareWith' => $uid,
189
+                    ],
190
+                ];
191
+            } else {
192
+                $this->result['users'][] = [
193
+                    'label' => $userDisplayName,
194
+                    'value' => [
195
+                        'shareType' => Share::SHARE_TYPE_USER,
196
+                        'shareWith' => $uid,
197
+                    ],
198
+                ];
199
+            }
200
+        }
201
+
202
+        if ($this->offset === 0 && !$foundUserById) {
203
+            // On page one we try if the search result has a direct hit on the
204
+            // user id and if so, we add that to the exact match list
205
+            $user = $this->userManager->get($search);
206
+            if ($user instanceof IUser) {
207
+                $addUser = true;
208
+
209
+                if ($this->shareWithGroupOnly) {
210
+                    // Only add, if we have a common group
211
+                    $commonGroups = array_intersect($userGroups, $this->groupManager->getUserGroupIds($user));
212
+                    $addUser = !empty($commonGroups);
213
+                }
214
+
215
+                if ($addUser) {
216
+                    array_push($this->result['exact']['users'], [
217
+                        'label' => $user->getDisplayName(),
218
+                        'value' => [
219
+                            'shareType' => Share::SHARE_TYPE_USER,
220
+                            'shareWith' => $user->getUID(),
221
+                        ],
222
+                    ]);
223
+                }
224
+            }
225
+        }
226
+
227
+        if (!$this->shareeEnumeration) {
228
+            $this->result['users'] = [];
229
+        }
230
+    }
231
+
232
+    /**
233
+     * @param string $search
234
+     */
235
+    protected function getGroups($search) {
236
+        $this->result['groups'] = $this->result['exact']['groups'] = [];
237
+
238
+        $groups = $this->groupManager->search($search, $this->limit, $this->offset);
239
+        $groupIds = array_map(function (IGroup $group) { return $group->getGID(); }, $groups);
240
+
241
+        if (!$this->shareeEnumeration || sizeof($groups) < $this->limit) {
242
+            $this->reachedEndFor[] = 'groups';
243
+        }
244
+
245
+        $userGroups =  [];
246
+        if (!empty($groups) && $this->shareWithGroupOnly) {
247
+            // Intersect all the groups that match with the groups this user is a member of
248
+            $userGroups = $this->groupManager->getUserGroups($this->userSession->getUser());
249
+            $userGroups = array_map(function (IGroup $group) { return $group->getGID(); }, $userGroups);
250
+            $groupIds = array_intersect($groupIds, $userGroups);
251
+        }
252
+
253
+        $lowerSearch = strtolower($search);
254
+        foreach ($groups as $group) {
255
+            // FIXME: use a more efficient approach
256
+            $gid = $group->getGID();
257
+            if (!in_array($gid, $groupIds)) {
258
+                continue;
259
+            }
260
+            if (strtolower($gid) === $lowerSearch || strtolower($group->getDisplayName()) === $lowerSearch) {
261
+                $this->result['exact']['groups'][] = [
262
+                    'label' => $group->getDisplayName(),
263
+                    'value' => [
264
+                        'shareType' => Share::SHARE_TYPE_GROUP,
265
+                        'shareWith' => $gid,
266
+                    ],
267
+                ];
268
+            } else {
269
+                $this->result['groups'][] = [
270
+                    'label' => $group->getDisplayName(),
271
+                    'value' => [
272
+                        'shareType' => Share::SHARE_TYPE_GROUP,
273
+                        'shareWith' => $gid,
274
+                    ],
275
+                ];
276
+            }
277
+        }
278
+
279
+        if ($this->offset === 0 && empty($this->result['exact']['groups'])) {
280
+            // On page one we try if the search result has a direct hit on the
281
+            // user id and if so, we add that to the exact match list
282
+            $group = $this->groupManager->get($search);
283
+            if ($group instanceof IGroup && (!$this->shareWithGroupOnly || in_array($group->getGID(), $userGroups))) {
284
+                array_push($this->result['exact']['groups'], [
285
+                    'label' => $group->getDisplayName(),
286
+                    'value' => [
287
+                        'shareType' => Share::SHARE_TYPE_GROUP,
288
+                        'shareWith' => $group->getGID(),
289
+                    ],
290
+                ]);
291
+            }
292
+        }
293
+
294
+        if (!$this->shareeEnumeration) {
295
+            $this->result['groups'] = [];
296
+        }
297
+    }
298
+
299
+
300
+    /**
301
+     * @param string $search
302
+     */
303
+    protected function getCircles($search) {
304
+        $this->result['circles'] = $this->result['exact']['circles'] = [];
305
+
306
+        $result = \OCA\Circles\Api\Sharees::search($search, $this->limit, $this->offset);
307
+        if (array_key_exists('circles', $result['exact'])) {
308
+            $this->result['exact']['circles'] = $result['exact']['circles'];
309
+        }
310
+        if (array_key_exists('circles', $result)) {
311
+            $this->result['circles'] = $result['circles'];
312
+        }
313
+    }
314
+
315
+
316
+    /**
317
+     * @param string $search
318
+     * @return array
319
+     */
320
+    protected function getRemote($search) {
321
+        $result = ['results' => [], 'exact' => []];
322
+
323
+        // Search in contacts
324
+        //@todo Pagination missing
325
+        $addressBookContacts = $this->contactsManager->search($search, ['CLOUD', 'FN']);
326
+        $result['exactIdMatch'] = false;
327
+        foreach ($addressBookContacts as $contact) {
328
+            if (isset($contact['isLocalSystemBook'])) {
329
+                continue;
330
+            }
331
+            if (isset($contact['CLOUD'])) {
332
+                $cloudIds = $contact['CLOUD'];
333
+                if (!is_array($cloudIds)) {
334
+                    $cloudIds = [$cloudIds];
335
+                }
336
+                $lowerSearch = strtolower($search);
337
+                foreach ($cloudIds as $cloudId) {
338
+                    list(, $serverUrl) = $this->splitUserRemote($cloudId);
339
+                    if (strtolower($contact['FN']) === $lowerSearch || strtolower($cloudId) === $lowerSearch) {
340
+                        if (strtolower($cloudId) === $lowerSearch) {
341
+                            $result['exactIdMatch'] = true;
342
+                        }
343
+                        $result['exact'][] = [
344
+                            'label' => $contact['FN'] . " ($cloudId)",
345
+                            'value' => [
346
+                                'shareType' => Share::SHARE_TYPE_REMOTE,
347
+                                'shareWith' => $cloudId,
348
+                                'server' => $serverUrl,
349
+                            ],
350
+                        ];
351
+                    } else {
352
+                        $result['results'][] = [
353
+                            'label' => $contact['FN'] . " ($cloudId)",
354
+                            'value' => [
355
+                                'shareType' => Share::SHARE_TYPE_REMOTE,
356
+                                'shareWith' => $cloudId,
357
+                                'server' => $serverUrl,
358
+                            ],
359
+                        ];
360
+                    }
361
+                }
362
+            }
363
+        }
364
+
365
+        if (!$this->shareeEnumeration) {
366
+            $result['results'] = [];
367
+        }
368
+
369
+        if (!$result['exactIdMatch'] && $this->cloudIdManager->isValidCloudId($search) && $this->offset === 0) {
370
+            $result['exact'][] = [
371
+                'label' => $search,
372
+                'value' => [
373
+                    'shareType' => Share::SHARE_TYPE_REMOTE,
374
+                    'shareWith' => $search,
375
+                ],
376
+            ];
377
+        }
378
+
379
+        $this->reachedEndFor[] = 'remotes';
380
+
381
+        return $result;
382
+    }
383
+
384
+    /**
385
+     * split user and remote from federated cloud id
386
+     *
387
+     * @param string $address federated share address
388
+     * @return array [user, remoteURL]
389
+     * @throws \Exception
390
+     */
391
+    public function splitUserRemote($address) {
392
+        try {
393
+            $cloudId = $this->cloudIdManager->resolveCloudId($address);
394
+            return [$cloudId->getUser(), $cloudId->getRemote()];
395
+        } catch (\InvalidArgumentException $e) {
396
+            throw new \Exception('Invalid Federated Cloud ID', 0, $e);
397
+        }
398
+    }
399
+
400
+    /**
401
+     * Strips away a potential file names and trailing slashes:
402
+     * - http://localhost
403
+     * - http://localhost/
404
+     * - http://localhost/index.php
405
+     * - http://localhost/index.php/s/{shareToken}
406
+     *
407
+     * all return: http://localhost
408
+     *
409
+     * @param string $remote
410
+     * @return string
411
+     */
412
+    protected function fixRemoteURL($remote) {
413
+        $remote = str_replace('\\', '/', $remote);
414
+        if ($fileNamePosition = strpos($remote, '/index.php')) {
415
+            $remote = substr($remote, 0, $fileNamePosition);
416
+        }
417
+        $remote = rtrim($remote, '/');
418
+
419
+        return $remote;
420
+    }
421
+
422
+    /**
423
+     * @NoAdminRequired
424
+     *
425
+     * @param string $search
426
+     * @param string $itemType
427
+     * @param int $page
428
+     * @param int $perPage
429
+     * @param int|int[] $shareType
430
+     * @param bool $lookup
431
+     * @return DataResponse
432
+     * @throws OCSBadRequestException
433
+     */
434
+    public function search($search = '', $itemType = null, $page = 1, $perPage = 200, $shareType = null, $lookup = true) {
435
+
436
+        // only search for string larger than a given threshold
437
+        $threshold = (int)$this->config->getSystemValue('sharing.minSearchStringLength', 0);
438
+        if (strlen($search) < $threshold) {
439
+            return new DataResponse($this->result);
440
+        }
441
+
442
+        // never return more than the max. number of results configured in the config.php
443
+        $maxResults = (int)$this->config->getSystemValue('sharing.maxAutocompleteResults', 0);
444
+        if ($maxResults > 0) {
445
+            $perPage = min($perPage, $maxResults);
446
+        }
447
+        if ($perPage <= 0) {
448
+            throw new OCSBadRequestException('Invalid perPage argument');
449
+        }
450
+        if ($page <= 0) {
451
+            throw new OCSBadRequestException('Invalid page');
452
+        }
453
+
454
+        $shareTypes = [
455
+            Share::SHARE_TYPE_USER,
456
+        ];
457
+
458
+        if ($itemType === 'file' || $itemType === 'folder') {
459
+            if ($this->shareManager->allowGroupSharing()) {
460
+                $shareTypes[] = Share::SHARE_TYPE_GROUP;
461
+            }
462
+
463
+            if ($this->isRemoteSharingAllowed($itemType)) {
464
+                $shareTypes[] = Share::SHARE_TYPE_REMOTE;
465
+            }
466
+
467
+            if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_EMAIL)) {
468
+                $shareTypes[] = Share::SHARE_TYPE_EMAIL;
469
+            }
470
+        } else {
471
+            $shareTypes[] = Share::SHARE_TYPE_GROUP;
472
+            $shareTypes[] = Share::SHARE_TYPE_EMAIL;
473
+        }
474
+
475
+        if (\OCP\App::isEnabled('circles')) {
476
+            $shareTypes[] = Share::SHARE_TYPE_CIRCLE;
477
+        }
478
+
479
+        if (isset($_GET['shareType']) && is_array($_GET['shareType'])) {
480
+            $shareTypes = array_intersect($shareTypes, $_GET['shareType']);
481
+            sort($shareTypes);
482
+        } else if (is_numeric($shareType)) {
483
+            $shareTypes = array_intersect($shareTypes, [(int) $shareType]);
484
+            sort($shareTypes);
485
+        }
486
+
487
+        $this->shareWithGroupOnly = $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
488
+        $this->shareeEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
489
+        $this->limit = (int) $perPage;
490
+        $this->offset = $perPage * ($page - 1);
491
+
492
+        return $this->searchSharees($search, $itemType, $shareTypes, $page, $perPage, $lookup);
493
+    }
494
+
495
+    /**
496
+     * Method to get out the static call for better testing
497
+     *
498
+     * @param string $itemType
499
+     * @return bool
500
+     */
501
+    protected function isRemoteSharingAllowed($itemType) {
502
+        try {
503
+            $backend = Share::getBackend($itemType);
504
+            return $backend->isShareTypeAllowed(Share::SHARE_TYPE_REMOTE);
505
+        } catch (\Exception $e) {
506
+            return false;
507
+        }
508
+    }
509
+
510
+    /**
511
+     * Testable search function that does not need globals
512
+     *
513
+     * @param string $search
514
+     * @param string $itemType
515
+     * @param array $shareTypes
516
+     * @param int $page
517
+     * @param int $perPage
518
+     * @param bool $lookup
519
+     * @return DataResponse
520
+     * @throws OCSBadRequestException
521
+     */
522
+    protected function searchSharees($search, $itemType, array $shareTypes, $page, $perPage, $lookup) {
523
+        // Verify arguments
524
+        if ($itemType === null) {
525
+            throw new OCSBadRequestException('Missing itemType');
526
+        }
527
+
528
+        // Get users
529
+        if (in_array(Share::SHARE_TYPE_USER, $shareTypes)) {
530
+            $this->getUsers($search);
531
+        }
532
+
533
+        // Get groups
534
+        if (in_array(Share::SHARE_TYPE_GROUP, $shareTypes)) {
535
+            $this->getGroups($search);
536
+        }
537
+
538
+        // Get circles
539
+        if (in_array(Share::SHARE_TYPE_CIRCLE, $shareTypes)) {
540
+            $this->getCircles($search);
541
+        }
542
+
543
+
544
+        // Get remote
545
+        $remoteResults = ['results' => [], 'exact' => [], 'exactIdMatch' => false];
546
+        if (in_array(Share::SHARE_TYPE_REMOTE, $shareTypes)) {
547
+            $remoteResults = $this->getRemote($search);
548
+        }
549
+
550
+        // Get emails
551
+        $mailResults = ['results' => [], 'exact' => [], 'exactIdMatch' => false];
552
+        if (in_array(Share::SHARE_TYPE_EMAIL, $shareTypes)) {
553
+            $mailResults = $this->getEmail($search);
554
+        }
555
+
556
+        // Get from lookup server
557
+        if ($lookup) {
558
+            $this->getLookup($search);
559
+        }
560
+
561
+        // if we have a exact match, either for the federated cloud id or for the
562
+        // email address we only return the exact match. It is highly unlikely
563
+        // that the exact same email address and federated cloud id exists
564
+        if ($mailResults['exactIdMatch'] && !$remoteResults['exactIdMatch']) {
565
+            $this->result['emails'] = $mailResults['results'];
566
+            $this->result['exact']['emails'] = $mailResults['exact'];
567
+        } else if (!$mailResults['exactIdMatch'] && $remoteResults['exactIdMatch']) {
568
+            $this->result['remotes'] = $remoteResults['results'];
569
+            $this->result['exact']['remotes'] = $remoteResults['exact'];
570
+        } else {
571
+            $this->result['remotes'] = $remoteResults['results'];
572
+            $this->result['exact']['remotes'] = $remoteResults['exact'];
573
+            $this->result['emails'] = $mailResults['results'];
574
+            $this->result['exact']['emails'] = $mailResults['exact'];
575
+        }
576
+
577
+        $response = new DataResponse($this->result);
578
+
579
+        if (sizeof($this->reachedEndFor) < 3) {
580
+            $response->addHeader('Link', $this->getPaginationLink($page, [
581
+                'search' => $search,
582
+                'itemType' => $itemType,
583
+                'shareType' => $shareTypes,
584
+                'perPage' => $perPage,
585
+            ]));
586
+        }
587
+
588
+        return $response;
589
+    }
590
+
591
+    /**
592
+     * @param string $search
593
+     * @return array
594
+     */
595
+    protected function getEmail($search) {
596
+        $result = ['results' => [], 'exact' => []];
597
+
598
+        // Search in contacts
599
+        //@todo Pagination missing
600
+        $addressBookContacts = $this->contactsManager->search($search, ['EMAIL', 'FN']);
601
+        $result['exactIdMatch'] = false;
602
+        foreach ($addressBookContacts as $contact) {
603
+            if (isset($contact['isLocalSystemBook'])) {
604
+                continue;
605
+            }
606
+            if (isset($contact['EMAIL'])) {
607
+                $emailAddresses = $contact['EMAIL'];
608
+                if (!is_array($emailAddresses)) {
609
+                    $emailAddresses = [$emailAddresses];
610
+                }
611
+                foreach ($emailAddresses as $emailAddress) {
612
+                    if (strtolower($contact['FN']) === strtolower($search) || strtolower($emailAddress) === strtolower($search)) {
613
+                        if (strtolower($emailAddress) === strtolower($search)) {
614
+                            $result['exactIdMatch'] = true;
615
+                        }
616
+                        $result['exact'][] = [
617
+                            'label' => $contact['FN'] . " ($emailAddress)",
618
+                            'value' => [
619
+                                'shareType' => Share::SHARE_TYPE_EMAIL,
620
+                                'shareWith' => $emailAddress,
621
+                            ],
622
+                        ];
623
+                    } else {
624
+                        $result['results'][] = [
625
+                            'label' => $contact['FN'] . " ($emailAddress)",
626
+                            'value' => [
627
+                                'shareType' => Share::SHARE_TYPE_EMAIL,
628
+                                'shareWith' => $emailAddress,
629
+                            ],
630
+                        ];
631
+                    }
632
+                }
633
+            }
634
+        }
635
+
636
+        if (!$this->shareeEnumeration) {
637
+            $result['results'] = [];
638
+        }
639
+
640
+        if (!$result['exactIdMatch'] && filter_var($search, FILTER_VALIDATE_EMAIL)) {
641
+            $result['exact'][] = [
642
+                'label' => $search,
643
+                'value' => [
644
+                    'shareType' => Share::SHARE_TYPE_EMAIL,
645
+                    'shareWith' => $search,
646
+                ],
647
+            ];
648
+        }
649
+
650
+        $this->reachedEndFor[] = 'emails';
651
+
652
+        return $result;
653
+    }
654
+
655
+    protected function getLookup($search) {
656
+        $isEnabled = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no');
657
+        $lookupServerUrl = $this->config->getSystemValue('lookup_server', 'https://lookup.nextcloud.com');
658
+        $lookupServerUrl = rtrim($lookupServerUrl, '/');
659
+        $result = [];
660
+
661
+        if($isEnabled === 'yes') {
662
+            try {
663
+                $client = $this->clientService->newClient();
664
+                $response = $client->get(
665
+                    $lookupServerUrl . '/users?search=' . urlencode($search),
666
+                    [
667
+                        'timeout' => 10,
668
+                        'connect_timeout' => 3,
669
+                    ]
670
+                );
671
+
672
+                $body = json_decode($response->getBody(), true);
673
+
674
+                $result = [];
675
+                foreach ($body as $lookup) {
676
+                    $result[] = [
677
+                        'label' => $lookup['federationId'],
678
+                        'value' => [
679
+                            'shareType' => Share::SHARE_TYPE_REMOTE,
680
+                            'shareWith' => $lookup['federationId'],
681
+                        ],
682
+                        'extra' => $lookup,
683
+                    ];
684
+                }
685
+            } catch (\Exception $e) {}
686
+        }
687
+
688
+        $this->result['lookup'] = $result;
689
+    }
690
+
691
+    /**
692
+     * Generates a bunch of pagination links for the current page
693
+     *
694
+     * @param int $page Current page
695
+     * @param array $params Parameters for the URL
696
+     * @return string
697
+     */
698
+    protected function getPaginationLink($page, array $params) {
699
+        if ($this->isV2()) {
700
+            $url = $this->urlGenerator->getAbsoluteURL('/ocs/v2.php/apps/files_sharing/api/v1/sharees') . '?';
701
+        } else {
702
+            $url = $this->urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/sharees') . '?';
703
+        }
704
+        $params['page'] = $page + 1;
705
+        $link = '<' . $url . http_build_query($params) . '>; rel="next"';
706
+
707
+        return $link;
708
+    }
709
+
710
+    /**
711
+     * @return bool
712
+     */
713
+    protected function isV2() {
714
+        return $this->request->getScriptName() === '/ocs/v2.php';
715
+    }
716 716
 }
Please login to merge, or discard this patch.
settings/templates/personal.php 1 patch
Indentation   +54 added lines, -54 removed lines patch added patch discarded remove patch
@@ -22,14 +22,14 @@  discard block
 block discarded – undo
22 22
 <div id="app-navigation">
23 23
 	<ul class="with-icon">
24 24
 	<?php foreach($_['forms'] as $form) {
25
-		if (isset($form['anchor'])) {
26
-			$anchor = '#' . $form['anchor'];
27
-			$class = 'nav-icon-' . $form['anchor'];
28
-			$sectionName = $form['section-name'];
29
-			print_unescaped(sprintf("<li><a href='%s' class='%s'>%s</a></li>", \OCP\Util::sanitizeHTML($anchor),
30
-			\OCP\Util::sanitizeHTML($class), \OCP\Util::sanitizeHTML($sectionName)));
31
-		}
32
-	}?>
25
+        if (isset($form['anchor'])) {
26
+            $anchor = '#' . $form['anchor'];
27
+            $class = 'nav-icon-' . $form['anchor'];
28
+            $sectionName = $form['section-name'];
29
+            print_unescaped(sprintf("<li><a href='%s' class='%s'>%s</a></li>", \OCP\Util::sanitizeHTML($anchor),
30
+            \OCP\Util::sanitizeHTML($class), \OCP\Util::sanitizeHTML($sectionName)));
31
+        }
32
+    }?>
33 33
 	</ul>
34 34
 </div>
35 35
 
@@ -41,10 +41,10 @@  discard block
 block discarded – undo
41 41
 		<p id="quotatext">
42 42
 			<?php if ($_['quota'] === \OCP\Files\FileInfo::SPACE_UNLIMITED): ?>
43 43
 				<?php print_unescaped($l->t('You are using <strong>%s</strong> of <strong>%s</strong>',
44
-					[$_['usage'], $_['total_space']]));?>
44
+                    [$_['usage'], $_['total_space']]));?>
45 45
 			<?php else: ?>
46 46
 				<?php print_unescaped($l->t('You are using <strong>%s</strong> of <strong>%s</strong> (<strong>%s %%</strong>)',
47
-					[$_['usage'], $_['total_space'],  $_['usage_relative']]));?>
47
+                    [$_['usage'], $_['total_space'],  $_['usage_relative']]));?>
48 48
 			<?php endif ?>
49 49
 		</p>
50 50
 	</div>
@@ -112,17 +112,17 @@  discard block
 block discarded – undo
112 112
 			</h2>
113 113
 			<div class="verify">
114 114
 				<img id="verify-email" <?php
115
-				switch($_['emailVerification']) {
116
-					case \OC\Accounts\AccountManager::VERIFICATION_IN_PROGRESS:
117
-						print_unescaped('src="' . image_path('core', 'actions/verifying.svg') . '" title="' . \OC::$server->getL10N()->t('Verifying …') . '"');
118
-						break;
119
-					case \OC\Accounts\AccountManager::VERIFIED:
120
-						print_unescaped('src="' . image_path('core', 'actions/verified.svg') . '"' . \OC::$server->getL10N()->t('Verified') . '"');
121
-						break;
122
-					default:
123
-						print_unescaped('src="' . image_path('core', 'actions/verify.svg') . '" title="' . \OC::$server->getL10N()->t('Verify') . '"');
124
-				}
125
-				?>>
115
+                switch($_['emailVerification']) {
116
+                    case \OC\Accounts\AccountManager::VERIFICATION_IN_PROGRESS:
117
+                        print_unescaped('src="' . image_path('core', 'actions/verifying.svg') . '" title="' . \OC::$server->getL10N()->t('Verifying …') . '"');
118
+                        break;
119
+                    case \OC\Accounts\AccountManager::VERIFIED:
120
+                        print_unescaped('src="' . image_path('core', 'actions/verified.svg') . '"' . \OC::$server->getL10N()->t('Verified') . '"');
121
+                        break;
122
+                    default:
123
+                        print_unescaped('src="' . image_path('core', 'actions/verify.svg') . '" title="' . \OC::$server->getL10N()->t('Verify') . '"');
124
+                }
125
+                ?>>
126 126
 			</div>
127 127
 			<input type="email" name="email" id="email" value="<?php p($_['email']); ?>"
128 128
 				<?php if(!$_['displayNameChangeSupported']) { print_unescaped('class="hidden"'); } ?>
@@ -178,17 +178,17 @@  discard block
 block discarded – undo
178 178
 			</h2>
179 179
 			<div class="verify">
180 180
 				<img id="verify-website" <?php
181
-				switch($_['websiteVerification']) {
182
-					case \OC\Accounts\AccountManager::VERIFICATION_IN_PROGRESS:
183
-						print_unescaped('src="' . image_path('core', 'actions/verifying.svg') . '" title="' . \OC::$server->getL10N()->t('Verifying …') . '"');
184
-						break;
185
-					case \OC\Accounts\AccountManager::VERIFIED:
186
-						print_unescaped('src="' . image_path('core', 'actions/verified.svg') . '"' . \OC::$server->getL10N()->t('Verified') . '"');
187
-						break;
188
-					default:
189
-						print_unescaped('src="' . image_path('core', 'actions/verify.svg') . '" title="' . \OC::$server->getL10N()->t('Verify') . '" class="verify-action"');
190
-				}
191
-				?>>
181
+                switch($_['websiteVerification']) {
182
+                    case \OC\Accounts\AccountManager::VERIFICATION_IN_PROGRESS:
183
+                        print_unescaped('src="' . image_path('core', 'actions/verifying.svg') . '" title="' . \OC::$server->getL10N()->t('Verifying …') . '"');
184
+                        break;
185
+                    case \OC\Accounts\AccountManager::VERIFIED:
186
+                        print_unescaped('src="' . image_path('core', 'actions/verified.svg') . '"' . \OC::$server->getL10N()->t('Verified') . '"');
187
+                        break;
188
+                    default:
189
+                        print_unescaped('src="' . image_path('core', 'actions/verify.svg') . '" title="' . \OC::$server->getL10N()->t('Verify') . '" class="verify-action"');
190
+                }
191
+                ?>>
192 192
 			</div>
193 193
 			<input type="text" name="website" id="website" value="<?php p($_['website']); ?>"
194 194
 			       placeholder="<?php p($l->t('Your website')); ?>"
@@ -205,17 +205,17 @@  discard block
 block discarded – undo
205 205
 			</h2>
206 206
 			<div class="verify">
207 207
 				<img id="verify-twitter" <?php
208
-				switch($_['twitterVerification']) {
209
-					case \OC\Accounts\AccountManager::VERIFICATION_IN_PROGRESS:
210
-						print_unescaped('src="' . image_path('core', 'actions/verifying.svg') . '" title="' . \OC::$server->getL10N()->t('Verifying …') . '"');
211
-						break;
212
-					case \OC\Accounts\AccountManager::VERIFIED:
213
-						print_unescaped('src="' . image_path('core', 'actions/verified.svg') . '"' . \OC::$server->getL10N()->t('Verified') . '"');
214
-						break;
215
-					default:
216
-						print_unescaped('src="' . image_path('core', 'actions/verify.svg') . '" title="' . \OC::$server->getL10N()->t('Verify') . '" class="verify-action"');
217
-				}
218
-				?>>
208
+                switch($_['twitterVerification']) {
209
+                    case \OC\Accounts\AccountManager::VERIFICATION_IN_PROGRESS:
210
+                        print_unescaped('src="' . image_path('core', 'actions/verifying.svg') . '" title="' . \OC::$server->getL10N()->t('Verifying …') . '"');
211
+                        break;
212
+                    case \OC\Accounts\AccountManager::VERIFIED:
213
+                        print_unescaped('src="' . image_path('core', 'actions/verified.svg') . '"' . \OC::$server->getL10N()->t('Verified') . '"');
214
+                        break;
215
+                    default:
216
+                        print_unescaped('src="' . image_path('core', 'actions/verify.svg') . '" title="' . \OC::$server->getL10N()->t('Verify') . '" class="verify-action"');
217
+                }
218
+                ?>>
219 219
 			</div>
220 220
 			<input type="text" name="twitter" id="twitter" value="<?php p($_['twitter']); ?>"
221 221
 				   placeholder="<?php p($l->t('Your Twitter handle')); ?>"
@@ -239,7 +239,7 @@  discard block
 block discarded – undo
239 239
 
240 240
 <?php
241 241
 if($_['passwordChangeSupported']) {
242
-	script('jquery-showpassword');
242
+    script('jquery-showpassword');
243 243
 ?>
244 244
 <form id="passwordform" class="section">
245 245
 	<h2 class="inlineblock"><?php p($l->t('Password'));?></h2>
@@ -308,15 +308,15 @@  discard block
 block discarded – undo
308 308
 
309 309
 		<p>
310 310
 			<?php print_unescaped(str_replace(
311
-				[
312
-					'{contributeopen}',
313
-					'{linkclose}',
314
-				],
315
-				[
316
-					'<a href="https://nextcloud.com/contribute" target="_blank" rel="noreferrer">',
317
-					'</a>',
318
-				],
319
-				$l->t('If you want to support the project {contributeopen}join development{linkclose} or {contributeopen}spread the word{linkclose}!'))); ?>
311
+                [
312
+                    '{contributeopen}',
313
+                    '{linkclose}',
314
+                ],
315
+                [
316
+                    '<a href="https://nextcloud.com/contribute" target="_blank" rel="noreferrer">',
317
+                    '</a>',
318
+                ],
319
+                $l->t('If you want to support the project {contributeopen}join development{linkclose} or {contributeopen}spread the word{linkclose}!'))); ?>
320 320
 		</p>
321 321
 
322 322
 	<?php if(OC_APP::isEnabled('firstrunwizard')) {?>
@@ -377,7 +377,7 @@  discard block
 block discarded – undo
377 377
 </div>
378 378
 
379 379
 <?php foreach($_['forms'] as $form) {
380
-	if (isset($form['form'])) {?>
380
+    if (isset($form['form'])) {?>
381 381
 	<div id="<?php isset($form['anchor']) ? p($form['anchor']) : p('');?>"><?php print_unescaped($form['form']);?></div>
382 382
 	<?php }
383 383
 };?>
Please login to merge, or discard this patch.
settings/BackgroundJobs/VerifyUserData.php 1 patch
Indentation   +234 added lines, -234 removed lines patch added patch discarded remove patch
@@ -35,239 +35,239 @@
 block discarded – undo
35 35
 
36 36
 class VerifyUserData extends Job {
37 37
 
38
-	/** @var  bool */
39
-	private $retainJob = true;
40
-
41
-	/** @var int max number of attempts to send the request */
42
-	private $maxTry = 24;
43
-
44
-	/** @var int how much time should be between two tries (1 hour) */
45
-	private $interval = 3600;
46
-
47
-	/** @var AccountManager */
48
-	private $accountManager;
49
-
50
-	/** @var IUserManager */
51
-	private $userManager;
52
-
53
-	/** @var IClientService */
54
-	private $httpClientService;
55
-
56
-	/** @var ILogger */
57
-	private $logger;
58
-
59
-	/** @var string */
60
-	private $lookupServerUrl;
61
-
62
-	/**
63
-	 * VerifyUserData constructor.
64
-	 *
65
-	 * @param AccountManager $accountManager
66
-	 * @param IUserManager $userManager
67
-	 * @param IClientService $clientService
68
-	 * @param ILogger $logger
69
-	 * @param IConfig $config
70
-	 */
71
-	public function __construct(AccountManager $accountManager,
72
-								IUserManager $userManager,
73
-								IClientService $clientService,
74
-								ILogger $logger,
75
-								IConfig $config
76
-	) {
77
-		$this->accountManager = $accountManager;
78
-		$this->userManager = $userManager;
79
-		$this->httpClientService = $clientService;
80
-		$this->logger = $logger;
81
-
82
-		$lookupServerUrl = $config->getSystemValue('lookup_server', 'https://lookup.nextcloud.com');
83
-		$this->lookupServerUrl = rtrim($lookupServerUrl, '/');
84
-	}
85
-
86
-	/**
87
-	 * run the job, then remove it from the jobList
88
-	 *
89
-	 * @param JobList $jobList
90
-	 * @param ILogger $logger
91
-	 */
92
-	public function execute($jobList, ILogger $logger = null) {
93
-
94
-		if ($this->shouldRun($this->argument)) {
95
-			parent::execute($jobList, $logger);
96
-			$jobList->remove($this, $this->argument);
97
-			if ($this->retainJob) {
98
-				$this->reAddJob($jobList, $this->argument);
99
-			}
100
-		}
101
-
102
-	}
103
-
104
-	protected function run($argument) {
105
-
106
-		$try = (int)$argument['try'] + 1;
107
-
108
-		switch($argument['type']) {
109
-			case AccountManager::PROPERTY_WEBSITE:
110
-				$result = $this->verifyWebsite($argument);
111
-				break;
112
-			case AccountManager::PROPERTY_TWITTER:
113
-			case AccountManager::PROPERTY_EMAIL:
114
-				$result = $this->verifyViaLookupServer($argument, $argument['type']);
115
-				break;
116
-			default:
117
-				// no valid type given, no need to retry
118
-				$this->logger->error($argument['type'] . ' is no valid type for user account data.');
119
-				$result = true;
120
-		}
121
-
122
-		if ($result === true || $try > $this->maxTry) {
123
-			$this->retainJob = false;
124
-		}
125
-	}
126
-
127
-	/**
128
-	 * verify web page
129
-	 *
130
-	 * @param array $argument
131
-	 * @return bool true if we could check the verification code, otherwise false
132
-	 */
133
-	protected function verifyWebsite(array $argument) {
134
-
135
-		$result = false;
136
-
137
-		$url = rtrim($argument['data'], '/') . '/well-known/' . 'CloudIdVerificationCode.txt';
138
-
139
-		$client = $this->httpClientService->newClient();
140
-		try {
141
-			$response = $client->get($url);
142
-		} catch (\Exception $e) {
143
-			return false;
144
-		}
145
-
146
-		if ($response->getStatusCode() === Http::STATUS_OK) {
147
-			$result = true;
148
-			$publishedCode = $response->getBody();
149
-			// remove new lines and spaces
150
-			$publishedCodeSanitized = trim(preg_replace('/\s\s+/', ' ', $publishedCode));
151
-			$user = $this->userManager->get($argument['uid']);
152
-			// we don't check a valid user -> give up
153
-			if ($user === null) {
154
-				$this->logger->error($argument['uid'] . ' doesn\'t exist, can\'t verify user data.');
155
-				return $result;
156
-			}
157
-			$userData = $this->accountManager->getUser($user);
158
-
159
-			if ($publishedCodeSanitized === $argument['verificationCode']) {
160
-				$userData[AccountManager::PROPERTY_WEBSITE]['verified'] = AccountManager::VERIFIED;
161
-			} else {
162
-				$userData[AccountManager::PROPERTY_WEBSITE]['verified'] = AccountManager::NOT_VERIFIED;
163
-			}
164
-
165
-			$this->accountManager->updateUser($user, $userData);
166
-		}
167
-
168
-		return $result;
169
-	}
170
-
171
-	/**
172
-	 * verify email address
173
-	 *
174
-	 * @param array $argument
175
-	 * @param string $dataType
176
-	 * @return bool true if we could check the verification code, otherwise false
177
-	 */
178
-	protected function verifyViaLookupServer(array $argument, $dataType) {
179
-
180
-		$user = $this->userManager->get($argument['uid']);
181
-
182
-		// we don't check a valid user -> give up
183
-		if ($user === null) {
184
-			$this->logger->error($argument['uid'] . ' doesn\'t exist, can\'t verify user data.');
185
-			return true;
186
-		}
187
-
188
-		$localUserData = $this->accountManager->getUser($user);
189
-		$cloudId = $user->getCloudId();
190
-
191
-		// ask lookup-server for user data
192
-		$lookupServerData = $this->queryLookupServer($cloudId);
193
-
194
-		// for some reasons we couldn't read any data from the lookup server, try again later
195
-		if (empty($lookupServerData)) {
196
-			return false;
197
-		}
198
-
199
-		// lookup server has verification data for wrong user data (e.g. email address), try again later
200
-		if ($lookupServerData[$dataType]['value'] !== $argument['data']) {
201
-			return false;
202
-		}
203
-
204
-		// lookup server hasn't verified the email address so far, try again later
205
-		if ($lookupServerData[$dataType]['verified'] === AccountManager::NOT_VERIFIED) {
206
-			return false;
207
-		}
208
-
209
-		$localUserData[$dataType]['verified'] = AccountManager::VERIFIED;
210
-		$this->accountManager->updateUser($user, $localUserData);
211
-
212
-		return true;
213
-	}
214
-
215
-	/**
216
-	 * @param string $cloudId
217
-	 * @return array
218
-	 */
219
-	protected function queryLookupServer($cloudId) {
220
-		try {
221
-			$client = $this->httpClientService->newClient();
222
-			$response = $client->get(
223
-				$this->lookupServerUrl . '/users?search=' . urlencode($cloudId) . '&exactCloudId=1',
224
-				[
225
-					'timeout' => 10,
226
-					'connect_timeout' => 3,
227
-				]
228
-			);
229
-
230
-			$body = json_decode($response->getBody(), true);
231
-
232
-			if ($body['federationId'] === $cloudId) {
233
-				return $body;
234
-			}
235
-
236
-		} catch (\Exception $e) {
237
-			// do nothing, we will just re-try later
238
-		}
239
-
240
-		return [];
241
-	}
242
-
243
-	/**
244
-	 * re-add background job with new arguments
245
-	 *
246
-	 * @param IJobList $jobList
247
-	 * @param array $argument
248
-	 */
249
-	protected function reAddJob(IJobList $jobList, array $argument) {
250
-		$jobList->add('OC\Settings\BackgroundJobs\VerifyUserData',
251
-			[
252
-				'verificationCode' => $argument['verificationCode'],
253
-				'data' => $argument['data'],
254
-				'type' => $argument['type'],
255
-				'uid' => $argument['uid'],
256
-				'try' => (int)$argument['try'] + 1,
257
-				'lastRun' => time()
258
-			]
259
-		);
260
-	}
261
-
262
-	/**
263
-	 * test if it is time for the next run
264
-	 *
265
-	 * @param array $argument
266
-	 * @return bool
267
-	 */
268
-	protected function shouldRun(array $argument) {
269
-		$lastRun = (int)$argument['lastRun'];
270
-		return ((time() - $lastRun) > $this->interval);
271
-	}
38
+    /** @var  bool */
39
+    private $retainJob = true;
40
+
41
+    /** @var int max number of attempts to send the request */
42
+    private $maxTry = 24;
43
+
44
+    /** @var int how much time should be between two tries (1 hour) */
45
+    private $interval = 3600;
46
+
47
+    /** @var AccountManager */
48
+    private $accountManager;
49
+
50
+    /** @var IUserManager */
51
+    private $userManager;
52
+
53
+    /** @var IClientService */
54
+    private $httpClientService;
55
+
56
+    /** @var ILogger */
57
+    private $logger;
58
+
59
+    /** @var string */
60
+    private $lookupServerUrl;
61
+
62
+    /**
63
+     * VerifyUserData constructor.
64
+     *
65
+     * @param AccountManager $accountManager
66
+     * @param IUserManager $userManager
67
+     * @param IClientService $clientService
68
+     * @param ILogger $logger
69
+     * @param IConfig $config
70
+     */
71
+    public function __construct(AccountManager $accountManager,
72
+                                IUserManager $userManager,
73
+                                IClientService $clientService,
74
+                                ILogger $logger,
75
+                                IConfig $config
76
+    ) {
77
+        $this->accountManager = $accountManager;
78
+        $this->userManager = $userManager;
79
+        $this->httpClientService = $clientService;
80
+        $this->logger = $logger;
81
+
82
+        $lookupServerUrl = $config->getSystemValue('lookup_server', 'https://lookup.nextcloud.com');
83
+        $this->lookupServerUrl = rtrim($lookupServerUrl, '/');
84
+    }
85
+
86
+    /**
87
+     * run the job, then remove it from the jobList
88
+     *
89
+     * @param JobList $jobList
90
+     * @param ILogger $logger
91
+     */
92
+    public function execute($jobList, ILogger $logger = null) {
93
+
94
+        if ($this->shouldRun($this->argument)) {
95
+            parent::execute($jobList, $logger);
96
+            $jobList->remove($this, $this->argument);
97
+            if ($this->retainJob) {
98
+                $this->reAddJob($jobList, $this->argument);
99
+            }
100
+        }
101
+
102
+    }
103
+
104
+    protected function run($argument) {
105
+
106
+        $try = (int)$argument['try'] + 1;
107
+
108
+        switch($argument['type']) {
109
+            case AccountManager::PROPERTY_WEBSITE:
110
+                $result = $this->verifyWebsite($argument);
111
+                break;
112
+            case AccountManager::PROPERTY_TWITTER:
113
+            case AccountManager::PROPERTY_EMAIL:
114
+                $result = $this->verifyViaLookupServer($argument, $argument['type']);
115
+                break;
116
+            default:
117
+                // no valid type given, no need to retry
118
+                $this->logger->error($argument['type'] . ' is no valid type for user account data.');
119
+                $result = true;
120
+        }
121
+
122
+        if ($result === true || $try > $this->maxTry) {
123
+            $this->retainJob = false;
124
+        }
125
+    }
126
+
127
+    /**
128
+     * verify web page
129
+     *
130
+     * @param array $argument
131
+     * @return bool true if we could check the verification code, otherwise false
132
+     */
133
+    protected function verifyWebsite(array $argument) {
134
+
135
+        $result = false;
136
+
137
+        $url = rtrim($argument['data'], '/') . '/well-known/' . 'CloudIdVerificationCode.txt';
138
+
139
+        $client = $this->httpClientService->newClient();
140
+        try {
141
+            $response = $client->get($url);
142
+        } catch (\Exception $e) {
143
+            return false;
144
+        }
145
+
146
+        if ($response->getStatusCode() === Http::STATUS_OK) {
147
+            $result = true;
148
+            $publishedCode = $response->getBody();
149
+            // remove new lines and spaces
150
+            $publishedCodeSanitized = trim(preg_replace('/\s\s+/', ' ', $publishedCode));
151
+            $user = $this->userManager->get($argument['uid']);
152
+            // we don't check a valid user -> give up
153
+            if ($user === null) {
154
+                $this->logger->error($argument['uid'] . ' doesn\'t exist, can\'t verify user data.');
155
+                return $result;
156
+            }
157
+            $userData = $this->accountManager->getUser($user);
158
+
159
+            if ($publishedCodeSanitized === $argument['verificationCode']) {
160
+                $userData[AccountManager::PROPERTY_WEBSITE]['verified'] = AccountManager::VERIFIED;
161
+            } else {
162
+                $userData[AccountManager::PROPERTY_WEBSITE]['verified'] = AccountManager::NOT_VERIFIED;
163
+            }
164
+
165
+            $this->accountManager->updateUser($user, $userData);
166
+        }
167
+
168
+        return $result;
169
+    }
170
+
171
+    /**
172
+     * verify email address
173
+     *
174
+     * @param array $argument
175
+     * @param string $dataType
176
+     * @return bool true if we could check the verification code, otherwise false
177
+     */
178
+    protected function verifyViaLookupServer(array $argument, $dataType) {
179
+
180
+        $user = $this->userManager->get($argument['uid']);
181
+
182
+        // we don't check a valid user -> give up
183
+        if ($user === null) {
184
+            $this->logger->error($argument['uid'] . ' doesn\'t exist, can\'t verify user data.');
185
+            return true;
186
+        }
187
+
188
+        $localUserData = $this->accountManager->getUser($user);
189
+        $cloudId = $user->getCloudId();
190
+
191
+        // ask lookup-server for user data
192
+        $lookupServerData = $this->queryLookupServer($cloudId);
193
+
194
+        // for some reasons we couldn't read any data from the lookup server, try again later
195
+        if (empty($lookupServerData)) {
196
+            return false;
197
+        }
198
+
199
+        // lookup server has verification data for wrong user data (e.g. email address), try again later
200
+        if ($lookupServerData[$dataType]['value'] !== $argument['data']) {
201
+            return false;
202
+        }
203
+
204
+        // lookup server hasn't verified the email address so far, try again later
205
+        if ($lookupServerData[$dataType]['verified'] === AccountManager::NOT_VERIFIED) {
206
+            return false;
207
+        }
208
+
209
+        $localUserData[$dataType]['verified'] = AccountManager::VERIFIED;
210
+        $this->accountManager->updateUser($user, $localUserData);
211
+
212
+        return true;
213
+    }
214
+
215
+    /**
216
+     * @param string $cloudId
217
+     * @return array
218
+     */
219
+    protected function queryLookupServer($cloudId) {
220
+        try {
221
+            $client = $this->httpClientService->newClient();
222
+            $response = $client->get(
223
+                $this->lookupServerUrl . '/users?search=' . urlencode($cloudId) . '&exactCloudId=1',
224
+                [
225
+                    'timeout' => 10,
226
+                    'connect_timeout' => 3,
227
+                ]
228
+            );
229
+
230
+            $body = json_decode($response->getBody(), true);
231
+
232
+            if ($body['federationId'] === $cloudId) {
233
+                return $body;
234
+            }
235
+
236
+        } catch (\Exception $e) {
237
+            // do nothing, we will just re-try later
238
+        }
239
+
240
+        return [];
241
+    }
242
+
243
+    /**
244
+     * re-add background job with new arguments
245
+     *
246
+     * @param IJobList $jobList
247
+     * @param array $argument
248
+     */
249
+    protected function reAddJob(IJobList $jobList, array $argument) {
250
+        $jobList->add('OC\Settings\BackgroundJobs\VerifyUserData',
251
+            [
252
+                'verificationCode' => $argument['verificationCode'],
253
+                'data' => $argument['data'],
254
+                'type' => $argument['type'],
255
+                'uid' => $argument['uid'],
256
+                'try' => (int)$argument['try'] + 1,
257
+                'lastRun' => time()
258
+            ]
259
+        );
260
+    }
261
+
262
+    /**
263
+     * test if it is time for the next run
264
+     *
265
+     * @param array $argument
266
+     * @return bool
267
+     */
268
+    protected function shouldRun(array $argument) {
269
+        $lastRun = (int)$argument['lastRun'];
270
+        return ((time() - $lastRun) > $this->interval);
271
+    }
272 272
 
273 273
 }
Please login to merge, or discard this patch.