]> git.immae.eu Git - github/wallabag/wallabag.git/blame - src/Wallabag/CoreBundle/Repository/EntryRepository.php
Added route to list entries with annotations
[github/wallabag/wallabag.git] / src / Wallabag / CoreBundle / Repository / EntryRepository.php
CommitLineData
9d50517c
NL
1<?php
2
ad4d1caa 3namespace Wallabag\CoreBundle\Repository;
9d50517c 4
9d50517c 5use Doctrine\ORM\EntityRepository;
091bafeb 6use Doctrine\ORM\NoResultException;
52b84c11 7use Doctrine\ORM\QueryBuilder;
bcf53ab7
WD
8use Pagerfanta\Adapter\DoctrineORMAdapter;
9use Pagerfanta\Pagerfanta;
52b84c11 10use Wallabag\CoreBundle\Entity\Entry;
fc732227 11use Wallabag\CoreBundle\Entity\Tag;
4a551637 12use Wallabag\CoreBundle\Helper\UrlHasher;
9d50517c 13
be463487 14class EntryRepository extends EntityRepository
9d50517c 15{
2b7a4889
NL
16 /**
17 * Retrieves all entries for a user.
18 *
19 * @param int $userId
20 *
21 * @return QueryBuilder
22 */
23 public function getBuilderForAllByUser($userId)
24 {
25 return $this
b7c5fda5 26 ->getSortedQueryBuilderByUser($userId)
2b7a4889
NL
27 ;
28 }
29
0ab7404f
JB
30 /**
31 * Retrieves unread entries for a user.
32 *
33 * @param int $userId
34 *
35 * @return QueryBuilder
36 */
37 public function getBuilderForUnreadByUser($userId)
38 {
39 return $this
b7c5fda5 40 ->getSortedQueryBuilderByUser($userId)
0ab7404f
JB
41 ->andWhere('e.isArchived = false')
42 ;
9d50517c 43 }
bd9f0815 44
b84a8055 45 /**
4346a860 46 * Retrieves read entries for a user.
b84a8055 47 *
3b815d2d 48 * @param int $userId
3b815d2d 49 *
26864574 50 * @return QueryBuilder
b84a8055 51 */
0ab7404f 52 public function getBuilderForArchiveByUser($userId)
bd9f0815 53 {
0ab7404f 54 return $this
9007fe00 55 ->getSortedQueryBuilderByUser($userId, 'archivedAt', 'desc')
0ab7404f
JB
56 ->andWhere('e.isArchived = true')
57 ;
bd9f0815
NL
58 }
59
b84a8055 60 /**
4346a860 61 * Retrieves starred entries for a user.
b84a8055 62 *
3b815d2d 63 * @param int $userId
3b815d2d 64 *
26864574 65 * @return QueryBuilder
b84a8055 66 */
0ab7404f 67 public function getBuilderForStarredByUser($userId)
bd9f0815 68 {
0ab7404f 69 return $this
b7c5fda5 70 ->getSortedQueryBuilderByUser($userId, 'starredAt', 'desc')
0ab7404f
JB
71 ->andWhere('e.isStarred = true')
72 ;
bd9f0815 73 }
a8c90c5c 74
ee122a75
NL
75 /**
76 * Retrieves entries filtered with a search term for a user.
77 *
78 * @param int $userId
79 * @param string $term
52b84c11 80 * @param string $currentRoute
ee122a75
NL
81 *
82 * @return QueryBuilder
83 */
49b042df 84 public function getBuilderForSearchByUser($userId, $term, $currentRoute)
ee122a75 85 {
49b042df 86 $qb = $this
b7c5fda5 87 ->getSortedQueryBuilderByUser($userId);
49b042df
NL
88
89 if ('starred' === $currentRoute) {
90 $qb->andWhere('e.isStarred = true');
91 } elseif ('unread' === $currentRoute) {
92 $qb->andWhere('e.isArchived = false');
93 } elseif ('archive' === $currentRoute) {
94 $qb->andWhere('e.isArchived = true');
95 }
96
eac09b48 97 // We lower() all parts here because PostgreSQL 'LIKE' verb is case-sensitive
49b042df 98 $qb
f808b016 99 ->andWhere('lower(e.content) LIKE lower(:term) OR lower(e.title) LIKE lower(:term) OR lower(e.url) LIKE lower(:term)')->setParameter('term', '%' . $term . '%')
ee122a75 100 ->leftJoin('e.tags', 't')
32f455c1 101 ->groupBy('e.id');
49b042df
NL
102
103 return $qb;
ee122a75
NL
104 }
105
b6520f0b 106 /**
06366972 107 * Retrieve a sorted list of untagged entries for a user.
b6520f0b
NL
108 *
109 * @param int $userId
110 *
111 * @return QueryBuilder
112 */
113 public function getBuilderForUntaggedByUser($userId)
114 {
09ef25c3 115 return $this->sortQueryBuilder($this->getRawBuilderForUntaggedByUser($userId));
06366972
KD
116 }
117
4b997bc8
NL
118 /**
119 * Retrieve entries with annotations for a user.
120 *
121 * @param int $userId
122 *
123 * @return QueryBuilder
124 */
125 public function getBuilderForAnnotationsByUser($userId)
126 {
127 return $this
128 ->getSortedQueryBuilderByUser($userId)
129 ->innerJoin('e.annotations', 'a')
130 ;
131 }
132
06366972
KD
133 /**
134 * Retrieve untagged entries for a user.
b8115ff4 135 *
06366972 136 * @param int $userId
b8115ff4 137 *
06366972
KD
138 * @return QueryBuilder
139 */
140 public function getRawBuilderForUntaggedByUser($userId)
141 {
142 return $this->getQueryBuilderByUser($userId)
143 ->leftJoin('e.tags', 't')
144 ->andWhere('t.id is null');
b6520f0b
NL
145 }
146
ad51743e
KD
147 /**
148 * Retrieve the number of untagged entries for a user.
0f2d24fe 149 *
ad51743e 150 * @param int $userId
0f2d24fe 151 *
ad51743e
KD
152 * @return int
153 */
154 public function countUntaggedEntriesByUser($userId)
155 {
0f2d24fe 156 return (int) $this->getRawBuilderForUntaggedByUser($userId)
ad51743e 157 ->select('count(e.id)')
0f2d24fe 158 ->getQuery()
ad51743e
KD
159 ->getSingleScalarResult();
160 }
161
3b815d2d 162 /**
4346a860 163 * Find Entries.
3b815d2d 164 *
2a94b1d1
NL
165 * @param int $userId
166 * @param bool $isArchived
167 * @param bool $isStarred
1112e547 168 * @param bool $isPublic
2a94b1d1
NL
169 * @param string $sort
170 * @param string $order
8cb869ea
TC
171 * @param int $since
172 * @param string $tags
2c290747
KD
173 * @param string $detail 'metadata' or 'full'. Include content field if 'full'
174 *
175 * @todo Breaking change: replace default detail=full by detail=metadata in a future version
3b815d2d 176 *
52b84c11 177 * @return Pagerfanta
3b815d2d 178 */
2c290747 179 public function findEntries($userId, $isArchived = null, $isStarred = null, $isPublic = null, $sort = 'created', $order = 'asc', $since = 0, $tags = '', $detail = 'full')
a8c90c5c 180 {
2c290747
KD
181 if (!\in_array(strtolower($detail), ['full', 'metadata'], true)) {
182 throw new \Exception('Detail "' . $detail . '" parameter is wrong, allowed: full or metadata');
183 }
184
a8c90c5c 185 $qb = $this->createQueryBuilder('e')
28803f10 186 ->leftJoin('e.tags', 't')
7c04b739 187 ->where('e.user = :userId')->setParameter('userId', $userId);
6e334aba 188
2c290747
KD
189 if ('metadata' === $detail) {
190 $fieldNames = $this->getClassMetadata()->getFieldNames();
191 $fields = array_filter($fieldNames, function ($k) {
192 return 'content' !== $k;
193 });
194 $qb->select(sprintf('partial e.{%s}', implode(',', $fields)));
195 }
196
3b815d2d 197 if (null !== $isArchived) {
1112e547 198 $qb->andWhere('e.isArchived = :isArchived')->setParameter('isArchived', (bool) $isArchived);
6e334aba
NL
199 }
200
3b815d2d 201 if (null !== $isStarred) {
1112e547
JB
202 $qb->andWhere('e.isStarred = :isStarred')->setParameter('isStarred', (bool) $isStarred);
203 }
204
205 if (null !== $isPublic) {
f808b016 206 $qb->andWhere('e.uid IS ' . (true === $isPublic ? 'NOT' : '') . ' NULL');
6e334aba
NL
207 }
208
c3f8b428 209 if ($since > 0) {
e5fb89e5 210 $qb->andWhere('e.updatedAt > :since')->setParameter('since', new \DateTime(date('Y-m-d H:i:s', $since)));
4f0558a0
TC
211 }
212
2a1ceb67 213 if (\is_string($tags) && '' !== $tags) {
7c04b739
JB
214 foreach (explode(',', $tags) as $i => $tag) {
215 $entryAlias = 'e' . $i;
216 $tagAlias = 't' . $i;
217
33264c2d 218 // Complexe queries to ensure multiple tags are associated to an entry
7c04b739
JB
219 // https://stackoverflow.com/a/6638146/569101
220 $qb->andWhere($qb->expr()->in(
221 'e.id',
222 $this->createQueryBuilder($entryAlias)
223 ->select($entryAlias . '.id')
224 ->leftJoin($entryAlias . '.tags', $tagAlias)
225 ->where($tagAlias . '.label = :label' . $i)
226 ->getDQL()
227 ));
228
229 // bound parameter to the main query builder
230 $qb->setParameter('label' . $i, $tag);
28803f10 231 }
e5fb89e5
TC
232 }
233
78e3fafa
JB
234 if (!\in_array(strtolower($order), ['asc', 'desc'], true)) {
235 throw new \Exception('Order "' . $order . '" parameter is wrong, allowed: asc or desc');
236 }
237
bc782eaa 238 if ('created' === $sort) {
2385f891 239 $qb->orderBy('e.id', $order);
bc782eaa
NL
240 } elseif ('updated' === $sort) {
241 $qb->orderBy('e.updatedAt', $order);
7c0d6826 242 } elseif ('archived' === $sort) {
0e70e812 243 $qb->orderBy('e.archivedAt', $order);
bc782eaa
NL
244 }
245
5a5da369 246 $pagerAdapter = new DoctrineORMAdapter($qb, true, false);
bcf53ab7
WD
247
248 return new Pagerfanta($pagerAdapter);
a8c90c5c 249 }
46bbd8d3 250
a36737f4
NL
251 /**
252 * Fetch an entry with a tag. Only used for tests.
253 *
5c072d2b
NL
254 * @param int $userId
255 *
52b84c11 256 * @return array
a36737f4 257 */
092ca707 258 public function findOneWithTags($userId)
46bbd8d3
NL
259 {
260 $qb = $this->createQueryBuilder('e')
261 ->innerJoin('e.tags', 't')
0ca374e6
NL
262 ->innerJoin('e.user', 'u')
263 ->addSelect('t', 'u')
7c04b739 264 ->where('e.user = :userId')->setParameter('userId', $userId)
0ca374e6 265 ;
092ca707 266
0ca374e6 267 return $qb->getQuery()->getResult();
46bbd8d3 268 }
d4ebe5c5
JB
269
270 /**
271 * Find distinct language for a given user.
272 * Used to build the filter language list.
273 *
274 * @param int $userId User id
275 *
276 * @return array
277 */
278 public function findDistinctLanguageByUser($userId)
279 {
280 $results = $this->createQueryBuilder('e')
281 ->select('e.language')
282 ->where('e.user = :userId')->setParameter('userId', $userId)
283 ->andWhere('e.language IS NOT NULL')
284 ->groupBy('e.language')
285 ->orderBy('e.language', ' ASC')
286 ->getQuery()
287 ->getResult();
288
4094ea47 289 $languages = [];
d4ebe5c5
JB
290 foreach ($results as $result) {
291 $languages[$result['language']] = $result['language'];
292 }
293
294 return $languages;
295 }
159986c4 296
159986c4 297 /**
cfb28c9d 298 * Used only in test case to get the right entry associated to the right user.
159986c4 299 *
cfb28c9d 300 * @param string $username
159986c4
JB
301 *
302 * @return Entry
303 */
304 public function findOneByUsernameAndNotArchived($username)
305 {
306 return $this->createQueryBuilder('e')
307 ->leftJoin('e.user', 'u')
308 ->where('u.username = :username')->setParameter('username', $username)
309 ->andWhere('e.isArchived = false')
310 ->setMaxResults(1)
311 ->getQuery()
312 ->getSingleResult();
313 }
fc732227
JB
314
315 /**
316 * Remove a tag from all user entries.
4059a061
JB
317 *
318 * 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.
6be97501
JB
319 * 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:
320 *
321 * 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
fc732227
JB
322 *
323 * @param int $userId
fc732227
JB
324 */
325 public function removeTag($userId, Tag $tag)
326 {
b7c5fda5 327 $entries = $this->getSortedQueryBuilderByUser($userId)
4059a061
JB
328 ->innerJoin('e.tags', 't')
329 ->andWhere('t.id = :tagId')->setParameter('tagId', $tag->getId())
330 ->getQuery()
331 ->getResult();
332
333 foreach ($entries as $entry) {
334 $entry->removeTag($tag);
335 }
336
337 $this->getEntityManager()->flush();
4059a061
JB
338 }
339
4da01f49 340 /**
9bf83f1f 341 * Remove tags from all user entries.
4da01f49 342 *
9bf83f1f 343 * @param int $userId
4da01f49
TC
344 * @param Array<Tag> $tags
345 */
9bf83f1f
TC
346 public function removeTags($userId, $tags)
347 {
4da01f49
TC
348 foreach ($tags as $tag) {
349 $this->removeTag($userId, $tag);
350 }
351 }
352
4059a061
JB
353 /**
354 * Find all entries that are attached to a give tag id.
355 *
356 * @param int $userId
357 * @param int $tagId
358 *
359 * @return array
360 */
361 public function findAllByTagId($userId, $tagId)
362 {
b7c5fda5 363 return $this->getSortedQueryBuilderByUser($userId)
4059a061
JB
364 ->innerJoin('e.tags', 't')
365 ->andWhere('t.id = :tagId')->setParameter('tagId', $tagId)
366 ->getQuery()
367 ->getResult();
fc732227 368 }
303768df
NL
369
370 /**
371 * Find an entry by its url and its owner.
5a4bbcc9 372 * If it exists, return the entry otherwise return false.
303768df 373 *
50f35f0d
JB
374 * @param string $url
375 * @param int $userId
303768df 376 *
52e8d932 377 * @return Entry|false
303768df 378 */
78833672 379 public function findByUrlAndUserId($url, $userId)
303768df 380 {
d5744bf0 381 return $this->findByHashedUrlAndUserId(
4a551637 382 UrlHasher::hashUrl($url),
0132ccd2
JB
383 $userId
384 );
303768df 385 }
5c072d2b 386
9c2b2aae
JB
387 /**
388 * Find an entry by its hashed url and its owner.
389 * If it exists, return the entry otherwise return false.
390 *
c579ce23
JB
391 * @param string $hashedUrl Url hashed using sha1
392 * @param int $userId
9c2b2aae 393 *
52e8d932 394 * @return Entry|false
9c2b2aae
JB
395 */
396 public function findByHashedUrlAndUserId($hashedUrl, $userId)
397 {
70df4c33 398 // try first using hashed_url (to use the database index)
9c2b2aae 399 $res = $this->createQueryBuilder('e')
c579ce23 400 ->where('e.hashedUrl = :hashed_url')->setParameter('hashed_url', $hashedUrl)
9c2b2aae
JB
401 ->andWhere('e.user = :user_id')->setParameter('user_id', $userId)
402 ->getQuery()
403 ->getResult();
404
405 if (\count($res)) {
406 return current($res);
407 }
408
70df4c33
JB
409 // then try using hashed_given_url (to use the database index)
410 $res = $this->createQueryBuilder('e')
411 ->where('e.hashedGivenUrl = :hashed_given_url')->setParameter('hashed_given_url', $hashedUrl)
9c2b2aae
JB
412 ->andWhere('e.user = :user_id')->setParameter('user_id', $userId)
413 ->getQuery()
414 ->getResult();
415
416 if (\count($res)) {
417 return current($res);
418 }
419
420 return false;
421 }
422
5c072d2b
NL
423 /**
424 * Count all entries for a user.
425 *
426 * @param int $userId
427 *
e678c475 428 * @return int
5c072d2b 429 */
273b6f06 430 public function countAllEntriesByUser($userId)
5c072d2b
NL
431 {
432 $qb = $this->createQueryBuilder('e')
433 ->select('count(e)')
7c04b739
JB
434 ->where('e.user = :userId')->setParameter('userId', $userId)
435 ;
436
437 return (int) $qb->getQuery()->getSingleScalarResult();
438 }
439
191564b7
JB
440 /**
441 * Remove all entries for a user id.
8c61fd12 442 * Used when a user want to reset all informations.
191564b7 443 *
8c61fd12 444 * @param int $userId
191564b7
JB
445 */
446 public function removeAllByUserId($userId)
447 {
448 $this->getEntityManager()
b0de88f7
JB
449 ->createQuery('DELETE FROM Wallabag\CoreBundle\Entity\Entry e WHERE e.user = :userId')
450 ->setParameter('userId', $userId)
191564b7
JB
451 ->execute();
452 }
6da1aebc
TC
453
454 public function removeArchivedByUserId($userId)
455 {
456 $this->getEntityManager()
457 ->createQuery('DELETE FROM Wallabag\CoreBundle\Entity\Entry e WHERE e.user = :userId AND e.isArchived = TRUE')
458 ->setParameter('userId', $userId)
459 ->execute();
460 }
e2f3800c
TC
461
462 /**
463 * Get id and url from all entries
464 * Used for the clean-duplicates command.
465 */
dbf1188c 466 public function findAllEntriesIdAndUrlByUserId($userId)
e2f3800c
TC
467 {
468 $qb = $this->createQueryBuilder('e')
469 ->select('e.id, e.url')
470 ->where('e.user = :userid')->setParameter(':userid', $userId);
471
472 return $qb->getQuery()->getArrayResult();
473 }
d09fe4d2 474
511f1ce1
NH
475 /**
476 * @param int $userId
477 *
478 * @return array
479 */
215409a8 480 public function findAllEntriesIdByUserId($userId = null)
511f1ce1
NH
481 {
482 $qb = $this->createQueryBuilder('e')
483 ->select('e.id');
484
485 if (null !== $userId) {
486 $qb->where('e.user = :userid')->setParameter(':userid', $userId);
487 }
488
489 return $qb->getQuery()->getArrayResult();
490 }
491
d09fe4d2
NL
492 /**
493 * Find all entries by url and owner.
494 *
50f35f0d
JB
495 * @param string $url
496 * @param int $userId
d09fe4d2
NL
497 *
498 * @return array
499 */
500 public function findAllByUrlAndUserId($url, $userId)
501 {
89f108b4 502 return $this->createQueryBuilder('e')
d09fe4d2
NL
503 ->where('e.url = :url')->setParameter('url', urldecode($url))
504 ->andWhere('e.user = :user_id')->setParameter('user_id', $userId)
505 ->getQuery()
506 ->getResult();
d09fe4d2 507 }
f808b016 508
09ef25c3
NL
509 /**
510 * Returns a random entry, filtering by status.
511 *
50f35f0d
JB
512 * @param int $userId
513 * @param string $type Can be unread, archive, starred, etc
09ef25c3 514 *
091bafeb 515 * @throws NoResultException
062fad43 516 *
09ef25c3
NL
517 * @return Entry
518 */
9a57653a 519 public function getRandomEntry($userId, $type = '')
09ef25c3 520 {
062fad43 521 $qb = $this->getQueryBuilderByUser($userId)
50f35f0d 522 ->select('e.id');
09ef25c3 523
9a57653a
JB
524 switch ($type) {
525 case 'unread':
526 $qb->andWhere('e.isArchived = false');
527 break;
528 case 'archive':
529 $qb->andWhere('e.isArchived = true');
530 break;
531 case 'starred':
532 $qb->andWhere('e.isStarred = true');
533 break;
534 case 'untagged':
535 $qb->leftJoin('e.tags', 't');
536 $qb->andWhere('t.id is null');
537 break;
4b997bc8
NL
538 case 'with_annotations':
539 $qb->leftJoin('e.annotations', 'a');
540 $qb->andWhere('a.id is not null');
541 break;
f85d220c
JB
542 }
543
50f35f0d 544 $ids = $qb->getQuery()->getArrayResult();
062fad43 545
091bafeb
JB
546 if (empty($ids)) {
547 throw new NoResultException();
548 }
549
50f35f0d
JB
550 // random select one in the list
551 $randomId = $ids[mt_rand(0, \count($ids) - 1)]['id'];
552
553 return $this->find($randomId);
09ef25c3
NL
554 }
555
f808b016 556 /**
b7c5fda5
KD
557 * Return a query builder to be used by other getBuilderFor* method.
558 *
b8115ff4 559 * @param int $userId
b7c5fda5
KD
560 *
561 * @return QueryBuilder
562 */
563 private function getQueryBuilderByUser($userId)
564 {
565 return $this->createQueryBuilder('e')
566 ->andWhere('e.user = :userId')->setParameter('userId', $userId);
567 }
568
569 /**
570 * Return a sorted query builder to be used by other getBuilderFor* method.
f808b016 571 *
a991c46e
F
572 * @param int $userId
573 * @param string $sortBy
574 * @param string $direction
f808b016
JB
575 *
576 * @return QueryBuilder
577 */
b7c5fda5 578 private function getSortedQueryBuilderByUser($userId, $sortBy = 'createdAt', $direction = 'desc')
f808b016 579 {
17476f4d 580 return $this->sortQueryBuilder($this->getQueryBuilderByUser($userId), $sortBy, $direction);
b7c5fda5
KD
581 }
582
583 /**
b8115ff4
KD
584 * Return the given QueryBuilder with an orderBy() call.
585 *
8d4ed0df
JB
586 * @param string $sortBy
587 * @param string $direction
b7c5fda5
KD
588 *
589 * @return QueryBuilder
590 */
591 private function sortQueryBuilder(QueryBuilder $qb, $sortBy = 'createdAt', $direction = 'desc')
592 {
09ef25c3 593 return $qb->orderBy(sprintf('e.%s', $sortBy), $direction);
f808b016 594 }
9d50517c 595}