Completed
Pull Request — master (#8)
by Joas
07:10
created

Manager::getGroups()   B

Complexity

Conditions 5
Paths 12

Size

Total Lines 24
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 5

Importance

Changes 3
Bugs 1 Features 0
Metric Value
c 3
b 1
f 0
dl 0
loc 24
ccs 20
cts 20
cp 1
rs 8.5125
cc 5
eloc 17
nc 12
nop 1
crap 5
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 11
	public function __construct(IDBConnection $connection, IGroupManager $groupManager, IUserSession $userSession) {
48 11
		$this->connection = $connection;
49 11
		$this->groupManager = $groupManager;
50 11
		$this->userSession = $userSession;
51 11
	}
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 7
	public function announce($subject, $message, $user, $time, array $groups) {
63 7
		$subject = trim($subject);
64 7
		$message = trim($message);
65 7
		if (isset($subject[512])) {
66 1
			throw new \InvalidArgumentException('Invalid subject', 1);
67
		}
68
69 6
		if ($subject === '') {
70 1
			throw new \InvalidArgumentException('Invalid subject', 2);
71
		}
72
73 5
		$queryBuilder = $this->connection->getQueryBuilder();
74 5
		$queryBuilder->insert('announcements')
75 5
			->values([
76 5
				'announcement_time' => $queryBuilder->createNamedParameter($time),
77 5
				'announcement_user' => $queryBuilder->createNamedParameter($user),
78 5
				'announcement_subject' => $queryBuilder->createNamedParameter($subject),
79 5
				'announcement_message' => $queryBuilder->createNamedParameter($message),
80 5
			]);
81 5
		$queryBuilder->execute();
82
83 5
		$id = $queryBuilder->getLastInsertId();
84
85 5
		$addedGroups = 0;
86 5
		foreach ($groups as $group) {
87 5
			if ($this->groupManager->groupExists($group)) {
88 4
				$this->addGroupLink((int) $id, $group);
89 4
				$addedGroups++;
90 4
			}
91 5
		}
92
93 5
		if ($addedGroups === 0) {
94 4
			$this->addGroupLink((int) $id, 'everyone');
95 4
		}
96
97 5
		return $this->getAnnouncement($id, true, true);
98
	}
99
100
	/**
101
	 * @param int $announcementId
102
	 * @param string $group
103
	 */
104 5
	protected function addGroupLink($announcementId, $group) {
105 5
		$query = $this->connection->getQueryBuilder();
106 5
		$query->insert('announcements_groups')
107 5
			->values([
108 5
				'announcement_id' => $query->createNamedParameter($announcementId),
109 5
				'gid' => $query->createNamedParameter($group),
110 5
			]);
111 5
		$query->execute();
112 5
	}
113
114
	/**
115
	 * @param int $id
116
	 */
117 5
	public function delete($id) {
118 5
		$query = $this->connection->getQueryBuilder();
119 5
		$query->delete('announcements')
120 5
			->where($query->expr()->eq('announcement_id', $query->createNamedParameter((int) $id)));
121 5
		$query->execute();
122
123 5
		$query = $this->connection->getQueryBuilder();
124 5
		$query->delete('announcements_groups')
125 5
			->where($query->expr()->eq('announcement_id', $query->createNamedParameter((int) $id)));
126 5
		$query->execute();
127 5
	}
128
129
	/**
130
	 * @param int $id
131
	 * @param bool $parseStrings
132
	 * @param bool $ignorePermissions
133
	 * @return array
134
	 * @throws \InvalidArgumentException when the id is invalid
135
	 */
136 6
	public function getAnnouncement($id, $parseStrings = true, $ignorePermissions = false) {
137 6
		if (!$ignorePermissions) {
138 4
			$user = $this->userSession->getUser();
139 4 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...
140 2
				$userGroups = $this->groupManager->getUserGroupIds($user);
141 2
				$userGroups[] = 'everyone';
142 2
			} else {
143 2
				$userGroups = ['everyone'];
144
			}
145
146 4
			if (!in_array('admin', $userGroups)) {
147 3
				$query = $this->connection->getQueryBuilder();
148 3
				$query->select('*')
149 3
					->from('announcements_groups')
150 3
					->where($query->expr()->eq('announcement_id', $query->createNamedParameter((int) $id)))
151 3
					->andWhere($query->expr()->in('gid', $query->createNamedParameter($userGroups, IQueryBuilder::PARAM_STR_ARRAY)))
152 3
					->setMaxResults(1);
153 3
				$result = $query->execute();
154 3
				$entry = $result->fetch();
155 3
				$result->closeCursor();
156
157 3
				if (!$entry) {
158 3
					throw new \InvalidArgumentException('Invalid ID');
159
				}
160 2
			}
161 3
		}
162
163 5
		$queryBuilder = $this->connection->getQueryBuilder();
164 5
		$query = $queryBuilder->select('*')
165 5
			->from('announcements')
166 5
			->where($queryBuilder->expr()->eq('announcement_id', $queryBuilder->createParameter('id')))
167 5
			->setParameter('id', (int) $id);
168 5
		$result = $query->execute();
169 5
		$row = $result->fetch();
170 5
		$result->closeCursor();
171
172 5
		if ($row === false) {
173 3
			throw new \InvalidArgumentException('Invalid ID');
174
		}
175
176 5
		$groups = null;
177 5
		if ($ignorePermissions || (isset($userGroups) && in_array('admin', $userGroups))) {
0 ignored issues
show
Bug introduced by
The variable $userGroups does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
178 5
			$groups = $this->getGroups($id);
179 5
		}
180
181
		return [
182 5
			'id'		=> (int) $row['announcement_id'],
183 5
			'author'	=> $row['announcement_user'],
184 5
			'time'		=> (int) $row['announcement_time'],
185 5
			'subject'	=> ($parseStrings) ? $this->parseSubject($row['announcement_subject']) : $row['announcement_subject'],
186 5
			'message'	=> ($parseStrings) ? $this->parseMessage($row['announcement_message']) : $row['announcement_message'],
187 5
			'groups'	=> $groups,
188 5
		];
189
	}
