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

MiscService::mustContains()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 11
rs 9.9
cc 4
nc 6
nop 2
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 daita\MySmallPhpTools\Traits\TArrayTools;
30
use Exception;
31
use OC;
32
use OC\User\NoUserException;
33
use OCA\Circles\AppInfo\Application;
34
use OCA\Circles\Exceptions\MissingKeyInArrayException;
35
use OCA\Circles\Model\Member;
36
use OCP\AppFramework\Http;
37
use OCP\AppFramework\Http\DataResponse;
38
use OCP\Contacts\ContactsMenu\IContactsStore;
39
use OCP\ILogger;
40
use OCP\IUserManager;
41
42
class MiscService {
43
44
45
	use TArrayTools;
46
47
48
	/** @var ILogger */
49
	private $logger;
50
51
	/** @var IContactsStore */
52
	private $contactsStore;
53
54
	/** @var string */
55
	private $appName;
56
57
	/** @var IUserManager */
58
	private $userManager;
59
60
	public function __construct(
61
		ILogger $logger, IContactsStore $contactsStore, $appName, IUserManager $userManager
62
	) {
63
		$this->logger = $logger;
64
		$this->contactsStore = $contactsStore;
65
		$this->appName = $appName;
66
		$this->userManager = $userManager;
67
	}
68
69
	public function log($message, $level = 4) {
70
		$data = array(
71
			'app'   => $this->appName,
72
			'level' => $level
73
		);
74
75
		$this->logger->log($level, $message, $data);
76
	}
77
78
79
	/**
80
	 * @param $arr
81
	 * @param $k
82
	 *
83
	 * @param string $default
84
	 *
85
	 * @return array|string
86
	 */
87
	public static function get($arr, $k, $default = '') {
88
		if (!key_exists($k, $arr)) {
89
			return $default;
90
		}
91
92
		return $arr[$k];
93
	}
94
95
96
	public static function mustContains($data, $arr) {
97
		if (!is_array($arr)) {
98
			$arr = [$arr];
99
		}
100
101
		foreach ($arr as $k) {
102
			if (!key_exists($k, $data)) {
103
				throw new MissingKeyInArrayException('missing_key_in_array');
104
			}
105
		}
106
	}
107
108
109
	/**
110
	 * @param $data
111
	 *
112
	 * @return DataResponse
113
	 */
114
	public function fail($data) {
115
		$this->log(json_encode($data));
116
117
		return new DataResponse(
118
			array_merge($data, array('status' => 0)),
119
			Http::STATUS_NON_AUTHORATIVE_INFORMATION
120
		);
121
	}
122
123
124
	/**
125
	 * @param $data
126
	 *
127
	 * @return DataResponse
128
	 */
129
	public function success($data) {
130
		return new DataResponse(
131
			array_merge($data, array('status' => 1)),
132
			Http::STATUS_CREATED
133
		);
134
	}
135
136
137
	/**
138
	 * return the real userId, with its real case
139
	 *
140
	 * @param $userId
141
	 *
142
	 * @return string
143
	 * @throws NoUserException
144
	 */
145
	public function getRealUserId($userId) {
146
		if ($this->userManager->userExists($userId)) {
147
			return $this->userManager->get($userId)
148
									 ->getUID();
149
		}
150
151
		$result = $this->userManager->search($userId);
152
		if (sizeof($result) !== 1) {
153
			throw new NoUserException();
154
		}
155
156
		$user = array_shift($result);
157
158
		return $user->getUID();
159
	}
160
161
162
	/**
163
	 * @param Member $member
164
	 */
165
	public function updateCachedName(Member $member) {
166
		try {
167
			$cachedName = $this->getDisplay($member->getUserId(), $member->getType());
168
			if ($cachedName !== $member->getUserId()) {
169
				$member->setCachedName($cachedName);
170
			}
171
		} catch (Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
172
		}
173
	}
174
175
176
	/**
177
	 * @param string $ident
178
	 * @param int $type
179
	 *
180
	 * @return string
181
	 */
182
	public static function getDisplay($ident, $type) {
183
		$display = $ident;
184
185
		self::getDisplayMember($display, $ident, $type);
186
		self::getDisplayContact($display, $ident, $type);
187
188
		return $display;
189
	}
190
191
192
	/**
193
	 * @param string $display
194
	 * @param string $ident
195
	 * @param int $type
196
	 */
197
	private static function getDisplayMember(&$display, $ident, $type) {
198
		if ($type !== Member::TYPE_USER) {
199
			return;
200
		}
201
202
		$user = OC::$server->getUserManager()
203
						   ->get($ident);
204
		if ($user !== null) {
205
			$display = $user->getDisplayName();
206
		}
207
	}
208
209
210
	/**
211
	 * @param string $display
212
	 * @param string $ident
213
	 * @param int $type
214
	 */
215
	private static function getDisplayContact(&$display, $ident, $type) {
216
		if ($type !== Member::TYPE_CONTACT) {
217
			return;
218
		}
219
220
		$contact = self::getContactData($ident);
221
		if ($contact === null) {
222
			return;
223
		}
224
		self::getDisplayContactFromArray($display, $contact);
225
	}
226
227
228
	/**
229
	 * @param $ident
230
	 *
231
	 * @return mixed|string
232
	 */
233
	public static function getContactData($ident) {
234
		if (!class_exists(\OCA\DAV\CardDAV\ContactsManager::class) || !strpos($ident, ':')) {
235
			return [];
236
		}
237
238
		list($userId, $contactId) = explode(':', $ident);
239
240
		try {
241
			/** @var \OCA\DAV\CardDAV\ContactsManager $cManager */
242
			$cManager = OC::$server->query(\OCA\DAV\CardDAV\ContactsManager::class);
243
			$urlGenerator = OC::$server->getURLGenerator();
244
245
			$cm = OC::$server->getContactsManager();
246
			$cManager->setupContactsProvider($cm, $userId, $urlGenerator);
247
			$contact = $cm->search($contactId, ['UID']);
248
249
			return array_shift($contact);
250
		} catch (Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
251
		}
252
253
		return [];
254
	}
255
256
257
	/**
258
	 * @param string $display
259
	 * @param array $contact
260
	 */
261
	private static function getDisplayContactFromArray(string &$display, array $contact) {
262
		if (!is_array($contact)) {
263
			return;
264
		}
265
266
		if (key_exists('FN', $contact) && $contact['FN'] !== '') {
267
			$display = $contact['FN'];
268
269
			return;
270
		}
271
272
		if (key_exists('EMAIL', $contact) && $contact['EMAIL'] !== '') {
273
			$display = $contact['EMAIL'];
274
275
			return;
276
		}
277
	}
278
279
	/**
280
	 * return Display Name if user exists and display name exists.
281
	 * returns Exception if user does not exist.
282
	 *
283
	 * However, with noException set to true, will return userId even if user does not exist
284
	 *
285
	 * @param $userId
286
	 * @param bool $noException
287
	 *
288
	 * @return string
289
	 * @throws NoUserException
290
	 */
291
	public function getDisplayName($userId, $noException = false) {
292
		$user = $this->userManager->get($userId);
293
		if ($user === null) {
294
			if ($noException) {
295
				return $userId;
296
			} else {
297
				throw new NoUserException();
298
			}
299
		}
300
301
		return $user->getDisplayName();
302
	}
303
304
305
	/**
306
	 * @param array $options
307
	 *
308
	 * @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...
309
	 */
310
	public static function generateClientBodyData($options = []) {
311
		return [
312
			'body'            => ['data' => $options],
313
			'timeout'         => Application::CLIENT_TIMEOUT,
314
			'connect_timeout' => Application::CLIENT_TIMEOUT
315
		];
316
	}
317
318
319
	/**
320
	 * Hacky way to async the rest of the process without keeping client on hold.
321
	 *
322
	 * @param string $result
323
	 */
324
	public function asyncAndLeaveClientOutOfThis($result = '') {
325
		if (ob_get_contents() !== false) {
326
			ob_end_clean();
327
		}
328
329
		header('Connection: close');
330
		ignore_user_abort();
331
		ob_start();
332
		echo(json_encode($result));
333
		$size = ob_get_length();
334
		header('Content-Length: ' . $size);
335
		ob_end_flush();
336
		flush();
337
	}
338
339
340
	/**
341
	 * Generate uuid: 2b5a7a87-8db1-445f-a17b-405790f91c80
342
	 *
343
	 * @param int $length
344
	 *
345
	 * @return string
346
	 */
347 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...
348
		$chars = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890';
349
350
		$str = '';
351
		$max = strlen($chars) - 1;
352
		for ($i = 0; $i <= $length; $i++) {
353
			try {
354
				$str .= $chars[random_int(0, $max)];
355
			} catch (Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
356
			}
357
		}
358
359
		return $str;
360
	}
361
362
363
	/**
364
	 * @param Member $member
365
	 *
366
	 * @return array
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use array<string,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...
367
	 */
368
	public function getInfosFromContact(Member $member) {
369
		$contact = MiscService::getContactData($member->getUserId());
370
371
		return [
372
			'memberId' => $member->getMemberId(),
373
			'emails'   => $this->getArray('EMAIL', $contact),
374
			'cloudIds' => $this->getArray('CLOUD', $contact)
375
		];
376
377
	}
378
379
}
380
381