Completed
Pull Request — master (#346)
by Raffael
08:56
created

Filesystem::findNodesByFilterUser()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 0
cts 11
cp 0
rs 9.584
c 0
b 0
f 0
cc 3
nc 3
nop 4
crap 12
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * balloon
7
 *
8
 * @copyright   Copryright (c) 2012-2019 gyselroth GmbH (https://gyselroth.com)
9
 * @license     GPL-3.0 https://opensource.org/licenses/GPL-3.0
10
 */
11
12
namespace Balloon;
13
14
use Balloon\Filesystem\Acl;
15
use Balloon\Filesystem\Acl\Exception\Forbidden as ForbiddenException;
16
use Balloon\Filesystem\Delta;
17
use Balloon\Filesystem\Exception;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Balloon\Exception.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
18
use Balloon\Filesystem\Node\Collection;
19
use Balloon\Filesystem\Node\Factory as NodeFactory;
20
use Balloon\Filesystem\Node\NodeInterface;
21
use Balloon\Server\User;
22
use Generator;
23
use MongoDB\BSON\ObjectId;
24
use MongoDB\BSON\UTCDateTime;
25
use MongoDB\Database;
26
use Psr\Log\LoggerInterface;
27
28
class Filesystem
29
{
30
    /**
31
     * Database.
32
     *
33
     * @var Database
34
     */
35
    protected $db;
36
37
    /**
38
     * LoggerInterface.
39
     *
40
     * @var LoggerInterface
41
     */
42
    protected $logger;
43
44
    /**
45
     * Hook.
46
     *
47
     * @var Hook
48
     */
49
    protected $hook;
50
51
    /**
52
     * Server.
53
     *
54
     * @var Server
55
     */
56
    protected $server;
57
58
    /**
59
     * Root collection.
60
     *
61
     * @var Collection
62
     */
63
    protected $root;
64
65
    /**
66
     * User.
67
     *
68
     * @var Delta
69
     */
70
    protected $delta;
71
72
    /**
73
     * Get user.
74
     *
75
     * @var User
76
     */
77
    protected $user;
78
79
    /**
80
     * Node factory.
81
     *
82
     * @var NodeFactory
83
     */
84
    protected $node_factory;
85
86
    /**
87
     * Acl.
88
     *
89
     * @var Acl
90
     */
91
    protected $acl;
92
93
    /**
94
     * Cache.
95
     *
96
     * @var array
97
     */
98
    protected $cache = [];
99
100
    /**
101
     * RAW Cache.
102
     *
103
     * @var array
104
     */
105
    protected $raw_cache = [];
106
107
    /**
108
     * Initialize.
109
     */
110
    public function __construct(Server $server, Database $db, Hook $hook, LoggerInterface $logger, NodeFactory $node_factory, Acl $acl, ?User $user = null)
111
    {
112
        $this->user = $user;
113
        $this->server = $server;
114
        $this->db = $db;
115
        $this->logger = $logger;
116
        $this->hook = $hook;
117
        $this->node_factory = $node_factory;
118
        $this->acl = $acl;
119
    }
120
121
    /**
122
     * Get user.
123
     */
124
    public function getUser(): ?User
125
    {
126
        return $this->user;
127
    }
128
129
    /**
130
     * Get server.
131
     */
132
    public function getServer(): Server
133
    {
134
        return $this->server;
135
    }
136
137
    /**
138
     * Get database.
139
     */
140
    public function getDatabase(): Database
141
    {
142
        return $this->db;
143
    }
144
145
    /**
146
     * Get root.
147
     */
148
    public function getRoot(): Collection
149
    {
150
        if ($this->root instanceof Collection) {
151
            return $this->root;
152
        }
153
154
        return $this->root = $this->initNode([
155
            'directory' => true,
156
            '_id' => null,
157
            'owner' => $this->user ? $this->user->getId() : null,
158
        ]);
159
    }
160
161
    /**
162
     * Get delta.
163
     */
164
    public function getDelta(): Delta
165
    {
166
        if ($this->delta instanceof Delta) {
167
            return $this->delta;
168
        }
169
170
        return $this->delta = new Delta($this, $this->db, $this->acl);
171
    }
172
173
    /**
174
     * Find raw node.
175
     */
176
    public function findRawNode(ObjectId $id): array
177
    {
178
        if (isset($this->raw_cache[(string) $id])) {
179
            return $this->raw_cache[(string) $id];
180
        }
181
182
        $node = $this->db->storage->findOne(['_id' => $id]);
183
        if (null === $node) {
184
            throw new Exception\NotFound(
185
                'node '.$id.' not found',
186
                Exception\NotFound::NODE_NOT_FOUND
187
            );
188
        }
189
190
        $this->raw_cache[(string) $id] = $node;
191
192
        return $node;
193
    }
194
195
    /**
196
     * Factory loader.
197
     */
198
    public function findNodeById($id, ?string $class = null, int $deleted = NodeInterface::DELETED_INCLUDE): NodeInterface
199
    {
200
        if (isset($this->cache[(string) $id])) {
201
            return $this->cache[(string) $id];
202
        }
203
204
        if (!is_string($id) && !($id instanceof ObjectId)) {
0 ignored issues
show
Bug introduced by
The class MongoDB\BSON\ObjectId 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...
205
            throw new Exception\InvalidArgument($id.' node id has to be a string or instance of \MongoDB\BSON\ObjectId');
206
        }
207
208
        try {
209
            if (is_string($id)) {
210
                $id = new ObjectId($id);
211
            }
212
        } catch (\Exception $e) {
213
            throw new Exception\InvalidArgument('invalid node id specified');
214
        }
215
216
        $filter = [
217
            '_id' => $id,
218
        ];
219
220
        switch ($deleted) {
221
            case NodeInterface::DELETED_INCLUDE:
222
                break;
223
            case NodeInterface::DELETED_EXCLUDE:
224
                $filter['deleted'] = false;
225
226
                break;
227
            case NodeInterface::DELETED_ONLY:
228
                $filter['deleted'] = ['$type' => 9];
229
230
                break;
231
        }
232
233
        $node = $this->db->storage->findOne($filter);
234
235
        if (null === $node) {
236
            throw new Exception\NotFound(
237
                'node ['.$id.'] not found',
238
                Exception\NotFound::NODE_NOT_FOUND
239
            );
240
        }
241
242
        $return = $this->initNode($node);
243
244
        if (null !== $class && !($return instanceof $class)) {
245
            throw new Exception('node '.get_class($return).' is not instance of '.$class);
246
        }
247
248
        return $return;
249
    }
250
251
    /**
252
     * Load nodes by id.
253
     */
254
    public function findNodesById(array $id = [], ?string $class = null, int $deleted = NodeInterface::DELETED_INCLUDE): Generator
255
    {
256
        $find = [];
257
        foreach ($id as $i) {
258
            $find[] = new ObjectId($i);
259
        }
260
261
        $filter = [
262
            '_id' => ['$in' => $find],
263
        ];
264
265
        switch ($deleted) {
266
            case NodeInterface::DELETED_INCLUDE:
267
                break;
268
            case NodeInterface::DELETED_EXCLUDE:
269
                $filter['deleted'] = false;
270
271
                break;
272
            case NodeInterface::DELETED_ONLY:
273
                $filter['deleted'] = ['$type' => 9];
274
275
                break;
276
        }
277
278
        $result = $this->db->storage->find($filter);
279
280
        $nodes = [];
281
        foreach ($result as $node) {
282
            try {
283
                $return = $this->initNode($node);
284
285
                if (in_array($return->getId(), $nodes)) {
286
                    continue;
287
                }
288
289
                $nodes[] = $return->getId();
290
            } catch (\Exception $e) {
291
                $this->logger->error('remove node from result list, failed load node', [
292
                    'category' => get_class($this),
293
                    'exception' => $e,
294
                ]);
295
296
                continue;
297
            }
298
299
            if (null !== $class && !($return instanceof $class)) {
300
                throw new Exception('node is not an instance of '.$class);
301
            }
302
303
            yield $return;
304
        }
305
    }
306
307
    /**
308
     * Load nodes by id.
309
     */
310
    public function getNodes(?array $id = null, $class = null, int $deleted = NodeInterface::DELETED_EXCLUDE): Generator
311
    {
312
        return $this->findNodesById($id, $class, $deleted);
313
    }
314
315
    /**
316
     * Load node.
317
     */
318
    public function getNode($id = null, $class = null, bool $multiple = false, bool $allow_root = false, ?int $deleted = null): NodeInterface
319
    {
320
        if (empty($id)) {
321
            if (true === $allow_root) {
322
                return $this->getRoot();
323
            }
324
325
            throw new Exception\InvalidArgument('invalid id given');
326
        }
327
328
        if (null === $deleted) {
329
            $deleted = NodeInterface::DELETED_INCLUDE;
330
        }
331
332
        if (true === $multiple && is_array($id)) {
333
            return $this->findNodesById($id, $class, $deleted);
334
        }
335
336
        return $this->findNodeById($id, $class, $deleted);
337
    }
338
339
    /**
340
     * Find node with custom filter.
341
     */
342
    public function findNodeByFilter(array $filter): NodeInterface
343
    {
344
        $result = $this->db->storage->findOne($filter);
345
        if (null === $result) {
346
            throw new Exception\NotFound(
347
                'node with custom filter was not found',
348
                Exception\NotFound::NODE_NOT_FOUND
349
            );
350
        }
351
352
        return $this->initNode($result);
353
    }
354
355
    /**
356
     * Count.
357
     */
358
    public function countNodes(array $filter = []): int
359
    {
360
        return $this->db->storage->count($filter);
361
    }
362
363
    /**
364
     * Find nodes with custom filters.
365
     */
366
    public function findNodesByFilter(array $filter, ?int $offset = null, ?int $limit = null): Generator
367
    {
368
        $result = $this->db->storage->find($filter, [
369
            'skip' => $offset,
370
            'limit' => $limit,
371
        ]);
372
373
        $count = $this->countNodes($filter);
374
375
        foreach ($result as $node) {
376
            try {
377
                yield $this->initNode($node);
378
            } catch (\Exception $e) {
379
                $this->logger->error('remove node from result list, failed load node', [
380
                    'category' => get_class($this),
381
                    'exception' => $e,
382
                ]);
383
            }
384
        }
385
386
        return $count;
387
    }
388
389
    /**
390
     * Find nodes with custom filter recursive.
391
     */
392
    public function findNodesByFilterRecursiveToArray(Collection $collection, array $filter = []): array
393
    {
394
        $graph = [
395
            'from' => 'storage',
396
            'startWith' => '$pointer',
397
            'connectFromField' => 'pointer',
398
            'connectToField' => 'parent',
399
            'as' => 'children',
400
        ];
401
402
        if (count($filter) > 0) {
403
            $graph['restrictSearchWithMatch'] = $filter;
404
        }
405
406
        $query = [
407
            ['$match' => ['_id' => $collection->getId()]],
408
            ['$graphLookup' => $graph],
409
            ['$unwind' => '$children'],
410
            ['$project' => ['id' => '$children._id']],
411
        ];
412
413
        $result = $this->db->storage->aggregate($query);
414
415
        return array_column(iterator_to_array($result), 'id');
416
    }
417
418
    /**
419
     * Find nodes with custom filter recursive.
420
     */
421
    public function findNodesByFilterRecursiveChildren(array $parent_filter=[], int $deleted, ?int $offset = null, ?int $limit = null): Generator
422
    {
423
        $deleted_filter = [];
424
        if (NodeInterface::DELETED_EXCLUDE === $deleted) {
425
            $deleted_filter['deleted'] = false;
426
        } elseif (NodeInterface::DELETED_ONLY === $deleted) {
427
            $deleted_filter['deleted'] = ['$type' => 9];
428
        }
429
430
        $query = [
431
            '$or' => [
432
                [
433
                    'acl' => ['$exists' => false],
434
                ], [
435
                    'acl.id' => (string)$this->user->getId(),
436
                ]
437
            ]
438
        ];
439
440
        if(count($deleted_filter) > 0) {
441
            $query = ['$and' => [$deleted_filter, $query]];
442
        }
443
444
        $query = [
445
            ['$match' => $parent_filter],
446
            ['$graphLookup' => [
447
                'from' => 'storage',
448
                'startWith' => '$pointer',
449
                'connectFromField' => 'pointer',
450
                'connectToField' => 'parent',
451
                'as' => 'children',
452
                'maxDepth' => 0,
453
                'restrictSearchWithMatch' => $query,
454
            ]],
455
            ['$addFields' => [
456
                'size' => [
457
                    '$cond' => [
458
                        'if' => ['$eq' => ['$directory', true]],
459
                        'then' => ['$size' => '$children'],
460
                        'else' => '$size',
461
                    ]
462
                ]
463
            ]],
464
            ['$project' => ['children' => 0]],
465
            ['$group' => ['_id' => null, 'total' => ['$sum' => 1]]],
466
        ];
467
468
        $result = $this->db->storage->aggregate($query);
469
470
        $total = 0;
471
        $result = iterator_to_array($result);
472
        if (count($result) > 0) {
473
            $total = $result[0]['total'];
474
        }
475
476
        array_pop($query);
477
478
        $offset !== null ? $query[] = ['$skip' => $offset] : false;
479
        $limit !== null ? $query[] = ['$limit' => $limit]: false;
480
        $result = $this->db->storage->aggregate($query);
481
482
        foreach ($result as $node) {
483
            try {
484
                yield $this->initNode($node);
485
            } catch (\Exception $e) {
486
                $this->logger->error('remove node from result list, failed load node', [
487
                    'category' => get_class($this),
488
                    'exception' => $e,
489
                ]);
490
            }
491
        }
492
493
        return $total;
494
    }
495
496
    /**
497
     * Find nodes with custom filter recursive.
498
     */
499
    public function findNodesByFilterRecursive(Collection $collection, array $filter = [], ?int $offset = null, ?int $limit = null): Generator
500
    {
501
        $graph = [
502
            'from' => 'storage',
503
            'startWith' => '$pointer',
504
            'connectFromField' => 'pointer',
505
            'connectToField' => 'parent',
506
            'as' => 'children',
507
        ];
508
509
        if (count($filter) > 0) {
510
            $graph['restrictSearchWithMatch'] = $filter;
511
        }
512
513
        $query = [
514
            ['$match' => ['_id' => $collection->getId()]],
515
            ['$graphLookup' => $graph],
516
            ['$unwind' => '$children'],
517
            ['$group' => ['_id' => null, 'total' => ['$sum' => 1]]],
518
        ];
519
520
        $result = $this->db->storage->aggregate($query);
521
522
        $total = 0;
523
        $result = iterator_to_array($result);
524
        if (count($result) > 0) {
525
            $total = $result[0]['total'];
526
        }
527
528
        array_pop($query);
529
530
        $offset !== null ? $query[] = ['$skip' => $offset] : false;
531
        $limit !== null ? $query[] = ['$limit' => $limit] : false;
532
        $result = $this->db->storage->aggregate($query);
533
534
        foreach ($result as $node) {
535
            try {
536
                if (isset($node['children'])) {
537
                    $node = $node['children'];
538
                }
539
540
                yield $this->initNode($node);
541
            } catch (\Exception $e) {
542
                $this->logger->error('remove node from result list, failed load node', [
543
                    'category' => get_class($this),
544
                    'exception' => $e,
545
                ]);
546
            }
547
        }
548
549
        return $total;
550
    }
551
552
    /**
553
     * Get custom filtered children.
554
     */
555
    public function findNodesByFilterUser(int $deleted, array $filter, ?int $offset = null, ?int $limit = null): Generator
556
    {
557
        $shares = $this->user->getShares();
558
        $stored_filter = ['$and' => [
559
            [],
560
            ['$or' => [
561
                ['owner' => $this->user->getId()],
562
                ['shared' => ['$in' => $shares]],
563
            ]],
564
        ]];
565
566
        if (NodeInterface::DELETED_EXCLUDE === $deleted) {
567
            $stored_filter['$and'][0]['deleted'] = false;
568
        } elseif (NodeInterface::DELETED_ONLY === $deleted) {
569
            $stored_filter['$and'][0]['deleted'] = ['$type' => 9];
570
        }
571
572
        $stored_filter['$and'][0] = array_merge($filter, $stored_filter['$and'][0]);
573
574
        return $this->findNodesByFilterRecursiveChildren($stored_filter, $deleted, $offset, $limit);
575
    }
576
577
    /**
578
     * Init node.
579
     */
580
    public function initNode(array $node): NodeInterface
581
    {
582
        $id = $node['_id'];
0 ignored issues
show
Unused Code introduced by
$id is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
583
584
        if (isset($node['shared']) && true === $node['shared'] && null !== $this->user && $node['owner'] != $this->user->getId()) {
585
            $node = $this->findReferenceNode($node);
586
        }
587
588
        if (isset($node['parent'])) {
589
            $parent = $this->findNodeById($node['parent']);
590
        } elseif ($node['_id'] !== null) {
591
            $parent = $this->getRoot();
592
        } else {
593
            $parent = null;
594
        }
595
596
        if (!array_key_exists('directory', $node)) {
597
            throw new Exception('invalid node ['.$node['_id'].'] found, directory attribute does not exists');
598
        }
599
600
        $instance = $this->node_factory->build($this, $node, $parent);
601
602
        if (!$this->acl->isAllowed($instance, 'r')) {
603
            if ($instance->isReference()) {
604
                $instance->delete(true);
605
            }
606
607
            throw new ForbiddenException(
608
                'not allowed to access node',
609
                ForbiddenException::NOT_ALLOWED_TO_ACCESS
610
            );
611
        }
612
613
        $loaded = isset($this->cache[(string) $node['_id']]);
614
615
        if ($loaded === false) {
616
            $this->cache[(string) $node['_id']] = $instance;
617
        }
618
619
        if ($loaded === false && isset($node['destroy']) && $node['destroy'] instanceof UTCDateTime && $node['destroy']->toDateTime()->format('U') <= time()) {
0 ignored issues
show
Bug introduced by
The class MongoDB\BSON\UTCDateTime 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...
620
            $this->logger->info('node ['.$node['_id'].'] is not accessible anmyore, destroy node cause of expired destroy flag', [
621
                'category' => get_class($this),
622
            ]);
623
624
            $instance->delete(true);
625
626
            throw new Exception\Conflict('node is not available anymore');
627
        }
628
629
        if (PHP_SAPI === 'cli') {
630
            unset($this->cache[(string) $node['_id']]);
631
        }
632
633
        return $instance;
634
    }
635
636
    /**
637
     * Resolve shared node to reference or share depending who requested.
638
     */
639
    protected function findReferenceNode(array $node): array
640
    {
641
        if (isset($node['reference']) && ($node['reference'] instanceof ObjectId)) {
0 ignored issues
show
Bug introduced by
The class MongoDB\BSON\ObjectId 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...
642
            $this->logger->debug('reference node ['.$node['_id'].'] requested from share owner, trying to find the shared node', [
643
                'category' => get_class($this),
644
            ]);
645
646
            $result = $this->db->storage->findOne([
647
                'owner' => $this->user->getId(),
648
                'shared' => true,
649
                '_id' => $node['reference'],
650
            ]);
651
652
            if (null === $result) {
653
                throw new Exception\NotFound(
654
                    'no share node for reference node '.$node['reference'].' found',
655
                    Exception\NotFound::SHARE_NOT_FOUND
656
                );
657
            }
658
        } else {
659
            $this->logger->debug('share node ['.$node['_id'].'] requested from member, trying to find the reference node', [
660
                'category' => get_class($this),
661
            ]);
662
663
            $result = $this->db->storage->findOne([
664
                'owner' => $this->user->getId(),
665
                'shared' => true,
666
                'reference' => $node['_id'],
667
            ]);
668
669
            if (null === $result) {
670
                throw new Exception\NotFound(
671
                    'no share reference for node '.$node['_id'].' found',
672
                    Exception\NotFound::REFERENCE_NOT_FOUND
673
                );
674
            }
675
        }
676
677
        return $result;
678
    }
679
}
680