Completed
Pull Request — master (#467)
by Maxence
01:47
created

CirclesRequestBuilder::getCirclesInsertSql()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 7
Ratio 100 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 7
loc 7
rs 10
cc 1
nc 1
nop 0
1
<?php
2
3
/**
4
 * Circles - Bring cloud-users closer together.
5
 *
6
 * This file is licensed under the Affero General Public License version 3 or
7
 * later. See the COPYING file.
8
 *
9
 * @author Maxence Lange <[email protected]>
10
 * @copyright 2017
11
 * @license GNU AGPL version 3 or any later version
12
 *
13
 * This program is free software: you can redistribute it and/or modify
14
 * it under the terms of the GNU Affero General Public License as
15
 * published by the Free Software Foundation, either version 3 of the
16
 * License, or (at your option) any later version.
17
 *
18
 * This program is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21
 * GNU Affero General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU Affero General Public License
24
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
25
 *
26
 */
27
28
namespace OCA\Circles\Db;
29
30
31
use Doctrine\DBAL\Query\QueryBuilder;
32
use OCA\Circles\Exceptions\ConfigNoCircleAvailableException;
33
use OCA\Circles\Model\Circle;
34
use OCA\Circles\Model\Member;
35
use OCA\Circles\Service\ConfigService;
36
use OCA\Circles\Service\MiscService;
37
use OCA\Circles\Service\TimezoneService;
38
use OCP\DB\QueryBuilder\ICompositeExpression;
39
use OCP\DB\QueryBuilder\IQueryBuilder;
40
use OCP\IDBConnection;
41
use OCP\IL10N;
42
43
class CirclesRequestBuilder extends CoreRequestBuilder {
44
45
46
	/** @var MembersRequest */
47
	protected $membersRequest;
48
49
	/**
50
	 * CirclesRequestBuilder constructor.
51
	 *
52
	 * {@inheritdoc}
53
	 * @param MembersRequest $membersRequest
54
	 */
55 View Code Duplication
	public function __construct(
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...
56
		IL10N $l10n, IDBConnection $connection, MembersRequest $membersRequest,
57
		ConfigService $configService, TimezoneService $timezoneService, MiscService $miscService
58
	) {
59
		parent::__construct($l10n, $connection, $configService, $timezoneService, $miscService);
60
		$this->membersRequest = $membersRequest;
61
	}
62
63
64
	/**
65
	 * Limit the search to a non-personal circle
66
	 *
67
	 * @param IQueryBuilder $qb
68
	 */
69
	protected function limitToNonPersonalCircle(IQueryBuilder &$qb) {
70
		$expr = $qb->expr();
71
72
		$qb->andWhere(
73
			$expr->neq('c.type', $qb->createNamedParameter(Circle::CIRCLES_PERSONAL))
74
		);
75
	}
76
77
78
	/**
79
	 * @param IQueryBuilder $qb
80
	 * @param string $userId
81
	 * @param string $circleUniqueId
82
	 * @param $type
83
	 * @param $name
84
	 * @param bool $forceAll
85
	 *
86
	 * @throws ConfigNoCircleAvailableException
87
	 */
88
	protected function limitRegardingCircleType(
89
		IQueryBuilder &$qb, string $userId, $circleUniqueId, int $type,
90
		string $name, bool $forceAll = false
91
	) {
92
		$orTypes = $this->generateLimit($qb, $circleUniqueId, $userId, $type, $name, $forceAll);
93
		if (sizeof($orTypes) === 0) {
94
			throw new ConfigNoCircleAvailableException(
95
				$this->l10n->t(
96
					'You cannot use the Circles Application until your administrator has allowed at least one type of circles'
97
				)
98
			);
99
		}
100
101
		$orXTypes = $qb->expr()
102
					   ->orX();
103
		foreach ($orTypes as $orType) {
104
			$orXTypes->add($orType);
105
		}
106
107
		$qb->andWhere($orXTypes);
108
	}
109
110
111
	/**
112
	 * @param IQueryBuilder $qb
113
	 * @param string $circleUniqueId
114
	 * @param $userId
115
	 * @param $type
116
	 * @param $name
117
	 * @param bool $forceAll
118
	 *
119
	 * @return array
120
	 */
121
	private function generateLimit(
122
		IQueryBuilder &$qb, $circleUniqueId, $userId, $type, $name, $forceAll = false
123
	) {
124
		$orTypes = [];
125
		array_push($orTypes, $this->generateLimitPersonal($qb, $userId, $type, $forceAll));
126
		array_push($orTypes, $this->generateLimitSecret($qb, $circleUniqueId, $type, $name));
127
		array_push($orTypes, $this->generateLimitClosed($qb, $type));
128
		array_push($orTypes, $this->generateLimitPublic($qb, $type));
129
130
		return array_filter($orTypes);
131
	}
132
133
134
	/**
135
	 * @param IQueryBuilder $qb
136
	 * @param int|string $userId
137
	 * @param int $type
138
	 * @param bool $forceAll
139
	 *
140
	 * @return ICompositeExpression
141
	 */
142
	private function generateLimitPersonal(IQueryBuilder $qb, $userId, $type, $forceAll = false) {
143
		if (!(Circle::CIRCLES_PERSONAL & (int)$type)) {
144
			return null;
145
		}
146
		$expr = $qb->expr();
147
148
		$andX = $expr->andX();
149
		$andX->add($expr->eq('c.type', $qb->createNamedParameter(Circle::CIRCLES_PERSONAL)));
150
		$andX->add($expr->eq('o.instance', $qb->createNamedParameter('')));
151
152
		if (!$forceAll) {
153
			$andX->add($expr->eq('o.user_id', $qb->createNamedParameter((string)$userId)));
154
		}
155
156
		return $andX;
157
	}
158
159
160
	/**
161
	 * @param IQueryBuilder $qb
162
	 * @param string $circleUniqueId
163
	 * @param int $type
164
	 * @param string $name
165
	 *
166
	 * @return string
167
	 */
168
	private function generateLimitSecret(IQueryBuilder $qb, $circleUniqueId, $type, $name) {
169
		if (!(Circle::CIRCLES_SECRET & (int)$type)) {
170
			return null;
171
		}
172
		$expr = $qb->expr();
173
174
		$orX = $expr->orX($expr->gte('u.level', $qb->createNamedParameter(Member::LEVEL_MEMBER)));
175
		$orX->add($expr->eq('c.name', $qb->createNamedParameter($name)))
176
			->add($expr->eq('c.unique_id', $qb->createNamedParameter($circleUniqueId)));
177
178
		if ($this->leftJoinedNCGroupAndUser) {
179
			$orX->add($expr->gte('g.level', $qb->createNamedParameter(Member::LEVEL_MEMBER)));
180
		}
181
182
		/** @noinspection PhpMethodParametersCountMismatchInspection */
183
		$sqb = $expr->andX(
184
			$expr->eq('c.type', $qb->createNamedParameter(Circle::CIRCLES_SECRET)),
185
			$expr->orX($orX)
186
		);
187
188
		return $sqb;
189
	}
190
191
192
	/**
193
	 * @param IQueryBuilder $qb
194
	 * @param int $type
195
	 *
196
	 * @return string
197
	 */
198 View Code Duplication
	private function generateLimitClosed(IQueryBuilder $qb, $type) {
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...
199
		if (!(Circle::CIRCLES_CLOSED & (int)$type)) {
200
			return null;
201
		}
202
203
		return $qb->expr()
204
				  ->eq(
205
					  'c.type',
206
					  $qb->createNamedParameter(Circle::CIRCLES_CLOSED)
207
				  );
208
	}
209
210
211
	/**
212
	 * @param IQueryBuilder $qb
213
	 * @param int $type
214
	 *
215
	 * @return string
216
	 */
217 View Code Duplication
	private function generateLimitPublic(IQueryBuilder $qb, $type) {
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...
218
		if (!(Circle::CIRCLES_PUBLIC & (int)$type)) {
219
			return null;
220
		}
221
222
		return $qb->expr()
223
				  ->eq(
224
					  'c.type',
225
					  $qb->createNamedParameter(Circle::CIRCLES_PUBLIC)
226
				  );
227
	}
228
229
230
	/**
231
	 * add a request to the members list, using the current user ID.
232
	 * will returns level and stuff.
233
	 *
234
	 * @param IQueryBuilder $qb
235
	 * @param string $userId
236
	 * @param int $type
237
	 * @param string $instanceId
238
	 */
239
	public function leftJoinUserIdAsViewer(IQueryBuilder &$qb, string $userId, int $type, string $instanceId
240
	) {
241
		if ($qb->getType() !== QueryBuilder::SELECT) {
242
			return;
243
		}
244
245
		$expr = $qb->expr();
246
		$pf = '' . $this->default_select_alias . '.';
247
248
		/** @noinspection PhpMethodParametersCountMismatchInspection */
249
		$qb->selectAlias('u.user_id', 'viewer_userid')
250
		   ->selectAlias('u.user_type', 'viewer_type')
251
		   ->selectAlias('u.instance', 'viewer_instance')
252
		   ->selectAlias('u.status', 'viewer_status')
253
		   ->selectAlias('u.member_id', 'viewer_member_id')
254
		   ->selectAlias('u.cached_name', 'viewer_cached_name')
255
		   ->selectAlias('u.level', 'viewer_level')
256
		   ->leftJoin(
257
			   $this->default_select_alias, CoreRequestBuilder::TABLE_MEMBERS, 'u',
258
			   $expr->andX(
259
				   $expr->eq('u.circle_id', $pf . 'unique_id'),
260
				   $expr->eq('u.user_id', $qb->createNamedParameter($userId)),
261
				   $expr->eq('u.instance', $qb->createNamedParameter($instanceId)),
262
				   $expr->eq('u.user_type', $qb->createNamedParameter($type))
263
			   )
264
		   );
265
	}
266
267
268
	/**
269
	 * Left Join members table to get the owner of the circle.
270
	 *
271
	 * @param IQueryBuilder $qb
272
	 * @param string $ownerId
273
	 */
274
	public function leftJoinOwner(IQueryBuilder &$qb, string $ownerId = '') {
275
276
		if ($qb->getType() !== QueryBuilder::SELECT) {
277
			return;
278
		}
279
280
		$expr = $qb->expr();
281
		$pf = $this->default_select_alias . '.';
282
283
		/** @noinspection PhpMethodParametersCountMismatchInspection */
284
		$qb->selectAlias('o.user_id', 'owner_userid')
285
		   ->selectAlias('o.instance', 'owner_instance')
286
		   ->selectAlias('o.status', 'owner_status')
287
		   ->selectAlias('o.level', 'owner_level')
288
		   ->leftJoin(
289
			   $this->default_select_alias, CoreRequestBuilder::TABLE_MEMBERS, 'o',
290
			   $expr->andX(
291
				   $expr->eq('o.circle_id', $pf . 'unique_id'),
292
				   $expr->eq('o.level', $qb->createNamedParameter(Member::LEVEL_OWNER)),
293
				   $expr->eq('o.user_type', $qb->createNamedParameter(Member::TYPE_USER))
294
			   )
295
		   );
296
297
		if ($ownerId !== '') {
298
			$qb->andWhere($expr->eq('o.user_id', $qb->createNamedParameter($ownerId)));
299
		}
300
	}
301
302
303
	/**
304
	 * Base of the Sql Insert request for Shares
305
	 *
306
	 *
307
	 * @return IQueryBuilder
308
	 */
309 View Code Duplication
	protected function getCirclesInsertSql() {
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...
310
		$qb = $this->dbConnection->getQueryBuilder();
311
		$qb->insert(self::TABLE_CIRCLES)
312
		   ->setValue('creation', $qb->createNamedParameter($this->timezoneService->getUTCDate()));
313
314
		return $qb;
315
	}
316
317
318
	/**
319
	 * Base of the Sql Update request for Shares
320
	 *
321
	 * @param int $uniqueId
322
	 *
323
	 * @return IQueryBuilder
324
	 */
325 View Code Duplication
	protected function getCirclesUpdateSql($uniqueId) {
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...
326
		$qb = $this->dbConnection->getQueryBuilder();
327
		$qb->update(self::TABLE_CIRCLES)
328
		   ->where(
329
			   $qb->expr()
330
				  ->eq('unique_id', $qb->createNamedParameter($uniqueId))
331
		   );
332
333
		return $qb;
334
	}
335
336
337
	/**
338
	 * Base of the Sql Delete request
339
	 *
340
	 * @param string $circleUniqueId
341
	 *
342
	 * @return IQueryBuilder
343
	 */
344 View Code Duplication
	protected function getCirclesDeleteSql($circleUniqueId) {
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...
345
		$qb = $this->dbConnection->getQueryBuilder();
346
		$qb->delete(self::TABLE_CIRCLES)
347
		   ->where(
348
			   $qb->expr()
349
				  ->eq('unique_id', $qb->createNamedParameter($circleUniqueId))
350
		   );
351
352
		return $qb;
353
	}
354
355
356
	/**
357
	 * @return IQueryBuilder
358
	 */
359
	protected function getCirclesSelectSql() {
360
		$qb = $this->dbConnection->getQueryBuilder();
361
362
		/** @noinspection PhpMethodParametersCountMismatchInspection */
363
		$qb->selectDistinct('c.unique_id')
364
		   ->addSelect(
365
			   'c.id', 'c.name', 'c.alt_name', 'c.description', 'c.settings', 'c.type', 'contact_addressbook',
366
			   'contact_groupname', 'c.creation'
367
		   )
368
		   ->from(CoreRequestBuilder::TABLE_CIRCLES, 'c');
369
		$this->default_select_alias = 'c';
370
371
		return $qb;
372
	}
373
374
375
	/**
376
	 * @param array $data
377
	 *
378
	 * @return Circle
379
	 */
380
	protected function parseCirclesSelectSql($data) {
381
382
		$circle = new Circle();
383
		$circle->setId($data['id']);
384
		$circle->setUniqueId($data['unique_id']);
385
		$circle->setName($data['name']);
386
		$circle->setAltName($data['alt_name']);
387
		$circle->setDescription($data['description']);
388
		if ($data['contact_addressbook'] !== null) {
389
			$circle->setContactAddressBook($data['contact_addressbook']);
390
		}
391
		if ($data['contact_groupname'] !== null) {
392
			$circle->setContactGroupName($data['contact_groupname']);
393
		}
394
		$circle->setSettings($data['settings']);
395
		$circle->setType($data['type']);
396
		$circle->setCreation($data['creation']);
397
398
		if (key_exists('viewer_level', $data)) {
399
			$user = new Member($data['viewer_userid'], Member::TYPE_USER, $circle->getUniqueId());
400
			$user->setStatus($data['viewer_status']);
401
			$user->setMemberId($data['viewer_member_id']);
402
			$user->setCachedName($data['viewer_cached_name']);
403
			$user->setType($data['viewer_type']);
404
			$user->setInstance($data['viewer_instance']);
405
			$user->setLevel($data['viewer_level']);
406
			$circle->setViewer($user);
407
		}
408
409
		if (key_exists('owner_level', $data)) {
410
			$owner = new Member($data['owner_userid'], Member::TYPE_USER, $circle->getUniqueId());
411
			$owner->setStatus($data['owner_status']);
412
			$owner->setInstance($data['owner_instance']);
413
			$owner->setLevel($data['owner_level']);
414
			$circle->setOwner($owner);
415
		}
416
417
		return $circle;
418
	}
419
420
421
}
422