Completed
Push — master ( ae7490...12fdd1 )
by Maxence
01:48 queued 12s
created

MiscService::getDisplayContactFromArray()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

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