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