Completed
Push — master ( 2235ba...fa8fa8 )
by Maxence
02:29
created

limitToShareChildren()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 10
rs 9.4285
cc 2
eloc 7
nc 2
nop 3
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\Platforms\PostgreSqlPlatform;
32
use Doctrine\DBAL\Query\QueryBuilder;
33
use OCA\Circles\Model\Member;
34
use OCP\DB\QueryBuilder\IQueryBuilder;
35
use OCP\IDBConnection;
36
use OCP\Share;
37
use OCP\Share\IShare;
38
39
class CircleProviderRequestBuilder {
40
41
42
	/** @var IDBConnection */
43
	protected $dbConnection;
44
45
46
	/**
47
	 * returns the SQL request to get a specific share from the fileId and circleId
48
	 *
49
	 * @param int $fileId
50
	 * @param int $circleId
51
	 *
52
	 * @return IQueryBuilder
53
	 */
54
	protected function findShareParentSql($fileId, $circleId) {
55
56
		$qb = $this->getBaseSelectSql();
57
		$this->limitToShareParent($qb);
58
		$this->limitToCircle($qb, $circleId);
59
		$this->limitToFiles($qb, $fileId);
60
61
		return $qb;
62
	}
63
64
65
	/**
66
	 * Limit the request to a Circle.
67
	 *
68
	 * @param IQueryBuilder $qb
69
	 * @param int $circleId
70
	 */
71
	protected function limitToCircle(& $qb, $circleId) {
72
		$expr = $qb->expr();
73
		$pf = ($qb->getType() === QueryBuilder::SELECT) ? 's.' : '';
74
75
		$qb->andWhere($expr->eq($pf . 'share_with', $qb->createNamedParameter($circleId)));
76
	}
77
78
79
	/**
80
	 * Limit the request to the Share by its Id.
81
	 *
82
	 * @param IQueryBuilder $qb
83
	 * @param $shareId
84
	 */
85
	protected function limitToShare(& $qb, $shareId) {
86
		$expr = $qb->expr();
87
		$pf = ($qb->getType() === QueryBuilder::SELECT) ? 's.' : '';
88
89
		$qb->andWhere($expr->eq($pf . 'id', $qb->createNamedParameter($shareId)));
90
	}
91
92
93
	/**
94
	 * Limit the request to the top share (no children)
95
	 *
96
	 * @param IQueryBuilder $qb
97
	 */
98
	protected function limitToShareParent(& $qb) {
99
		$expr = $qb->expr();
100
101
		$qb->andWhere($expr->isNull('parent'));
102
	}
103
104
105
	/**
106
	 * limit the request to the children of a share
107
	 *
108
	 * @param IQueryBuilder $qb
109
	 * @param $userId
110
	 * @param int $parentId
111
	 */
112
	protected function limitToShareChildren(& $qb, $userId, $parentId = -1) {
113
		$expr = $qb->expr();
114
		$qb->andWhere($expr->eq('share_with', $qb->createNamedParameter($userId)));
115
116
		if ($parentId > -1) {
117
			$qb->andWhere($expr->eq('parent', $qb->createNamedParameter($parentId)));
118
		} else {
119
			$qb->andWhere($expr->isNotNull('parent'));
120
		}
121
	}
122
123
124
	/**
125
	 * limit the request to the share itself AND its children.
126
	 * perfect if you want to delete everything related to a share
127
	 *
128
	 * @param IQueryBuilder $qb
129
	 * @param $circleId
130
	 */
131
	protected function limitToShareAndChildren(& $qb, $circleId) {
132
		$expr = $qb->expr();
133
		$pf = ($qb->getType() === QueryBuilder::SELECT) ? 's.' : '';
134
135
		/** @noinspection PhpMethodParametersCountMismatchInspection */
136
		$qb->andWhere(
137
			$expr->orX(
138
				$expr->eq($pf . 'parent', $qb->createNamedParameter($circleId)),
139
				$expr->eq($pf . 'id', $qb->createNamedParameter($circleId))
140
			)
141
		);
142
	}
143
144
145
	/**
146
	 * limit the request to a fileId.
147
	 *
148
	 * @param IQueryBuilder $qb
149
	 * @param $files
150
	 *
151
	 * @internal param $fileId
152
	 */
153
	protected function limitToFiles(& $qb, $files) {
154
155
		if (!is_array($files)) {
156
			$files = array($files);
157
		}
158
159
		$expr = $qb->expr();
160
		$pf = ($qb->getType() === QueryBuilder::SELECT) ? 's.' : '';
161
		$qb->andWhere(
162
			$expr->in(
163
				$pf . 'file_source',
164
				$qb->createNamedParameter($files, IQueryBuilder::PARAM_INT_ARRAY)
165
			)
166
		);
167
	}
168
169
170
	/**
171
	 * @param IQueryBuilder $qb
172
	 * @param int $limit
173
	 * @param int $offset
174
	 */
175
	protected function limitToPage(& $qb, $limit = -1, $offset = 0) {
176
		if ($limit !== -1) {
177
			$qb->setMaxResults($limit);
178
		}
179
180
		$qb->setFirstResult($offset);
181
	}
182
183
184
	/**
185
	 * limit the request to a userId
186
	 *
187
	 * @param IQueryBuilder $qb
188
	 * @param string $userId
189
	 * @param bool $reShares
190
	 */
191
	protected function limitToShareOwner(& $qb, $userId, $reShares = false) {
192
		$expr = $qb->expr();
193
		$pf = ($qb->getType() === QueryBuilder::SELECT) ? 's.' : '';
194
195
		if ($reShares === false) {
196
			$qb->andWhere($expr->eq($pf . 'uid_initiator', $qb->createNamedParameter($userId)));
197
		} else {
198
			/** @noinspection PhpMethodParametersCountMismatchInspection */
199
			$qb->andWhere(
200
				$expr->orX(
201
					$expr->eq($pf . 'uid_owner', $qb->createNamedParameter($userId)),
202
					$expr->eq($pf . 'uid_initiator', $qb->createNamedParameter($userId))
203
				)
204
			);
205
		}
206
	}
207
208
209
	/**
210
	 * link circle field
211
	 *
212
	 * @deprecated
213
	 *
214
	 * @param IQueryBuilder $qb
215
	 * @param int $shareId
216
	 */
217
	protected function linkCircleField(& $qb, $shareId = -1) {
218
		$expr = $qb->expr();
219
220
		// TODO - Remove this in 12.0.1
221 View Code Duplication
		if ($qb->getConnection()
0 ignored issues
show
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...
222
			   ->getDatabasePlatform() instanceof PostgreSqlPlatform
223
		) {
224
			$tmpOrX = $expr->eq('s.share_with', $qb->createFunction('CAST(c.id AS TEXT)'));
225
		} else {
226
			$tmpOrX =
227
				$expr->eq('s.share_with', $expr->castColumn('c.id', IQueryBuilder::PARAM_STR));
228
		}
229
230
		$qb->from(CoreRequestBuilder::TABLE_CIRCLES, 'c');
231
232
		if ($shareId === -1) {
233
			$qb->andWhere($tmpOrX);
234
235
			return;
236
		}
237
238
		/** @noinspection PhpMethodParametersCountMismatchInspection */
239
		$qb->andWhere(
240
			$expr->orX(
241
				$tmpOrX,
242
				$expr->eq('s.parent', $qb->createNamedParameter($shareId))
243
			)
244
		);
245
		//->orderBy('c.circle_name');
0 ignored issues
show
Unused Code Comprehensibility introduced by
84% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
246
	}
247
248
249
	/**
250
	 * @param IQueryBuilder $qb
251
	 */
252
	protected function linkToCircleOwner(& $qb) {
253
		$expr = $qb->expr();
254
255
		/** @noinspection PhpMethodParametersCountMismatchInspection */
256
		$qb->leftJoin(
257
			'c', 'circles_members', 'mo', $expr->andX(
258
			$expr->eq('c.id', 'mo.circle_id'),
259
			$expr->eq('mo.level', $qb->createNamedParameter(Member::LEVEL_OWNER))
260
		)
261
		);
262
	}
263
264
265
	/**
266
	 * Link to member (userId) of circle
267
	 *
268
	 * @param IQueryBuilder $qb
269
	 * @param string $userId
270
	 */
271
	protected function linkToMember(& $qb, $userId) {
272
		$expr = $qb->expr();
273
274
		$qb->from(CoreRequestBuilder::TABLE_MEMBERS, 'm');
275
		$qb->from(CoreRequestBuilder::TABLE_GROUPS, 'g');
276
		$qb->from(CoreRequestBuilder::NC_TABLE_GROUP_USER, 'ncgu');
277
278
		$qb->andWhere(
279
			$expr->orX(
280
			// We check if user is members of the circle with the right level
281
				$expr->andX(
282
					$expr->eq('m.user_id', $qb->createNamedParameter($userId)),
283
					$expr->eq('m.circle_id', 'c.id'),
284
					$expr->gte('m.level', $qb->createNamedParameter(Member::LEVEL_MEMBER))
285
				),
286
287
//				 Or if user is member of one of the group linked to the circle with the right level
288
				$expr->andX(
289
					$expr->eq('g.circle_id', 'c.id'),
290
					$expr->gte('g.level', $qb->createNamedParameter(Member::LEVEL_MEMBER)),
291
					$expr->eq('ncgu.gid', 'g.group_id'),
292
					$expr->eq('ncgu.uid', $qb->createNamedParameter($userId))
293
				)
294
			)
295
		);
296
	}
297
298
299
	/**
300
	 * left join to get more data about the initiator of the share
301
	 *
302
	 * @param IQueryBuilder $qb
303
	 */
304
	protected function leftJoinShareInitiator(IQueryBuilder &$qb) {
305
		$expr = $qb->expr();
306
307
308
		// Circle member
309 View Code Duplication
		if ($qb->getConnection()
0 ignored issues
show
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...
310
			   ->getDatabasePlatform() instanceof PostgreSqlPlatform
311
		) {
312
			$req = $expr->eq('s.share_with', $qb->createFunction('CAST(fo.circle_id AS TEXT)'));
313
		} else {
314
			$req = $expr->eq(
315
				's.share_with', $expr->castColumn('src_m.circle_id', IQueryBuilder::PARAM_STR)
316
			);
317
		}
318
319
		$qb->selectAlias('src_m.level', 'initiator_circle_level');
320
		$qb->leftJoin(
321
			's', CoreRequestBuilder::TABLE_MEMBERS, 'src_m', $expr->andX(
322
			$expr->eq('s.uid_initiator', 'src_m.user_id'),
323
			$req
324
		)
325
		);
326
327
328
		// group member
329 View Code Duplication
		if ($qb->getConnection()
0 ignored issues
show
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...
330
			   ->getDatabasePlatform() instanceof PostgreSqlPlatform
331
		) {
332
			$req = $expr->eq('s.share_with', $qb->createFunction('CAST(src_g.circle_id AS TEXT)'));
333
		} else {
334
			$req = $expr->eq(
335
				's.share_with', $expr->castColumn('src_g.circle_id', IQueryBuilder::PARAM_STR)
336
			);
337
		}
338
339
		$qb->selectAlias('src_g.level', 'initiator_group_level');
340
		$qb->leftJoin(
341
			's', CoreRequestBuilder::NC_TABLE_GROUP_USER, 'src_ncgu', $expr->andX(
342
			$expr->eq('s.uid_initiator', 'src_ncgu.uid')
343
		)
344
		);
345
		$qb->leftJoin(
346
			's', 'circles_groups', 'src_g', $expr->andX(
347
			$expr->gte('src_g.level', $qb->createNamedParameter(Member::LEVEL_MEMBER)),
348
			$expr->eq('src_ncgu.gid', 'src_g.group_id'),
349
			$req
350
		)
351
		);
352
	}
353
354
355
	/**
356
	 * Link to all members of circle
357
	 *
358
	 * @param IQueryBuilder $qb
359
	 */
360
	protected function joinCircleMembers(& $qb) {
361
		$expr = $qb->expr();
362
363
		$qb->from(CoreRequestBuilder::TABLE_MEMBERS, 'm');
364
365
		// TODO - Remove this in 12.0.1
366 View Code Duplication
		if ($qb->getConnection()
0 ignored issues
show
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...
367
			   ->getDatabasePlatform() instanceof PostgreSqlPlatform
0 ignored issues
show
Bug introduced by
The class Doctrine\DBAL\Platforms\PostgreSqlPlatform 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...
368
		) {
369
			$qb->andWhere(
370
				$expr->eq('s.share_with', $qb->createFunction('CAST(m.circle_id AS TEXT)'))
371
			);
372
		} else {
373
374
			$qb->andWhere(
375
				$expr->eq(
376
					's.share_with', $expr->castColumn('m.circle_id', IQueryBuilder::PARAM_STR)
377
				)
378
			);
379
		}
380
	}
381
382
383
	/**
384
	 * Link to storage/filecache
385
	 *
386
	 * @param IQueryBuilder $qb
387
	 * @param string $userId
388
	 */
389
	protected function linkToFileCache(& $qb, $userId) {
390
		$expr = $qb->expr();
391
392
		/** @noinspection PhpMethodParametersCountMismatchInspection */
393
		$qb->leftJoin('s', 'filecache', 'f', $expr->eq('s.file_source', 'f.fileid'))
394
		   ->leftJoin('f', 'storages', 'st', $expr->eq('f.storage', 'st.numeric_id'))
395
		   ->leftJoin(
396
			   's', 'share', 's2', $expr->andX(
397
			   $expr->eq('s.id', 's2.parent'),
398
			   $expr->eq('s2.share_with', $qb->createNamedParameter($userId))
399
		   )
400
		   );
401
402
		$qb->selectAlias('s2.id', 'parent_id');
403
		$qb->selectAlias('s2.file_target', 'parent_target');
404
		$qb->selectAlias('s2.permissions', 'parent_perms');
405
406
	}
407
408
409
	/**
410
	 * add share to the database and return the ID
411
	 *
412
	 * @param IShare $share
413
	 *
414
	 * @return IQueryBuilder
415
	 */
416
	protected function getBaseInsertSql($share) {
417
		$qb = $this->dbConnection->getQueryBuilder();
418
		$qb->insert('share')
419
		   ->setValue('share_type', $qb->createNamedParameter(Share::SHARE_TYPE_CIRCLE))
420
		   ->setValue('item_type', $qb->createNamedParameter($share->getNodeType()))
421
		   ->setValue('item_source', $qb->createNamedParameter($share->getNodeId()))
422
		   ->setValue('file_source', $qb->createNamedParameter($share->getNodeId()))
423
		   ->setValue('file_target', $qb->createNamedParameter($share->getTarget()))
424
		   ->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()))
