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.
20 * @param string $sortBy Field to sort
21 * @param string $direction Direction of the order
23 * @return QueryBuilder
25 public function getBuilderForAllByUser($userId, $sortBy = 'id', $direction = 'DESC')
28 ->getSortedQueryBuilderByUser($userId, $sortBy, $direction)
33 * Retrieves unread entries for a user.
36 * @param string $sortBy Field to sort
37 * @param string $direction Direction of the order
39 * @return QueryBuilder
41 public function getBuilderForUnreadByUser($userId, $sortBy = 'id', $direction = 'DESC')
44 ->getSortedQueryBuilderByUser($userId, $sortBy, $direction)
45 ->andWhere('e.isArchived = false')
50 * Retrieves read entries for a user.
53 * @param string $sortBy Field to sort
54 * @param string $direction Direction of the order
56 * @return QueryBuilder
58 public function getBuilderForArchiveByUser($userId, $sortBy = 'archivedAt', $direction = 'DESC')
61 ->getSortedQueryBuilderByUser($userId, $sortBy, $direction)
62 ->andWhere('e.isArchived = true')
67 * Retrieves starred entries for a user.
70 * @param string $sortBy Field to sort
71 * @param string $direction Direction of the order
73 * @return QueryBuilder
75 public function getBuilderForStarredByUser($userId, $sortBy = 'starredAt', $direction = 'DESC')
78 ->getSortedQueryBuilderByUser($userId, $sortBy, $direction)
79 ->andWhere('e.isStarred = true')
84 * Retrieves entries filtered with a search term for a user.
88 * @param string $currentRoute
90 * @return QueryBuilder
92 public function getBuilderForSearchByUser($userId, $term, $currentRoute)
95 ->getSortedQueryBuilderByUser($userId);
97 if ('starred' === $currentRoute) {
98 $qb->andWhere('e.isStarred = true');
99 } elseif ('unread' === $currentRoute) {
100 $qb->andWhere('e.isArchived = false');
101 } elseif ('archive' === $currentRoute) {
102 $qb->andWhere('e.isArchived = true');
105 // We lower() all parts here because PostgreSQL 'LIKE' verb is case-sensitive
107 ->andWhere('lower(e.content) LIKE lower(:term) OR lower(e.title) LIKE lower(:term) OR lower(e.url) LIKE lower(:term)')->setParameter('term', '%' . $term . '%')
108 ->leftJoin('e.tags', 't')
115 * Retrieve a sorted list of untagged entries for a user.
119 * @return QueryBuilder
121 public function getBuilderForUntaggedByUser($userId)
123 return $this->sortQueryBuilder($this->getRawBuilderForUntaggedByUser($userId));
127 * Retrieve untagged entries for a user.
131 * @return QueryBuilder
133 public function getRawBuilderForUntaggedByUser($userId)
135 return $this->getQueryBuilderByUser($userId)
136 ->leftJoin('e.tags', 't')
137 ->andWhere('t.id is null');
141 * Retrieve the number of untagged entries for a user.
147 public function countUntaggedEntriesByUser($userId)
149 return (int) $this->getRawBuilderForUntaggedByUser($userId)
150 ->select('count(e.id)')
152 ->getSingleScalarResult();
159 * @param bool $isArchived
160 * @param bool $isStarred
161 * @param bool $isPublic
162 * @param string $sort
163 * @param string $order
165 * @param string $tags
166 * @param string $detail 'metadata' or 'full'. Include content field if 'full'
168 * @todo Breaking change: replace default detail=full by detail=metadata in a future version
172 public function findEntries($userId, $isArchived = null, $isStarred = null, $isPublic = null, $sort = 'created', $order = 'asc', $since = 0, $tags = '', $detail = 'full')
174 if (!\
in_array(strtolower($detail), ['full', 'metadata'], true)) {
175 throw new \
Exception('Detail "' . $detail . '" parameter is wrong, allowed: full or metadata');
178 $qb = $this->createQueryBuilder('e')
179 ->leftJoin('e.tags', 't')
180 ->where('e.user = :userId')->setParameter('userId', $userId);
182 if ('metadata' === $detail) {
183 $fieldNames = $this->getClassMetadata()->getFieldNames();
184 $fields = array_filter($fieldNames, function ($k) {
185 return 'content' !== $k;
187 $qb->select(sprintf('partial e.{%s}', implode(',', $fields)));
190 if (null !== $isArchived) {
191 $qb->andWhere('e.isArchived = :isArchived')->setParameter('isArchived', (bool) $isArchived);
194 if (null !== $isStarred) {
195 $qb->andWhere('e.isStarred = :isStarred')->setParameter('isStarred', (bool) $isStarred);
198 if (null !== $isPublic) {
199 $qb->andWhere('e.uid IS ' . (true === $isPublic ? 'NOT' : '') . ' NULL');
203 $qb->andWhere('e.updatedAt > :since')->setParameter('since', new \
DateTime(date('Y-m-d H:i:s', $since)));
206 if (\
is_string($tags) && '' !== $tags) {
207 foreach (explode(',', $tags) as $i => $tag) {
208 $entryAlias = 'e' . $i;
209 $tagAlias = 't' . $i;
211 // Complexe queries to ensure multiple tags are associated to an entry
212 // https://stackoverflow.com/a/6638146/569101
213 $qb->andWhere($qb->expr()->in(
215 $this->createQueryBuilder($entryAlias)
216 ->select($entryAlias . '.id')
217 ->leftJoin($entryAlias . '.tags', $tagAlias)
218 ->where($tagAlias . '.label = :label' . $i)
222 // bound parameter to the main query builder
223 $qb->setParameter('label' . $i, $tag);
227 if (!\
in_array(strtolower($order), ['asc', 'desc'], true)) {
228 throw new \
Exception('Order "' . $order . '" parameter is wrong, allowed: asc or desc');
231 if ('created' === $sort) {
232 $qb->orderBy('e.id', $order);
233 } elseif ('updated' === $sort) {
234 $qb->orderBy('e.updatedAt', $order);
235 } elseif ('archived' === $sort) {
236 $qb->orderBy('e.archivedAt', $order);
239 $pagerAdapter = new DoctrineORMAdapter($qb, true, false);
241 return new Pagerfanta($pagerAdapter);
245 * Fetch an entry with a tag. Only used for tests.
251 public function findOneWithTags($userId)
253 $qb = $this->createQueryBuilder('e')
254 ->innerJoin('e.tags', 't')
255 ->innerJoin('e.user', 'u')
256 ->addSelect('t', 'u')
257 ->where('e.user = :userId')->setParameter('userId', $userId)
260 return $qb->getQuery()->getResult();
264 * Find distinct language for a given user.
265 * Used to build the filter language list.
267 * @param int $userId User id
271 public function findDistinctLanguageByUser($userId)
273 $results = $this->createQueryBuilder('e')
274 ->select('e.language')
275 ->where('e.user = :userId')->setParameter('userId', $userId)
276 ->andWhere('e.language IS NOT NULL')
277 ->groupBy('e.language')
278 ->orderBy('e.language', ' ASC')
283 foreach ($results as $result) {
284 $languages[$result['language']] = $result['language'];
291 * Used only in test case to get the right entry associated to the right user.
293 * @param string $username
297 public function findOneByUsernameAndNotArchived($username)
299 return $this->createQueryBuilder('e')
300 ->leftJoin('e.user', 'u')
301 ->where('u.username = :username')->setParameter('username', $username)
302 ->andWhere('e.isArchived = false')
309 * Remove a tag from all user entries.
311 * 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.
312 * 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:
314 * 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
318 public function removeTag($userId, Tag
$tag)
320 $entries = $this->getSortedQueryBuilderByUser($userId)
321 ->innerJoin('e.tags', 't')
322 ->andWhere('t.id = :tagId')->setParameter('tagId', $tag->getId())
326 foreach ($entries as $entry) {
327 $entry->removeTag($tag);
330 $this->getEntityManager()->flush();
334 * Remove tags from all user entries.
337 * @param Array<Tag> $tags
339 public function removeTags($userId, $tags)
341 foreach ($tags as $tag) {
342 $this->removeTag($userId, $tag);
347 * Find all entries that are attached to a give tag id.
354 public function findAllByTagId($userId, $tagId)
356 return $this->getSortedQueryBuilderByUser($userId)
357 ->innerJoin('e.tags', 't')
358 ->andWhere('t.id = :tagId')->setParameter('tagId', $tagId)
364 * Find an entry by its url and its owner.
365 * If it exists, return the entry otherwise return false.
370 * @return Entry|false
372 public function findByUrlAndUserId($url, $userId)
374 return $this->findByHashedUrlAndUserId(
375 UrlHasher
::hashUrl($url),
381 * Find an entry by its hashed url and its owner.
382 * If it exists, return the entry otherwise return false.
384 * @param string $hashedUrl Url hashed using sha1
387 * @return Entry|false
389 public function findByHashedUrlAndUserId($hashedUrl, $userId)
391 // try first using hashed_url (to use the database index)
392 $res = $this->createQueryBuilder('e')
393 ->where('e.hashedUrl = :hashed_url')->setParameter('hashed_url', $hashedUrl)
394 ->andWhere('e.user = :user_id')->setParameter('user_id', $userId)
399 return current($res);
402 // then try using hashed_given_url (to use the database index)
403 $res = $this->createQueryBuilder('e')
404 ->where('e.hashedGivenUrl = :hashed_given_url')->setParameter('hashed_given_url', $hashedUrl)
405 ->andWhere('e.user = :user_id')->setParameter('user_id', $userId)
410 return current($res);
417 * Count all entries for a user.
423 public function countAllEntriesByUser($userId)
425 $qb = $this->createQueryBuilder('e')
427 ->where('e.user = :userId')->setParameter('userId', $userId)
430 return (int) $qb->getQuery()->getSingleScalarResult();
434 * Remove all entries for a user id.
435 * Used when a user want to reset all informations.
439 public function removeAllByUserId($userId)
441 $this->getEntityManager()
442 ->createQuery('DELETE FROM Wallabag\CoreBundle\Entity\Entry e WHERE e.user = :userId')
443 ->setParameter('userId', $userId)
447 public function removeArchivedByUserId($userId)
449 $this->getEntityManager()
450 ->createQuery('DELETE FROM Wallabag\CoreBundle\Entity\Entry e WHERE e.user = :userId AND e.isArchived = TRUE')
451 ->setParameter('userId', $userId)
456 * Get id and url from all entries
457 * Used for the clean-duplicates command.
459 public function findAllEntriesIdAndUrlByUserId($userId)
461 $qb = $this->createQueryBuilder('e')
462 ->select('e.id, e.url')
463 ->where('e.user = :userid')->setParameter(':userid', $userId);
465 return $qb->getQuery()->getArrayResult();
473 public function findAllEntriesIdByUserId($userId = null)
475 $qb = $this->createQueryBuilder('e')
478 if (null !== $userId) {
479 $qb->where('e.user = :userid')->setParameter(':userid', $userId);
482 return $qb->getQuery()->getArrayResult();
486 * Find all entries by url and owner.
493 public function findAllByUrlAndUserId($url, $userId)
495 return $this->createQueryBuilder('e')
496 ->where('e.url = :url')->setParameter('url', urldecode($url))
497 ->andWhere('e.user = :user_id')->setParameter('user_id', $userId)
503 * Returns a random entry, filtering by status.
506 * @param string $type Can be unread, archive, starred, etc
508 * @throws NoResultException
512 public function getRandomEntry($userId, $type = '')
514 $qb = $this->getQueryBuilderByUser($userId)
519 $qb->andWhere('e.isArchived = false');
522 $qb->andWhere('e.isArchived = true');
525 $qb->andWhere('e.isStarred = true');
528 $qb->leftJoin('e.tags', 't');
529 $qb->andWhere('t.id is null');
533 $ids = $qb->getQuery()->getArrayResult();
536 throw new NoResultException();
539 // random select one in the list
540 $randomId = $ids[mt_rand(0, \
count($ids) - 1)]['id'];
542 return $this->find($randomId);
546 * Return a query builder to be used by other getBuilderFor* method.
550 * @return QueryBuilder
552 private function getQueryBuilderByUser($userId)
554 return $this->createQueryBuilder('e')
555 ->andWhere('e.user = :userId')->setParameter('userId', $userId);
559 * Return a sorted query builder to be used by other getBuilderFor* method.
562 * @param string $sortBy
563 * @param string $direction
565 * @return QueryBuilder
567 private function getSortedQueryBuilderByUser($userId, $sortBy = 'createdAt', $direction = 'desc')
569 return $this->sortQueryBuilder($this->getQueryBuilderByUser($userId), $sortBy, $direction);
573 * Return the given QueryBuilder with an orderBy() call.
575 * @param string $sortBy
576 * @param string $direction
578 * @return QueryBuilder
580 private function sortQueryBuilder(QueryBuilder
$qb, $sortBy = 'createdAt', $direction = 'desc')
582 return $qb->orderBy(sprintf('e.%s', $sortBy), $direction);