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