Completed
Pull Request — master (#3869)
by Björn
93:22 queued 61:54
created
apps/lookup_server_connector/lib/UpdateLookupServer.php 1 patch
Indentation   +90 added lines, -90 removed lines patch added patch discarded remove patch
@@ -35,102 +35,102 @@
 block discarded – undo
35 35
  * @package OCA\LookupServerConnector
36 36
  */
37 37
 class UpdateLookupServer {
38
-	/** @var AccountManager */
39
-	private $accountManager;
40
-	/** @var IClientService */
41
-	private $clientService;
42
-	/** @var Signer */
43
-	private $signer;
44
-	/** @var IJobList */
45
-	private $jobList;
46
-	/** @var string URL point to lookup server */
47
-	private $lookupServer = 'https://lookup.nextcloud.com';
38
+    /** @var AccountManager */
39
+    private $accountManager;
40
+    /** @var IClientService */
41
+    private $clientService;
42
+    /** @var Signer */
43
+    private $signer;
44
+    /** @var IJobList */
45
+    private $jobList;
46
+    /** @var string URL point to lookup server */
47
+    private $lookupServer = 'https://lookup.nextcloud.com';
48 48
 
49
-	/**
50
-	 * @param AccountManager $accountManager
51
-	 * @param IClientService $clientService
52
-	 * @param Signer $signer
53
-	 * @param IJobList $jobList
54
-	 * @param string $lookupServer if nothing is given we use the default lookup server
55
-	 */
56
-	public function __construct(AccountManager $accountManager,
57
-								IClientService $clientService,
58
-								Signer $signer,
59
-								IJobList $jobList,
60
-								$lookupServer = '') {
61
-		$this->accountManager = $accountManager;
62
-		$this->clientService = $clientService;
63
-		$this->signer = $signer;
64
-		$this->jobList = $jobList;
65
-		if ($lookupServer !== '') {
66
-			$this->lookupServer = $lookupServer;
67
-		}
68
-		$this->lookupServer = rtrim($this->lookupServer, '/');
69
-		$this->lookupServer .= '/users';
70
-	}
49
+    /**
50
+     * @param AccountManager $accountManager
51
+     * @param IClientService $clientService
52
+     * @param Signer $signer
53
+     * @param IJobList $jobList
54
+     * @param string $lookupServer if nothing is given we use the default lookup server
55
+     */
56
+    public function __construct(AccountManager $accountManager,
57
+                                IClientService $clientService,
58
+                                Signer $signer,
59
+                                IJobList $jobList,
60
+                                $lookupServer = '') {
61
+        $this->accountManager = $accountManager;
62
+        $this->clientService = $clientService;
63
+        $this->signer = $signer;
64
+        $this->jobList = $jobList;
65
+        if ($lookupServer !== '') {
66
+            $this->lookupServer = $lookupServer;
67
+        }
68
+        $this->lookupServer = rtrim($this->lookupServer, '/');
69
+        $this->lookupServer .= '/users';
70
+    }
71 71
 
72
-	/**
73
-	 * @param IUser $user
74
-	 */
75
-	public function userUpdated(IUser $user) {
76
-		$userData = $this->accountManager->getUser($user);
77
-		$publicData = [];
72
+    /**
73
+     * @param IUser $user
74
+     */
75
+    public function userUpdated(IUser $user) {
76
+        $userData = $this->accountManager->getUser($user);
77
+        $publicData = [];
78 78
 
79
-		foreach ($userData as $key => $data) {
80
-			if ($data['scope'] === AccountManager::VISIBILITY_PUBLIC) {
81
-				$publicData[$key] = $data;
82
-			}
83
-		}
79
+        foreach ($userData as $key => $data) {
80
+            if ($data['scope'] === AccountManager::VISIBILITY_PUBLIC) {
81
+                $publicData[$key] = $data;
82
+            }
83
+        }
84 84
 
85
-		$this->sendToLookupServer($user, $publicData);
86
-	}
85
+        $this->sendToLookupServer($user, $publicData);
86
+    }
87 87
 
88
-	/**
89
-	 * send public user data to the lookup server
90
-	 *
91
-	 * @param IUser $user
92
-	 * @param array $publicData
93
-	 */
94
-	protected function sendToLookupServer(IUser $user, array $publicData) {
88
+    /**
89
+     * send public user data to the lookup server
90
+     *
91
+     * @param IUser $user
92
+     * @param array $publicData
93
+     */
94
+    protected function sendToLookupServer(IUser $user, array $publicData) {
95 95
 
96
-		$dataArray = ['federationId' => $user->getCloudId()];
96
+        $dataArray = ['federationId' => $user->getCloudId()];
97 97
 
98
-		if (!empty($publicData)) {
99
-			$dataArray['name'] = isset($publicData[AccountManager::PROPERTY_DISPLAYNAME]) ? $publicData[AccountManager::PROPERTY_DISPLAYNAME]['value'] : '';
100
-			$dataArray['email'] = isset($publicData[AccountManager::PROPERTY_EMAIL]) ? $publicData[AccountManager::PROPERTY_EMAIL]['value'] : '';
101
-			$dataArray['address'] = isset($publicData[AccountManager::PROPERTY_ADDRESS]) ? $publicData[AccountManager::PROPERTY_ADDRESS]['value'] : '';
102
-			$dataArray['website'] = isset($publicData[AccountManager::PROPERTY_WEBSITE]) ? $publicData[AccountManager::PROPERTY_WEBSITE]['value'] : '';
103
-			$dataArray['twitter'] = isset($publicData[AccountManager::PROPERTY_TWITTER]) ? $publicData[AccountManager::PROPERTY_TWITTER]['value'] : '';
104
-			$dataArray['phone'] = isset($publicData[AccountManager::PROPERTY_PHONE]) ? $publicData[AccountManager::PROPERTY_PHONE]['value'] : '';
105
-		}
98
+        if (!empty($publicData)) {
99
+            $dataArray['name'] = isset($publicData[AccountManager::PROPERTY_DISPLAYNAME]) ? $publicData[AccountManager::PROPERTY_DISPLAYNAME]['value'] : '';
100
+            $dataArray['email'] = isset($publicData[AccountManager::PROPERTY_EMAIL]) ? $publicData[AccountManager::PROPERTY_EMAIL]['value'] : '';
101
+            $dataArray['address'] = isset($publicData[AccountManager::PROPERTY_ADDRESS]) ? $publicData[AccountManager::PROPERTY_ADDRESS]['value'] : '';
102
+            $dataArray['website'] = isset($publicData[AccountManager::PROPERTY_WEBSITE]) ? $publicData[AccountManager::PROPERTY_WEBSITE]['value'] : '';
103
+            $dataArray['twitter'] = isset($publicData[AccountManager::PROPERTY_TWITTER]) ? $publicData[AccountManager::PROPERTY_TWITTER]['value'] : '';
104
+            $dataArray['phone'] = isset($publicData[AccountManager::PROPERTY_PHONE]) ? $publicData[AccountManager::PROPERTY_PHONE]['value'] : '';
105
+        }
106 106
 
107
-		$dataArray = $this->signer->sign('lookupserver', $dataArray, $user);
108
-		$httpClient = $this->clientService->newClient();
109
-		try {
110
-			if (empty($publicData)) {
111
-				$httpClient->delete($this->lookupServer,
112
-					[
113
-						'body' => json_encode($dataArray),
114
-						'timeout' => 10,
115
-						'connect_timeout' => 3,
116
-					]
117
-				);
118
-			} else {
119
-				$httpClient->post($this->lookupServer,
120
-					[
121
-						'body' => json_encode($dataArray),
122
-						'timeout' => 10,
123
-						'connect_timeout' => 3,
124
-					]
125
-				);
126
-			}
127
-		} catch (\Exception $e) {
128
-			$this->jobList->add(RetryJob::class,
129
-				[
130
-					'dataArray' => $dataArray,
131
-					'retryNo' => 0,
132
-				]
133
-			);
134
-		}
135
-	}
107
+        $dataArray = $this->signer->sign('lookupserver', $dataArray, $user);
108
+        $httpClient = $this->clientService->newClient();
109
+        try {
110
+            if (empty($publicData)) {
111
+                $httpClient->delete($this->lookupServer,
112
+                    [
113
+                        'body' => json_encode($dataArray),
114
+                        'timeout' => 10,
115
+                        'connect_timeout' => 3,
116
+                    ]
117
+                );
118
+            } else {
119
+                $httpClient->post($this->lookupServer,
120
+                    [
121
+                        'body' => json_encode($dataArray),
122
+                        'timeout' => 10,
123
+                        'connect_timeout' => 3,
124
+                    ]
125
+                );
126
+            }
127
+        } catch (\Exception $e) {
128
+            $this->jobList->add(RetryJob::class,
129
+                [
130
+                    'dataArray' => $dataArray,
131
+                    'retryNo' => 0,
132
+                ]
133
+            );
134
+        }
135
+    }
136 136
 }
Please login to merge, or discard this patch.
apps/lookup_server_connector/appinfo/app.php 1 patch
Indentation   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -22,26 +22,26 @@
 block discarded – undo
22 22
 $dispatcher = \OC::$server->getEventDispatcher();
23 23
 
24 24
 $dispatcher->addListener('OC\AccountManager::userUpdated', function(\Symfony\Component\EventDispatcher\GenericEvent $event) {
25
-	$user = $event->getSubject();
25
+    $user = $event->getSubject();
26 26
 
27
-	$keyManager = new \OC\Security\IdentityProof\Manager(
28
-		\OC::$server->getAppDataDir('identityproof'),
29
-		\OC::$server->getCrypto()
30
-	);
27
+    $keyManager = new \OC\Security\IdentityProof\Manager(
28
+        \OC::$server->getAppDataDir('identityproof'),
29
+        \OC::$server->getCrypto()
30
+    );
31 31
 
32
-	$config = \OC::$server->getConfig();
33
-	$lookupServer = $config->getSystemValue('lookup_server', '');
32
+    $config = \OC::$server->getConfig();
33
+    $lookupServer = $config->getSystemValue('lookup_server', '');
34 34
 
35
-	$updateLookupServer = new \OCA\LookupServerConnector\UpdateLookupServer(
36
-		new \OC\Accounts\AccountManager(\OC::$server->getDatabaseConnection(), \OC::$server->getEventDispatcher()),
37
-		\OC::$server->getHTTPClientService(),
38
-		new \OC\Security\IdentityProof\Signer(
39
-			$keyManager,
40
-			new \OC\AppFramework\Utility\TimeFactory(),
41
-			\OC::$server->getUserManager()
42
-		),
43
-		\OC::$server->getJobList(),
44
-		$lookupServer
45
-	);
46
-	$updateLookupServer->userUpdated($user);
35
+    $updateLookupServer = new \OCA\LookupServerConnector\UpdateLookupServer(
36
+        new \OC\Accounts\AccountManager(\OC::$server->getDatabaseConnection(), \OC::$server->getEventDispatcher()),
37
+        \OC::$server->getHTTPClientService(),
38
+        new \OC\Security\IdentityProof\Signer(
39
+            $keyManager,
40
+            new \OC\AppFramework\Utility\TimeFactory(),
41
+            \OC::$server->getUserManager()
42
+        ),
43
+        \OC::$server->getJobList(),
44
+        $lookupServer
45
+    );
46
+    $updateLookupServer->userUpdated($user);
47 47
 });
Please login to merge, or discard this patch.
lib/private/Accounts/AccountManager.php 2 patches
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -141,19 +141,19 @@
 block discarded – undo
141 141
 		$websiteVerified = isset($oldData[self::PROPERTY_WEBSITE]['verified']) && $oldData[self::PROPERTY_WEBSITE]['verified'] === self::VERIFIED;
142 142
 		$emailVerified = isset($oldData[self::PROPERTY_EMAIL]['verified']) && $oldData[self::PROPERTY_EMAIL]['verified'] === self::VERIFIED;
143 143
 
144
-		if($twitterVerified &&
144
+		if ($twitterVerified &&
145 145
 			$oldData[self::PROPERTY_TWITTER]['value'] !== $newData[self::PROPERTY_TWITTER]['value']
146 146
 		) {
147 147
 			$newData[self::PROPERTY_TWITTER]['value']['verified'] = self::NOT_VERIFIED;
148 148
 		}
149 149
 
150
-		if($websiteVerified &&
150
+		if ($websiteVerified &&
151 151
 			$oldData[self::PROPERTY_WEBSITE]['value'] !== $newData[self::PROPERTY_WEBSITE]['value']
152 152
 		) {
153 153
 			$newData[self::PROPERTY_WEBSITE]['value']['verified'] = self::NOT_VERIFIED;
154 154
 		}
155 155
 
156
-		if($emailVerified &&
156
+		if ($emailVerified &&
157 157
 			$oldData[self::PROPERTY_EMAIL]['value'] !== $newData[self::PROPERTY_EMAIL]['value']
158 158
 		) {
159 159
 			$newData[self::PROPERTY_EMAIL]['value']['verified'] = self::NOT_VERIFIED;
Please login to merge, or discard this patch.
Indentation   +211 added lines, -211 removed lines patch added patch discarded remove patch
@@ -38,216 +38,216 @@
 block discarded – undo
38 38
  */
39 39
 class AccountManager {
40 40
 
41
-	/** nobody can see my account details */
42
-	const VISIBILITY_PRIVATE = 'private';
43
-	/** only contacts, especially trusted servers can see my contact details */
44
-	const VISIBILITY_CONTACTS_ONLY = 'contacts';
45
-	/** every body ca see my contact detail, will be published to the lookup server */
46
-	const VISIBILITY_PUBLIC = 'public';
47
-
48
-	const PROPERTY_AVATAR = 'avatar';
49
-	const PROPERTY_DISPLAYNAME = 'displayname';
50
-	const PROPERTY_PHONE = 'phone';
51
-	const PROPERTY_EMAIL = 'email';
52
-	const PROPERTY_WEBSITE = 'website';
53
-	const PROPERTY_ADDRESS = 'address';
54
-	const PROPERTY_TWITTER = 'twitter';
55
-
56
-	const NOT_VERIFIED = '0';
57
-	const VERIFICATION_IN_PROGRESS = '1';
58
-	const VERIFIED = '2';
59
-
60
-	/** @var  IDBConnection database connection */
61
-	private $connection;
62
-
63
-	/** @var string table name */
64
-	private $table = 'accounts';
65
-
66
-	/** @var EventDispatcherInterface */
67
-	private $eventDispatcher;
68
-
69
-	/**
70
-	 * AccountManager constructor.
71
-	 *
72
-	 * @param IDBConnection $connection
73
-	 * @param EventDispatcherInterface $eventDispatcher
74
-	 */
75
-	public function __construct(IDBConnection $connection, EventDispatcherInterface $eventDispatcher) {
76
-		$this->connection = $connection;
77
-		$this->eventDispatcher = $eventDispatcher;
78
-	}
79
-
80
-	/**
81
-	 * update user record
82
-	 *
83
-	 * @param IUser $user
84
-	 * @param $data
85
-	 */
86
-	public function updateUser(IUser $user, $data) {
87
-		$userData = $this->getUser($user);
88
-		$updated = true;
89
-		if (empty($userData)) {
90
-			$this->insertNewUser($user, $data);
91
-		} elseif ($userData !== $data) {
92
-			$data = $this->updateVerifyStatus($userData, $data);
93
-			$this->updateExistingUser($user, $data);
94
-		} else {
95
-			// nothing needs to be done if new and old data set are the same
96
-			$updated = false;
97
-		}
98
-
99
-		if ($updated) {
100
-			$this->eventDispatcher->dispatch(
101
-				'OC\AccountManager::userUpdated',
102
-				new GenericEvent($user, $data)
103
-			);
104
-		}
105
-	}
106
-
107
-	/**
108
-	 * get stored data from a given user
109
-	 *
110
-	 * @param IUser $user
111
-	 * @return array
112
-	 */
113
-	public function getUser(IUser $user) {
114
-		$uid = $user->getUID();
115
-		$query = $this->connection->getQueryBuilder();
116
-		$query->select('data')->from($this->table)
117
-			->where($query->expr()->eq('uid', $query->createParameter('uid')))
118
-			->setParameter('uid', $uid);
119
-		$query->execute();
120
-		$result = $query->execute()->fetchAll();
121
-
122
-		if (empty($result)) {
123
-			$userData = $this->buildDefaultUserRecord($user);
124
-			$this->insertNewUser($user, $userData);
125
-			return $userData;
126
-		}
127
-
128
-		return json_decode($result[0]['data'], true);
129
-	}
130
-
131
-	/**
132
-	 * reset verification status if personal data changed
133
-	 *
134
-	 * @param array $oldData
135
-	 * @param array $newData
136
-	 * @return array
137
-	 */
138
-	protected function updateVerifyStatus($oldData, $newData) {
139
-
140
-		$twitterVerified = isset($oldData[self::PROPERTY_TWITTER]['verified']) && $oldData[self::PROPERTY_TWITTER]['verified'] === self::VERIFIED;
141
-		$websiteVerified = isset($oldData[self::PROPERTY_WEBSITE]['verified']) && $oldData[self::PROPERTY_WEBSITE]['verified'] === self::VERIFIED;
142
-		$emailVerified = isset($oldData[self::PROPERTY_EMAIL]['verified']) && $oldData[self::PROPERTY_EMAIL]['verified'] === self::VERIFIED;
143
-
144
-		if($twitterVerified &&
145
-			$oldData[self::PROPERTY_TWITTER]['value'] !== $newData[self::PROPERTY_TWITTER]['value']
146
-		) {
147
-			$newData[self::PROPERTY_TWITTER]['value']['verified'] = self::NOT_VERIFIED;
148
-		}
149
-
150
-		if($websiteVerified &&
151
-			$oldData[self::PROPERTY_WEBSITE]['value'] !== $newData[self::PROPERTY_WEBSITE]['value']
152
-		) {
153
-			$newData[self::PROPERTY_WEBSITE]['value']['verified'] = self::NOT_VERIFIED;
154
-		}
155
-
156
-		if($emailVerified &&
157
-			$oldData[self::PROPERTY_EMAIL]['value'] !== $newData[self::PROPERTY_EMAIL]['value']
158
-		) {
159
-			$newData[self::PROPERTY_EMAIL]['value']['verified'] = self::NOT_VERIFIED;
160
-		}
161
-
162
-		return $newData;
163
-
164
-	}
165
-
166
-	/**
167
-	 * add new user to accounts table
168
-	 *
169
-	 * @param IUser $user
170
-	 * @param array $data
171
-	 */
172
-	protected function insertNewUser(IUser $user, $data) {
173
-		$uid = $user->getUID();
174
-		$jsonEncodedData = json_encode($data);
175
-		$query = $this->connection->getQueryBuilder();
176
-		$query->insert($this->table)
177
-			->values(
178
-				[
179
-					'uid' => $query->createNamedParameter($uid),
180
-					'data' => $query->createNamedParameter($jsonEncodedData),
181
-				]
182
-			)
183
-			->execute();
184
-	}
185
-
186
-	/**
187
-	 * update existing user in accounts table
188
-	 *
189
-	 * @param IUser $user
190
-	 * @param array $data
191
-	 */
192
-	protected function updateExistingUser(IUser $user, $data) {
193
-		$uid = $user->getUID();
194
-		$jsonEncodedData = json_encode($data);
195
-		$query = $this->connection->getQueryBuilder();
196
-		$query->update($this->table)
197
-			->set('data', $query->createNamedParameter($jsonEncodedData))
198
-			->where($query->expr()->eq('uid', $query->createNamedParameter($uid)))
199
-			->execute();
200
-	}
201
-
202
-	/**
203
-	 * build default user record in case not data set exists yet
204
-	 *
205
-	 * @param IUser $user
206
-	 * @return array
207
-	 */
208
-	protected function buildDefaultUserRecord(IUser $user) {
209
-		return [
210
-			self::PROPERTY_DISPLAYNAME =>
211
-				[
212
-					'value' => $user->getDisplayName(),
213
-					'scope' => self::VISIBILITY_CONTACTS_ONLY,
214
-					'verified' => '0',
215
-				],
216
-			self::PROPERTY_ADDRESS =>
217
-				[
218
-					'value' => '',
219
-					'scope' => self::VISIBILITY_PRIVATE,
220
-					'verified' => '0',
221
-				],
222
-			self::PROPERTY_WEBSITE =>
223
-				[
224
-					'value' => '',
225
-					'scope' => self::VISIBILITY_PRIVATE,
226
-					'verified' => '0',
227
-				],
228
-			self::PROPERTY_EMAIL =>
229
-				[
230
-					'value' => $user->getEMailAddress(),
231
-					'scope' => self::VISIBILITY_CONTACTS_ONLY,
232
-					'verified' => '0',
233
-				],
234
-			self::PROPERTY_AVATAR =>
235
-				[
236
-					'scope' => self::VISIBILITY_CONTACTS_ONLY
237
-				],
238
-			self::PROPERTY_PHONE =>
239
-				[
240
-					'value' => '',
241
-					'scope' => self::VISIBILITY_PRIVATE,
242
-					'verified' => '0',
243
-				],
244
-			self::PROPERTY_TWITTER =>
245
-				[
246
-					'value' => '',
247
-					'scope' => self::VISIBILITY_PRIVATE,
248
-					'verified' => '0',
249
-				],
250
-		];
251
-	}
41
+    /** nobody can see my account details */
42
+    const VISIBILITY_PRIVATE = 'private';
43
+    /** only contacts, especially trusted servers can see my contact details */
44
+    const VISIBILITY_CONTACTS_ONLY = 'contacts';
45
+    /** every body ca see my contact detail, will be published to the lookup server */
46
+    const VISIBILITY_PUBLIC = 'public';
47
+
48
+    const PROPERTY_AVATAR = 'avatar';
49
+    const PROPERTY_DISPLAYNAME = 'displayname';
50
+    const PROPERTY_PHONE = 'phone';
51
+    const PROPERTY_EMAIL = 'email';
52
+    const PROPERTY_WEBSITE = 'website';
53
+    const PROPERTY_ADDRESS = 'address';
54
+    const PROPERTY_TWITTER = 'twitter';
55
+
56
+    const NOT_VERIFIED = '0';
57
+    const VERIFICATION_IN_PROGRESS = '1';
58
+    const VERIFIED = '2';
59
+
60
+    /** @var  IDBConnection database connection */
61
+    private $connection;
62
+
63
+    /** @var string table name */
64
+    private $table = 'accounts';
65
+
66
+    /** @var EventDispatcherInterface */
67
+    private $eventDispatcher;
68
+
69
+    /**
70
+     * AccountManager constructor.
71
+     *
72
+     * @param IDBConnection $connection
73
+     * @param EventDispatcherInterface $eventDispatcher
74
+     */
75
+    public function __construct(IDBConnection $connection, EventDispatcherInterface $eventDispatcher) {
76
+        $this->connection = $connection;
77
+        $this->eventDispatcher = $eventDispatcher;
78
+    }
79
+
80
+    /**
81
+     * update user record
82
+     *
83
+     * @param IUser $user
84
+     * @param $data
85
+     */
86
+    public function updateUser(IUser $user, $data) {
87
+        $userData = $this->getUser($user);
88
+        $updated = true;
89
+        if (empty($userData)) {
90
+            $this->insertNewUser($user, $data);
91
+        } elseif ($userData !== $data) {
92
+            $data = $this->updateVerifyStatus($userData, $data);
93
+            $this->updateExistingUser($user, $data);
94
+        } else {
95
+            // nothing needs to be done if new and old data set are the same
96
+            $updated = false;
97
+        }
98
+
99
+        if ($updated) {
100
+            $this->eventDispatcher->dispatch(
101
+                'OC\AccountManager::userUpdated',
102
+                new GenericEvent($user, $data)
103
+            );
104
+        }
105
+    }
106
+
107
+    /**
108
+     * get stored data from a given user
109
+     *
110
+     * @param IUser $user
111
+     * @return array
112
+     */
113
+    public function getUser(IUser $user) {
114
+        $uid = $user->getUID();
115
+        $query = $this->connection->getQueryBuilder();
116
+        $query->select('data')->from($this->table)
117
+            ->where($query->expr()->eq('uid', $query->createParameter('uid')))
118
+            ->setParameter('uid', $uid);
119
+        $query->execute();
120
+        $result = $query->execute()->fetchAll();
121
+
122
+        if (empty($result)) {
123
+            $userData = $this->buildDefaultUserRecord($user);
124
+            $this->insertNewUser($user, $userData);
125
+            return $userData;
126
+        }
127
+
128
+        return json_decode($result[0]['data'], true);
129
+    }
130
+
131
+    /**
132
+     * reset verification status if personal data changed
133
+     *
134
+     * @param array $oldData
135
+     * @param array $newData
136
+     * @return array
137
+     */
138
+    protected function updateVerifyStatus($oldData, $newData) {
139
+
140
+        $twitterVerified = isset($oldData[self::PROPERTY_TWITTER]['verified']) && $oldData[self::PROPERTY_TWITTER]['verified'] === self::VERIFIED;
141
+        $websiteVerified = isset($oldData[self::PROPERTY_WEBSITE]['verified']) && $oldData[self::PROPERTY_WEBSITE]['verified'] === self::VERIFIED;
142
+        $emailVerified = isset($oldData[self::PROPERTY_EMAIL]['verified']) && $oldData[self::PROPERTY_EMAIL]['verified'] === self::VERIFIED;
143
+
144
+        if($twitterVerified &&
145
+            $oldData[self::PROPERTY_TWITTER]['value'] !== $newData[self::PROPERTY_TWITTER]['value']
146
+        ) {
147
+            $newData[self::PROPERTY_TWITTER]['value']['verified'] = self::NOT_VERIFIED;
148
+        }
149
+
150
+        if($websiteVerified &&
151
+            $oldData[self::PROPERTY_WEBSITE]['value'] !== $newData[self::PROPERTY_WEBSITE]['value']
152
+        ) {
153
+            $newData[self::PROPERTY_WEBSITE]['value']['verified'] = self::NOT_VERIFIED;
154
+        }
155
+
156
+        if($emailVerified &&
157
+            $oldData[self::PROPERTY_EMAIL]['value'] !== $newData[self::PROPERTY_EMAIL]['value']
158
+        ) {
159
+            $newData[self::PROPERTY_EMAIL]['value']['verified'] = self::NOT_VERIFIED;
160
+        }
161
+
162
+        return $newData;
163
+
164
+    }
165
+
166
+    /**
167
+     * add new user to accounts table
168
+     *
169
+     * @param IUser $user
170
+     * @param array $data
171
+     */
172
+    protected function insertNewUser(IUser $user, $data) {
173
+        $uid = $user->getUID();
174
+        $jsonEncodedData = json_encode($data);
175
+        $query = $this->connection->getQueryBuilder();
176
+        $query->insert($this->table)
177
+            ->values(
178
+                [
179
+                    'uid' => $query->createNamedParameter($uid),
180
+                    'data' => $query->createNamedParameter($jsonEncodedData),
181
+                ]
182
+            )
183
+            ->execute();
184
+    }
185
+
186
+    /**
187
+     * update existing user in accounts table
188
+     *
189
+     * @param IUser $user
190
+     * @param array $data
191
+     */
192
+    protected function updateExistingUser(IUser $user, $data) {
193
+        $uid = $user->getUID();
194
+        $jsonEncodedData = json_encode($data);
195
+        $query = $this->connection->getQueryBuilder();
196
+        $query->update($this->table)
197
+            ->set('data', $query->createNamedParameter($jsonEncodedData))
198
+            ->where($query->expr()->eq('uid', $query->createNamedParameter($uid)))
199
+            ->execute();
200
+    }
201
+
202
+    /**
203
+     * build default user record in case not data set exists yet
204
+     *
205
+     * @param IUser $user
206
+     * @return array
207
+     */
208
+    protected function buildDefaultUserRecord(IUser $user) {
209
+        return [
210
+            self::PROPERTY_DISPLAYNAME =>
211
+                [
212
+                    'value' => $user->getDisplayName(),
213
+                    'scope' => self::VISIBILITY_CONTACTS_ONLY,
214
+                    'verified' => '0',
215
+                ],
216
+            self::PROPERTY_ADDRESS =>
217
+                [
218
+                    'value' => '',
219
+                    'scope' => self::VISIBILITY_PRIVATE,
220
+                    'verified' => '0',
221
+                ],
222
+            self::PROPERTY_WEBSITE =>
223
+                [
224
+                    'value' => '',
225
+                    'scope' => self::VISIBILITY_PRIVATE,
226
+                    'verified' => '0',
227
+                ],
228
+            self::PROPERTY_EMAIL =>
229
+                [
230
+                    'value' => $user->getEMailAddress(),
231
+                    'scope' => self::VISIBILITY_CONTACTS_ONLY,
232
+                    'verified' => '0',
233
+                ],
234
+            self::PROPERTY_AVATAR =>
235
+                [
236
+                    'scope' => self::VISIBILITY_CONTACTS_ONLY
237
+                ],
238
+            self::PROPERTY_PHONE =>
239
+                [
240
+                    'value' => '',
241
+                    'scope' => self::VISIBILITY_PRIVATE,
242
+                    'verified' => '0',
243
+                ],
244
+            self::PROPERTY_TWITTER =>
245
+                [
246
+                    'value' => '',
247
+                    'scope' => self::VISIBILITY_PRIVATE,
248
+                    'verified' => '0',
249
+                ],
250
+        ];
251
+    }
252 252
 
253 253
 }
Please login to merge, or discard this patch.
settings/routes.php 1 patch
Indentation   +52 added lines, -52 removed lines patch added patch discarded remove patch
@@ -36,77 +36,77 @@
 block discarded – undo
36 36
 
37 37
 $application = new Application();
38 38
 $application->registerRoutes($this, [
39
-	'resources' => [
40
-		'users' => ['url' => '/settings/users/users'],
41
-		'AuthSettings' => ['url' => '/settings/personal/authtokens'],
42
-	],
43
-	'routes' => [
44
-		['name' => 'MailSettings#setMailSettings', 'url' => '/settings/admin/mailsettings', 'verb' => 'POST'],
45
-		['name' => 'MailSettings#storeCredentials', 'url' => '/settings/admin/mailsettings/credentials', 'verb' => 'POST'],
46
-		['name' => 'MailSettings#sendTestMail', 'url' => '/settings/admin/mailtest', 'verb' => 'POST'],
47
-		['name' => 'Encryption#startMigration', 'url' => '/settings/admin/startmigration', 'verb' => 'POST'],
48
-		['name' => 'AppSettings#listCategories', 'url' => '/settings/apps/categories', 'verb' => 'GET'],
49
-		['name' => 'AppSettings#viewApps', 'url' => '/settings/apps', 'verb' => 'GET'],
50
-		['name' => 'AppSettings#listApps', 'url' => '/settings/apps/list', 'verb' => 'GET'],
51
-		['name' => 'SecuritySettings#trustedDomains', 'url' => '/settings/admin/security/trustedDomains', 'verb' => 'POST'],
52
-		['name' => 'Users#setDisplayName', 'url' => '/settings/users/{username}/displayName', 'verb' => 'POST'],
53
-		['name' => 'Users#setEMailAddress', 'url' => '/settings/users/{id}/mailAddress', 'verb' => 'PUT'],
54
-		['name' => 'Users#setUserSettings', 'url' => '/settings/users/{username}/settings', 'verb' => 'PUT'],
55
-		['name' => 'Users#getVerificationCode', 'url' => '/settings/users/{account}/verify', 'verb' => 'GET'],
56
-		['name' => 'Users#stats', 'url' => '/settings/users/stats', 'verb' => 'GET'],
57
-		['name' => 'LogSettings#setLogLevel', 'url' => '/settings/admin/log/level', 'verb' => 'POST'],
58
-		['name' => 'LogSettings#getEntries', 'url' => '/settings/admin/log/entries', 'verb' => 'GET'],
59
-		['name' => 'LogSettings#download', 'url' => '/settings/admin/log/download', 'verb' => 'GET'],
60
-		['name' => 'CheckSetup#check', 'url' => '/settings/ajax/checksetup', 'verb' => 'GET'],
61
-		['name' => 'CheckSetup#getFailedIntegrityCheckFiles', 'url' => '/settings/integrity/failed', 'verb' => 'GET'],
62
-		['name' => 'CheckSetup#rescanFailedIntegrityCheck', 'url' => '/settings/integrity/rescan', 'verb' => 'GET'],
63
-		['name' => 'Certificate#addPersonalRootCertificate', 'url' => '/settings/personal/certificate', 'verb' => 'POST'],
64
-		['name' => 'Certificate#removePersonalRootCertificate', 'url' => '/settings/personal/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
65
-		['name' => 'Certificate#addSystemRootCertificate', 'url' => '/settings/admin/certificate', 'verb' => 'POST'],
66
-		['name' => 'Certificate#removeSystemRootCertificate', 'url' => '/settings/admin/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
67
-		['name' => 'AdminSettings#index', 'url' => '/settings/admin/{section}', 'verb' => 'GET', 'defaults' => ['section' => 'server']],
68
-		['name' => 'AdminSettings#form', 'url' => '/settings/admin/{section}', 'verb' => 'GET'],
69
-		['name' => 'ChangePassword#changePersonalPassword', 'url' => '/settings/personal/changepassword', 'verb' => 'POST'],
70
-		['name' => 'ChangePassword#changeUserPassword', 'url' => '/settings/users/changepassword', 'verb' => 'POST'],
71
-		['name' => 'Personal#setLanguage', 'url' => '/settings/ajax/setlanguage.php', 'verb' => 'POST'],
72
-		['name' => 'Groups#index', 'url' => '/settings/users/groups', 'verb' => 'GET'],
73
-		['name' => 'Groups#show', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'GET'],
74
-		['name' => 'Groups#create', 'url' => '/settings/users/groups', 'verb' => 'POST'],
75
-		['name' => 'Groups#update', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'PUT'],
76
-		['name' => 'Groups#destroy', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'DELETE'],
77
-	]
39
+    'resources' => [
40
+        'users' => ['url' => '/settings/users/users'],
41
+        'AuthSettings' => ['url' => '/settings/personal/authtokens'],
42
+    ],
43
+    'routes' => [
44
+        ['name' => 'MailSettings#setMailSettings', 'url' => '/settings/admin/mailsettings', 'verb' => 'POST'],
45
+        ['name' => 'MailSettings#storeCredentials', 'url' => '/settings/admin/mailsettings/credentials', 'verb' => 'POST'],
46
+        ['name' => 'MailSettings#sendTestMail', 'url' => '/settings/admin/mailtest', 'verb' => 'POST'],
47
+        ['name' => 'Encryption#startMigration', 'url' => '/settings/admin/startmigration', 'verb' => 'POST'],
48
+        ['name' => 'AppSettings#listCategories', 'url' => '/settings/apps/categories', 'verb' => 'GET'],
49
+        ['name' => 'AppSettings#viewApps', 'url' => '/settings/apps', 'verb' => 'GET'],
50
+        ['name' => 'AppSettings#listApps', 'url' => '/settings/apps/list', 'verb' => 'GET'],
51
+        ['name' => 'SecuritySettings#trustedDomains', 'url' => '/settings/admin/security/trustedDomains', 'verb' => 'POST'],
52
+        ['name' => 'Users#setDisplayName', 'url' => '/settings/users/{username}/displayName', 'verb' => 'POST'],
53
+        ['name' => 'Users#setEMailAddress', 'url' => '/settings/users/{id}/mailAddress', 'verb' => 'PUT'],
54
+        ['name' => 'Users#setUserSettings', 'url' => '/settings/users/{username}/settings', 'verb' => 'PUT'],
55
+        ['name' => 'Users#getVerificationCode', 'url' => '/settings/users/{account}/verify', 'verb' => 'GET'],
56
+        ['name' => 'Users#stats', 'url' => '/settings/users/stats', 'verb' => 'GET'],
57
+        ['name' => 'LogSettings#setLogLevel', 'url' => '/settings/admin/log/level', 'verb' => 'POST'],
58
+        ['name' => 'LogSettings#getEntries', 'url' => '/settings/admin/log/entries', 'verb' => 'GET'],
59
+        ['name' => 'LogSettings#download', 'url' => '/settings/admin/log/download', 'verb' => 'GET'],
60
+        ['name' => 'CheckSetup#check', 'url' => '/settings/ajax/checksetup', 'verb' => 'GET'],
61
+        ['name' => 'CheckSetup#getFailedIntegrityCheckFiles', 'url' => '/settings/integrity/failed', 'verb' => 'GET'],
62
+        ['name' => 'CheckSetup#rescanFailedIntegrityCheck', 'url' => '/settings/integrity/rescan', 'verb' => 'GET'],
63
+        ['name' => 'Certificate#addPersonalRootCertificate', 'url' => '/settings/personal/certificate', 'verb' => 'POST'],
64
+        ['name' => 'Certificate#removePersonalRootCertificate', 'url' => '/settings/personal/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
65
+        ['name' => 'Certificate#addSystemRootCertificate', 'url' => '/settings/admin/certificate', 'verb' => 'POST'],
66
+        ['name' => 'Certificate#removeSystemRootCertificate', 'url' => '/settings/admin/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
67
+        ['name' => 'AdminSettings#index', 'url' => '/settings/admin/{section}', 'verb' => 'GET', 'defaults' => ['section' => 'server']],
68
+        ['name' => 'AdminSettings#form', 'url' => '/settings/admin/{section}', 'verb' => 'GET'],
69
+        ['name' => 'ChangePassword#changePersonalPassword', 'url' => '/settings/personal/changepassword', 'verb' => 'POST'],
70
+        ['name' => 'ChangePassword#changeUserPassword', 'url' => '/settings/users/changepassword', 'verb' => 'POST'],
71
+        ['name' => 'Personal#setLanguage', 'url' => '/settings/ajax/setlanguage.php', 'verb' => 'POST'],
72
+        ['name' => 'Groups#index', 'url' => '/settings/users/groups', 'verb' => 'GET'],
73
+        ['name' => 'Groups#show', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'GET'],
74
+        ['name' => 'Groups#create', 'url' => '/settings/users/groups', 'verb' => 'POST'],
75
+        ['name' => 'Groups#update', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'PUT'],
76
+        ['name' => 'Groups#destroy', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'DELETE'],
77
+    ]
78 78
 ]);
79 79
 
80 80
 /** @var $this \OCP\Route\IRouter */
81 81
 
82 82
 // Settings pages
83 83
 $this->create('settings_help', '/settings/help')
84
-	->actionInclude('settings/help.php');
84
+    ->actionInclude('settings/help.php');
85 85
 $this->create('settings_personal', '/settings/personal')
86
-	->actionInclude('settings/personal.php');
86
+    ->actionInclude('settings/personal.php');
87 87
 $this->create('settings_users', '/settings/users')
88
-	->actionInclude('settings/users.php');
88
+    ->actionInclude('settings/users.php');
89 89
 // Settings ajax actions
90 90
 // users
91 91
 $this->create('settings_ajax_setquota', '/settings/ajax/setquota.php')
92
-	->actionInclude('settings/ajax/setquota.php');
92
+    ->actionInclude('settings/ajax/setquota.php');
93 93
 $this->create('settings_ajax_togglegroups', '/settings/ajax/togglegroups.php')
94
-	->actionInclude('settings/ajax/togglegroups.php');
94
+    ->actionInclude('settings/ajax/togglegroups.php');
95 95
 $this->create('settings_ajax_togglesubadmins', '/settings/ajax/togglesubadmins.php')
96
-	->actionInclude('settings/ajax/togglesubadmins.php');
96
+    ->actionInclude('settings/ajax/togglesubadmins.php');
97 97
 $this->create('settings_ajax_changegorupname', '/settings/ajax/changegroupname.php')
98
-	->actionInclude('settings/ajax/changegroupname.php');
98
+    ->actionInclude('settings/ajax/changegroupname.php');
99 99
 // apps
100 100
 $this->create('settings_ajax_enableapp', '/settings/ajax/enableapp.php')
101
-	->actionInclude('settings/ajax/enableapp.php');
101
+    ->actionInclude('settings/ajax/enableapp.php');
102 102
 $this->create('settings_ajax_disableapp', '/settings/ajax/disableapp.php')
103
-	->actionInclude('settings/ajax/disableapp.php');
103
+    ->actionInclude('settings/ajax/disableapp.php');
104 104
 $this->create('settings_ajax_updateapp', '/settings/ajax/updateapp.php')
105
-	->actionInclude('settings/ajax/updateapp.php');
105
+    ->actionInclude('settings/ajax/updateapp.php');
106 106
 $this->create('settings_ajax_uninstallapp', '/settings/ajax/uninstallapp.php')
107
-	->actionInclude('settings/ajax/uninstallapp.php');
107
+    ->actionInclude('settings/ajax/uninstallapp.php');
108 108
 $this->create('settings_ajax_navigationdetect', '/settings/ajax/navigationdetect.php')
109
-	->actionInclude('settings/ajax/navigationdetect.php');
109
+    ->actionInclude('settings/ajax/navigationdetect.php');
110 110
 // admin
111 111
 $this->create('settings_ajax_excludegroups', '/settings/ajax/excludegroups.php')
112
-	->actionInclude('settings/ajax/excludegroups.php');
112
+    ->actionInclude('settings/ajax/excludegroups.php');
Please login to merge, or discard this patch.
settings/templates/personal.php 1 patch
Spacing   +52 added lines, -52 removed lines patch added patch discarded remove patch
@@ -22,10 +22,10 @@  discard block
 block discarded – undo
22 22
 
23 23
 <div id="app-navigation">
24 24
 	<ul class="with-icon">
25
-	<?php foreach($_['forms'] as $form) {
25
+	<?php foreach ($_['forms'] as $form) {
26 26
 		if (isset($form['anchor'])) {
27
-			$anchor = '#' . $form['anchor'];
28
-			$class = 'nav-icon-' . $form['anchor'];
27
+			$anchor = '#'.$form['anchor'];
28
+			$class = 'nav-icon-'.$form['anchor'];
29 29
 			$sectionName = $form['section-name'];
30 30
 			print_unescaped(sprintf("<li><a href='%s' class='%s'>%s</a></li>", \OCP\Util::sanitizeHTML($anchor),
31 31
 			\OCP\Util::sanitizeHTML($class), \OCP\Util::sanitizeHTML($sectionName)));
@@ -37,15 +37,15 @@  discard block
 block discarded – undo
37 37
 <div id="app-content">
38 38
 
39 39
 <div id="quota" class="section">
40
-	<div style="width:<?php p($_['usage_relative']);?>%"
41
-		<?php if($_['usage_relative'] > 80): ?> class="quota-warning" <?php endif; ?>>
40
+	<div style="width:<?php p($_['usage_relative']); ?>%"
41
+		<?php if ($_['usage_relative'] > 80): ?> class="quota-warning" <?php endif; ?>>
42 42
 		<p id="quotatext">
43 43
 			<?php if ($_['quota'] === \OCP\Files\FileInfo::SPACE_UNLIMITED): ?>
44 44
 				<?php print_unescaped($l->t('You are using <strong>%s</strong> of <strong>%s</strong>',
45
-					[$_['usage'], $_['total_space']]));?>
45
+					[$_['usage'], $_['total_space']])); ?>
46 46
 			<?php else: ?>
47 47
 				<?php print_unescaped($l->t('You are using <strong>%s</strong> of <strong>%s</strong> (<strong>%s %%</strong>)',
48
-					[$_['usage'], $_['total_space'],  $_['usage_relative']]));?>
48
+					[$_['usage'], $_['total_space'], $_['usage_relative']])); ?>
49 49
 			<?php endif ?>
50 50
 		</p>
51 51
 	</div>
@@ -79,7 +79,7 @@  discard block
 block discarded – undo
79 79
 			</div>
80 80
 		</div>
81 81
 		<span class="icon-checkmark hidden"/>
82
-		<?php if($_['lookupServerUploadEnabled']) { ?>
82
+		<?php if ($_['lookupServerUploadEnabled']) { ?>
83 83
 		<input type="hidden" id="avatarscope" value="<?php p($_['avatarScope']) ?>">
84 84
 		<?php } ?>
85 85
 	</form>
@@ -93,14 +93,14 @@  discard block
 block discarded – undo
93 93
 				<span class="icon-password"/>
94 94
 			</h2>
95 95
 			<input type="text" id="displayname" name="displayname"
96
-				<?php if(!$_['displayNameChangeSupported']) { print_unescaped('class="hidden"'); } ?>
96
+				<?php if (!$_['displayNameChangeSupported']) { print_unescaped('class="hidden"'); } ?>
97 97
 				value="<?php p($_['displayName']) ?>"
98 98
 				autocomplete="on" autocapitalize="none" autocorrect="off" />
99
-			<?php if(!$_['displayNameChangeSupported']) { ?>
100
-				<span><?php if(isset($_['displayName']) && !empty($_['displayName'])) { p($_['displayName']); } else { p($l->t('No display name set')); } ?></span>
99
+			<?php if (!$_['displayNameChangeSupported']) { ?>
100
+				<span><?php if (isset($_['displayName']) && !empty($_['displayName'])) { p($_['displayName']); } else { p($l->t('No display name set')); } ?></span>
101 101
 			<?php } ?>
102 102
 			<span class="icon-checkmark hidden"/>
103
-			<?php if($_['lookupServerUploadEnabled']) { ?>
103
+			<?php if ($_['lookupServerUploadEnabled']) { ?>
104 104
 			<input type="hidden" id="displaynamescope" value="<?php p($_['displayNameScope']) ?>">
105 105
 			<?php } ?>
106 106
 		</form>
@@ -113,23 +113,23 @@  discard block
 block discarded – undo
113 113
 			</h2>
114 114
 			<span class="verify" id="verify-email">Verify</span>
115 115
 			<input type="email" name="email" id="email" value="<?php p($_['email']); ?>"
116
-				<?php if(!$_['displayNameChangeSupported']) { print_unescaped('class="hidden"'); } ?>
116
+				<?php if (!$_['displayNameChangeSupported']) { print_unescaped('class="hidden"'); } ?>
117 117
 				placeholder="<?php p($l->t('Your email address')); ?>"
118 118
 				autocomplete="on" autocapitalize="none" autocorrect="off" />
119
-			<?php if(!$_['displayNameChangeSupported']) { ?>
120
-				<span><?php if(isset($_['email']) && !empty($_['email'])) { p($_['email']); } else { p($l->t('No email address set')); }?></span>
119
+			<?php if (!$_['displayNameChangeSupported']) { ?>
120
+				<span><?php if (isset($_['email']) && !empty($_['email'])) { p($_['email']); } else { p($l->t('No email address set')); }?></span>
121 121
 			<?php } ?>
122
-			<?php if($_['displayNameChangeSupported']) { ?>
122
+			<?php if ($_['displayNameChangeSupported']) { ?>
123 123
 				<br />
124 124
 				<em><?php p($l->t('For password reset and notifications')); ?></em>
125 125
 			<?php } ?>
126 126
 			<span class="icon-checkmark hidden"/>
127
-			<?php if($_['lookupServerUploadEnabled']) { ?>
127
+			<?php if ($_['lookupServerUploadEnabled']) { ?>
128 128
 			<input type="hidden" id="emailscope" value="<?php p($_['emailScope']) ?>">
129 129
 			<?php } ?>
130 130
 		</form>
131 131
 	</div>
132
-	<?php if($_['lookupServerUploadEnabled']) { ?>
132
+	<?php if ($_['lookupServerUploadEnabled']) { ?>
133 133
 	<div class="personal-settings-setting-box">
134 134
 		<form id="phoneform" class="section">
135 135
 			<h2>
@@ -200,19 +200,19 @@  discard block
 block discarded – undo
200 200
 </div>
201 201
 
202 202
 <?php
203
-if($_['passwordChangeSupported']) {
203
+if ($_['passwordChangeSupported']) {
204 204
 	script('jquery-showpassword');
205 205
 ?>
206 206
 <form id="passwordform" class="section">
207
-	<h2 class="inlineblock"><?php p($l->t('Password'));?></h2>
207
+	<h2 class="inlineblock"><?php p($l->t('Password')); ?></h2>
208 208
 	<div id="password-error-msg" class="msg success inlineblock" style="display: none;">Saved</div>
209 209
 	<br>
210 210
 	<label for="pass1" class="hidden-visually"><?php p($l->t('Current password')); ?>: </label>
211 211
 	<input type="password" id="pass1" name="oldpassword"
212
-		placeholder="<?php p($l->t('Current password'));?>"
212
+		placeholder="<?php p($l->t('Current password')); ?>"
213 213
 		autocomplete="off" autocapitalize="none" autocorrect="off" />
214 214
 	<div class="personal-show-container">
215
-		<label for="pass2" class="hidden-visually"><?php p($l->t('New password'));?>: </label>
215
+		<label for="pass2" class="hidden-visually"><?php p($l->t('New password')); ?>: </label>
216 216
 		<input type="password" id="pass2" name="newpassword"
217 217
 			placeholder="<?php p($l->t('New password')); ?>"
218 218
 			data-typetoggle="#personal-show"
@@ -228,44 +228,44 @@  discard block
 block discarded – undo
228 228
 
229 229
 <form id="language" class="section">
230 230
 	<h2>
231
-		<label for="languageinput"><?php p($l->t('Language'));?></label>
231
+		<label for="languageinput"><?php p($l->t('Language')); ?></label>
232 232
 	</h2>
233
-	<select id="languageinput" name="lang" data-placeholder="<?php p($l->t('Language'));?>">
234
-		<option value="<?php p($_['activelanguage']['code']);?>">
235
-			<?php p($_['activelanguage']['name']);?>
233
+	<select id="languageinput" name="lang" data-placeholder="<?php p($l->t('Language')); ?>">
234
+		<option value="<?php p($_['activelanguage']['code']); ?>">
235
+			<?php p($_['activelanguage']['name']); ?>
236 236
 		</option>
237
-		<?php foreach($_['commonlanguages'] as $language):?>
238
-			<option value="<?php p($language['code']);?>">
239
-				<?php p($language['name']);?>
237
+		<?php foreach ($_['commonlanguages'] as $language):?>
238
+			<option value="<?php p($language['code']); ?>">
239
+				<?php p($language['name']); ?>
240 240
 			</option>
241
-		<?php endforeach;?>
241
+		<?php endforeach; ?>
242 242
 		<optgroup label="––––––––––"></optgroup>
243
-		<?php foreach($_['languages'] as $language):?>
244
-			<option value="<?php p($language['code']);?>">
245
-				<?php p($language['name']);?>
243
+		<?php foreach ($_['languages'] as $language):?>
244
+			<option value="<?php p($language['code']); ?>">
245
+				<?php p($language['name']); ?>
246 246
 			</option>
247
-		<?php endforeach;?>
247
+		<?php endforeach; ?>
248 248
 	</select>
249 249
 	<a href="https://www.transifex.com/nextcloud/nextcloud/"
250 250
 		target="_blank" rel="noreferrer">
251
-		<em><?php p($l->t('Help translate'));?></em>
251
+		<em><?php p($l->t('Help translate')); ?></em>
252 252
 	</a>
253 253
 </form>
254 254
 
255 255
 
256 256
 <div id="clientsbox" class="section clientsbox">
257
-	<h2><?php p($l->t('Get the apps to sync your files'));?></h2>
257
+	<h2><?php p($l->t('Get the apps to sync your files')); ?></h2>
258 258
 	<a href="<?php p($_['clients']['desktop']); ?>" rel="noreferrer" target="_blank">
259 259
 		<img src="<?php print_unescaped(image_path('core', 'desktopapp.svg')); ?>"
260
-			 alt="<?php p($l->t('Desktop client'));?>" />
260
+			 alt="<?php p($l->t('Desktop client')); ?>" />
261 261
 	</a>
262 262
 	<a href="<?php p($_['clients']['android']); ?>" rel="noreferrer" target="_blank">
263 263
 		<img src="<?php print_unescaped(image_path('core', 'googleplay.png')); ?>"
264
-			 alt="<?php p($l->t('Android app'));?>" />
264
+			 alt="<?php p($l->t('Android app')); ?>" />
265 265
 	</a>
266 266
 	<a href="<?php p($_['clients']['ios']); ?>" rel="noreferrer" target="_blank">
267 267
 		<img src="<?php print_unescaped(image_path('core', 'appstore.svg')); ?>"
268
-			 alt="<?php p($l->t('iOS app'));?>" />
268
+			 alt="<?php p($l->t('iOS app')); ?>" />
269 269
 	</a>
270 270
 
271 271
 		<p>
@@ -281,19 +281,19 @@  discard block
 block discarded – undo
281 281
 				$l->t('If you want to support the project {contributeopen}join development{linkclose} or {contributeopen}spread the word{linkclose}!'))); ?>
282 282
 		</p>
283 283
 
284
-	<?php if(OC_APP::isEnabled('firstrunwizard')) {?>
285
-		<p><a class="button" href="#" id="showWizard"><?php p($l->t('Show First Run Wizard again'));?></a></p>
284
+	<?php if (OC_APP::isEnabled('firstrunwizard')) {?>
285
+		<p><a class="button" href="#" id="showWizard"><?php p($l->t('Show First Run Wizard again')); ?></a></p>
286 286
 	<?php }?>
287 287
 </div>
288 288
 
289 289
 <div id="sessions" class="section">
290
-	<h2><?php p($l->t('Sessions'));?></h2>
291
-	<span class="hidden-when-empty"><?php p($l->t('Web, desktop and mobile clients currently logged in to your account.'));?></span>
290
+	<h2><?php p($l->t('Sessions')); ?></h2>
291
+	<span class="hidden-when-empty"><?php p($l->t('Web, desktop and mobile clients currently logged in to your account.')); ?></span>
292 292
 	<table class="icon-loading">
293 293
 		<thead class="token-list-header">
294 294
 			<tr>
295
-				<th><?php p($l->t('Device'));?></th>
296
-				<th><?php p($l->t('Last activity'));?></th>
295
+				<th><?php p($l->t('Device')); ?></th>
296
+				<th><?php p($l->t('Last activity')); ?></th>
297 297
 				<th></th>
298 298
 			</tr>
299 299
 		</thead>
@@ -303,13 +303,13 @@  discard block
 block discarded – undo
303 303
 </div>
304 304
 
305 305
 <div id="apppasswords" class="section">
306
-	<h2><?php p($l->t('App passwords'));?></h2>
307
-	<p><?php p($l->t('Passcodes that give an app or device permissions to access your account.'));?></p>
306
+	<h2><?php p($l->t('App passwords')); ?></h2>
307
+	<p><?php p($l->t('Passcodes that give an app or device permissions to access your account.')); ?></p>
308 308
 	<table class="icon-loading">
309 309
 		<thead class="hidden-when-empty">
310 310
 			<tr>
311
-				<th><?php p($l->t('Name'));?></th>
312
-				<th><?php p($l->t('Last activity'));?></th>
311
+				<th><?php p($l->t('Name')); ?></th>
312
+				<th><?php p($l->t('Last activity')); ?></th>
313 313
 				<th></th>
314 314
 			</tr>
315 315
 		</thead>
@@ -338,14 +338,14 @@  discard block
 block discarded – undo
338 338
 	</div>
339 339
 </div>
340 340
 
341
-<?php foreach($_['forms'] as $form) {
341
+<?php foreach ($_['forms'] as $form) {
342 342
 	if (isset($form['form'])) {?>
343
-	<div id="<?php isset($form['anchor']) ? p($form['anchor']) : p('');?>"><?php print_unescaped($form['form']);?></div>
343
+	<div id="<?php isset($form['anchor']) ? p($form['anchor']) : p(''); ?>"><?php print_unescaped($form['form']); ?></div>
344 344
 	<?php }
345 345
 };?>
346 346
 
347 347
 <div class="section">
348
-	<h2><?php p($l->t('Version'));?></h2>
348
+	<h2><?php p($l->t('Version')); ?></h2>
349 349
 	<p><a href="<?php print_unescaped($theme->getBaseUrl()); ?>" target="_blank"><?php p($theme->getTitle()); ?></a> <?php p(OC_Util::getHumanVersion()) ?></p>
350 350
 	<p><?php include('settings.development.notice.php'); ?></p>
351 351
 </div>
Please login to merge, or discard this patch.
apps/federation/lib/BackgroundJob/RequestSharedSecret.php 2 patches
Indentation   +150 added lines, -150 removed lines patch added patch discarded remove patch
@@ -48,154 +48,154 @@
 block discarded – undo
48 48
  */
49 49
 class RequestSharedSecret extends Job {
50 50
 
51
-	/** @var IClient */
52
-	private $httpClient;
53
-
54
-	/** @var IJobList */
55
-	private $jobList;
56
-
57
-	/** @var IURLGenerator */
58
-	private $urlGenerator;
59
-
60
-	/** @var DbHandler */
61
-	private $dbHandler;
62
-
63
-	/** @var TrustedServers */
64
-	private $trustedServers;
65
-
66
-	/** @var IDiscoveryService  */
67
-	private $ocsDiscoveryService;
68
-
69
-	/** @var ILogger */
70
-	private $logger;
71
-
72
-	/** @var bool */
73
-	protected $retainJob = false;
74
-
75
-	private $format = '?format=json';
76
-
77
-	private $defaultEndPoint = '/ocs/v2.php/apps/federation/api/v1/request-shared-secret';
78
-
79
-	/**
80
-	 * RequestSharedSecret constructor.
81
-	 *
82
-	 * @param IClient $httpClient
83
-	 * @param IURLGenerator $urlGenerator
84
-	 * @param IJobList $jobList
85
-	 * @param TrustedServers $trustedServers
86
-	 * @param DbHandler $dbHandler
87
-	 * @param IDiscoveryService $ocsDiscoveryService
88
-	 */
89
-	public function __construct(
90
-		IClient $httpClient = null,
91
-		IURLGenerator $urlGenerator = null,
92
-		IJobList $jobList = null,
93
-		TrustedServers $trustedServers = null,
94
-		DbHandler $dbHandler = null,
95
-		IDiscoveryService $ocsDiscoveryService = null
96
-	) {
97
-		$this->httpClient = $httpClient ? $httpClient : \OC::$server->getHTTPClientService()->newClient();
98
-		$this->jobList = $jobList ? $jobList : \OC::$server->getJobList();
99
-		$this->urlGenerator = $urlGenerator ? $urlGenerator : \OC::$server->getURLGenerator();
100
-		$this->dbHandler = $dbHandler ? $dbHandler : new DbHandler(\OC::$server->getDatabaseConnection(), \OC::$server->getL10N('federation'));
101
-		$this->logger = \OC::$server->getLogger();
102
-		$this->ocsDiscoveryService = $ocsDiscoveryService ? $ocsDiscoveryService : \OC::$server->query(\OCP\OCS\IDiscoveryService::class);
103
-		if ($trustedServers) {
104
-			$this->trustedServers = $trustedServers;
105
-		} else {
106
-			$this->trustedServers = new TrustedServers(
107
-				$this->dbHandler,
108
-				\OC::$server->getHTTPClientService(),
109
-				$this->logger,
110
-				$this->jobList,
111
-				\OC::$server->getSecureRandom(),
112
-				\OC::$server->getConfig(),
113
-				\OC::$server->getEventDispatcher()
114
-			);
115
-		}
116
-	}
117
-
118
-
119
-	/**
120
-	 * run the job, then remove it from the joblist
121
-	 *
122
-	 * @param JobList $jobList
123
-	 * @param ILogger $logger
124
-	 */
125
-	public function execute($jobList, ILogger $logger = null) {
126
-		$target = $this->argument['url'];
127
-		// only execute if target is still in the list of trusted domains
128
-		if ($this->trustedServers->isTrustedServer($target)) {
129
-			$this->parentExecute($jobList, $logger);
130
-		}
131
-
132
-		if (!$this->retainJob) {
133
-			$jobList->remove($this, $this->argument);
134
-		}
135
-	}
136
-
137
-	/**
138
-	 * call execute() method of parent
139
-	 *
140
-	 * @param JobList $jobList
141
-	 * @param ILogger $logger
142
-	 */
143
-	protected function parentExecute($jobList, $logger) {
144
-		parent::execute($jobList, $logger);
145
-	}
146
-
147
-	protected function run($argument) {
148
-
149
-		$target = $argument['url'];
150
-		$source = $this->urlGenerator->getAbsoluteURL('/');
151
-		$source = rtrim($source, '/');
152
-		$token = $argument['token'];
153
-
154
-		$endPoints = $this->ocsDiscoveryService->discover($target, 'FEDERATED_SHARING');
155
-		$endPoint = isset($endPoints['shared-secret']) ? $endPoints['shared-secret'] : $this->defaultEndPoint;
156
-
157
-		// make sure that we have a well formated url
158
-		$url = rtrim($target, '/') . '/' . trim($endPoint, '/') . $this->format;
159
-
160
-		try {
161
-			$result = $this->httpClient->post(
162
-				$url,
163
-				[
164
-					'body' => [
165
-						'url' => $source,
166
-						'token' => $token,
167
-					],
168
-					'timeout' => 3,
169
-					'connect_timeout' => 3,
170
-				]
171
-			);
172
-
173
-			$status = $result->getStatusCode();
174
-
175
-		} catch (ClientException $e) {
176
-			$status = $e->getCode();
177
-			if ($status === Http::STATUS_FORBIDDEN) {
178
-				$this->logger->info($target . ' refused to ask for a shared secret.', ['app' => 'federation']);
179
-			} else {
180
-				$this->logger->info($target . ' responded with a ' . $status . ' containing: ' . $e->getMessage(), ['app' => 'federation']);
181
-			}
182
-		} catch (\Exception $e) {
183
-			$status = Http::STATUS_INTERNAL_SERVER_ERROR;
184
-			$this->logger->logException($e, ['app' => 'federation']);
185
-		}
186
-
187
-		// if we received a unexpected response we try again later
188
-		if (
189
-			$status !== Http::STATUS_OK
190
-			&& $status !== Http::STATUS_FORBIDDEN
191
-		) {
192
-			$this->retainJob = true;
193
-		}
194
-
195
-		if ($status === Http::STATUS_FORBIDDEN) {
196
-			// clear token if remote server refuses to ask for shared secret
197
-			$this->dbHandler->addToken($target, '');
198
-		}
199
-
200
-	}
51
+    /** @var IClient */
52
+    private $httpClient;
53
+
54
+    /** @var IJobList */
55
+    private $jobList;
56
+
57
+    /** @var IURLGenerator */
58
+    private $urlGenerator;
59
+
60
+    /** @var DbHandler */
61
+    private $dbHandler;
62
+
63
+    /** @var TrustedServers */
64
+    private $trustedServers;
65
+
66
+    /** @var IDiscoveryService  */
67
+    private $ocsDiscoveryService;
68
+
69
+    /** @var ILogger */
70
+    private $logger;
71
+
72
+    /** @var bool */
73
+    protected $retainJob = false;
74
+
75
+    private $format = '?format=json';
76
+
77
+    private $defaultEndPoint = '/ocs/v2.php/apps/federation/api/v1/request-shared-secret';
78
+
79
+    /**
80
+     * RequestSharedSecret constructor.
81
+     *
82
+     * @param IClient $httpClient
83
+     * @param IURLGenerator $urlGenerator
84
+     * @param IJobList $jobList
85
+     * @param TrustedServers $trustedServers
86
+     * @param DbHandler $dbHandler
87
+     * @param IDiscoveryService $ocsDiscoveryService
88
+     */
89
+    public function __construct(
90
+        IClient $httpClient = null,
91
+        IURLGenerator $urlGenerator = null,
92
+        IJobList $jobList = null,
93
+        TrustedServers $trustedServers = null,
94
+        DbHandler $dbHandler = null,
95
+        IDiscoveryService $ocsDiscoveryService = null
96
+    ) {
97
+        $this->httpClient = $httpClient ? $httpClient : \OC::$server->getHTTPClientService()->newClient();
98
+        $this->jobList = $jobList ? $jobList : \OC::$server->getJobList();
99
+        $this->urlGenerator = $urlGenerator ? $urlGenerator : \OC::$server->getURLGenerator();
100
+        $this->dbHandler = $dbHandler ? $dbHandler : new DbHandler(\OC::$server->getDatabaseConnection(), \OC::$server->getL10N('federation'));
101
+        $this->logger = \OC::$server->getLogger();
102
+        $this->ocsDiscoveryService = $ocsDiscoveryService ? $ocsDiscoveryService : \OC::$server->query(\OCP\OCS\IDiscoveryService::class);
103
+        if ($trustedServers) {
104
+            $this->trustedServers = $trustedServers;
105
+        } else {
106
+            $this->trustedServers = new TrustedServers(
107
+                $this->dbHandler,
108
+                \OC::$server->getHTTPClientService(),
109
+                $this->logger,
110
+                $this->jobList,
111
+                \OC::$server->getSecureRandom(),
112
+                \OC::$server->getConfig(),
113
+                \OC::$server->getEventDispatcher()
114
+            );
115
+        }
116
+    }
117
+
118
+
119
+    /**
120
+     * run the job, then remove it from the joblist
121
+     *
122
+     * @param JobList $jobList
123
+     * @param ILogger $logger
124
+     */
125
+    public function execute($jobList, ILogger $logger = null) {
126
+        $target = $this->argument['url'];
127
+        // only execute if target is still in the list of trusted domains
128
+        if ($this->trustedServers->isTrustedServer($target)) {
129
+            $this->parentExecute($jobList, $logger);
130
+        }
131
+
132
+        if (!$this->retainJob) {
133
+            $jobList->remove($this, $this->argument);
134
+        }
135
+    }
136
+
137
+    /**
138
+     * call execute() method of parent
139
+     *
140
+     * @param JobList $jobList
141
+     * @param ILogger $logger
142
+     */
143
+    protected function parentExecute($jobList, $logger) {
144
+        parent::execute($jobList, $logger);
145
+    }
146
+
147
+    protected function run($argument) {
148
+
149
+        $target = $argument['url'];
150
+        $source = $this->urlGenerator->getAbsoluteURL('/');
151
+        $source = rtrim($source, '/');
152
+        $token = $argument['token'];
153
+
154
+        $endPoints = $this->ocsDiscoveryService->discover($target, 'FEDERATED_SHARING');
155
+        $endPoint = isset($endPoints['shared-secret']) ? $endPoints['shared-secret'] : $this->defaultEndPoint;
156
+
157
+        // make sure that we have a well formated url
158
+        $url = rtrim($target, '/') . '/' . trim($endPoint, '/') . $this->format;
159
+
160
+        try {
161
+            $result = $this->httpClient->post(
162
+                $url,
163
+                [
164
+                    'body' => [
165
+                        'url' => $source,
166
+                        'token' => $token,
167
+                    ],
168
+                    'timeout' => 3,
169
+                    'connect_timeout' => 3,
170
+                ]
171
+            );
172
+
173
+            $status = $result->getStatusCode();
174
+
175
+        } catch (ClientException $e) {
176
+            $status = $e->getCode();
177
+            if ($status === Http::STATUS_FORBIDDEN) {
178
+                $this->logger->info($target . ' refused to ask for a shared secret.', ['app' => 'federation']);
179
+            } else {
180
+                $this->logger->info($target . ' responded with a ' . $status . ' containing: ' . $e->getMessage(), ['app' => 'federation']);
181
+            }
182
+        } catch (\Exception $e) {
183
+            $status = Http::STATUS_INTERNAL_SERVER_ERROR;
184
+            $this->logger->logException($e, ['app' => 'federation']);
185
+        }
186
+
187
+        // if we received a unexpected response we try again later
188
+        if (
189
+            $status !== Http::STATUS_OK
190
+            && $status !== Http::STATUS_FORBIDDEN
191
+        ) {
192
+            $this->retainJob = true;
193
+        }
194
+
195
+        if ($status === Http::STATUS_FORBIDDEN) {
196
+            // clear token if remote server refuses to ask for shared secret
197
+            $this->dbHandler->addToken($target, '');
198
+        }
199
+
200
+    }
201 201
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
 		$endPoint = isset($endPoints['shared-secret']) ? $endPoints['shared-secret'] : $this->defaultEndPoint;
156 156
 
157 157
 		// make sure that we have a well formated url
158
-		$url = rtrim($target, '/') . '/' . trim($endPoint, '/') . $this->format;
158
+		$url = rtrim($target, '/').'/'.trim($endPoint, '/').$this->format;
159 159
 
160 160
 		try {
161 161
 			$result = $this->httpClient->post(
@@ -175,9 +175,9 @@  discard block
 block discarded – undo
175 175
 		} catch (ClientException $e) {
176 176
 			$status = $e->getCode();
177 177
 			if ($status === Http::STATUS_FORBIDDEN) {
178
-				$this->logger->info($target . ' refused to ask for a shared secret.', ['app' => 'federation']);
178
+				$this->logger->info($target.' refused to ask for a shared secret.', ['app' => 'federation']);
179 179
 			} else {
180
-				$this->logger->info($target . ' responded with a ' . $status . ' containing: ' . $e->getMessage(), ['app' => 'federation']);
180
+				$this->logger->info($target.' responded with a '.$status.' containing: '.$e->getMessage(), ['app' => 'federation']);
181 181
 			}
182 182
 		} catch (\Exception $e) {
183 183
 			$status = Http::STATUS_INTERNAL_SERVER_ERROR;
Please login to merge, or discard this patch.
apps/federation/lib/BackgroundJob/GetSharedSecret.php 2 patches
Indentation   +167 added lines, -167 removed lines patch added patch discarded remove patch
@@ -48,171 +48,171 @@
 block discarded – undo
48 48
  */
49 49
 class GetSharedSecret extends Job{
50 50
 
51
-	/** @var IClient */
52
-	private $httpClient;
53
-
54
-	/** @var IJobList */
55
-	private $jobList;
56
-
57
-	/** @var IURLGenerator */
58
-	private $urlGenerator;
59
-
60
-	/** @var TrustedServers  */
61
-	private $trustedServers;
62
-
63
-	/** @var DbHandler */
64
-	private $dbHandler;
65
-
66
-	/** @var IDiscoveryService  */
67
-	private $ocsDiscoveryService;
68
-
69
-	/** @var ILogger */
70
-	private $logger;
71
-
72
-	/** @var bool */
73
-	protected $retainJob = false;
74
-
75
-	private $format = '?format=json';
76
-
77
-	private $defaultEndPoint = '/ocs/v2.php/apps/federation/api/v1/shared-secret';
78
-
79
-	/**
80
-	 * RequestSharedSecret constructor.
81
-	 *
82
-	 * @param IClient $httpClient
83
-	 * @param IURLGenerator $urlGenerator
84
-	 * @param IJobList $jobList
85
-	 * @param TrustedServers $trustedServers
86
-	 * @param ILogger $logger
87
-	 * @param DbHandler $dbHandler
88
-	 * @param IDiscoveryService $ocsDiscoveryService
89
-	 */
90
-	public function __construct(
91
-		IClient $httpClient = null,
92
-		IURLGenerator $urlGenerator = null,
93
-		IJobList $jobList = null,
94
-		TrustedServers $trustedServers = null,
95
-		ILogger $logger = null,
96
-		DbHandler $dbHandler = null,
97
-		IDiscoveryService $ocsDiscoveryService = null
98
-	) {
99
-		$this->logger = $logger ? $logger : \OC::$server->getLogger();
100
-		$this->httpClient = $httpClient ? $httpClient : \OC::$server->getHTTPClientService()->newClient();
101
-		$this->jobList = $jobList ? $jobList : \OC::$server->getJobList();
102
-		$this->urlGenerator = $urlGenerator ? $urlGenerator : \OC::$server->getURLGenerator();
103
-		$this->dbHandler = $dbHandler ? $dbHandler : new DbHandler(\OC::$server->getDatabaseConnection(), \OC::$server->getL10N('federation'));
104
-		$this->ocsDiscoveryService = $ocsDiscoveryService ? $ocsDiscoveryService : \OC::$server->query(\OCP\OCS\IDiscoveryService::class);
105
-		if ($trustedServers) {
106
-			$this->trustedServers = $trustedServers;
107
-		} else {
108
-			$this->trustedServers = new TrustedServers(
109
-				$this->dbHandler,
110
-				\OC::$server->getHTTPClientService(),
111
-				$this->logger,
112
-				$this->jobList,
113
-				\OC::$server->getSecureRandom(),
114
-				\OC::$server->getConfig(),
115
-				\OC::$server->getEventDispatcher()
116
-			);
117
-		}
118
-	}
119
-
120
-	/**
121
-	 * run the job, then remove it from the joblist
122
-	 *
123
-	 * @param JobList $jobList
124
-	 * @param ILogger $logger
125
-	 */
126
-	public function execute($jobList, ILogger $logger = null) {
127
-		$target = $this->argument['url'];
128
-		// only execute if target is still in the list of trusted domains
129
-		if ($this->trustedServers->isTrustedServer($target)) {
130
-			$this->parentExecute($jobList, $logger);
131
-		}
132
-
133
-		if (!$this->retainJob) {
134
-			$jobList->remove($this, $this->argument);
135
-		}
136
-	}
137
-
138
-	/**
139
-	 * call execute() method of parent
140
-	 *
141
-	 * @param JobList $jobList
142
-	 * @param ILogger $logger
143
-	 */
144
-	protected function parentExecute($jobList, $logger = null) {
145
-		parent::execute($jobList, $logger);
146
-	}
147
-
148
-	protected function run($argument) {
149
-		$target = $argument['url'];
150
-		$source = $this->urlGenerator->getAbsoluteURL('/');
151
-		$source = rtrim($source, '/');
152
-		$token = $argument['token'];
153
-
154
-		$endPoints = $this->ocsDiscoveryService->discover($target, 'FEDERATED_SHARING');
155
-		$endPoint = isset($endPoints['shared-secret']) ? $endPoints['shared-secret'] : $this->defaultEndPoint;
156
-
157
-		// make sure that we have a well formated url
158
-		$url = rtrim($target, '/') . '/' . trim($endPoint, '/') . $this->format;
159
-
160
-		$result = null;
161
-		try {
162
-			$result = $this->httpClient->get(
163
-				$url,
164
-				[
165
-					'query' =>
166
-						[
167
-							'url' => $source,
168
-							'token' => $token
169
-						],
170
-					'timeout' => 3,
171
-					'connect_timeout' => 3,
172
-				]
173
-			);
174
-
175
-			$status = $result->getStatusCode();
176
-
177
-		} catch (ClientException $e) {
178
-			$status = $e->getCode();
179
-			if ($status === Http::STATUS_FORBIDDEN) {
180
-				$this->logger->info($target . ' refused to exchange a shared secret with you.', ['app' => 'federation']);
181
-			} else {
182
-				$this->logger->info($target . ' responded with a ' . $status . ' containing: ' . $e->getMessage(), ['app' => 'federation']);
183
-			}
184
-		} catch (\Exception $e) {
185
-			$status = Http::STATUS_INTERNAL_SERVER_ERROR;
186
-			$this->logger->logException($e, ['app' => 'federation']);
187
-		}
188
-
189
-		// if we received a unexpected response we try again later
190
-		if (
191
-			$status !== Http::STATUS_OK
192
-			&& $status !== Http::STATUS_FORBIDDEN
193
-		) {
194
-			$this->retainJob = true;
195
-		}  else {
196
-			// reset token if we received a valid response
197
-			$this->dbHandler->addToken($target, '');
198
-		}
199
-
200
-		if ($status === Http::STATUS_OK && $result instanceof IResponse) {
201
-			$body = $result->getBody();
202
-			$result = json_decode($body, true);
203
-			if (isset($result['ocs']['data']['sharedSecret'])) {
204
-				$this->trustedServers->addSharedSecret(
205
-						$target,
206
-						$result['ocs']['data']['sharedSecret']
207
-				);
208
-			} else {
209
-				$this->logger->error(
210
-						'remote server "' . $target . '"" does not return a valid shared secret',
211
-						['app' => 'federation']
212
-				);
213
-				$this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE);
214
-			}
215
-		}
216
-
217
-	}
51
+    /** @var IClient */
52
+    private $httpClient;
53
+
54
+    /** @var IJobList */
55
+    private $jobList;
56
+
57
+    /** @var IURLGenerator */
58
+    private $urlGenerator;
59
+
60
+    /** @var TrustedServers  */
61
+    private $trustedServers;
62
+
63
+    /** @var DbHandler */
64
+    private $dbHandler;
65
+
66
+    /** @var IDiscoveryService  */
67
+    private $ocsDiscoveryService;
68
+
69
+    /** @var ILogger */
70
+    private $logger;
71
+
72
+    /** @var bool */
73
+    protected $retainJob = false;
74
+
75
+    private $format = '?format=json';
76
+
77
+    private $defaultEndPoint = '/ocs/v2.php/apps/federation/api/v1/shared-secret';
78
+
79
+    /**
80
+     * RequestSharedSecret constructor.
81
+     *
82
+     * @param IClient $httpClient
83
+     * @param IURLGenerator $urlGenerator
84
+     * @param IJobList $jobList
85
+     * @param TrustedServers $trustedServers
86
+     * @param ILogger $logger
87
+     * @param DbHandler $dbHandler
88
+     * @param IDiscoveryService $ocsDiscoveryService
89
+     */
90
+    public function __construct(
91
+        IClient $httpClient = null,
92
+        IURLGenerator $urlGenerator = null,
93
+        IJobList $jobList = null,
94
+        TrustedServers $trustedServers = null,
95
+        ILogger $logger = null,
96
+        DbHandler $dbHandler = null,
97
+        IDiscoveryService $ocsDiscoveryService = null
98
+    ) {
99
+        $this->logger = $logger ? $logger : \OC::$server->getLogger();
100
+        $this->httpClient = $httpClient ? $httpClient : \OC::$server->getHTTPClientService()->newClient();
101
+        $this->jobList = $jobList ? $jobList : \OC::$server->getJobList();
102
+        $this->urlGenerator = $urlGenerator ? $urlGenerator : \OC::$server->getURLGenerator();
103
+        $this->dbHandler = $dbHandler ? $dbHandler : new DbHandler(\OC::$server->getDatabaseConnection(), \OC::$server->getL10N('federation'));
104
+        $this->ocsDiscoveryService = $ocsDiscoveryService ? $ocsDiscoveryService : \OC::$server->query(\OCP\OCS\IDiscoveryService::class);
105
+        if ($trustedServers) {
106
+            $this->trustedServers = $trustedServers;
107
+        } else {
108
+            $this->trustedServers = new TrustedServers(
109
+                $this->dbHandler,
110
+                \OC::$server->getHTTPClientService(),
111
+                $this->logger,
112
+                $this->jobList,
113
+                \OC::$server->getSecureRandom(),
114
+                \OC::$server->getConfig(),
115
+                \OC::$server->getEventDispatcher()
116
+            );
117
+        }
118
+    }
119
+
120
+    /**
121
+     * run the job, then remove it from the joblist
122
+     *
123
+     * @param JobList $jobList
124
+     * @param ILogger $logger
125
+     */
126
+    public function execute($jobList, ILogger $logger = null) {
127
+        $target = $this->argument['url'];
128
+        // only execute if target is still in the list of trusted domains
129
+        if ($this->trustedServers->isTrustedServer($target)) {
130
+            $this->parentExecute($jobList, $logger);
131
+        }
132
+
133
+        if (!$this->retainJob) {
134
+            $jobList->remove($this, $this->argument);
135
+        }
136
+    }
137
+
138
+    /**
139
+     * call execute() method of parent
140
+     *
141
+     * @param JobList $jobList
142
+     * @param ILogger $logger
143
+     */
144
+    protected function parentExecute($jobList, $logger = null) {
145
+        parent::execute($jobList, $logger);
146
+    }
147
+
148
+    protected function run($argument) {
149
+        $target = $argument['url'];
150
+        $source = $this->urlGenerator->getAbsoluteURL('/');
151
+        $source = rtrim($source, '/');
152
+        $token = $argument['token'];
153
+
154
+        $endPoints = $this->ocsDiscoveryService->discover($target, 'FEDERATED_SHARING');
155
+        $endPoint = isset($endPoints['shared-secret']) ? $endPoints['shared-secret'] : $this->defaultEndPoint;
156
+
157
+        // make sure that we have a well formated url
158
+        $url = rtrim($target, '/') . '/' . trim($endPoint, '/') . $this->format;
159
+
160
+        $result = null;
161
+        try {
162
+            $result = $this->httpClient->get(
163
+                $url,
164
+                [
165
+                    'query' =>
166
+                        [
167
+                            'url' => $source,
168
+                            'token' => $token
169
+                        ],
170
+                    'timeout' => 3,
171
+                    'connect_timeout' => 3,
172
+                ]
173
+            );
174
+
175
+            $status = $result->getStatusCode();
176
+
177
+        } catch (ClientException $e) {
178
+            $status = $e->getCode();
179
+            if ($status === Http::STATUS_FORBIDDEN) {
180
+                $this->logger->info($target . ' refused to exchange a shared secret with you.', ['app' => 'federation']);
181
+            } else {
182
+                $this->logger->info($target . ' responded with a ' . $status . ' containing: ' . $e->getMessage(), ['app' => 'federation']);
183
+            }
184
+        } catch (\Exception $e) {
185
+            $status = Http::STATUS_INTERNAL_SERVER_ERROR;
186
+            $this->logger->logException($e, ['app' => 'federation']);
187
+        }
188
+
189
+        // if we received a unexpected response we try again later
190
+        if (
191
+            $status !== Http::STATUS_OK
192
+            && $status !== Http::STATUS_FORBIDDEN
193
+        ) {
194
+            $this->retainJob = true;
195
+        }  else {
196
+            // reset token if we received a valid response
197
+            $this->dbHandler->addToken($target, '');
198
+        }
199
+
200
+        if ($status === Http::STATUS_OK && $result instanceof IResponse) {
201
+            $body = $result->getBody();
202
+            $result = json_decode($body, true);
203
+            if (isset($result['ocs']['data']['sharedSecret'])) {
204
+                $this->trustedServers->addSharedSecret(
205
+                        $target,
206
+                        $result['ocs']['data']['sharedSecret']
207
+                );
208
+            } else {
209
+                $this->logger->error(
210
+                        'remote server "' . $target . '"" does not return a valid shared secret',
211
+                        ['app' => 'federation']
212
+                );
213
+                $this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE);
214
+            }
215
+        }
216
+
217
+    }
218 218
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -46,7 +46,7 @@  discard block
 block discarded – undo
46 46
  *
47 47
  * @package OCA\Federation\Backgroundjob
48 48
  */
49
-class GetSharedSecret extends Job{
49
+class GetSharedSecret extends Job {
50 50
 
51 51
 	/** @var IClient */
52 52
 	private $httpClient;
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
 		$endPoint = isset($endPoints['shared-secret']) ? $endPoints['shared-secret'] : $this->defaultEndPoint;
156 156
 
157 157
 		// make sure that we have a well formated url
158
-		$url = rtrim($target, '/') . '/' . trim($endPoint, '/') . $this->format;
158
+		$url = rtrim($target, '/').'/'.trim($endPoint, '/').$this->format;
159 159
 
160 160
 		$result = null;
161 161
 		try {
@@ -177,9 +177,9 @@  discard block
 block discarded – undo
177 177
 		} catch (ClientException $e) {
178 178
 			$status = $e->getCode();
179 179
 			if ($status === Http::STATUS_FORBIDDEN) {
180
-				$this->logger->info($target . ' refused to exchange a shared secret with you.', ['app' => 'federation']);
180
+				$this->logger->info($target.' refused to exchange a shared secret with you.', ['app' => 'federation']);
181 181
 			} else {
182
-				$this->logger->info($target . ' responded with a ' . $status . ' containing: ' . $e->getMessage(), ['app' => 'federation']);
182
+				$this->logger->info($target.' responded with a '.$status.' containing: '.$e->getMessage(), ['app' => 'federation']);
183 183
 			}
184 184
 		} catch (\Exception $e) {
185 185
 			$status = Http::STATUS_INTERNAL_SERVER_ERROR;
@@ -192,7 +192,7 @@  discard block
 block discarded – undo
192 192
 			&& $status !== Http::STATUS_FORBIDDEN
193 193
 		) {
194 194
 			$this->retainJob = true;
195
-		}  else {
195
+		} else {
196 196
 			// reset token if we received a valid response
197 197
 			$this->dbHandler->addToken($target, '');
198 198
 		}
@@ -207,7 +207,7 @@  discard block
 block discarded – undo
207 207
 				);
208 208
 			} else {
209 209
 				$this->logger->error(
210
-						'remote server "' . $target . '"" does not return a valid shared secret',
210
+						'remote server "'.$target.'"" does not return a valid shared secret',
211 211
 						['app' => 'federation']
212 212
 				);
213 213
 				$this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE);
Please login to merge, or discard this patch.
apps/files_sharing/lib/Controller/ShareesAPIController.php 3 patches
Doc Comments   +4 added lines, -1 removed lines patch added patch discarded remove patch
@@ -385,7 +385,7 @@  discard block
 block discarded – undo
385 385
 	 * split user and remote from federated cloud id
386 386
 	 *
387 387
 	 * @param string $address federated share address
388
-	 * @return array [user, remoteURL]
388
+	 * @return string[] [user, remoteURL]
389 389
 	 * @throws \Exception
390 390
 	 */
391 391
 	public function splitUserRemote($address) {
@@ -652,6 +652,9 @@  discard block
 block discarded – undo
652 652
 		return $result;
653 653
 	}
654 654
 
655
+	/**
656
+	 * @param string $search
657
+	 */
655 658
 	protected function getLookup($search) {
656 659
 		$isEnabled = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no');
657 660
 		$lookupServerUrl = $this->config->getSystemValue('lookup_server', 'https://lookup.nextcloud.com');
Please login to merge, or discard this patch.
Indentation   +669 added lines, -669 removed lines patch added patch discarded remove patch
@@ -43,673 +43,673 @@
 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
-		$result = [];
659
-
660
-		if($isEnabled === 'yes') {
661
-			try {
662
-				$client = $this->clientService->newClient();
663
-				$response = $client->get(
664
-					$lookupServerUrl . '/users?search=' . urlencode($search),
665
-					[
666
-						'timeout' => 10,
667
-						'connect_timeout' => 3,
668
-					]
669
-				);
670
-
671
-				$body = json_decode($response->getBody(), true);
672
-
673
-				$result = [];
674
-				foreach ($body as $lookup) {
675
-					$result[] = [
676
-						'label' => $lookup['federationId'],
677
-						'value' => [
678
-							'shareType' => Share::SHARE_TYPE_REMOTE,
679
-							'shareWith' => $lookup['federationId'],
680
-						],
681
-						'extra' => $lookup,
682
-					];
683
-				}
684
-			} catch (\Exception $e) {}
685
-		}
686
-
687
-		$this->result['lookup'] = $result;
688
-	}
689
-
690
-	/**
691
-	 * Generates a bunch of pagination links for the current page
692
-	 *
693
-	 * @param int $page Current page
694
-	 * @param array $params Parameters for the URL
695
-	 * @return string
696
-	 */
697
-	protected function getPaginationLink($page, array $params) {
698
-		if ($this->isV2()) {
699
-			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v2.php/apps/files_sharing/api/v1/sharees') . '?';
700
-		} else {
701
-			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/sharees') . '?';
702
-		}
703
-		$params['page'] = $page + 1;
704
-		$link = '<' . $url . http_build_query($params) . '>; rel="next"';
705
-
706
-		return $link;
707
-	}
708
-
709
-	/**
710
-	 * @return bool
711
-	 */
712
-	protected function isV2() {
713
-		return $this->request->getScriptName() === '/ocs/v2.php';
714
-	}
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
+        $result = [];
659
+
660
+        if($isEnabled === 'yes') {
661
+            try {
662
+                $client = $this->clientService->newClient();
663
+                $response = $client->get(
664
+                    $lookupServerUrl . '/users?search=' . urlencode($search),
665
+                    [
666
+                        'timeout' => 10,
667
+                        'connect_timeout' => 3,
668
+                    ]
669
+                );
670
+
671
+                $body = json_decode($response->getBody(), true);
672
+
673
+                $result = [];
674
+                foreach ($body as $lookup) {
675
+                    $result[] = [
676
+                        'label' => $lookup['federationId'],
677
+                        'value' => [
678
+                            'shareType' => Share::SHARE_TYPE_REMOTE,
679
+                            'shareWith' => $lookup['federationId'],
680
+                        ],
681
+                        'extra' => $lookup,
682
+                    ];
683
+                }
684
+            } catch (\Exception $e) {}
685
+        }
686
+
687
+        $this->result['lookup'] = $result;
688
+    }
689
+
690
+    /**
691
+     * Generates a bunch of pagination links for the current page
692
+     *
693
+     * @param int $page Current page
694
+     * @param array $params Parameters for the URL
695
+     * @return string
696
+     */
697
+    protected function getPaginationLink($page, array $params) {
698
+        if ($this->isV2()) {
699
+            $url = $this->urlGenerator->getAbsoluteURL('/ocs/v2.php/apps/files_sharing/api/v1/sharees') . '?';
700
+        } else {
701
+            $url = $this->urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/sharees') . '?';
702
+        }
703
+        $params['page'] = $page + 1;
704
+        $link = '<' . $url . http_build_query($params) . '>; rel="next"';
705
+
706
+        return $link;
707
+    }
708
+
709
+    /**
710
+     * @return bool
711
+     */
712
+    protected function isV2() {
713
+        return $this->request->getScriptName() === '/ocs/v2.php';
714
+    }
715 715
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -236,17 +236,17 @@  discard block
 block discarded – undo
236 236
 		$this->result['groups'] = $this->result['exact']['groups'] = [];
237 237
 
238 238
 		$groups = $this->groupManager->search($search, $this->limit, $this->offset);
239
-		$groupIds = array_map(function (IGroup $group) { return $group->getGID(); }, $groups);
239
+		$groupIds = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
240 240
 
241 241
 		if (!$this->shareeEnumeration || sizeof($groups) < $this->limit) {
242 242
 			$this->reachedEndFor[] = 'groups';
243 243
 		}
244 244
 
245
-		$userGroups =  [];
245
+		$userGroups = [];
246 246
 		if (!empty($groups) && $this->shareWithGroupOnly) {
247 247
 			// Intersect all the groups that match with the groups this user is a member of
248 248
 			$userGroups = $this->groupManager->getUserGroups($this->userSession->getUser());
249
-			$userGroups = array_map(function (IGroup $group) { return $group->getGID(); }, $userGroups);
249
+			$userGroups = array_map(function(IGroup $group) { return $group->getGID(); }, $userGroups);
250 250
 			$groupIds = array_intersect($groupIds, $userGroups);
251 251
 		}
252 252
 
@@ -341,7 +341,7 @@  discard block
 block discarded – undo
341 341
 							$result['exactIdMatch'] = true;
342 342
 						}
343 343
 						$result['exact'][] = [
344
-							'label' => $contact['FN'] . " ($cloudId)",
344
+							'label' => $contact['FN']." ($cloudId)",
345 345
 							'value' => [
346 346
 								'shareType' => Share::SHARE_TYPE_REMOTE,
347 347
 								'shareWith' => $cloudId,
@@ -350,7 +350,7 @@  discard block
 block discarded – undo
350 350
 						];
351 351
 					} else {
352 352
 						$result['results'][] = [
353
-							'label' => $contact['FN'] . " ($cloudId)",
353
+							'label' => $contact['FN']." ($cloudId)",
354 354
 							'value' => [
355 355
 								'shareType' => Share::SHARE_TYPE_REMOTE,
356 356
 								'shareWith' => $cloudId,
@@ -434,13 +434,13 @@  discard block
 block discarded – undo
434 434
 	public function search($search = '', $itemType = null, $page = 1, $perPage = 200, $shareType = null, $lookup = true) {
435 435
 
436 436
 		// only search for string larger than a given threshold
437
-		$threshold = (int)$this->config->getSystemValue('sharing.minSearchStringLength', 0);
437
+		$threshold = (int) $this->config->getSystemValue('sharing.minSearchStringLength', 0);
438 438
 		if (strlen($search) < $threshold) {
439 439
 			return new DataResponse($this->result);
440 440
 		}
441 441
 
442 442
 		// never return more than the max. number of results configured in the config.php
443
-		$maxResults = (int)$this->config->getSystemValue('sharing.maxAutocompleteResults', 0);
443
+		$maxResults = (int) $this->config->getSystemValue('sharing.maxAutocompleteResults', 0);
444 444
 		if ($maxResults > 0) {
445 445
 			$perPage = min($perPage, $maxResults);
446 446
 		}
@@ -614,7 +614,7 @@  discard block
 block discarded – undo
614 614
 							$result['exactIdMatch'] = true;
615 615
 						}
616 616
 						$result['exact'][] = [
617
-							'label' => $contact['FN'] . " ($emailAddress)",
617
+							'label' => $contact['FN']." ($emailAddress)",
618 618
 							'value' => [
619 619
 								'shareType' => Share::SHARE_TYPE_EMAIL,
620 620
 								'shareWith' => $emailAddress,
@@ -622,7 +622,7 @@  discard block
 block discarded – undo
622 622
 						];
623 623
 					} else {
624 624
 						$result['results'][] = [
625
-							'label' => $contact['FN'] . " ($emailAddress)",
625
+							'label' => $contact['FN']." ($emailAddress)",
626 626
 							'value' => [
627 627
 								'shareType' => Share::SHARE_TYPE_EMAIL,
628 628
 								'shareWith' => $emailAddress,
@@ -657,11 +657,11 @@  discard block
 block discarded – undo
657 657
 		$lookupServerUrl = $this->config->getSystemValue('lookup_server', 'https://lookup.nextcloud.com');
658 658
 		$result = [];
659 659
 
660
-		if($isEnabled === 'yes') {
660
+		if ($isEnabled === 'yes') {
661 661
 			try {
662 662
 				$client = $this->clientService->newClient();
663 663
 				$response = $client->get(
664
-					$lookupServerUrl . '/users?search=' . urlencode($search),
664
+					$lookupServerUrl.'/users?search='.urlencode($search),
665 665
 					[
666 666
 						'timeout' => 10,
667 667
 						'connect_timeout' => 3,
@@ -696,12 +696,12 @@  discard block
 block discarded – undo
696 696
 	 */
697 697
 	protected function getPaginationLink($page, array $params) {
698 698
 		if ($this->isV2()) {
699
-			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v2.php/apps/files_sharing/api/v1/sharees') . '?';
699
+			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v2.php/apps/files_sharing/api/v1/sharees').'?';
700 700
 		} else {
701
-			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/sharees') . '?';
701
+			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/sharees').'?';
702 702
 		}
703 703
 		$params['page'] = $page + 1;
704
-		$link = '<' . $url . http_build_query($params) . '>; rel="next"';
704
+		$link = '<'.$url.http_build_query($params).'>; rel="next"';
705 705
 
706 706
 		return $link;
707 707
 	}
Please login to merge, or discard this patch.
settings/BackgroundJobs/VerifyUserData.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -245,7 +245,7 @@
 block discarded – undo
245 245
 	/**
246 246
 	 * re-add background job with new arguments
247 247
 	 *
248
-	 * @param IJobList $jobList
248
+	 * @param JobList $jobList
249 249
 	 * @param array $argument
250 250
 	 */
251 251
 	protected function reAddJob(IJobList $jobList, array $argument) {
Please login to merge, or discard this patch.
Indentation   +237 added lines, -237 removed lines patch added patch discarded remove patch
@@ -34,242 +34,242 @@
 block discarded – undo
34 34
 
35 35
 class VerifyUserData extends Job {
36 36
 
37
-	/** @var  bool */
38
-	private $retainJob = true;
39
-
40
-	/** @var int max number of attempts to send the request */
41
-	private $maxTry = 24;
42
-
43
-	/** @var int how much time should be between two tries (1 hour) */
44
-	private $interval = 3600;
45
-
46
-	/** @var AccountManager */
47
-	private $accountManager;
48
-
49
-	/** @var IUserManager */
50
-	private $userManager;
51
-
52
-	/** @var IClientService */
53
-	private $httpClientService;
54
-
55
-	/** @var ILogger */
56
-	private $logger;
57
-
58
-	/** @var string */
59
-	private $lookupServerUrl;
60
-
61
-	/**
62
-	 * VerifyUserData constructor.
63
-	 *
64
-	 * @param AccountManager|null $accountManager
65
-	 * @param IUserManager|null $userManager
66
-	 * @param IClientService|null $clientService
67
-	 * @param IConfig|null $config
68
-	 */
69
-	public function __construct(AccountManager $accountManager = null,
70
-								IUserManager $userManager = null,
71
-								IClientService $clientService = null,
72
-								ILogger $logger = null,
73
-								IConfig $config = null
74
-	) {
75
-		$this->accountManager = $accountManager !== null ? $accountManager : \OC::$server->query(AccountManager::class);
76
-		$this->userManager = $userManager !== null ? $userManager : \OC::$server->getUserManager();
77
-		$this->httpClientService = $clientService !== null ? $clientService : \OC::$server->getHTTPClientService();
78
-		$this->logger = $logger !== null ? $logger : \OC::$server->getLogger();
79
-
80
-		if ($config !== null) {
81
-			$this->lookupServerUrl = $config->getSystemValue('lookup_server', 'https://lookup.nextcloud.com');
82
-		} else {
83
-			$this->lookupServerUrl = \OC::$server->getConfig()->getSystemValue('lookup_server', 'https://lookup.nextcloud.com');
84
-		}
85
-	}
86
-
87
-	/**
88
-	 * run the job, then remove it from the jobList
89
-	 *
90
-	 * @param JobList $jobList
91
-	 * @param ILogger $logger
92
-	 */
93
-	public function execute($jobList, ILogger $logger = null) {
94
-
95
-		if ($this->shouldRun($this->argument)) {
96
-			parent::execute($jobList, $logger);
97
-			$jobList->remove($this, $this->argument);
98
-			if ($this->retainJob) {
99
-				$this->reAddJob($jobList, $this->argument);
100
-			}
101
-		}
102
-
103
-	}
104
-
105
-	protected function run($argument) {
106
-
107
-		$try = (int)$argument['try'] + 1;
108
-
109
-		switch($argument['type']) {
110
-			case AccountManager::PROPERTY_WEBSITE:
111
-				$result = $this->verifyWebsite($argument);
112
-				break;
113
-			case AccountManager::PROPERTY_TWITTER:
114
-			case AccountManager::PROPERTY_EMAIL:
115
-				$result = $this->verifyViaLookupServer($argument, $argument['type']);
116
-				break;
117
-			default:
118
-				// no valid type given, no need to retry
119
-				$this->logger->error($argument['type'] . ' is no valid type for user account data.');
120
-				$result = true;
121
-		}
122
-
123
-		if ($result === true || $try > $this->maxTry) {
124
-			$this->retainJob = false;
125
-		}
126
-	}
127
-
128
-	/**
129
-	 * verify web page
130
-	 *
131
-	 * @param array $argument
132
-	 * @return bool true if we could check the verification code, otherwise false
133
-	 */
134
-	protected function verifyWebsite(array $argument) {
135
-
136
-		$result = false;
137
-
138
-		$url = rtrim($argument['data'], '/') . '/' . 'CloudIdVerificationCode.txt';
139
-
140
-		$client = $this->httpClientService->newClient();
141
-		try {
142
-			$response = $client->get($url);
143
-		} catch (\Exception $e) {
144
-			return false;
145
-		}
146
-
147
-		if ($response->getStatusCode() === Http::STATUS_OK) {
148
-			$result = true;
149
-			$publishedCode = $response->getBody();
150
-			$user = $this->userManager->get($argument['uid']);
151
-			// we don't check a valid user -> give up
152
-			if ($user === null) {
153
-				$this->logger->error($argument['uid'] . ' doesn\'t exist, can\'t verify user data.');
154
-				return $result;
155
-			}
156
-			$userData = $this->accountManager->getUser($user);
157
-
158
-			if ($publishedCode === $argument['verificationCode']) {
159
-
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::VERIFICATION_IN_PROGRESS) {
206
-			return false;
207
-		}
208
-
209
-		$localUserData[$dataType]['verified'] === $lookupServerData[$dataType]['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->clientService->newClient();
222
-			$response = $client->get(
223
-				$this->lookupServerUrl . '/users?search=' . urlencode($cloudId),
224
-				[
225
-					'timeout' => 10,
226
-					'connect_timeout' => 3,
227
-				]
228
-			);
229
-
230
-			$body = json_decode($response->getBody(), true);
231
-
232
-			foreach ($body as $lookup) {
233
-				if ($lookup['federationId'] === $cloudId) {
234
-					return $lookup;
235
-				}
236
-			}
237
-
238
-		} catch (\Exception $e) {
239
-			// do nothing, we will just re-try later
240
-		}
241
-
242
-		return [];
243
-	}
244
-
245
-	/**
246
-	 * re-add background job with new arguments
247
-	 *
248
-	 * @param IJobList $jobList
249
-	 * @param array $argument
250
-	 */
251
-	protected function reAddJob(IJobList $jobList, array $argument) {
252
-		$jobList->add('OC\Settings\BackgroundJobs\VerifyUserData',
253
-			[
254
-				'verificationCode' => $argument['verificationCode'],
255
-				'data' => $argument['data'],
256
-				'type' => $argument['type'],
257
-				'uid' => $argument['uid'],
258
-				'try' => (int)$argument['try'] + 1,
259
-				'lastRun' => time()
260
-			]
261
-		);
262
-	}
263
-
264
-	/**
265
-	 * test if it is time for the next run
266
-	 *
267
-	 * @param array $argument
268
-	 * @return bool
269
-	 */
270
-	protected function shouldRun(array $argument) {
271
-		$lastRun = (int)$argument['lastRun'];
272
-		return ((time() - $lastRun) > $this->interval);
273
-	}
37
+    /** @var  bool */
38
+    private $retainJob = true;
39
+
40
+    /** @var int max number of attempts to send the request */
41
+    private $maxTry = 24;
42
+
43
+    /** @var int how much time should be between two tries (1 hour) */
44
+    private $interval = 3600;
45
+
46
+    /** @var AccountManager */
47
+    private $accountManager;
48
+
49
+    /** @var IUserManager */
50
+    private $userManager;
51
+
52
+    /** @var IClientService */
53
+    private $httpClientService;
54
+
55
+    /** @var ILogger */
56
+    private $logger;
57
+
58
+    /** @var string */
59
+    private $lookupServerUrl;
60
+
61
+    /**
62
+     * VerifyUserData constructor.
63
+     *
64
+     * @param AccountManager|null $accountManager
65
+     * @param IUserManager|null $userManager
66
+     * @param IClientService|null $clientService
67
+     * @param IConfig|null $config
68
+     */
69
+    public function __construct(AccountManager $accountManager = null,
70
+                                IUserManager $userManager = null,
71
+                                IClientService $clientService = null,
72
+                                ILogger $logger = null,
73
+                                IConfig $config = null
74
+    ) {
75
+        $this->accountManager = $accountManager !== null ? $accountManager : \OC::$server->query(AccountManager::class);
76
+        $this->userManager = $userManager !== null ? $userManager : \OC::$server->getUserManager();
77
+        $this->httpClientService = $clientService !== null ? $clientService : \OC::$server->getHTTPClientService();
78
+        $this->logger = $logger !== null ? $logger : \OC::$server->getLogger();
79
+
80
+        if ($config !== null) {
81
+            $this->lookupServerUrl = $config->getSystemValue('lookup_server', 'https://lookup.nextcloud.com');
82
+        } else {
83
+            $this->lookupServerUrl = \OC::$server->getConfig()->getSystemValue('lookup_server', 'https://lookup.nextcloud.com');
84
+        }
85
+    }
86
+
87
+    /**
88
+     * run the job, then remove it from the jobList
89
+     *
90
+     * @param JobList $jobList
91
+     * @param ILogger $logger
92
+     */
93
+    public function execute($jobList, ILogger $logger = null) {
94
+
95
+        if ($this->shouldRun($this->argument)) {
96
+            parent::execute($jobList, $logger);
97
+            $jobList->remove($this, $this->argument);
98
+            if ($this->retainJob) {
99
+                $this->reAddJob($jobList, $this->argument);
100
+            }
101
+        }
102
+
103
+    }
104
+
105
+    protected function run($argument) {
106
+
107
+        $try = (int)$argument['try'] + 1;
108
+
109
+        switch($argument['type']) {
110
+            case AccountManager::PROPERTY_WEBSITE:
111
+                $result = $this->verifyWebsite($argument);
112
+                break;
113
+            case AccountManager::PROPERTY_TWITTER:
114
+            case AccountManager::PROPERTY_EMAIL:
115
+                $result = $this->verifyViaLookupServer($argument, $argument['type']);
116
+                break;
117
+            default:
118
+                // no valid type given, no need to retry
119
+                $this->logger->error($argument['type'] . ' is no valid type for user account data.');
120
+                $result = true;
121
+        }
122
+
123
+        if ($result === true || $try > $this->maxTry) {
124
+            $this->retainJob = false;
125
+        }
126
+    }
127
+
128
+    /**
129
+     * verify web page
130
+     *
131
+     * @param array $argument
132
+     * @return bool true if we could check the verification code, otherwise false
133
+     */
134
+    protected function verifyWebsite(array $argument) {
135
+
136
+        $result = false;
137
+
138
+        $url = rtrim($argument['data'], '/') . '/' . 'CloudIdVerificationCode.txt';
139
+
140
+        $client = $this->httpClientService->newClient();
141
+        try {
142
+            $response = $client->get($url);
143
+        } catch (\Exception $e) {
144
+            return false;
145
+        }
146
+
147
+        if ($response->getStatusCode() === Http::STATUS_OK) {
148
+            $result = true;
149
+            $publishedCode = $response->getBody();
150
+            $user = $this->userManager->get($argument['uid']);
151
+            // we don't check a valid user -> give up
152
+            if ($user === null) {
153
+                $this->logger->error($argument['uid'] . ' doesn\'t exist, can\'t verify user data.');
154
+                return $result;
155
+            }
156
+            $userData = $this->accountManager->getUser($user);
157
+
158
+            if ($publishedCode === $argument['verificationCode']) {
159
+
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::VERIFICATION_IN_PROGRESS) {
206
+            return false;
207
+        }
208
+
209
+        $localUserData[$dataType]['verified'] === $lookupServerData[$dataType]['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->clientService->newClient();
222
+            $response = $client->get(
223
+                $this->lookupServerUrl . '/users?search=' . urlencode($cloudId),
224
+                [
225
+                    'timeout' => 10,
226
+                    'connect_timeout' => 3,
227
+                ]
228
+            );
229
+
230
+            $body = json_decode($response->getBody(), true);
231
+
232
+            foreach ($body as $lookup) {
233
+                if ($lookup['federationId'] === $cloudId) {
234
+                    return $lookup;
235
+                }
236
+            }
237
+
238
+        } catch (\Exception $e) {
239
+            // do nothing, we will just re-try later
240
+        }
241
+
242
+        return [];
243
+    }
244
+
245
+    /**
246
+     * re-add background job with new arguments
247
+     *
248
+     * @param IJobList $jobList
249
+     * @param array $argument
250
+     */
251
+    protected function reAddJob(IJobList $jobList, array $argument) {
252
+        $jobList->add('OC\Settings\BackgroundJobs\VerifyUserData',
253
+            [
254
+                'verificationCode' => $argument['verificationCode'],
255
+                'data' => $argument['data'],
256
+                'type' => $argument['type'],
257
+                'uid' => $argument['uid'],
258
+                'try' => (int)$argument['try'] + 1,
259
+                'lastRun' => time()
260
+            ]
261
+        );
262
+    }
263
+
264
+    /**
265
+     * test if it is time for the next run
266
+     *
267
+     * @param array $argument
268
+     * @return bool
269
+     */
270
+    protected function shouldRun(array $argument) {
271
+        $lastRun = (int)$argument['lastRun'];
272
+        return ((time() - $lastRun) > $this->interval);
273
+    }
274 274
 
275 275
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -104,9 +104,9 @@  discard block
 block discarded – undo
104 104
 
105 105
 	protected function run($argument) {
106 106
 
107
-		$try = (int)$argument['try'] + 1;
107
+		$try = (int) $argument['try'] + 1;
108 108
 
109
-		switch($argument['type']) {
109
+		switch ($argument['type']) {
110 110
 			case AccountManager::PROPERTY_WEBSITE:
111 111
 				$result = $this->verifyWebsite($argument);
112 112
 				break;
@@ -116,7 +116,7 @@  discard block
 block discarded – undo
116 116
 				break;
117 117
 			default:
118 118
 				// no valid type given, no need to retry
119
-				$this->logger->error($argument['type'] . ' is no valid type for user account data.');
119
+				$this->logger->error($argument['type'].' is no valid type for user account data.');
120 120
 				$result = true;
121 121
 		}
122 122
 
@@ -135,7 +135,7 @@  discard block
 block discarded – undo
135 135
 
136 136
 		$result = false;
137 137
 
138
-		$url = rtrim($argument['data'], '/') . '/' . 'CloudIdVerificationCode.txt';
138
+		$url = rtrim($argument['data'], '/').'/'.'CloudIdVerificationCode.txt';
139 139
 
140 140
 		$client = $this->httpClientService->newClient();
141 141
 		try {
@@ -150,7 +150,7 @@  discard block
 block discarded – undo
150 150
 			$user = $this->userManager->get($argument['uid']);
151 151
 			// we don't check a valid user -> give up
152 152
 			if ($user === null) {
153
-				$this->logger->error($argument['uid'] . ' doesn\'t exist, can\'t verify user data.');
153
+				$this->logger->error($argument['uid'].' doesn\'t exist, can\'t verify user data.');
154 154
 				return $result;
155 155
 			}
156 156
 			$userData = $this->accountManager->getUser($user);
@@ -181,7 +181,7 @@  discard block
 block discarded – undo
181 181
 
182 182
 		// we don't check a valid user -> give up
183 183
 		if ($user === null) {
184
-			$this->logger->error($argument['uid'] . ' doesn\'t exist, can\'t verify user data.');
184
+			$this->logger->error($argument['uid'].' doesn\'t exist, can\'t verify user data.');
185 185
 			return true;
186 186
 		}
187 187
 
@@ -220,7 +220,7 @@  discard block
 block discarded – undo
220 220
 		try {
221 221
 			$client = $this->clientService->newClient();
222 222
 			$response = $client->get(
223
-				$this->lookupServerUrl . '/users?search=' . urlencode($cloudId),
223
+				$this->lookupServerUrl.'/users?search='.urlencode($cloudId),
224 224
 				[
225 225
 					'timeout' => 10,
226 226
 					'connect_timeout' => 3,
@@ -255,7 +255,7 @@  discard block
 block discarded – undo
255 255
 				'data' => $argument['data'],
256 256
 				'type' => $argument['type'],
257 257
 				'uid' => $argument['uid'],
258
-				'try' => (int)$argument['try'] + 1,
258
+				'try' => (int) $argument['try'] + 1,
259 259
 				'lastRun' => time()
260 260
 			]
261 261
 		);
@@ -268,7 +268,7 @@  discard block
 block discarded – undo
268 268
 	 * @return bool
269 269
 	 */
270 270
 	protected function shouldRun(array $argument) {
271
-		$lastRun = (int)$argument['lastRun'];
271
+		$lastRun = (int) $argument['lastRun'];
272 272
 		return ((time() - $lastRun) > $this->interval);
273 273
 	}
274 274
 
Please login to merge, or discard this patch.