Completed
Pull Request — master (#477)
by Maxence
02:01
created

MiscService::updateCachedName()   A

Complexity

Conditions 2
Paths 3

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 2
nc 3
nop 1
1
<?php
2
/**
3
 * Circles - Bring cloud-users closer together.
4
 *
5
 * This file is licensed under the Affero General Public License version 3 or
6
 * later. See the COPYING file.
7
 *
8
 * @author Maxence Lange <[email protected]>
9
 * @copyright 2017
10
 * @license GNU AGPL version 3 or any later version
11
 *
12
 * This program is free software: you can redistribute it and/or modify
13
 * it under the terms of the GNU Affero General Public License as
14
 * published by the Free Software Foundation, either version 3 of the
15
 * License, or (at your option) any later version.
16
 *
17
 * This program is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
 * GNU Affero General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU Affero General Public License
23
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
24
 *
25
 */
26
27
namespace OCA\Circles\Service;
28
29
use Exception;
30
use OC;
31
use OC\User\NoUserException;
32
use OCA\Circles\AppInfo\Application;
33
use OCA\Circles\Exceptions\MissingKeyInArrayException;
34
use OCA\Circles\Model\Member;
35
use OCP\AppFramework\Http;
36
use OCP\AppFramework\Http\DataResponse;
37
use OCP\Contacts\ContactsMenu\IContactsStore;
38
use OCP\ILogger;
39
use OCP\IUserManager;
40
41
class MiscService {
42
43
	/** @var ILogger */
44
	private $logger;
45
46
	/** @var IContactsStore */
47
	private $contactsStore;
48
49
	/** @var string */
50
	private $appName;
51
52
	/** @var IUserManager */
53
	private $userManager;
54
55
	public function __construct(
56
		ILogger $logger, IContactsStore $contactsStore, $appName, IUserManager $userManager
57
	) {
58
		$this->logger = $logger;
59
		$this->contactsStore = $contactsStore;
60
		$this->appName = $appName;
61
		$this->userManager = $userManager;
62
	}
63
64
	public function log($message, $level = 4) {
65
		$data = array(
66
			'app'   => $this->appName,
67
			'level' => $level
68
		);
69
70
		$this->logger->log($level, $message, $data);
71
	}
72
73
74
	/**
75
	 * @param $arr
76
	 * @param $k
77
	 *
78
	 * @param string $default
79
	 *
80
	 * @return array|string
81
	 */
82
	public static function get($arr, $k, $default = '') {
83
		if (!key_exists($k, $arr)) {
84
			return $default;
85
		}
86
87
		return $arr[$k];
88
	}
89
90
91
	public static function mustContains($data, $arr) {
92
		if (!is_array($arr)) {
93
			$arr = [$arr];
94
		}
95
96
		foreach ($arr as $k) {
97
			if (!key_exists($k, $data)) {
98
				throw new MissingKeyInArrayException('missing_key_in_array');
99
			}
100
		}
101
	}
102
103
104
	/**
105
	 * @param $data
106
	 *
107
	 * @return DataResponse
108
	 */
109
	public function fail($data) {
110
		$this->log(json_encode($data));
111
112
		return new DataResponse(
113
			array_merge($data, array('status' => 0)),
114
			Http::STATUS_NON_AUTHORATIVE_INFORMATION
115
		);
116
	}
117
118
119
	/**
120
	 * @param $data
121
	 *
122
	 * @return DataResponse
123
	 */
124
	public function success($data) {
125
		return new DataResponse(
126
			array_merge($data, array('status' => 1)),
127
			Http::STATUS_CREATED
128
		);
129
	}
130
131
132
	/**
133
	 * return the real userId, with its real case
134
	 *
135
	 * @param $userId
136
	 *
137
	 * @return string
138
	 * @throws NoUserException
139
	 */
140
	public function getRealUserId($userId) {
141
		if ($this->userManager->userExists($userId)) {
142
			return $this->userManager->get($userId)
143
									 ->getUID();
144
		}
145
146
		$result = $this->userManager->search($userId);
147
		if (sizeof($result) !== 1) {
148
			throw new NoUserException();
149
		}
150
151
		$user = array_shift($result);
152
153
		return $user->getUID();
154
	}
155
156
157
	/**
158
	 * @param Member $member
159
	 */
160
	public function updateCachedName(Member $member) {
161
		try {
162
			$cachedName = $this->getDisplay($member->getUserId(), $member->getType());
163
			$member->setCachedName($cachedName);
164
		} catch (Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
165
		}
166
	}
167
168
169
	/**
170
	 * @param string $ident
171
	 * @param int $type
172
	 *
173
	 * @return string
174
	 */
175
	public static function getDisplay($ident, $type) {
176
		$display = $ident;
177
178
		self::getDisplayMember($display, $ident, $type);
179
		self::getDisplayContact($display, $ident, $type);
180
181
		return $display;
182
	}
183
184
185
	/**
186
	 * @param string $display
187
	 * @param string $ident
188
	 * @param int $type
189
	 */
190
	private static function getDisplayMember(&$display, $ident, $type) {
191
		if ($type !== Member::TYPE_USER) {
192
			return;
193
		}
194
195
		$user = OC::$server->getUserManager()
196
						   ->get($ident);
197
		if ($user !== null) {
198
			$display = $user->getDisplayName();
199
		}
200
	}
201
202
203
	/**
204
	 * @param string $display
205
	 * @param string $ident
206
	 * @param int $type
207
	 */
208
	private static function getDisplayContact(&$display, $ident, $type) {
209
		if ($type !== Member::TYPE_CONTACT) {
210
			return;
211
		}
212
213
		$contact = self::getContactData($ident);
214
		if ($contact === null) {
215
			return;
216
		}
217
		self::getDisplayContactFromArray($display, $contact);
218
	}
219
220
221
	/**
222
	 * @param $ident
223
	 *
224
	 * @return mixed|string
225
	 */
226
	public static function getContactData($ident) {
227
		if (!class_exists(\OCA\DAV\CardDAV\ContactsManager::class) || !strpos($ident, ':')) {
228
			return [];
229
		}
230
231
		list($userId, $contactId) = explode(':', $ident);
232
233
		try {
234
			/** @var \OCA\DAV\CardDAV\ContactsManager $cManager */
235
			$cManager = OC::$server->query(\OCA\DAV\CardDAV\ContactsManager::class);
236
			$urlGenerator = OC::$server->getURLGenerator();
237
238
			$cm = OC::$server->getContactsManager();
239
			$cManager->setupContactsProvider($cm, $userId, $urlGenerator);
240
			$contact = $cm->search($contactId, ['UID']);
241
242
			return array_shift($contact);
243
		} catch (Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
244
		}
245
246
		return [];
247
	}
248
249
250
	/**
251
	 * @param string $display
252
	 * @param array $contact
253
	 */
254
	private static function getDisplayContactFromArray(string &$display, array $contact) {
255
		if (!is_array($contact)) {
256
			return;
257
		}
258
259
		if (key_exists('FN', $contact) && $contact['FN'] !== '') {
260
			$display = $contact['FN'];
261
262
			return;
263
		}
264
265
		if (key_exists('EMAIL', $contact) && $contact['EMAIL'] !== '') {
266
			$display = $contact['EMAIL'];
267
268
			return;
269
		}
270
	}
271
272
	/**
273
	 * return Display Name if user exists and display name exists.
274
	 * returns Exception if user does not exist.
275
	 *
276
	 * However, with noException set to true, will return userId even if user does not exist
277
	 *
278
	 * @param $userId
279
	 * @param bool $noException
280
	 *
281
	 * @return string
282
	 * @throws NoUserException
283
	 */
284
	public function getDisplayName($userId, $noException = false) {
285
		$user = $this->userManager->get($userId);
286
		if ($user === null) {
287
			if ($noException) {
288
				return $userId;
289
			} else {
290
				throw new NoUserException();
291
			}
292
		}
293
294
		return $user->getDisplayName();
295
	}
296
297
298
	/**
299
	 * @param array $options
300
	 *
301
	 * @return array
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use array<string,array<string,array>>.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
302
	 */
303
	public static function generateClientBodyData($options = []) {
304
		return [
305
			'body'            => ['data' => $options],
306
			'timeout'         => Application::CLIENT_TIMEOUT,
307
			'connect_timeout' => Application::CLIENT_TIMEOUT
308
		];
309
	}
310
311
312
	/**
313
	 * Hacky way to async the rest of the process without keeping client on hold.
314
	 *
315
	 * @param string $result
316
	 */
317
	public function asyncAndLeaveClientOutOfThis($result = '') {
318
		if (ob_get_contents() !== false) {
319
			ob_end_clean();
320
		}
321
322
		header('Connection: close');
323
		ignore_user_abort();
324
		ob_start();
325
		echo(json_encode($result));
326
		$size = ob_get_length();
327
		header('Content-Length: ' . $size);
328
		ob_end_flush();
329
		flush();
330
	}
331
332
333
	/**
334
	 * Generate uuid: 2b5a7a87-8db1-445f-a17b-405790f91c80
335
	 *
336
	 * @param int $length
337
	 *
338
	 * @return string
339
	 */
340 View Code Duplication
	public function token(int $length = 0): string {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
341
		$chars = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890';
342
343
		$str = '';
344
		$max = strlen($chars) - 1;
345
		for ($i = 0; $i <= $length; $i++) {
346
			try {
347
				$str .= $chars[random_int(0, $max)];
348
			} catch (Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
349
			}
350
		}
351
352
		return $str;
353
	}
354
355
}
356
357