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
;
13 class EntryRepository
extends EntityRepository
16 * Retrieves all entries for a user.
20 * @return QueryBuilder
22 public function getBuilderForAllByUser($userId)
25 ->getSortedQueryBuilderByUser($userId)
30 * Retrieves unread entries for a user.
34 * @return QueryBuilder
36 public function getBuilderForUnreadByUser($userId)
39 ->getSortedQueryBuilderByUser($userId)
40 ->andWhere('e.isArchived = false')
45 * Retrieves read entries for a user.
49 * @return QueryBuilder
51 public function getBuilderForArchiveByUser($userId)
54 ->getSortedQueryBuilderByUser($userId, 'archivedAt', 'desc')
55 ->andWhere('e.isArchived = true')
60 * Retrieves starred entries for a user.
64 * @return QueryBuilder
66 public function getBuilderForStarredByUser($userId)
69 ->getSortedQueryBuilderByUser($userId, 'starredAt', 'desc')
70 ->andWhere('e.isStarred = true')
75 * Retrieves entries filtered with a search term for a user.
79 * @param string $currentRoute
81 * @return QueryBuilder
83 public function getBuilderForSearchByUser($userId, $term, $currentRoute)
86 ->getSortedQueryBuilderByUser($userId);
88 if ('starred' === $currentRoute) {
89 $qb->andWhere('e.isStarred = true');
90 } elseif ('unread' === $currentRoute) {
91 $qb->andWhere('e.isArchived = false');
92 } elseif ('archive' === $currentRoute) {
93 $qb->andWhere('e.isArchived = true');
96 // We lower() all parts here because PostgreSQL 'LIKE' verb is case-sensitive
98 ->andWhere('lower(e.content) LIKE lower(:term) OR lower(e.title) LIKE lower(:term) OR lower(e.url) LIKE lower(:term)')->setParameter('term', '%' . $term . '%')
99 ->leftJoin('e.tags', 't')
106 * Retrieve a sorted list of untagged entries for a user.
110 * @return QueryBuilder
112 public function getBuilderForUntaggedByUser($userId)
114 return $this->sortQueryBuilder($this->getRawBuilderForUntaggedByUser($userId));
118 * Retrieve untagged entries for a user.
122 * @return QueryBuilder
124 public function getRawBuilderForUntaggedByUser($userId)
126 return $this->getQueryBuilderByUser($userId)
127 ->leftJoin('e.tags', 't')
128 ->andWhere('t.id is null');
135 * @param bool $isArchived
136 * @param bool $isStarred
137 * @param bool $isPublic
138 * @param string $sort
139 * @param string $order
141 * @param string $tags
142 * @param string $detail 'metadata' or 'full'. Include content field if 'full'
144 * @todo Breaking change: replace default detail=full by detail=metadata in a future version
148 public function findEntries($userId, $isArchived = null, $isStarred = null, $isPublic = null, $sort = 'created', $order = 'asc', $since = 0, $tags = '', $detail = 'full')
150 if (!\
in_array(strtolower($detail), ['full', 'metadata'], true)) {
151 throw new \
Exception('Detail "' . $detail . '" parameter is wrong, allowed: full or metadata');
154 $qb = $this->createQueryBuilder('e')
155 ->leftJoin('e.tags', 't')
156 ->where('e.user = :userId')->setParameter('userId', $userId);
158 if ('metadata' === $detail) {
159 $fieldNames = $this->getClassMetadata()->getFieldNames();
160 $fields = array_filter($fieldNames, function ($k) {
161 return 'content' !== $k;
163 $qb->select(sprintf('partial e.{%s}', implode(',', $fields)));
166 if (null !== $isArchived) {
167 $qb->andWhere('e.isArchived = :isArchived')->setParameter('isArchived', (bool) $isArchived);
170 if (null !== $isStarred) {
171 $qb->andWhere('e.isStarred = :isStarred')->setParameter('isStarred', (bool) $isStarred);
174 if (null !== $isPublic) {
175 $qb->andWhere('e.uid IS ' . (true === $isPublic ? 'NOT' : '') . ' NULL');
179 $qb->andWhere('e.updatedAt > :since')->setParameter('since', new \
DateTime(date('Y-m-d H:i:s', $since)));
182 if (\
is_string($tags) && '' !== $tags) {
183 foreach (explode(',', $tags) as $i => $tag) {
184 $entryAlias = 'e' . $i;
185 $tagAlias = 't' . $i;
187 // Complexe queries to ensure multiple tags are associated to an entry
188 // https://stackoverflow.com/a/6638146/569101
189 $qb->andWhere($qb->expr()->in(
191 $this->createQueryBuilder($entryAlias)
192 ->select($entryAlias . '.id')
193 ->leftJoin($entryAlias . '.tags', $tagAlias)
194 ->where($tagAlias . '.label = :label' . $i)
198 // bound parameter to the main query builder
199 $qb->setParameter('label' . $i, $tag);
203 if (!\
in_array(strtolower($order), ['asc', 'desc'], true)) {
204 throw new \
Exception('Order "' . $order . '" parameter is wrong, allowed: asc or desc');
207 if ('created' === $sort) {
208 $qb->orderBy('e.id', $order);
209 } elseif ('updated' === $sort) {
210 $qb->orderBy('e.updatedAt', $order);
211 } elseif ('archived' === $sort) {
212 $qb->orderBy('e.archivedAt', $order);
215 $pagerAdapter = new DoctrineORMAdapter($qb, true, false);
217 return new Pagerfanta($pagerAdapter);
221 * Fetch an entry with a tag. Only used for tests.
227 public function findOneWithTags($userId)
229 $qb = $this->createQueryBuilder('e')
230 ->innerJoin('e.tags', 't')
231 ->innerJoin('e.user', 'u')
232 ->addSelect('t', 'u')
233 ->where('e.user = :userId')->setParameter('userId', $userId)
236 return $qb->getQuery()->getResult();
240 * Find distinct language for a given user.
241 * Used to build the filter language list.
243 * @param int $userId User id
247 public function findDistinctLanguageByUser($userId)
249 $results = $this->createQueryBuilder('e')
250 ->select('e.language')
251 ->where('e.user = :userId')->setParameter('userId', $userId)
252 ->andWhere('e.language IS NOT NULL')
253 ->groupBy('e.language')
254 ->orderBy('e.language', ' ASC')
259 foreach ($results as $result) {
260 $languages[$result['language']] = $result['language'];
267 * Used only in test case to get the right entry associated to the right user.
269 * @param string $username
273 public function findOneByUsernameAndNotArchived($username)
275 return $this->createQueryBuilder('e')
276 ->leftJoin('e.user', 'u')
277 ->where('u.username = :username')->setParameter('username', $username)
278 ->andWhere('e.isArchived = false')
285 * Remove a tag from all user entries.
287 * 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.
288 * 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 * 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
295 public function removeTag($userId, Tag
$tag)
297 $entries = $this->getSortedQueryBuilderByUser($userId)
298 ->innerJoin('e.tags', 't')
299 ->andWhere('t.id = :tagId')->setParameter('tagId', $tag->getId())
303 foreach ($entries as $entry) {
304 $entry->removeTag($tag);
307 $this->getEntityManager()->flush();
311 * Remove tags from all user entries.
314 * @param Array<Tag> $tags
316 public function removeTags($userId, $tags)
318 foreach ($tags as $tag) {
319 $this->removeTag($userId, $tag);
324 * Find all entries that are attached to a give tag id.
331 public function findAllByTagId($userId, $tagId)
333 return $this->getSortedQueryBuilderByUser($userId)
334 ->innerJoin('e.tags', 't')
335 ->andWhere('t.id = :tagId')->setParameter('tagId', $tagId)
341 * Find an entry by its url and its owner.
342 * If it exists, return the entry otherwise return false.
349 public function findByUrlAndUserId($url, $userId)
351 $res = $this->createQueryBuilder('e')
352 ->where('e.url = :url')->setParameter('url', urldecode($url))
353 ->andWhere('e.user = :user_id')->setParameter('user_id', $userId)
358 return current($res);
365 * Find an entry by its hashed url and its owner.
366 * If it exists, return the entry otherwise return false.
368 * @param string $hashedUrl Url hashed using sha1
373 public function findByHashedUrlAndUserId($hashedUrl, $userId)
375 $res = $this->createQueryBuilder('e')
376 ->where('e.hashedUrl = :hashed_url')->setParameter('hashed_url', $hashedUrl)
377 ->andWhere('e.user = :user_id')->setParameter('user_id', $userId)
382 return current($res);
389 * Count all entries for a user.
395 public function countAllEntriesByUser($userId)
397 $qb = $this->createQueryBuilder('e')
399 ->where('e.user = :userId')->setParameter('userId', $userId)
402 return (int) $qb->getQuery()->getSingleScalarResult();
406 * Remove all entries for a user id.
407 * Used when a user want to reset all informations.
411 public function removeAllByUserId($userId)
413 $this->getEntityManager()
414 ->createQuery('DELETE FROM Wallabag\CoreBundle\Entity\Entry e WHERE e.user = :userId')
415 ->setParameter('userId', $userId)
419 public function removeArchivedByUserId($userId)
421 $this->getEntityManager()
422 ->createQuery('DELETE FROM Wallabag\CoreBundle\Entity\Entry e WHERE e.user = :userId AND e.isArchived = TRUE')
423 ->setParameter('userId', $userId)
428 * Get id and url from all entries
429 * Used for the clean-duplicates command.
431 public function findAllEntriesIdAndUrlByUserId($userId)
433 $qb = $this->createQueryBuilder('e')
434 ->select('e.id, e.url')
435 ->where('e.user = :userid')->setParameter(':userid', $userId);
437 return $qb->getQuery()->getArrayResult();
445 public function findAllEntriesIdByUserId($userId = null)
447 $qb = $this->createQueryBuilder('e')
450 if (null !== $userId) {
451 $qb->where('e.user = :userid')->setParameter(':userid', $userId);
454 return $qb->getQuery()->getArrayResult();
458 * Find all entries by url and owner.
465 public function findAllByUrlAndUserId($url, $userId)
467 return $this->createQueryBuilder('e')
468 ->where('e.url = :url')->setParameter('url', urldecode($url))
469 ->andWhere('e.user = :user_id')->setParameter('user_id', $userId)
475 * Returns a random entry, filtering by status.
478 * @param string $type Can be unread, archive, starred, etc
480 * @throws NoResultException
484 public function getRandomEntry($userId, $type = '')
486 $qb = $this->getQueryBuilderByUser($userId)
491 $qb->andWhere('e.isArchived = false');
494 $qb->andWhere('e.isArchived = true');
497 $qb->andWhere('e.isStarred = true');
500 $qb->leftJoin('e.tags', 't');
501 $qb->andWhere('t.id is null');
505 $ids = $qb->getQuery()->getArrayResult();
508 throw new NoResultException();
511 // random select one in the list
512 $randomId = $ids[mt_rand(0, \
count($ids) - 1)]['id'];
514 return $this->find($randomId);
518 * Return a query builder to be used by other getBuilderFor* method.
522 * @return QueryBuilder
524 private function getQueryBuilderByUser($userId)
526 return $this->createQueryBuilder('e')
527 ->andWhere('e.user = :userId')->setParameter('userId', $userId);
531 * Return a sorted query builder to be used by other getBuilderFor* method.
534 * @param string $sortBy
535 * @param string $direction
537 * @return QueryBuilder
539 private function getSortedQueryBuilderByUser($userId, $sortBy = 'createdAt', $direction = 'desc')
541 return $this->sortQueryBuilder($this->getQueryBuilderByUser($userId), $sortBy, $direction);
545 * Return the given QueryBuilder with an orderBy() call.
547 * @param QueryBuilder $qb
548 * @param string $sortBy
549 * @param string $direction
551 * @return QueryBuilder
553 private function sortQueryBuilder(QueryBuilder
$qb, $sortBy = 'createdAt', $direction = 'desc')
555 return $qb->orderBy(sprintf('e.%s', $sortBy), $direction);