aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/Wallabag/CoreBundle/Repository/EntryRepository.php
blob: f2c73bbfffcdfbd99ee629e1cf449fde626f67ba (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
<?php

namespace Wallabag\CoreBundle\Repository;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\NoResultException;
use Doctrine\ORM\QueryBuilder;
use Pagerfanta\Adapter\DoctrineORMAdapter;
use Pagerfanta\Pagerfanta;
use Wallabag\CoreBundle\Entity\Entry;
use Wallabag\CoreBundle\Entity\Tag;
use Wallabag\CoreBundle\Helper\UrlHasher;

class EntryRepository extends EntityRepository
{
    /**
     * Retrieves all entries for a user.
     *
     * @param int $userId
     *
     * @return QueryBuilder
     */
    public function getBuilderForAllByUser($userId)
    {
        return $this
            ->getSortedQueryBuilderByUser($userId)
        ;
    }

    /**
     * Retrieves unread entries for a user.
     *
     * @param int $userId
     *
     * @return QueryBuilder
     */
    public function getBuilderForUnreadByUser($userId)
    {
        return $this
            ->getSortedQueryBuilderByUser($userId)
            ->andWhere('e.isArchived = false')
            ;
    }

    /**
     * Retrieves entries with the same domain.
     *
     * @param int $userId
     * @param int $entryId
     *
     * @return QueryBuilder
     */
    public function getBuilderForSameDomainByUser($userId, $entryId)
    {
        dump($entryId);die;

        $

        return $this
            ->getSortedQueryBuilderByUser($userId)
            ->andWhere('e.isArchived = false')
        ;
    }

    /**
     * Retrieves read entries for a user.
     *
     * @param int $userId
     *
     * @return QueryBuilder
     */
    public function getBuilderForArchiveByUser($userId)
    {
        return $this
            ->getSortedQueryBuilderByUser($userId, 'archivedAt', 'desc')
            ->andWhere('e.isArchived = true')
        ;
    }

    /**
     * Retrieves starred entries for a user.
     *
     * @param int $userId
     *
     * @return QueryBuilder
     */
    public function getBuilderForStarredByUser($userId)
    {
        return $this
            ->getSortedQueryBuilderByUser($userId, 'starredAt', 'desc')
            ->andWhere('e.isStarred = true')
        ;
    }

    /**
     * Retrieves entries filtered with a search term for a user.
     *
     * @param int    $userId
     * @param string $term
     * @param string $currentRoute
     *
     * @return QueryBuilder
     */
    public function getBuilderForSearchByUser($userId, $term, $currentRoute)
    {
        $qb = $this
            ->getSortedQueryBuilderByUser($userId);

        if ('starred' === $currentRoute) {
            $qb->andWhere('e.isStarred = true');
        } elseif ('unread' === $currentRoute) {
            $qb->andWhere('e.isArchived = false');
        } elseif ('archive' === $currentRoute) {
            $qb->andWhere('e.isArchived = true');
        }

        // We lower() all parts here because PostgreSQL 'LIKE' verb is case-sensitive
        $qb
            ->andWhere('lower(e.content) LIKE lower(:term) OR lower(e.title) LIKE lower(:term) OR lower(e.url) LIKE lower(:term)')->setParameter('term', '%' . $term . '%')
            ->leftJoin('e.tags', 't')
            ->groupBy('e.id');

        return $qb;
    }

    /**
     * Retrieve a sorted list of untagged entries for a user.
     *
     * @param int $userId
     *
     * @return QueryBuilder
     */
    public function getBuilderForUntaggedByUser($userId)
    {
        return $this->sortQueryBuilder($this->getRawBuilderForUntaggedByUser($userId));
    }

    /**
     * Retrieve untagged entries for a user.
     *
     * @param int $userId
     *
     * @return QueryBuilder
     */
    public function getRawBuilderForUntaggedByUser($userId)
    {
        return $this->getQueryBuilderByUser($userId)
            ->leftJoin('e.tags', 't')
            ->andWhere('t.id is null');
    }

    /**
     * Retrieve the number of untagged entries for a user.
     *
     * @param int $userId
     *
     * @return int
     */
    public function countUntaggedEntriesByUser($userId)
    {
        return (int) $this->getRawBuilderForUntaggedByUser($userId)
            ->select('count(e.id)')
            ->getQuery()
            ->getSingleScalarResult();
    }

    /**
     * Find Entries.
     *
     * @param int    $userId
     * @param bool   $isArchived
     * @param bool   $isStarred
     * @param bool   $isPublic
     * @param string $sort
     * @param string $order
     * @param int    $since
     * @param string $tags
     * @param string $detail     'metadata' or 'full'. Include content field if 'full'
     *
     * @todo Breaking change: replace default detail=full by detail=metadata in a future version
     *
     * @return Pagerfanta
     */
    public function findEntries($userId, $isArchived = null, $isStarred = null, $isPublic = null, $sort = 'created', $order = 'asc', $since = 0, $tags = '', $detail = 'full')
    {
        if (!\in_array(strtolower($detail), ['full', 'metadata'], true)) {
            throw new \Exception('Detail "' . $detail . '" parameter is wrong, allowed: full or metadata');
        }

        $qb = $this->createQueryBuilder('e')
            ->leftJoin('e.tags', 't')
            ->where('e.user = :userId')->setParameter('userId', $userId);

        if ('metadata' === $detail) {
            $fieldNames = $this->getClassMetadata()->getFieldNames();
            $fields = array_filter($fieldNames, function ($k) {
                return 'content' !== $k;
            });
            $qb->select(sprintf('partial e.{%s}', implode(',', $fields)));
        }

        if (null !== $isArchived) {
            $qb->andWhere('e.isArchived = :isArchived')->setParameter('isArchived', (bool) $isArchived);
        }

        if (null !== $isStarred) {
            $qb->andWhere('e.isStarred = :isStarred')->setParameter('isStarred', (bool) $isStarred);
        }

        if (null !== $isPublic) {
            $qb->andWhere('e.uid IS ' . (true === $isPublic ? 'NOT' : '') . ' NULL');
        }

        if ($since > 0) {
            $qb->andWhere('e.updatedAt > :since')->setParameter('since', new \DateTime(date('Y-m-d H:i:s', $since)));
        }

        if (\is_string($tags) && '' !== $tags) {
            foreach (explode(',', $tags) as $i => $tag) {
                $entryAlias = 'e' . $i;
                $tagAlias = 't' . $i;

                // Complexe queries to ensure multiple tags are associated to an entry
                // https://stackoverflow.com/a/6638146/569101
                $qb->andWhere($qb->expr()->in(
                    'e.id',
                    $this->createQueryBuilder($entryAlias)
                        ->select($entryAlias . '.id')
                        ->leftJoin($entryAlias . '.tags', $tagAlias)
                        ->where($tagAlias . '.label = :label' . $i)
                        ->getDQL()
                ));

                // bound parameter to the main query builder
                $qb->setParameter('label' . $i, $tag);
            }
        }

        if (!\in_array(strtolower($order), ['asc', 'desc'], true)) {
            throw new \Exception('Order "' . $order . '" parameter is wrong, allowed: asc or desc');
        }

        if ('created' === $sort) {
            $qb->orderBy('e.id', $order);
        } elseif ('updated' === $sort) {
            $qb->orderBy('e.updatedAt', $order);
        } elseif ('archived' === $sort) {
            $qb->orderBy('e.archivedAt', $order);
        }

        $pagerAdapter = new DoctrineORMAdapter($qb, true, false);

        return new Pagerfanta($pagerAdapter);
    }

    /**
     * Fetch an entry with a tag. Only used for tests.
     *
     * @param int $userId
     *
     * @return array
     */
    public function findOneWithTags($userId)
    {
        $qb = $this->createQueryBuilder('e')
            ->innerJoin('e.tags', 't')
            ->innerJoin('e.user', 'u')
            ->addSelect('t', 'u')
            ->where('e.user = :userId')->setParameter('userId', $userId)
        ;

        return $qb->getQuery()->getResult();
    }

    /**
     * Find distinct language for a given user.
     * Used to build the filter language list.
     *
     * @param int $userId User id
     *
     * @return array
     */
    public function findDistinctLanguageByUser($userId)
    {
        $results = $this->createQueryBuilder('e')
            ->select('e.language')
            ->where('e.user = :userId')->setParameter('userId', $userId)
            ->andWhere('e.language IS NOT NULL')
            ->groupBy('e.language')
            ->orderBy('e.language', ' ASC')
            ->getQuery()
            ->getResult();

        $languages = [];
        foreach ($results as $result) {
            $languages[$result['language']] = $result['language'];
        }

        return $languages;
    }

    /**
     * Used only in test case to get the right entry associated to the right user.
     *
     * @param string $username
     *
     * @return Entry
     */
    public function findOneByUsernameAndNotArchived($username)
    {
        return $this->createQueryBuilder('e')
            ->leftJoin('e.user', 'u')
            ->where('u.username = :username')->setParameter('username', $username)
            ->andWhere('e.isArchived = false')
            ->setMaxResults(1)
            ->getQuery()
            ->getSingleResult();
    }

    /**
     * Remove a tag from all user entries.
     *
     * We need to loop on each entry attached to the given tag to remove it, since Doctrine doesn't know EntryTag entity because it's a ManyToMany relation.
     * It could be faster with one query but I don't know how to retrieve the table name `entry_tag` which can have a prefix:
     *
     * DELETE et FROM entry_tag et WHERE et.entry_id IN ( SELECT e.id FROM entry e WHERE e.user_id = :userId ) AND et.tag_id = :tagId
     *
     * @param int $userId
     */
    public function removeTag($userId, Tag $tag)
    {
        $entries = $this->getSortedQueryBuilderByUser($userId)
            ->innerJoin('e.tags', 't')
            ->andWhere('t.id = :tagId')->setParameter('tagId', $tag->getId())
            ->getQuery()
            ->getResult();

        foreach ($entries as $entry) {
            $entry->removeTag($tag);
        }

        $this->getEntityManager()->flush();
    }

    /**
     * Remove tags from all user entries.
     *
     * @param int        $userId
     * @param Array<Tag> $tags
     */
    public function removeTags($userId, $tags)
    {
        foreach ($tags as $tag) {
            $this->removeTag($userId, $tag);
        }
    }

    /**
     * Find all entries that are attached to a give tag id.
     *
     * @param int $userId
     * @param int $tagId
     *
     * @return array
     */
    public function findAllByTagId($userId, $tagId)
    {
        return $this->getSortedQueryBuilderByUser($userId)
            ->innerJoin('e.tags', 't')
            ->andWhere('t.id = :tagId')->setParameter('tagId', $tagId)
            ->getQuery()
            ->getResult();
    }

    /**
     * Find an entry by its url and its owner.
     * If it exists, return the entry otherwise return false.
     *
     * @param string $url
     * @param int    $userId
     *
     * @return Entry|false
     */
    public function findByUrlAndUserId($url, $userId)
    {
        return $this->findByHashedUrlAndUserId(
            UrlHasher::hashUrl($url),
            $userId
        );
    }

    /**
     * Find an entry by its hashed url and its owner.
     * If it exists, return the entry otherwise return false.
     *
     * @param string $hashedUrl Url hashed using sha1
     * @param int    $userId
     *
     * @return Entry|false
     */
    public function findByHashedUrlAndUserId($hashedUrl, $userId)
    {
        // try first using hashed_url (to use the database index)
        $res = $this->createQueryBuilder('e')
            ->where('e.hashedUrl = :hashed_url')->setParameter('hashed_url', $hashedUrl)
            ->andWhere('e.user = :user_id')->setParameter('user_id', $userId)
            ->getQuery()
            ->getResult();

        if (\count($res)) {
            return current($res);
        }

        // then try using hashed_given_url (to use the database index)
        $res = $this->createQueryBuilder('e')
            ->where('e.hashedGivenUrl = :hashed_given_url')->setParameter('hashed_given_url', $hashedUrl)
            ->andWhere('e.user = :user_id')->setParameter('user_id', $userId)
            ->getQuery()
            ->getResult();

        if (\count($res)) {
            return current($res);
        }

        return false;
    }

    /**
     * Count all entries for a user.
     *
     * @param int $userId
     *
     * @return int
     */
    public function countAllEntriesByUser($userId)
    {
        $qb = $this->createQueryBuilder('e')
            ->select('count(e)')
            ->where('e.user = :userId')->setParameter('userId', $userId)
        ;

        return (int) $qb->getQuery()->getSingleScalarResult();
    }

    /**
     * Remove all entries for a user id.
     * Used when a user want to reset all informations.
     *
     * @param int $userId
     */
    public function removeAllByUserId($userId)
    {
        $this->getEntityManager()
            ->createQuery('DELETE FROM Wallabag\CoreBundle\Entity\Entry e WHERE e.user = :userId')
            ->setParameter('userId', $userId)
            ->execute();
    }

    public function removeArchivedByUserId($userId)
    {
        $this->getEntityManager()
            ->createQuery('DELETE FROM Wallabag\CoreBundle\Entity\Entry e WHERE e.user = :userId AND e.isArchived = TRUE')
            ->setParameter('userId', $userId)
            ->execute();
    }

    /**
     * Get id and url from all entries
     * Used for the clean-duplicates command.
     */
    public function findAllEntriesIdAndUrlByUserId($userId)
    {
        $qb = $this->createQueryBuilder('e')
            ->select('e.id, e.url')
            ->where('e.user = :userid')->setParameter(':userid', $userId);

        return $qb->getQuery()->getArrayResult();
    }

    /**
     * @param int $userId
     *
     * @return array
     */
    public function findAllEntriesIdByUserId($userId = null)
    {
        $qb = $this->createQueryBuilder('e')
            ->select('e.id');

        if (null !== $userId) {
            $qb->where('e.user = :userid')->setParameter(':userid', $userId);
        }

        return $qb->getQuery()->getArrayResult();
    }

    /**
     * Find all entries by url and owner.
     *
     * @param string $url
     * @param int    $userId
     *
     * @return array
     */
    public function findAllByUrlAndUserId($url, $userId)
    {
        return $this->createQueryBuilder('e')
            ->where('e.url = :url')->setParameter('url', urldecode($url))
            ->andWhere('e.user = :user_id')->setParameter('user_id', $userId)
            ->getQuery()
            ->getResult();
    }

    /**
     * Returns a random entry, filtering by status.
     *
     * @param int    $userId
     * @param string $type   Can be unread, archive, starred, etc
     *
     * @throws NoResultException
     *
     * @return Entry
     */
    public function getRandomEntry($userId, $type = '')
    {
        $qb = $this->getQueryBuilderByUser($userId)
            ->select('e.id');

        switch ($type) {
            case 'unread':
                $qb->andWhere('e.isArchived = false');
                break;
            case 'archive':
                $qb->andWhere('e.isArchived = true');
                break;
            case 'starred':
                $qb->andWhere('e.isStarred = true');
                break;
            case 'untagged':
                $qb->leftJoin('e.tags', 't');
                $qb->andWhere('t.id is null');
                break;
        }

        $ids = $qb->getQuery()->getArrayResult();

        if (empty($ids)) {
            throw new NoResultException();
        }

        // random select one in the list
        $randomId = $ids[mt_rand(0, \count($ids) - 1)]['id'];

        return $this->find($randomId);
    }

    /**
     * Return a query builder to be used by other getBuilderFor* method.
     *
     * @param int $userId
     *
     * @return QueryBuilder
     */
    private function getQueryBuilderByUser($userId)
    {
        return $this->createQueryBuilder('e')
            ->andWhere('e.user = :userId')->setParameter('userId', $userId);
    }

    /**
     * Return a sorted query builder to be used by other getBuilderFor* method.
     *
     * @param int    $userId
     * @param string $sortBy
     * @param string $direction
     *
     * @return QueryBuilder
     */
    private function getSortedQueryBuilderByUser($userId, $sortBy = 'createdAt', $direction = 'desc')
    {
        return $this->sortQueryBuilder($this->getQueryBuilderByUser($userId), $sortBy, $direction);
    }

    /**
     * Return the given QueryBuilder with an orderBy() call.
     *
     * @param string $sortBy
     * @param string $direction
     *
     * @return QueryBuilder
     */
    private function sortQueryBuilder(QueryBuilder $qb, $sortBy = 'createdAt', $direction = 'desc')
    {
        return $qb->orderBy(sprintf('e.%s', $sortBy), $direction);
    }
}