190
191
	/**
192
	 * @param int $limit
193
	 * @param int $offset
194
	 * @param bool $parseStrings
195
	 * @return array
196
	 */
197 3
	public function getAnnouncements($limit = 15, $offset = 0, $parseStrings = true) {
198 3
		$query = $this->connection->getQueryBuilder();
199 3
		$query->select('a.*')
200 3
			->from('announcements', 'a')
201 3
			->orderBy('a.announcement_time', 'DESC')
202 3
			->groupBy('a.announcement_id')
203 3
			->setMaxResults($limit);
204
205 3
		$user = $this->userSession->getUser();
206 3 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...
207 2
			$userGroups = $this->groupManager->getUserGroupIds($user);
208 2
			$userGroups[] = 'everyone';
209 2
		} else {
210 1
			$userGroups = ['everyone'];
211
		}
212
213 3
		if (!in_array('admin', $userGroups)) {
214 2
			$query->leftJoin('a', 'announcements_groups', 'ag', $query->expr()->eq(
215 2
					'a.announcement_id', 'ag.announcement_id'
216 2
				))
217 2
				->andWhere($query->expr()->in('ag.gid', $query->createNamedParameter($userGroups, IQueryBuilder::PARAM_STR_ARRAY)));
218 2
		}
219
220 3
		if ($offset > 0) {
221 3
			$query->andWhere($query->expr()->lt('a.announcement_id', $query->createNamedParameter($offset, IQueryBuilder::PARAM_INT)));
222 3
		}
223
224 3
		$result = $query->execute();
225
226 3
		$announcements = [];
227 3
		while ($row = $result->fetch()) {
228 3
			$id = (int) $row['announcement_id'];
229 3
			$announcements[$id] = [
230 3
				'id'		=> $id,
231 3
				'author'	=> $row['announcement_user'],
232 3
				'time'		=> (int) $row['announcement_time'],
233 3
				'subject'	=> ($parseStrings) ? $this->parseSubject($row['announcement_subject']) : $row['announcement_subject'],
234 3
				'message'	=> ($parseStrings) ? $this->parseMessage($row['announcement_message']) : $row['announcement_message'],
235 3
				'groups'	=> null,
236
			];
237 3
		}
238 3
		$result->closeCursor();
239
240 3
		if (in_array('admin', $userGroups)) {
241 1
			$allGroups = $this->getGroups(array_keys($announcements));
242 1
			foreach ($allGroups as $id => $groups) {
243 1
				$announcements[$id]['groups'] = $groups;
244 1
			}
245 1
		}
246
247 3
		return $announcements;
248
	}
249
250
	/**
251
	 * Return the groups (or string everyone) which have access to the announcement(s)
252
	 *
253
	 * @param int|int[] $ids
254
	 * @return string[]|array[]
255
	 */
256 5
	public function getGroups($ids) {
257 5
		$returnSingleResult = false;
258 5
		if (is_int($ids)) {
259 5
			$ids = [$ids];
260 5
			$returnSingleResult = true;
261 5
		}
262
263 5
		$query = $this->connection->getQueryBuilder();
264 5
		$query->select('*')
265 5
			->from('announcements_groups')
266 5
			->where($query->expr()->in('announcement_id', $query->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)));
267 5
		$result = $query->execute();
268
269 5
		$groups = [];
270 5
		while ($row = $result->fetch()) {
271 5
			if (!isset($groups[(int) $row['announcement_id']])) {
272 5
				$groups[(int) $row['announcement_id']] = [];
273 5
			}
274 5
			$groups[(int) $row['announcement_id']][] = $row['gid'];
275 5
		}
276 5
		$result->closeCursor();
277
278 5
		return $returnSingleResult ? (array) array_pop($groups) : $groups;
279
	}
280
281
	/**
282
	 * @param string $message
283
	 * @return string
284
	 */
285 5
	protected function parseMessage($message) {
286 5
		return str_replace("\n", '<br />', str_replace(['<', '>'], ['&lt;', '&gt;'], $message));
287
	}
288
289
	/**
290
	 * @param string $subject
291
	 * @return string
292
	 */
293 5
	protected function parseSubject($subject) {
294 5
		return str_replace("\n", ' ', str_replace(['<', '>'], ['&lt;', '&gt;'], $subject));
295
	}
296
}
297