Completed
Push — master ( c474c9...94398e )
by René
31s queued 13s
created

SystemController::isValidEmail()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 1
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 2
ccs 0
cts 2
cp 0
crap 6
rs 10
1
<?php
2
/**
3
 * @copyright Copyright (c) 2017 Vinzenz Rosenkranz <[email protected]>
4
 *
5
 * @author René Gieling <[email protected]>
6
 *
7
 * @license GNU AGPL version 3 or any later version
8
 *
9
 *  This program is free software: you can redistribute it and/or modify
10
 *  it under the terms of the GNU Affero General Public License as
11
 *  published by the Free Software Foundation, either version 3 of the
12
 *  License, or (at your option) any later version.
13
 *
14
 *  This program is distributed in the hope that it will be useful,
15
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 *  GNU Affero General Public License for more details.
18
 *
19
 *  You should have received a copy of the GNU Affero General Public License
20
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
21
 *
22
 */
23
24
namespace OCA\Polls\Controller;
25
26
use OCP\AppFramework\Controller;
27
use OCP\AppFramework\Http;
28
use OCP\AppFramework\Http\DataResponse;
29
30
use OCP\IGroupManager;
31
use OCP\IUser;
32
use OCP\IUserManager;
33
use OCP\IConfig;
34
use OCP\IRequest;
35
use OCA\Polls\Db\Share;
36
use OCA\Polls\Db\ShareMapper;
37
use OCA\Polls\Db\Vote;
38
use OCA\Polls\Db\VoteMapper;
39
use OCP\ILogger;
40
41
class SystemController extends Controller {
42
43
	private $userId;
44
	private $logger;
45
	private $systemConfig;
46
	private $groupManager;
47
	private $userManager;
48
	private $voteMapper;
49
	private $shareMapper;
50
51
	/**
52
	 * SystemController constructor.
53
	 * @param string $appName
54
	 * @param $userId
55
	 * @param IRequest $request
56
	 * @param ILogger $logger
57
	 * @param IConfig $systemConfig
58
	 * @param IGroupManager $groupManager
59
	 * @param IUserManager $userManager
60
	 * @param VoteMapper $voteMapper
61
	 * @param ShareMapper $shareMapper
62
	 */
63
	public function __construct(
64
		string $appName,
65
		$userId,
66
		IRequest $request,
67
		ILogger $logger,
68
		IConfig $systemConfig,
69
		IGroupManager $groupManager,
70
		IUserManager $userManager,
71
		VoteMapper $voteMapper,
72
		ShareMapper $shareMapper
73
	) {
74
		parent::__construct($appName, $request);
75
		$this->voteMapper = $voteMapper;
76
		$this->shareMapper = $shareMapper;
77
		$this->logger = $logger;
78
		$this->userId = $userId;
79
		$this->systemConfig = $systemConfig;
80
		$this->groupManager = $groupManager;
81
		$this->userManager = $userManager;
82
	}
83
84
	/**
85
	 * Validate string as email address
86
	 * @NoAdminRequired
87
	 * @param string $query
88
	 * @return Boolval
0 ignored issues
show
Bug introduced by
The type OCA\Polls\Controller\Boolval was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
89
	 */
90
	 private function isValidEmail($email) {
91
		 return (!preg_match('/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/', $email)) ? false : true;
92
	 }
93
94
	/**
95
	 * Get a list of NC users, groups and contacts
96
	 * @NoAdminRequired
97
	 * @NoCSRFRequired
98
	 * @param string $query
99
	 * @param bool $getGroups - search in groups
100
	 * @param bool $getUsers - search in site users
101
	 * @param bool $getContacts - search in contacs
102
	 * @param array $skipGroups - group names to skip in return array
103
	 * @param array $skipUsers - user names to skip in return array
104
	 * @return DataResponse
105
	 */
106
	public function getSiteUsersAndGroups($query = '', $getGroups = true, $getUsers = true, $getContacts = true, $getMail = false, $skipGroups = array(), $skipUsers = array()) {
0 ignored issues
show
Unused Code introduced by
The parameter $getMail is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

106
	public function getSiteUsersAndGroups($query = '', $getGroups = true, $getUsers = true, $getContacts = true, /** @scrutinizer ignore-unused */ $getMail = false, $skipGroups = array(), $skipUsers = array()) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
107
		$list = array();
108
		// if (filter_var($query, FILTER_VALIDATE_EMAIL)) {
109
		if ($this->isValidEmail($query)) {
110
			$list[] = [
111
				'id' => '',
112
				'user' => '',
113
				'organisation' => '',
114
				'displayName' => '',
115
				'emailAddress' => $query,
116
				'desc' => $query,
117
				'type' => 'email',
118
				'icon' => 'icon-mail',
119
				'avatarURL' => '',
120
				'avatar' => '',
121
				'lastLogin' => '',
122
				'cloudId' => ''
123
124
			];
125
		}
126
127
128
		if ($getGroups) {
129
			$groups = $this->groupManager->search($query);
130
			foreach ($groups as $group) {
131
				if (!in_array($group->getGID(), $skipGroups)) {
132
					$list[] = [
133
						'id' => $group->getGID(),
134
						'user' => $group->getGID(),
135
						'organisation' => '',
136
						'displayName' => $group->getGID(),
137
						'emailAddress' => '',
138
						'desc' => 'Group',
139
						'type' => 'group',
140
						'icon' => 'icon-group',
141
						'avatarURL' => '',
142
						'avatar' => '',
143
						'lastLogin' => '',
144
						'cloudId' => ''
145
146
					];
147
				}
148
			}
149
		}
150
151
		if ($getUsers) {
152
			$users = $this->userManager->searchDisplayName($query);
153
			foreach ($users as $user) {
154
				if (!in_array($user->getUID(), $skipUsers) && $user->isEnabled()) {
155
					$list[] = [
156
						'id' => $user->getUID(),
157
						'user' => $user->getUID(),
158
						'displayName' => $user->getDisplayName(),
159
						'organisation' => '',
160
						'emailAddress' => $user->getEMailAddress(),
161
						'desc' => 'User',
162
						'type' => 'user',
163
						'icon' => 'icon-user',
164
						'avatarURL' => '',
165
						'avatar' => '',
166
						'lastLogin' => $user->getLastLogin(),
167
						'cloudId' => $user->getCloudId()
168
					];
169
				}
170
			}
171
		}
172
173
		$contactsManager = \OC::$server->getContactsManager();
174
175
176
		if ($getContacts && $contactsManager->isEnabled()) {
177
			$contacts = $contactsManager->search($query, array('FN', 'EMAIL', 'ORG', 'CATEGORIES'));
178
179
			foreach ($contacts as $contact) {
180
				if (!array_key_exists('isLocalSystemBook', $contact) && array_key_exists('EMAIL', $contact)) {
181
182
					$emailAdresses = $contact['EMAIL'];
183
184
					if (!is_array($emailAdresses)) {
185
						$emailAdresses = array($emailAdresses);
186
					} else {
187
						// take the first eMail address for now
188
						$emailAdresses = array($emailAdresses[0]);
189
					}
190
191
					foreach ($emailAdresses as $emailAddress) {
192
						$list[] = [
193
							'id' => $contact['UID'],
194
							'user' => $contact['FN'],
195
							'displayName' => $contact['FN'],
196
							'organisation' => isset($contact['ORG']) ? $contact['ORG'] : '',
197
							'emailAddress' => $emailAddress,
198
							'desc' => 'Contact',
199
							'type' => 'contact',
200
							'icon' => 'icon-mail',
201
							'avatarURL' => '',
202
							'avatar' => isset($contact['PHOTO']) ? $contact['PHOTO'] : '',
203
							'lastLogin' => '',
204
							'cloudId' => ''
205
						];
206
					}
207
208
				}
209
			}
210
211
		}
212
213
		return new DataResponse([
214
			'siteusers' => $list
215
		], Http::STATUS_OK);
216
	}
217
218
	/**
219
	 * Validate it the user name is reservrd
220
	 * return false, if this username already exists as a user or as
221
	 * a participant of the poll
222
	 * @NoCSRFRequired
223
	 * @NoAdminRequired
224
	 * @PublicPage
225
	 * @return DataResponse
226
	 */
227
	public function validatePublicUsername($pollId, $userName, $token) {
228
229
		// return forbidden, if $pollId does not match the share's pollId, force int compare
230
		if (intval($this->shareMapper->findByToken($token)->getPollId()) !== intVal($pollId)) {
231
			return new DataResponse(['result' => false, 'error' => 'wrong token'], Http::STATUS_FORBIDDEN);
232
		}
233
234
		// return forbidden, if the length of the userame is lower than 3 characters
235
		if (strlen(trim($userName)) < 3) {
236
			return new DataResponse(['result' => false, 'error' => 'userName too short'], Http::STATUS_FORBIDDEN);
237
		}
238
239
		$list = array();
240
241
		// get all groups
242
		$groups = $this->groupManager->search('');
243
		foreach ($groups as $group) {
244
			$list[] = [
245
				'id' => $group->getGID(),
246
				'user' => $group->getGID(),
247
				'type' => 'group',
248
				'displayName' => $group->getGID(),
249
			];
250
		}
251
252
		// get all users
253
		$users = $this->userManager->searchDisplayName('');
254
		foreach ($users as $user) {
255
			$list[] = [
256
				'id' => $user->getUID(),
257
				'user' => $user->getUID(),
258
				'type' => 'user',
259
				'displayName' => $user->getDisplayName(),
260
			];
261
		}
262
263
		// get all participants
264
		$votes = $this->voteMapper->findParticipantsByPoll($pollId);
265
		foreach ($votes as $vote) {
266
			if ($vote->getUserId() !== '' && $vote->getUserId() !== null) {
267
				$list[] = [
268
					'id' => $vote->getUserId(),
269
					'user' => $vote->getUserId(),
270
					'type' => 'participant',
271
					'displayName' => $vote->getUserId(),
272
				];
273
			}
274
		}
275
276
		// get all shares for this poll
277
		$shares = $this->shareMapper->findByPoll($pollId);
278
		foreach ($shares as $share) {
279
			if ($share->getUserId() !== '' && $share->getUserId() !== null) {
280
				$list[] = [
281
					'id' => $share->getUserId(),
282
					'user' => $share->getUserId(),
283
					'type' => 'share',
284
					'displayName' => $share->getUserId(),
285
				];
286
			}
287
		}
288
289
		// check if the username is contained inside the generated list
290
		// return forbidden, if list contains requested username
291
		foreach ($list as $element) {
292
			if (strtolower(trim($userName)) === strtolower(trim($element['id'])) || strtolower(trim($userName)) === strtolower(trim($element['displayName']))) {
293
				return new DataResponse([
294
					'result' => false
295
				], Http::STATUS_FORBIDDEN);
296
			}
297
		}
298
299
		// return OK, if username is allowed
300
		return new DataResponse([
301
			'result' => true,
302
			'name' => $userName
303
		], Http::STATUS_OK);
304
	}
305
306
	public function getDisplayName() {
307
		$this->userManager = \OC::$server->getUserManager();
308
309
		if (\OC::$server->getUserManager()->get($this->userId) instanceof IUser) {
310
			return \OC::$server->getUserManager()->get($this->userId)->getDisplayName();
311
		} else {
312
			return $this->userId;
313
		}
314
	}
315
}
316