]> 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 {
ee360905 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 */
1112e547 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
bc782eaa 187 if ('created' === $sort) {
2385f891 188 $qb->orderBy('e.id', $order);
bc782eaa
NL
189 } elseif ('updated' === $sort) {
190 $qb->orderBy('e.updatedAt', $order);
7c0d6826 191 } elseif ('archived' === $sort) {
0e70e812 192 $qb->orderBy('e.archivedAt', $order);
bc782eaa
NL
193 }
194
5a5da369 195 $pagerAdapter = new DoctrineORMAdapter($qb, true, false);
bcf53ab7
WD
196
197 return new Pagerfanta($pagerAdapter);
a8c90c5c 198 }
46bbd8d3 199
a36737f4
NL
200 /**
201 * Fetch an entry with a tag. Only used for tests.
202 *
5c072d2b
NL
203 * @param int $userId
204 *
52b84c11 205 * @return array
a36737f4 206 */
092ca707 207 public function findOneWithTags($userId)
46bbd8d3
NL
208 {
209 $qb = $this->createQueryBuilder('e')
210 ->innerJoin('e.tags', 't')
0ca374e6
NL
211 ->innerJoin('e.user', 'u')
212 ->addSelect('t', 'u')
7c04b739 213 ->where('e.user = :userId')->setParameter('userId', $userId)
0ca374e6 214 ;
092ca707 215
0ca374e6 216 return $qb->getQuery()->getResult();
46bbd8d3 217 }
d4ebe5c5
JB
218
219 /**
220 * Find distinct language for a given user.
221 * Used to build the filter language list.
222 *
223 * @param int $userId User id
224 *
225 * @return array
226 */
227 public function findDistinctLanguageByUser($userId)
228 {
229 $results = $this->createQueryBuilder('e')
230 ->select('e.language')
231 ->where('e.user = :userId')->setParameter('userId', $userId)
232 ->andWhere('e.language IS NOT NULL')
233 ->groupBy('e.language')
234 ->orderBy('e.language', ' ASC')
235 ->getQuery()
236 ->getResult();
237
4094ea47 238 $languages = [];
d4ebe5c5
JB
239 foreach ($results as $result) {
240 $languages[$result['language']] = $result['language'];
241 }
242
243 return $languages;
244 }
159986c4 245
159986c4 246 /**
cfb28c9d 247 * Used only in test case to get the right entry associated to the right user.
159986c4 248 *
cfb28c9d 249 * @param string $username
159986c4
JB
250 *
251 * @return Entry
252 */
253 public function findOneByUsernameAndNotArchived($username)
254 {
255 return $this->createQueryBuilder('e')
256 ->leftJoin('e.user', 'u')
257 ->where('u.username = :username')->setParameter('username', $username)
258 ->andWhere('e.isArchived = false')
259 ->setMaxResults(1)
260 ->getQuery()
261 ->getSingleResult();
262 }
fc732227
JB
263
264 /**
265 * Remove a tag from all user entries.
4059a061
JB
266 *
267 * 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
268 * 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:
269 *
270 * 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
271 *
272 * @param int $userId
273 * @param Tag $tag
274 */
275 public function removeTag($userId, Tag $tag)
276 {
b7c5fda5 277 $entries = $this->getSortedQueryBuilderByUser($userId)
4059a061
JB
278 ->innerJoin('e.tags', 't')
279 ->andWhere('t.id = :tagId')->setParameter('tagId', $tag->getId())
280 ->getQuery()
281 ->getResult();
282
283 foreach ($entries as $entry) {
284 $entry->removeTag($tag);
285 }
286
287 $this->getEntityManager()->flush();
4059a061
JB
288 }
289
4da01f49 290 /**
9bf83f1f 291 * Remove tags from all user entries.
4da01f49 292 *
9bf83f1f 293 * @param int $userId
4da01f49
TC
294 * @param Array<Tag> $tags
295 */
9bf83f1f
TC
296 public function removeTags($userId, $tags)
297 {
4da01f49
TC
298 foreach ($tags as $tag) {
299 $this->removeTag($userId, $tag);
300 }
301 }
302
4059a061
JB
303 /**
304 * Find all entries that are attached to a give tag id.
305 *
306 * @param int $userId
307 * @param int $tagId
308 *
309 * @return array
310 */
311 public function findAllByTagId($userId, $tagId)
312 {
b7c5fda5 313 return $this->getSortedQueryBuilderByUser($userId)
4059a061
JB
314 ->innerJoin('e.tags', 't')
315 ->andWhere('t.id = :tagId')->setParameter('tagId', $tagId)
316 ->getQuery()
317 ->getResult();
fc732227 318 }
303768df
NL
319
320 /**
321 * Find an entry by its url and its owner.
5a4bbcc9 322 * If it exists, return the entry otherwise return false.
303768df
NL
323 *
324 * @param $url
325 * @param $userId
326 *
4094ea47 327 * @return Entry|bool
303768df 328 */
78833672 329 public function findByUrlAndUserId($url, $userId)
303768df 330 {
5a4bbcc9 331 $res = $this->createQueryBuilder('e')
19ca0b2f 332 ->where('e.url = :url')->setParameter('url', urldecode($url))
303768df
NL
333 ->andWhere('e.user = :user_id')->setParameter('user_id', $userId)
334 ->getQuery()
335 ->getResult();
5a4bbcc9 336
2a1ceb67 337 if (\count($res)) {
b4b592a0 338 return current($res);
5a4bbcc9
JB
339 }
340
341 return false;
303768df 342 }
5c072d2b
NL
343
344 /**
345 * Count all entries for a user.
346 *
347 * @param int $userId
348 *
e678c475 349 * @return int
5c072d2b 350 */
273b6f06 351 public function countAllEntriesByUser($userId)
5c072d2b
NL
352 {
353 $qb = $this->createQueryBuilder('e')
354 ->select('count(e)')
7c04b739
JB
355 ->where('e.user = :userId')->setParameter('userId', $userId)
356 ;
357
358 return (int) $qb->getQuery()->getSingleScalarResult();
359 }
360
191564b7
JB
361 /**
362 * Remove all entries for a user id.
8c61fd12 363 * Used when a user want to reset all informations.
191564b7 364 *
8c61fd12 365 * @param int $userId
191564b7
JB
366 */
367 public function removeAllByUserId($userId)
368 {
369 $this->getEntityManager()
b0de88f7
JB
370 ->createQuery('DELETE FROM Wallabag\CoreBundle\Entity\Entry e WHERE e.user = :userId')
371 ->setParameter('userId', $userId)
191564b7
JB
372 ->execute();
373 }
6da1aebc
TC
374
375 public function removeArchivedByUserId($userId)
376 {
377 $this->getEntityManager()
378 ->createQuery('DELETE FROM Wallabag\CoreBundle\Entity\Entry e WHERE e.user = :userId AND e.isArchived = TRUE')
379 ->setParameter('userId', $userId)
380 ->execute();
381 }
e2f3800c
TC
382
383 /**
384 * Get id and url from all entries
385 * Used for the clean-duplicates command.
386 */
dbf1188c 387 public function findAllEntriesIdAndUrlByUserId($userId)
e2f3800c
TC
388 {
389 $qb = $this->createQueryBuilder('e')
390 ->select('e.id, e.url')
391 ->where('e.user = :userid')->setParameter(':userid', $userId);
392
393 return $qb->getQuery()->getArrayResult();
394 }
d09fe4d2 395
511f1ce1
NH
396 /**
397 * @param int $userId
398 *
399 * @return array
400 */
215409a8 401 public function findAllEntriesIdByUserId($userId = null)
511f1ce1
NH
402 {
403 $qb = $this->createQueryBuilder('e')
404 ->select('e.id');
405
406 if (null !== $userId) {
407 $qb->where('e.user = :userid')->setParameter(':userid', $userId);
408 }
409
410 return $qb->getQuery()->getArrayResult();
411 }
412
d09fe4d2
NL
413 /**
414 * Find all entries by url and owner.
415 *
416 * @param $url
417 * @param $userId
418 *
419 * @return array
420 */
421 public function findAllByUrlAndUserId($url, $userId)
422 {
89f108b4 423 return $this->createQueryBuilder('e')
d09fe4d2
NL
424 ->where('e.url = :url')->setParameter('url', urldecode($url))
425 ->andWhere('e.user = :user_id')->setParameter('user_id', $userId)
426 ->getQuery()
427 ->getResult();
d09fe4d2 428 }
f808b016 429
ee360905
NL
430 /**
431 * Returns a random entry, filtering by status.
432 *
433 * @param $userId
434 * @param string $status can be unread, archive or starred
435 *
436 * @throws \Doctrine\ORM\NoResultException
437 * @throws \Doctrine\ORM\NonUniqueResultException
438 *
439 * @return Entry
440 */
441 public function getRandomEntry($userId, $status = '')
442 {
443 $max = $this->getEntityManager()
444 ->createQuery('SELECT MAX(e.id) FROM Wallabag\CoreBundle\Entity\Entry e WHERE e.user = :userId')
445 ->setParameter('userId', $userId)
446 ->getSingleScalarResult();
447
448 $qb = $this->createQueryBuilder('e')
449 ->where('e.user = :user_id')->setParameter('user_id', $userId);
450
451 if ('unread' === $status) {
452 $qb->andWhere('e.isArchived = false');
453 }
454
455 if ('archive' === $status) {
456 $qb->andWhere('e.isArchived = true');
457 }
458
459 if ('starred' === $status) {
460 $qb->andWhere('e.isStarred = true');
461 }
462
463 return $qb->andWhere('e.id >= :rand')
464 ->setParameter('rand', rand(0, $max))
465 ->setMaxResults(1)
466 ->getQuery()
467 ->getSingleResult();
468 }
469
f808b016 470 /**
b7c5fda5
KD
471 * Return a query builder to be used by other getBuilderFor* method.
472 *
b8115ff4 473 * @param int $userId
b7c5fda5
KD
474 *
475 * @return QueryBuilder
476 */
477 private function getQueryBuilderByUser($userId)
478 {
479 return $this->createQueryBuilder('e')
480 ->andWhere('e.user = :userId')->setParameter('userId', $userId);
481 }
482
483 /**
484 * Return a sorted query builder to be used by other getBuilderFor* method.
f808b016 485 *
a991c46e
F
486 * @param int $userId
487 * @param string $sortBy
488 * @param string $direction
f808b016
JB
489 *
490 * @return QueryBuilder
491 */
b7c5fda5 492 private function getSortedQueryBuilderByUser($userId, $sortBy = 'createdAt', $direction = 'desc')
f808b016 493 {
17476f4d 494 return $this->sortQueryBuilder($this->getQueryBuilderByUser($userId), $sortBy, $direction);
b7c5fda5
KD
495 }
496
497 /**
b8115ff4
KD
498 * Return the given QueryBuilder with an orderBy() call.
499 *
b7c5fda5 500 * @param QueryBuilder $qb
b8115ff4
KD
501 * @param string $sortBy
502 * @param string $direction
b7c5fda5
KD
503 *
504 * @return QueryBuilder
505 */
506 private function sortQueryBuilder(QueryBuilder $qb, $sortBy = 'createdAt', $direction = 'desc')
507 {
ee360905 508 return $qb->orderBy(sprintf('e.%s', $sortBy), $direction);
f808b016 509 }
9d50517c 510}