Completed
Pull Request — master (#8)
by Joas
02:16
created

Manager::addGroupLink()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 9
ccs 9
cts 9
cp 1
rs 9.6666
cc 1
eloc 7
nc 1
nop 2
crap 1
1
<?php
2
/**
3
 * @author Joas Schilling <[email protected]>
4
 *
5
 * @copyright Copyright (c) 2016, Joas Schilling <[email protected]>
6
 * @license AGPL-3.0
7
 *
8
 * This code is free software: you can redistribute it and/or modify
9
 * it under the terms of the GNU Affero General Public License, version 3,
10
 * as published by the Free Software Foundation.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
 * GNU Affero General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Affero General Public License, version 3,
18
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
19
 *
20
 */
21
22
namespace OCA\AnnouncementCenter;
23
24
use OCP\DB\QueryBuilder\IQueryBuilder;
25
use OCP\IDBConnection;
26
use OCP\IGroupManager;
27
use OCP\IUser;
28
use OCP\IUserSession;
29
30
class Manager {
31
32
	/** @var IDBConnection */
33
	private $connection;
34
35
	/** @var IGroupManager */
36
	private $groupManager;
37
38
39
	/** @var IUserSession */
40
	private $userSession;
41
42
	/**
43
	 * @param IDBConnection $connection
44
	 * @param IGroupManager $groupManager
45
	 * @param IUserSession $userSession
46
	 */
47 7
	public function __construct(IDBConnection $connection, IGroupManager $groupManager, IUserSession $userSession) {
48 7
		$this->connection = $connection;
49 7
		$this->groupManager = $groupManager;
50 7
		$this->userSession = $userSession;
51 7
	}
52
53
	/**
54
	 * @param string $subject
55
	 * @param string $message
56
	 * @param string $user
57
	 * @param int $time
58
	 * @param string[] $groups
59
	 * @return array
60
	 * @throws \InvalidArgumentException when the subject is empty or invalid
61
	 */
62 3
	public function announce($subject, $message, $user, $time, array $groups) {
63 3
		$subject = trim($subject);
64 3
		$message = trim($message);
65 3
		if (isset($subject[512])) {
66 1
			throw new \InvalidArgumentException('Invalid subject', 1);
67
		}
68
69 2
		if ($subject === '') {
70 1
			throw new \InvalidArgumentException('Invalid subject', 2);
71
		}
72
73 1
		$queryBuilder = $this->connection->getQueryBuilder();
74 1
		$queryBuilder->insert('announcements')
75 1
			->values([
76 1
				'announcement_time' => $queryBuilder->createParameter('time'),
77 1
				'announcement_user' => $queryBuilder->createParameter('user'),
78 1
				'announcement_subject' => $queryBuilder->createParameter('subject'),
79 1
				'announcement_message' => $queryBuilder->createParameter('message'),
80 1
			])
81 1
			->setParameter('time', $time)
82 1
			->setParameter('user', $user)
83 1
			->setParameter('subject', $subject)
84 1
			->setParameter('message', $message);
85 1
		$queryBuilder->execute();
86
87 1
		$queryBuilder = $this->connection->getQueryBuilder();
88 1
		$query = $queryBuilder->select('*')
89 1
			->from('announcements')
90 1
			->where($queryBuilder->expr()->eq('announcement_time', $queryBuilder->createParameter('time')))
91 1
			->andWhere($queryBuilder->expr()->eq('announcement_user', $queryBuilder->createParameter('user')))
92 1
			->orderBy('announcement_id', 'DESC')
93 1
			->setParameter('time', (int) $time)
94 1
			->setParameter('user', $user);
95 1
		$result = $query->execute();
96 1
		$row = $result->fetch();
97 1
		$result->closeCursor();
98
99 1
		$addedGroups = 0;
100 1
		foreach ($groups as $group) {
101
			if ($this->groupManager->groupExists($group)) {
102
				$this->addGroupLink((int) $row['announcement_id'], $group);
103
				$addedGroups++;
104
			}
105 1
		}
106
107 1
		if ($addedGroups === 0) {
108 1
			$this->addGroupLink((int) $row['announcement_id'], 'everyone');
109 1
		}
110
111
		return [
112 1
			'id'		=> (int) $row['announcement_id'],
113 1
			'author'	=> $row['announcement_user'],
114 1
			'time'		=> (int) $row['announcement_time'],
115 1
			'subject'	=> $this->parseSubject($row['announcement_subject']),
116 1
			'message'	=> $this->parseMessage($row['announcement_message']),
117 1
		];
118
	}
119
120
	/**
121
	 * @param int $announcementId
122
	 * @param string $group
123
	 */
124 1
	protected function addGroupLink($announcementId, $group) {
125 1
		$query = $this->connection->getQueryBuilder();
126 1
		$query->insert('announcements_groups')
127 1
			->values([
128 1
				'announcement_id' => $query->createNamedParameter($announcementId),
129 1
				'gid' => $query->createNamedParameter($group),
130 1
			]);
131 1
		$query->execute();
132 1
	}
133
134
	/**
135
	 * @param int $id
136
	 */
137 1
	public function delete($id) {
138 1
		$query = $this->connection->getQueryBuilder();
139 1
		$query->delete('announcements')
140 1
			->where($query->expr()->eq('announcement_id', $query->createNamedParameter((int) $id)));
141 1
		$query->execute();
142
143 1
		$query = $this->connection->getQueryBuilder();
144 1
		$query->delete('announcements_groups')
145 1
			->where($query->expr()->eq('announcement_id', $query->createNamedParameter((int) $id)));
146 1
		$query->execute();
147 1
	}
148
149
	/**
150
	 * @param int $id
151
	 * @param bool $parseStrings
152
	 * @param bool $ignorePermissions
153
	 * @return array
154
	 * @throws \InvalidArgumentException when the id is invalid
155
	 */
156 2
	public function getAnnouncement($id, $parseStrings = true, $ignorePermissions = false) {
157 2
		if (!$ignorePermissions) {
158 2
			$user = $this->userSession->getUser();
159 2 View Code Duplication
			if ($user instanceof IUser) {
0 ignored issues
show
Bug introduced by
The class OCP\IUser does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
Duplication introduced by
This code seems to be duplicated across 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...
160
				$groups = $this->groupManager->getUserGroupIds($user);
161
				$groups[] = 'everyone';
162
			} else {
163 2
				$groups = ['everyone'];
164
			}
165
166 2
			if (!in_array('admin', $groups)) {
167 2
				$query = $this->connection->getQueryBuilder();
168 2
				$query->select('*')
169 2
					->from('announcements_groups')
170 2
					->where($query->expr()->eq('announcement_id', $query->createNamedParameter((int) $id)))
171 2
					->andWhere($query->expr()->in('gid', $query->createNamedParameter($groups, IQueryBuilder::PARAM_STR_ARRAY)))
172 2
					->setMaxResults(1);
173 2
				$result = $query->execute();
174 2
				$entry = $result->fetch();
175 2
				$result->closeCursor();
176
177 2
				if ($entry === null) {
178
					throw new \InvalidArgumentException('Invalid ID');
179
				}
180 2
			}
181 2
		}
182
183 2
		$queryBuilder = $this->connection->getQueryBuilder();
184 2
		$query = $queryBuilder->select('*')
185 2
			->from('announcements')
186 2
			->where($queryBuilder->expr()->eq('announcement_id', $queryBuilder->createParameter('id')))
187 2
			->setParameter('id', (int) $id);
188 2
		$result = $query->execute();
189 2
		$row = $result->fetch();
190 2
		$result->closeCursor();
191
192 2
		if ($row === false) {
193 2
			throw new \InvalidArgumentException('Invalid ID');
194
		}
195
196
		return [
197 1
			'id'		=> (int) $row['announcement_id'],
198 1
			'author'	=> $row['announcement_user'],
199 1
			'time'		=> (int) $row['announcement_time'],
200 1
			'subject'	=> ($parseStrings) ? $this->parseSubject($row['announcement_subject']) : $row['announcement_subject'],
201 1
			'message'	=> ($parseStrings) ? $this->parseMessage($row['announcement_message']) : $row['announcement_message'],
202 1
		];
203
	}
204
205
	/**
206
	 * @param int $limit
207
	 * @param int $offset
208
	 * @param bool $parseStrings
209
	 * @return array
210
	 */
211 1
	public function getAnnouncements($limit = 15, $offset = 0, $parseStrings = true) {
212 1
		$query = $this->connection->getQueryBuilder();
213 1
		$query->select('a.*')
214 1
			->from('announcements', 'a')
215 1
			->orderBy('a.announcement_time', 'DESC')
216 1
			->setMaxResults($limit);
217
218 1
		$user = $this->userSession->getUser();
219 1 View Code Duplication
		if ($user instanceof IUser) {
0 ignored issues
show
Bug introduced by
The class OCP\IUser does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
Duplication introduced by
This code seems to be duplicated across 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...
220
			$groups = $this->groupManager->getUserGroupIds($user);
221
			$groups[] = 'everyone';
222
		} else {
223 1
			$groups = ['everyone'];
224
		}
225
226 1
		if (!in_array('admin', $groups)) {
227 1
			$query->leftJoin('a', 'announcements_groups', 'ag', $query->expr()->eq(
228 1
				'a.announcement_id', 'ag.announcement_id'
229 1
			))
230 1
				->andWhere($query->expr()->in('ag.gid', $query->createNamedParameter($groups, IQueryBuilder::PARAM_STR_ARRAY)));
231 1
		}
232
233 1
		if ($offset > 0) {
234
			$query->andWhere($query->expr()->lt('a.announcement_id', $query->createNamedParameter($offset, IQueryBuilder::PARAM_INT)));
235
		}
236
237 1
		$result = $query->execute();
238
239
240 1
		$announcements = [];
241 1
		while ($row = $result->fetch()) {
242 1
			$announcements[] = [
243 1
				'id'		=> (int) $row['announcement_id'],
244 1
				'author'	=> $row['announcement_user'],
245 1
				'time'		=> (int) $row['announcement_time'],
246 1
				'subject'	=> ($parseStrings) ? $this->parseSubject($row['announcement_subject']) : $row['announcement_subject'],
247 1
				'message'	=> ($parseStrings) ? $this->parseMessage($row['announcement_message']) : $row['announcement_message'],
248
			];
249 1
		}
250 1
		$result->closeCursor();
251
252
253 1
		return $announcements;
254
	}
255
256
	/**
257
	 * Return the groups (or string everyone) which have access to the announcement
258
	 *
259
	 * @param int $id
260
	 * @return string[]
261
	 */
262
	public function getGroups($id) {
263
		$query = $this->connection->getQueryBuilder();
264
		$query->select('gid')
265
			->from('announcements_groups')
266
			->where($query->expr()->eq('announcement_id', $query->createNamedParameter($id)));
267
		$result = $query->execute();
268
269
		$groups = [];
270
		while ($row = $result->fetch()) {
271
			$groups[] = $row['gid'];
272
		}
273
		$result->closeCursor();
274
275
		return $groups;
276
	}
277
278
	/**
279
	 * @param string $message
280
	 * @return string
281
	 */
282 1
	protected function parseMessage($message) {
283 1
		return str_replace("\n", '<br />', str_replace(['<', '>'], ['&lt;', '&gt;'], $message));
284
	}
285
286
	/**
287
	 * @param string $subject
288
	 * @return string
289
	 */
290 1
	protected function parseSubject($subject) {
291 1
		return str_replace("\n", ' ', str_replace(['<', '>'], ['&lt;', '&gt;'], $subject));
292
	}
293
}
294