3 namespace Wallabag\CoreBundle\Repository
;
5 use Doctrine\ORM\EntityRepository
;
6 use Doctrine\ORM\NoResultException
;
7 use Doctrine\ORM\QueryBuilder
;
8 use Pagerfanta\Adapter\DoctrineORMAdapter
;
9 use Pagerfanta\Pagerfanta
;
10 use Wallabag\CoreBundle\Entity\Entry
;
11 use Wallabag\CoreBundle\Entity\Tag
;
12 use Wallabag\CoreBundle\Helper\UrlHasher
;
14 class EntryRepository
extends EntityRepository
17 * Retrieves all entries for a user.
21 * @return QueryBuilder
23 public function getBuilderForAllByUser($userId)
26 ->getSortedQueryBuilderByUser($userId)
31 * Retrieves unread entries for a user.
35 * @return QueryBuilder
37 public function getBuilderForUnreadByUser($userId)
40 ->getSortedQueryBuilderByUser($userId)
41 ->andWhere('e.isArchived = false')
46 * Retrieves read entries for a user.
50 * @return QueryBuilder
52 public function getBuilderForArchiveByUser($userId)
55 ->getSortedQueryBuilderByUser($userId, 'archivedAt', 'desc')
56 ->andWhere('e.isArchived = true')
61 * Retrieves starred entries for a user.
65 * @return QueryBuilder
67 public function getBuilderForStarredByUser($userId)
70 ->getSortedQueryBuilderByUser($userId, 'starredAt', 'desc')
71 ->andWhere('e.isStarred = true')
76 * Retrieves entries filtered with a search term for a user.
80 * @param string $currentRoute
82 * @return QueryBuilder
84 public function getBuilderForSearchByUser($userId, $term, $currentRoute)
87 ->getSortedQueryBuilderByUser($userId);
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');
97 // We lower() all parts here because PostgreSQL 'LIKE' verb is case-sensitive
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 . '%')
100 ->leftJoin('e.tags', 't')
107 * Retrieve a sorted list of untagged entries for a user.
111 * @return QueryBuilder
113 public function getBuilderForUntaggedByUser($userId)
115 return $this->sortQueryBuilder($this->getRawBuilderForUntaggedByUser($userId));
119 * Retrieve untagged entries for a user.
123 * @return QueryBuilder
125 public function getRawBuilderForUntaggedByUser($userId)
127 return $this->getQueryBuilderByUser($userId)
128 ->leftJoin('e.tags', 't')
129 ->andWhere('t.id is null');
136 * @param bool $isArchived
137 * @param bool $isStarred
138 * @param bool $isPublic
139 * @param string $sort
140 * @param string $order
142 * @param string $tags
143 * @param string $detail 'metadata' or 'full'. Include content field if 'full'
145 * @todo Breaking change: replace default detail=full by detail=metadata in a future version
149 public function findEntries($userId, $isArchived = null, $isStarred = null, $isPublic = null, $sort = 'created', $order = 'asc', $since = 0, $tags = '', $detail = 'full')
151 if (!\
in_array(strtolower($detail), ['full', 'metadata'], true)) {
152 throw new \
Exception('Detail "' . $detail . '" parameter is wrong, allowed: full or metadata');
155 $qb = $this->createQueryBuilder('e')
156 ->leftJoin('e.tags', 't')
157 ->where('e.user = :userId')->setParameter('userId', $userId);
159 if ('metadata' === $detail) {
160 $fieldNames = $this->getClassMetadata()->getFieldNames();
161 $fields = array_filter($fieldNames, function ($k) {
162 return 'content' !== $k;
164 $qb->select(sprintf('partial e.{%s}', implode(',', $fields)));
167 if (null !== $isArchived) {
168 $qb->andWhere('e.isArchived = :isArchived')->setParameter('isArchived', (bool) $isArchived);
171 if (null !== $isStarred) {
172 $qb->andWhere('e.isStarred = :isStarred')->setParameter('isStarred', (bool) $isStarred);
175 if (null !== $isPublic) {
176 $qb->andWhere('e.uid IS ' . (true === $isPublic ? 'NOT' : '') . ' NULL');
180 $qb->andWhere('e.updatedAt > :since')->setParameter('since', new \
DateTime(date('Y-m-d H:i:s', $since)));
183 if (\
is_string($tags) && '' !== $tags) {
184 foreach (explode(',', $tags) as $i => $tag) {
185 $entryAlias = 'e' . $i;
186 $tagAlias = 't' . $i;
188 // Complexe queries to ensure multiple tags are associated to an entry
189 // https://stackoverflow.com/a/6638146/569101
190 $qb->andWhere($qb->expr()->in(
192 $this->createQueryBuilder($entryAlias)
193 ->select($entryAlias . '.id')
194 ->leftJoin($entryAlias . '.tags', $tagAlias)
195 ->where($tagAlias . '.label = :label' . $i)
199 // bound parameter to the main query builder
200 $qb->setParameter('label' . $i, $tag);
204 if (!\
in_array(strtolower($order), ['asc', 'desc'], true)) {
205 throw new \
Exception('Order "' . $order . '" parameter is wrong, allowed: asc or desc');
208 if ('created' === $sort) {
209 $qb->orderBy('e.id', $order);
210 } elseif ('updated' === $sort) {
211 $qb->orderBy('e.updatedAt', $order);
212 } elseif ('archived' === $sort) {
213 $qb->orderBy('e.archivedAt', $order);
216 $pagerAdapter = new DoctrineORMAdapter($qb, true, false);
218 return new Pagerfanta($pagerAdapter);
222 * Fetch an entry with a tag. Only used for tests.
228 public function findOneWithTags($userId)
230 $qb = $this->createQueryBuilder('e')
231 ->innerJoin('e.tags', 't')
232 ->innerJoin('e.user', 'u')
233 ->addSelect('t', 'u')
234 ->where('e.user = :userId')->setParameter('userId', $userId)
237 return $qb->getQuery()->getResult();
241 * Find distinct language for a given user.
242 * Used to build the filter language list.
244 * @param int $userId User id
248 public function findDistinctLanguageByUser($userId)
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')
260 foreach ($results as $result) {
261 $languages[$result['language']] = $result['language'];
268 * Used only in test case to get the right entry associated to the right user.
270 * @param string $username
274 public function findOneByUsernameAndNotArchived($username)
276 return $this->createQueryBuilder('e')
277 ->leftJoin('e.user', 'u')
278 ->where('u.username = :username')->setParameter('username', $username)
279 ->andWhere('e.isArchived = false')
286 * Remove a tag from all user entries.
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.
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:
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
296 public function removeTag($userId, Tag
$tag)
298 $entries = $this->getSortedQueryBuilderByUser($userId)
299 ->innerJoin('e.tags', 't')
300 ->andWhere('t.id = :tagId')->setParameter('tagId', $tag->getId())
304 foreach ($entries as $entry) {
305 $entry->removeTag($tag);
308 $this->getEntityManager()->flush();
312 * Remove tags from all user entries.
315 * @param Array<Tag> $tags
317 public function removeTags($userId, $tags)
319 foreach ($tags as $tag) {
320 $this->removeTag($userId, $tag);
325 * Find all entries that are attached to a give tag id.
332 public function findAllByTagId($userId, $tagId)
334 return $this->getSortedQueryBuilderByUser($userId)
335 ->innerJoin('e.tags', 't')
336 ->andWhere('t.id = :tagId')->setParameter('tagId', $tagId)
342 * Find an entry by its url and its owner.
343 * If it exists, return the entry otherwise return false.
348 * @return Entry|false
350 public function findByUrlAndUserId($url, $userId)
352 return $this->findByHashedUrlAndUserId(
353 UrlHasher
::hashUrl($url),
359 * Find an entry by its hashed url and its owner.
360 * If it exists, return the entry otherwise return false.
362 * @param string $hashedUrl Url hashed using sha1
365 * @return Entry|false
367 public function findByHashedUrlAndUserId($hashedUrl, $userId)
369 $res = $this->createQueryBuilder('e')
370 ->where('e.hashedUrl = :hashed_url')->setParameter('hashed_url', $hashedUrl)
371 ->andWhere('e.user = :user_id')->setParameter('user_id', $userId)
376 return current($res);
383 * Count all entries for a user.
389 public function countAllEntriesByUser($userId)
391 $qb = $this->createQueryBuilder('e')
393 ->where('e.user = :userId')->setParameter('userId', $userId)
396 return (int) $qb->getQuery()->getSingleScalarResult();
400 * Remove all entries for a user id.
401 * Used when a user want to reset all informations.
405 public function removeAllByUserId($userId)
407 $this->getEntityManager()
408 ->createQuery('DELETE FROM Wallabag\CoreBundle\Entity\Entry e WHERE e.user = :userId')
409 ->setParameter('userId', $userId)
413 public function removeArchivedByUserId($userId)
415 $this->getEntityManager()
416 ->createQuery('DELETE FROM Wallabag\CoreBundle\Entity\Entry e WHERE e.user = :userId AND e.isArchived = TRUE')
417 ->setParameter('userId', $userId)
422 * Get id and url from all entries
423 * Used for the clean-duplicates command.
425 public function findAllEntriesIdAndUrlByUserId($userId)
427 $qb = $this->createQueryBuilder('e')
428 ->select('e.id, e.url')
429 ->where('e.user = :userid')->setParameter(':userid', $userId);
431 return $qb->getQuery()->getArrayResult();
439 public function findAllEntriesIdByUserId($userId = null)
441 $qb = $this->createQueryBuilder('e')
444 if (null !== $userId) {
445 $qb->where('e.user = :userid')->setParameter(':userid', $userId);
448 return $qb->getQuery()->getArrayResult();
452 * Find all entries by url and owner.
459 public function findAllByUrlAndUserId($url, $userId)
461 return $this->createQueryBuilder('e')
462 ->where('e.url = :url')->setParameter('url', urldecode($url))
463 ->andWhere('e.user = :user_id')->setParameter('user_id', $userId)
469 * Returns a random entry, filtering by status.
472 * @param string $type Can be unread, archive, starred, etc
474 * @throws NoResultException
478 public function getRandomEntry($userId, $type = '')
480 $qb = $this->getQueryBuilderByUser($userId)
485 $qb->andWhere('e.isArchived = false');
488 $qb->andWhere('e.isArchived = true');
491 $qb->andWhere('e.isStarred = true');
494 $qb->leftJoin('e.tags', 't');
495 $qb->andWhere('t.id is null');
499 $ids = $qb->getQuery()->getArrayResult();
502 throw new NoResultException();
505 // random select one in the list
506 $randomId = $ids[mt_rand(0, \
count($ids) - 1)]['id'];
508 return $this->find($randomId);
512 * Return a query builder to be used by other getBuilderFor* method.
516 * @return QueryBuilder
518 private function getQueryBuilderByUser($userId)
520 return $this->createQueryBuilder('e')
521 ->andWhere('e.user = :userId')->setParameter('userId', $userId);
525 * Return a sorted query builder to be used by other getBuilderFor* method.
528 * @param string $sortBy
529 * @param string $direction
531 * @return QueryBuilder
533 private function getSortedQueryBuilderByUser($userId, $sortBy = 'createdAt', $direction = 'desc')
535 return $this->sortQueryBuilder($this->getQueryBuilderByUser($userId), $sortBy, $direction);
539 * Return the given QueryBuilder with an orderBy() call.
541 * @param QueryBuilder $qb
542 * @param string $sortBy
543 * @param string $direction
545 * @return QueryBuilder
547 private function sortQueryBuilder(QueryBuilder
$qb, $sortBy = 'createdAt', $direction = 'desc')
549 return $qb->orderBy(sprintf('e.%s', $sortBy), $direction);