425
		   ->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
426
		   ->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
427
		   ->setValue('permissions', $qb->createNamedParameter($share->getPermissions()))
428
		   ->setValue('token', $qb->createNamedParameter($share->getToken()))
429
		   ->setValue('stime', $qb->createFunction('UNIX_TIMESTAMP()'));
430
431
		return $qb;
432
	}
433
434
435
	/**
436
	 * generate and return a base sql request.
437
	 *
438
	 * @param int $shareId
439
	 *
440
	 * @return IQueryBuilder
441
	 */
442
	protected function getBaseSelectSql($shareId = -1) {
443
		$qb = $this->dbConnection->getQueryBuilder();
444
445
		/** @noinspection PhpMethodParametersCountMismatchInspection */
446
		$qb->select(
447
			's.id', 's.share_type', 's.share_with', 's.uid_owner', 's.uid_initiator',
448
			's.parent', 's.item_type', 's.item_source', 's.item_target', 's.file_source',
449
			's.file_target', 's.permissions', 's.stime', 's.accepted', 's.expiration',
450
			's.token', 's.mail_send', 'c.type AS circle_type', 'c.name AS circle_name',
451
			'mo.user_id AS circle_owner'
452
		);
453
		$this->linkToCircleOwner($qb);
454
		$this->joinShare($qb);
455
456
		// TODO: Left-join circle and REMOVE this line
457
		$this->linkCircleField($qb, $shareId);
0 ignored issues
show
Deprecated Code introduced by
The method OCA\Circles\Db\CirclePro...lder::linkCircleField() has been deprecated.

This method has been deprecated.

Loading history...
458
459
		return $qb;
460
	}
