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