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