461
462
463
	/**
464
	 * Generate and return a base sql request
465
	 * This one should be used to retrieve a complete list of users (ie. access list).
466
	 *
467
	 * @return IQueryBuilder
468
	 */
469
	protected function getAccessListBaseSelectSql() {
470
		$qb = $this->dbConnection->getQueryBuilder();
471
472
		/** @noinspection PhpMethodParametersCountMismatchInspection */
473
		$qb->select(
474
			'm.user_id', 's.file_source', 's.file_target'
475
		);
476
		$this->joinCircleMembers($qb);
477
		$this->joinShare($qb);
478
479
		return $qb;
480
	}
481
482
483
	protected function getCompleteSelectSql() {
484
		$qb = $this->dbConnection->getQueryBuilder();
485
486
		/** @noinspection PhpMethodParametersCountMismatchInspection */
487
		$qb->selectDistinct('s.id')
488
		   ->addSelect(
489
			   's.*', 'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage',
490
			   'f.path_hash', 'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart',
491
			   'f.size', 'f.mtime', 'f.storage_mtime', 'f.encrypted', 'f.unencrypted_size',
492
			   'f.etag', 'f.checksum', 'c.type AS circle_type', 'c.name AS circle_name',
493
			   'mo.user_id AS circle_owner'
494
		   )
495
		   ->selectAlias('st.id', 'storage_string_id');
496
497
498
		$this->linkToCircleOwner($qb);
499
		$this->joinShare($qb);
500
		$this->linkCircleField($qb);
0 ignored issues
show
Deprecated Code introduced by
The method OCA\Circles\Db\CirclePro...lder::linkCircleField() has been deprecated.

This method has been deprecated.

Loading history...
501
502
503
		return $qb;
504
	}
