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