Completed
Push — master ( 138f00...e3741d )
by Maxence
16s queued 10s
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
	/**
164
	 * @param string $ident
165
	 *
166
	 * @return string
167
	 */
168
	public function getContactDisplayName(string $ident): string {
169
		if (!class_exists(\OCA\DAV\CardDAV\ContactsManager::class) || !strpos($ident, ':')) {
170
			return '';
171
		}
172
173
		list($userId, $contactId) = explode(':', $ident);
174
		$entries = [];
175
		try {
176
			/** @var \OCA\DAV\CardDAV\ContactsManager $cManager */
177
			$cManager = OC::$server->query(\OCA\DAV\CardDAV\ContactsManager::class);
178
			$urlGenerator = OC::$server->getURLGenerator();
179
180
			$cm = OC::$server->getContactsManager();
181
			$cManager->setupContactsProvider($cm, $userId, $urlGenerator);
182
			$contact = $cm->search($contactId, ['UID']);
183
184
			$entries = array_shift($contact);
185
		} catch (Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
186
		}
187
188
		if (key_exists('FN', $entries) && $entries['FN'] !== '') {
189
			return $entries['FN'];
190
		}
191
192
		if (key_exists('EMAIL', $entries) && $entries['EMAIL'] !== '') {
193
			return $entries['EMAIL'];
194
		}
195
	}
196
197
198
	/**
199
	 * @param string $ident
200
	 * @param int $type
201
	 *
202
	 * @return string
203
	 * @deprecated
204
	 *
205
	 */
206
	public static function getDisplay($ident, $type) {
207
		$display = $ident;
208
209
		self::getDisplayMember($display, $ident, $type);
210
		self::getDisplayContact($display, $ident, $type);
211
212
		return $display;
213
	}
214
215
216
	/**
217
	 * @param string $display
218
	 * @param string $ident
219
	 * @param int $type
220
	 */
221
	private static function getDisplayMember(&$display, $ident, $type) {
222
		if ($type !== Member::TYPE_USER) {
223
			return;
224
		}
225
226
		$user = OC::$server->getUserManager()
227
						   ->get($ident);
228
		if ($user !== null) {
229
			$display = $user->getDisplayName();
230
		}
231
	}
232
233
234
	/**
235
	 * @param string $display
236
	 * @param string $ident
237
	 * @param int $type
238
	 */
239
	private static function getDisplayContact(&$display, $ident, $type) {
240
		if ($type !== Member::TYPE_CONTACT) {
241
			return;
242
		}
243
244
		$contact = self::getContactData($ident);
0 ignored issues
show
Deprecated Code introduced by
The method OCA\Circles\Service\MiscService::getContactData() has been deprecated.

This method has been deprecated.

Loading history...
245
		if ($contact === null) {
246
			return;
247
		}
248
		self::getDisplayContactFromArray($display, $contact);
0 ignored issues
show
Deprecated Code introduced by
The method OCA\Circles\Service\Misc...splayContactFromArray() has been deprecated.

This method has been deprecated.

Loading history...
249
	}
250
251
252
	/**
253
	 * @param $ident
254
	 *
255
	 * @return mixed|string
256
	 * @deprecated
257
	 *
258
	 */
259
	public static function getContactData($ident) {
260
		if (!class_exists(\OCA\DAV\CardDAV\ContactsManager::class) || !strpos($ident, ':')) {
261
			return [];
262
		}
263
264
		list($userId, $contactId) = explode(':', $ident);
265
266
		try {
267
			/** @var \OCA\DAV\CardDAV\ContactsManager $cManager */
268
			$cManager = OC::$server->query(\OCA\DAV\CardDAV\ContactsManager::class);
269
			$urlGenerator = OC::$server->getURLGenerator();
270
271
			$cm = OC::$server->getContactsManager();
272
			$cManager->setupContactsProvider($cm, $userId, $urlGenerator);
273
			$contact = $cm->search($contactId, ['UID']);
274
275
			return array_shift($contact);
276
		} catch (Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
277
		}
278
279
		return [];
280
	}
281
282
283
	/**
284
	 * @param string $display
285
	 * @param array $contact
286
	 *
287
	 * @deprecated
288
	 */
289
	private static function getDisplayContactFromArray(string &$display, array $contact) {
290
		if (!is_array($contact)) {
291
			return;
292
		}
293
294
		if (key_exists('FN', $contact) && $contact['FN'] !== '') {
295
			$display = $contact['FN'];
296
297
			return;
298
		}
299
300
		if (key_exists('EMAIL', $contact) && $contact['EMAIL'] !== '') {
301
			$display = $contact['EMAIL'];
302
303
			return;
304
		}
305
	}
306
307
308
	/**
309
	 * return Display Name if user exists and display name exists.
310
	 * returns Exception if user does not exist.
311
	 *
312
	 * However, with noException set to true, will return userId even if user does not exist
313
	 *
314
	 * @param $userId
315
	 * @param bool $noException
316
	 *
317
	 * @return string
318
	 * @throws NoUserException
319
	 */
320
	public function getDisplayName($userId, $noException = false) {
321
		$user = $this->userManager->get($userId);
322
		if ($user === null) {
323
			if ($noException) {
324
				return $userId;
325
			} else {
326
				throw new NoUserException();
327
			}
328
		}
329
330
		return $user->getDisplayName();
331
	}
332
333
334
	/**
335
	 * @param array $options
336
	 *
337
	 * @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...
338
	 */
339
	public static function generateClientBodyData($options = []) {
340
		return [
341
			'body'            => ['data' => $options],
342
			'timeout'         => Application::CLIENT_TIMEOUT,
343
			'connect_timeout' => Application::CLIENT_TIMEOUT
344
		];
345
	}
346
347
348
	/**
349
	 * Hacky way to async the rest of the process without keeping client on hold.
350
	 *
351
	 * @param string $result
352
	 */
353
	public function asyncAndLeaveClientOutOfThis($result = '') {
354
		if (ob_get_contents() !== false) {
355
			ob_end_clean();
356
		}
357
358
		header('Connection: close');
359
		ignore_user_abort();
360
		ob_start();
361
		echo(json_encode($result));
362
		$size = ob_get_length();
363
		header('Content-Length: ' . $size);
364
		ob_end_flush();
365
		flush();
366
	}
367
368
369
	/**
370
	 * Generate uuid: 2b5a7a87-8db1-445f-a17b-405790f91c80
371
	 *
372
	 * @param int $length
373
	 *
374
	 * @return string
375
	 */
376 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...
377
		$chars = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890';
378
379
		$str = '';
380
		$max = strlen($chars) - 1;
381
		for ($i = 0; $i <= $length; $i++) {
382
			try {
383
				$str .= $chars[random_int(0, $max)];
384
			} catch (Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
385
			}
386
		}
387
388
		return $str;
389
	}
390
391
392
	/**
393
	 * @param Member $member
394
	 *
395
	 * @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...
396
	 */
397
	public function getInfosFromContact(Member $member) {
398
		$contact = MiscService::getContactData($member->getUserId());
0 ignored issues
show
Deprecated Code introduced by
The method OCA\Circles\Service\MiscService::getContactData() has been deprecated.

This method has been deprecated.

Loading history...
399
400
		return [
401
			'memberId' => $member->getMemberId(),
402
			'emails'   => $this->getArray('EMAIL', $contact),
403
			'cloudIds' => $this->getArray('CLOUD', $contact)
404
		];
405
406
	}
407
408
}
409
410