505
506
507
	/**
508
	 * @param IQueryBuilder $qb
509
	 */
510
	private function joinShare(& $qb) {
511
		$expr = $qb->expr();
512
513
		/** @noinspection PhpMethodParametersCountMismatchInspection */
514
		$qb->from('share', 's')
515
		   ->where($expr->eq('s.share_type', $qb->createNamedParameter(Share::SHARE_TYPE_CIRCLE)))
516
		   ->andWhere(
517
			   $expr->orX(
518
				   $expr->eq('s.item_type', $qb->createNamedParameter('file')),
519
				   $expr->eq('s.item_type', $qb->createNamedParameter('folder'))
520
			   )
521
		   );
522
	}
523
524
525
	/**
526
	 * generate and return a base sql request.
527
	 *
528
	 * @return \OCP\DB\QueryBuilder\IQueryBuilder
529
	 */
530 View Code Duplication
	protected function getBaseDeleteSql() {
531
		$qb = $this->dbConnection->getQueryBuilder();
532
		$expr = $qb->expr();
533
534
		$qb->delete('share')
535
		   ->where($expr->eq('share_type', $qb->createNamedParameter(Share::SHARE_TYPE_CIRCLE)));
536
537
		return $qb;
538
	}
539
540
541
	/**
542
	 * generate and return a base sql request.
543
	 *
544
	 * @return \OCP\DB\QueryBuilder\IQueryBuilder
545
	 */
546 View Code Duplication
	protected function getBaseUpdateSql() {
547
		$qb = $this->dbConnection->getQueryBuilder();
548
		$expr = $qb->expr();
549
550
		$qb->update('share')
551
		   ->where($expr->eq('share_type', $qb->createNamedParameter(Share::SHARE_TYPE_CIRCLE)));
552
553
		return $qb;
554
	}
555
}
556