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, $sortBy = 'id', $direction = 'DESC')
26 ->getSortedQueryBuilderByUser($userId, $sortBy, $direction)
31 * Retrieves unread entries for a user.
35 * @return QueryBuilder
37 public function getBuilderForUnreadByUser($userId, $sortBy = 'id', $direction = 'DESC')
40 ->getSortedQueryBuilderByUser($userId)
41 ->andWhere('e.isArchived = false')
42 ->orderBy('e.'.$sortBy, $direction)
47 * Retrieves read entries for a user.
51 * @return QueryBuilder
53 public function getBuilderForArchiveByUser($userId, $sortBy = 'id', $direction = 'DESC')
56 ->getSortedQueryBuilderByUser($userId, 'archivedAt', 'desc')
57 ->andWhere('e.isArchived = true')
58 ->orderBy('e.'.$sortBy, $direction)
63 * Retrieves starred entries for a user.
67 * @return QueryBuilder
69 public function getBuilderForStarredByUser($userId, $sortBy = 'id', $direction = 'DESC')
72 ->getSortedQueryBuilderByUser($userId, 'starredAt', 'desc')
73 ->andWhere('e.isStarred = true')
74 ->orderBy('e.'.$sortBy, $direction)
79 * Retrieves entries filtered with a search term for a user.
83 * @param string $currentRoute
85 * @return QueryBuilder
87 public function getBuilderForSearchByUser($userId, $term, $currentRoute)
90 ->getSortedQueryBuilderByUser($userId);
92 if ('starred' === $currentRoute) {
93 $qb->andWhere('e.isStarred = true');
94 } elseif ('unread' === $currentRoute) {
95 $qb->andWhere('e.isArchived = false');
96 } elseif ('archive' === $currentRoute) {
97 $qb->andWhere('e.isArchived = true');
100 // We lower() all parts here because PostgreSQL 'LIKE' verb is case-sensitive
102 ->andWhere('lower(e.content) LIKE lower(:term) OR lower(e.title) LIKE lower(:term) OR lower(e.url) LIKE lower(:term)')->setParameter('term', '%' . $term . '%')
103 ->leftJoin('e.tags', 't')
110 * Retrieve a sorted list of untagged entries for a user.
114 * @return QueryBuilder
116 public function getBuilderForUntaggedByUser($userId)
118 return $this->sortQueryBuilder($this->getRawBuilderForUntaggedByUser($userId));
122 * Retrieve untagged entries for a user.
126 * @return QueryBuilder
128 public function getRawBuilderForUntaggedByUser($userId)
130 return $this->getQueryBuilderByUser($userId)
131 ->leftJoin('e.tags', 't')
132 ->andWhere('t.id is null');
136 * Retrieve the number of untagged entries for a user.
142 public function countUntaggedEntriesByUser($userId)
144 return (int) $this->getRawBuilderForUntaggedByUser($userId)
145 ->select('count(e.id)')
147 ->getSingleScalarResult();
154 * @param bool $isArchived
155 * @param bool $isStarred
156 * @param bool $isPublic
157 * @param string $sort
158 * @param string $order
160 * @param string $tags
161 * @param string $detail 'metadata' or 'full'. Include content field if 'full'
163 * @todo Breaking change: replace default detail=full by detail=metadata in a future version
167 public function findEntries($userId, $isArchived = null, $isStarred = null, $isPublic = null, $sort = 'created', $order = 'asc', $since = 0, $tags = '', $detail = 'full')
169 if (!\
in_array(strtolower($detail), ['full', 'metadata'], true)) {
170 throw new \
Exception('Detail "' . $detail . '" parameter is wrong, allowed: full or metadata');
173 $qb = $this->createQueryBuilder('e')
174 ->leftJoin('e.tags', 't')
175 ->where('e.user = :userId')->setParameter('userId', $userId);
177 if ('metadata' === $detail) {
178 $fieldNames = $this->getClassMetadata()->getFieldNames();
179 $fields = array_filter($fieldNames, function ($k) {
180 return 'content' !== $k;
182 $qb->select(sprintf('partial e.{%s}', implode(',', $fields)));
185 if (null !== $isArchived) {
186 $qb->andWhere('e.isArchived = :isArchived')->setParameter('isArchived', (bool) $isArchived);
189 if (null !== $isStarred) {
190 $qb->andWhere('e.isStarred = :isStarred')->setParameter('isStarred', (bool) $isStarred);
193 if (null !== $isPublic) {
194 $qb->andWhere('e.uid IS ' . (true === $isPublic ? 'NOT' : '') . ' NULL');
198 $qb->andWhere('e.updatedAt > :since')->setParameter('since', new \
DateTime(date('Y-m-d H:i:s', $since)));
201 if (\
is_string($tags) && '' !== $tags) {
202 foreach (explode(',', $tags) as $i => $tag) {
203 $entryAlias = 'e' . $i;
204 $tagAlias = 't' . $i;
206 // Complexe queries to ensure multiple tags are associated to an entry
207 // https://stackoverflow.com/a/6638146/569101
208 $qb->andWhere($qb->expr()->in(
210 $this->createQueryBuilder($entryAlias)
211 ->select($entryAlias . '.id')
212 ->leftJoin($entryAlias . '.tags', $tagAlias)
213 ->where($tagAlias . '.label = :label' . $i)
217 // bound parameter to the main query builder
218 $qb->setParameter('label' . $i, $tag);
222 if (!\
in_array(strtolower($order), ['asc', 'desc'], true)) {
223 throw new \
Exception('Order "' . $order . '" parameter is wrong, allowed: asc or desc');
226 if ('created' === $sort) {
227 $qb->orderBy('e.id', $order);
228 } elseif ('updated' === $sort) {
229 $qb->orderBy('e.updatedAt', $order);
230 } elseif ('archived' === $sort) {
231 $qb->orderBy('e.archivedAt', $order);
234 $pagerAdapter = new DoctrineORMAdapter($qb, true, false);
236 return new Pagerfanta($pagerAdapter);
240 * Fetch an entry with a tag. Only used for tests.
246 public function findOneWithTags($userId)
248 $qb = $this->createQueryBuilder('e')
249 ->innerJoin('e.tags', 't')
250 ->innerJoin('e.user', 'u')
251 ->addSelect('t', 'u')
252 ->where('e.user = :userId')->setParameter('userId', $userId)
255 return $qb->getQuery()->getResult();
259 * Find distinct language for a given user.
260 * Used to build the filter language list.
262 * @param int $userId User id
266 public function findDistinctLanguageByUser($userId)
268 $results = $this->createQueryBuilder('e')
269 ->select('e.language')
270 ->where('e.user = :userId')->setParameter('userId', $userId)
271 ->andWhere('e.language IS NOT NULL')
272 ->groupBy('e.language')
273 ->orderBy('e.language', ' ASC')
278 foreach ($results as $result) {
279 $languages[$result['language']] = $result['language'];
286 * Used only in test case to get the right entry associated to the right user.
288 * @param string $username
292 public function findOneByUsernameAndNotArchived($username)
294 return $this->createQueryBuilder('e')
295 ->leftJoin('e.user', 'u')
296 ->where('u.username = :username')->setParameter('username', $username)
297 ->andWhere('e.isArchived = false')
304 * Remove a tag from all user entries.
306 * 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.
307 * 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:
309 * 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
313 public function removeTag($userId, Tag
$tag)
315 $entries = $this->getSortedQueryBuilderByUser($userId)
316 ->innerJoin('e.tags', 't')
317 ->andWhere('t.id = :tagId')->setParameter('tagId', $tag->getId())
321 foreach ($entries as $entry) {
322 $entry->removeTag($tag);
325 $this->getEntityManager()->flush();
329 * Remove tags from all user entries.
332 * @param Array<Tag> $tags
334 public function removeTags($userId, $tags)
336 foreach ($tags as $tag) {
337 $this->removeTag($userId, $tag);
342 * Find all entries that are attached to a give tag id.
349 public function findAllByTagId($userId, $tagId)
351 return $this->getSortedQueryBuilderByUser($userId)
352 ->innerJoin('e.tags', 't')
353 ->andWhere('t.id = :tagId')->setParameter('tagId', $tagId)
359 * Find an entry by its url and its owner.
360 * If it exists, return the entry otherwise return false.
365 * @return Entry|false
367 public function findByUrlAndUserId($url, $userId)
369 return $this->findByHashedUrlAndUserId(
370 UrlHasher
::hashUrl($url),
376 * Find an entry by its hashed url and its owner.
377 * If it exists, return the entry otherwise return false.
379 * @param string $hashedUrl Url hashed using sha1
382 * @return Entry|false
384 public function findByHashedUrlAndUserId($hashedUrl, $userId)
386 // try first using hashed_url (to use the database index)
387 $res = $this->createQueryBuilder('e')
388 ->where('e.hashedUrl = :hashed_url')->setParameter('hashed_url', $hashedUrl)
389 ->andWhere('e.user = :user_id')->setParameter('user_id', $userId)
394 return current($res);
397 // then try using hashed_given_url (to use the database index)
398 $res = $this->createQueryBuilder('e')
399 ->where('e.hashedGivenUrl = :hashed_given_url')->setParameter('hashed_given_url', $hashedUrl)
400 ->andWhere('e.user = :user_id')->setParameter('user_id', $userId)
405 return current($res);
412 * Count all entries for a user.
418 public function countAllEntriesByUser($userId)
420 $qb = $this->createQueryBuilder('e')
422 ->where('e.user = :userId')->setParameter('userId', $userId)
425 return (int) $qb->getQuery()->getSingleScalarResult();
429 * Remove all entries for a user id.
430 * Used when a user want to reset all informations.
434 public function removeAllByUserId($userId)
436 $this->getEntityManager()
437 ->createQuery('DELETE FROM Wallabag\CoreBundle\Entity\Entry e WHERE e.user = :userId')
438 ->setParameter('userId', $userId)
442 public function removeArchivedByUserId($userId)
444 $this->getEntityManager()
445 ->createQuery('DELETE FROM Wallabag\CoreBundle\Entity\Entry e WHERE e.user = :userId AND e.isArchived = TRUE')
446 ->setParameter('userId', $userId)
451 * Get id and url from all entries
452 * Used for the clean-duplicates command.
454 public function findAllEntriesIdAndUrlByUserId($userId)
456 $qb = $this->createQueryBuilder('e')
457 ->select('e.id, e.url')
458 ->where('e.user = :userid')->setParameter(':userid', $userId);
460 return $qb->getQuery()->getArrayResult();
468 public function findAllEntriesIdByUserId($userId = null)
470 $qb = $this->createQueryBuilder('e')
473 if (null !== $userId) {
474 $qb->where('e.user = :userid')->setParameter(':userid', $userId);
477 return $qb->getQuery()->getArrayResult();
481 * Find all entries by url and owner.
488 public function findAllByUrlAndUserId($url, $userId)
490 return $this->createQueryBuilder('e')
491 ->where('e.url = :url')->setParameter('url', urldecode($url))
492 ->andWhere('e.user = :user_id')->setParameter('user_id', $userId)
498 * Returns a random entry, filtering by status.
501 * @param string $type Can be unread, archive, starred, etc
503 * @throws NoResultException
507 public function getRandomEntry($userId, $type = '')
509 $qb = $this->getQueryBuilderByUser($userId)
514 $qb->andWhere('e.isArchived = false');
517 $qb->andWhere('e.isArchived = true');
520 $qb->andWhere('e.isStarred = true');
523 $qb->leftJoin('e.tags', 't');
524 $qb->andWhere('t.id is null');
528 $ids = $qb->getQuery()->getArrayResult();
531 throw new NoResultException();
534 // random select one in the list
535 $randomId = $ids[mt_rand(0, \
count($ids) - 1)]['id'];
537 return $this->find($randomId);
541 * Return a query builder to be used by other getBuilderFor* method.
545 * @return QueryBuilder
547 private function getQueryBuilderByUser($userId)
549 return $this->createQueryBuilder('e')
550 ->andWhere('e.user = :userId')->setParameter('userId', $userId);
554 * Return a sorted query builder to be used by other getBuilderFor* method.
557 * @param string $sortBy
558 * @param string $direction
560 * @return QueryBuilder
562 private function getSortedQueryBuilderByUser($userId, $sortBy = 'createdAt', $direction = 'desc')
564 return $this->sortQueryBuilder($this->getQueryBuilderByUser($userId), $sortBy, $direction);
568 * Return the given QueryBuilder with an orderBy() call.
570 * @param string $sortBy
571 * @param string $direction
573 * @return QueryBuilder
575 private function sortQueryBuilder(QueryBuilder
$qb, $sortBy = 'createdAt', $direction = 'desc')
577 return $qb->orderBy(sprintf('e.%s', $sortBy), $direction);