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');
133 * Retrieve the number of untagged entries for a user.
139 public function countUntaggedEntriesByUser($userId)
141 return (int) $this->getRawBuilderForUntaggedByUser($userId)
142 ->select('count(e.id)')
144 ->getSingleScalarResult();
151 * @param bool $isArchived
152 * @param bool $isStarred
153 * @param bool $isPublic
154 * @param string $sort
155 * @param string $order
157 * @param string $tags
158 * @param string $detail 'metadata' or 'full'. Include content field if 'full'
160 * @todo Breaking change: replace default detail=full by detail=metadata in a future version
164 public function findEntries($userId, $isArchived = null, $isStarred = null, $isPublic = null, $sort = 'created', $order = 'asc', $since = 0, $tags = '', $detail = 'full')
166 if (!\
in_array(strtolower($detail), ['full', 'metadata'], true)) {
167 throw new \
Exception('Detail "' . $detail . '" parameter is wrong, allowed: full or metadata');
170 $qb = $this->createQueryBuilder('e')
171 ->leftJoin('e.tags', 't')
172 ->where('e.user = :userId')->setParameter('userId', $userId);
174 if ('metadata' === $detail) {
175 $fieldNames = $this->getClassMetadata()->getFieldNames();
176 $fields = array_filter($fieldNames, function ($k) {
177 return 'content' !== $k;
179 $qb->select(sprintf('partial e.{%s}', implode(',', $fields)));
182 if (null !== $isArchived) {
183 $qb->andWhere('e.isArchived = :isArchived')->setParameter('isArchived', (bool) $isArchived);
186 if (null !== $isStarred) {
187 $qb->andWhere('e.isStarred = :isStarred')->setParameter('isStarred', (bool) $isStarred);
190 if (null !== $isPublic) {
191 $qb->andWhere('e.uid IS ' . (true === $isPublic ? 'NOT' : '') . ' NULL');
195 $qb->andWhere('e.updatedAt > :since')->setParameter('since', new \
DateTime(date('Y-m-d H:i:s', $since)));
198 if (\
is_string($tags) && '' !== $tags) {
199 foreach (explode(',', $tags) as $i => $tag) {
200 $entryAlias = 'e' . $i;
201 $tagAlias = 't' . $i;
203 // Complexe queries to ensure multiple tags are associated to an entry
204 // https://stackoverflow.com/a/6638146/569101
205 $qb->andWhere($qb->expr()->in(
207 $this->createQueryBuilder($entryAlias)
208 ->select($entryAlias . '.id')
209 ->leftJoin($entryAlias . '.tags', $tagAlias)
210 ->where($tagAlias . '.label = :label' . $i)
214 // bound parameter to the main query builder
215 $qb->setParameter('label' . $i, $tag);
219 if (!\
in_array(strtolower($order), ['asc', 'desc'], true)) {
220 throw new \
Exception('Order "' . $order . '" parameter is wrong, allowed: asc or desc');
223 if ('created' === $sort) {
224 $qb->orderBy('e.id', $order);
225 } elseif ('updated' === $sort) {
226 $qb->orderBy('e.updatedAt', $order);
227 } elseif ('archived' === $sort) {
228 $qb->orderBy('e.archivedAt', $order);
231 $pagerAdapter = new DoctrineORMAdapter($qb, true, false);
233 return new Pagerfanta($pagerAdapter);
237 * Fetch an entry with a tag. Only used for tests.
243 public function findOneWithTags($userId)
245 $qb = $this->createQueryBuilder('e')
246 ->innerJoin('e.tags', 't')
247 ->innerJoin('e.user', 'u')
248 ->addSelect('t', 'u')
249 ->where('e.user = :userId')->setParameter('userId', $userId)
252 return $qb->getQuery()->getResult();
256 * Find distinct language for a given user.
257 * Used to build the filter language list.
259 * @param int $userId User id
263 public function findDistinctLanguageByUser($userId)
265 $results = $this->createQueryBuilder('e')
266 ->select('e.language')
267 ->where('e.user = :userId')->setParameter('userId', $userId)
268 ->andWhere('e.language IS NOT NULL')
269 ->groupBy('e.language')
270 ->orderBy('e.language', ' ASC')
275 foreach ($results as $result) {
276 $languages[$result['language']] = $result['language'];
283 * Used only in test case to get the right entry associated to the right user.
285 * @param string $username
289 public function findOneByUsernameAndNotArchived($username)
291 return $this->createQueryBuilder('e')
292 ->leftJoin('e.user', 'u')
293 ->where('u.username = :username')->setParameter('username', $username)
294 ->andWhere('e.isArchived = false')
301 * Remove a tag from all user entries.
303 * 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.
304 * 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:
306 * 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
311 public function removeTag($userId, Tag
$tag)
313 $entries = $this->getSortedQueryBuilderByUser($userId)
314 ->innerJoin('e.tags', 't')
315 ->andWhere('t.id = :tagId')->setParameter('tagId', $tag->getId())
319 foreach ($entries as $entry) {
320 $entry->removeTag($tag);
323 $this->getEntityManager()->flush();
327 * Remove tags from all user entries.
330 * @param Array<Tag> $tags
332 public function removeTags($userId, $tags)
334 foreach ($tags as $tag) {
335 $this->removeTag($userId, $tag);
340 * Find all entries that are attached to a give tag id.
347 public function findAllByTagId($userId, $tagId)
349 return $this->getSortedQueryBuilderByUser($userId)
350 ->innerJoin('e.tags', 't')
351 ->andWhere('t.id = :tagId')->setParameter('tagId', $tagId)
357 * Find an entry by its url and its owner.
358 * If it exists, return the entry otherwise return false.
363 * @return Entry|false
365 public function findByUrlAndUserId($url, $userId)
367 return $this->findByHashedUrlAndUserId(
368 UrlHasher
::hashUrl($url),
374 * Find an entry by its hashed url and its owner.
375 * If it exists, return the entry otherwise return false.
377 * @param string $hashedUrl Url hashed using sha1
380 * @return Entry|false
382 public function findByHashedUrlAndUserId($hashedUrl, $userId)
384 // try first using hashed_url (to use the database index)
385 $res = $this->createQueryBuilder('e')
386 ->where('e.hashedUrl = :hashed_url')->setParameter('hashed_url', $hashedUrl)
387 ->andWhere('e.user = :user_id')->setParameter('user_id', $userId)
392 return current($res);
395 // then try using hashed_given_url (to use the database index)
396 $res = $this->createQueryBuilder('e')
397 ->where('e.hashedGivenUrl = :hashed_given_url')->setParameter('hashed_given_url', $hashedUrl)
398 ->andWhere('e.user = :user_id')->setParameter('user_id', $userId)
403 return current($res);
410 * Count all entries for a user.
416 public function countAllEntriesByUser($userId)
418 $qb = $this->createQueryBuilder('e')
420 ->where('e.user = :userId')->setParameter('userId', $userId)
423 return (int) $qb->getQuery()->getSingleScalarResult();
427 * Remove all entries for a user id.
428 * Used when a user want to reset all informations.
432 public function removeAllByUserId($userId)
434 $this->getEntityManager()
435 ->createQuery('DELETE FROM Wallabag\CoreBundle\Entity\Entry e WHERE e.user = :userId')
436 ->setParameter('userId', $userId)
440 public function removeArchivedByUserId($userId)
442 $this->getEntityManager()
443 ->createQuery('DELETE FROM Wallabag\CoreBundle\Entity\Entry e WHERE e.user = :userId AND e.isArchived = TRUE')
444 ->setParameter('userId', $userId)
449 * Get id and url from all entries
450 * Used for the clean-duplicates command.
452 public function findAllEntriesIdAndUrlByUserId($userId)
454 $qb = $this->createQueryBuilder('e')
455 ->select('e.id, e.url')
456 ->where('e.user = :userid')->setParameter(':userid', $userId);
458 return $qb->getQuery()->getArrayResult();
466 public function findAllEntriesIdByUserId($userId = null)
468 $qb = $this->createQueryBuilder('e')
471 if (null !== $userId) {
472 $qb->where('e.user = :userid')->setParameter(':userid', $userId);
475 return $qb->getQuery()->getArrayResult();
479 * Find all entries by url and owner.
486 public function findAllByUrlAndUserId($url, $userId)
488 return $this->createQueryBuilder('e')
489 ->where('e.url = :url')->setParameter('url', urldecode($url))
490 ->andWhere('e.user = :user_id')->setParameter('user_id', $userId)
496 * Returns a random entry, filtering by status.
499 * @param string $type Can be unread, archive, starred, etc
501 * @throws NoResultException
505 public function getRandomEntry($userId, $type = '')
507 $qb = $this->getQueryBuilderByUser($userId)
512 $qb->andWhere('e.isArchived = false');
515 $qb->andWhere('e.isArchived = true');
518 $qb->andWhere('e.isStarred = true');
521 $qb->leftJoin('e.tags', 't');
522 $qb->andWhere('t.id is null');
526 $ids = $qb->getQuery()->getArrayResult();
529 throw new NoResultException();
532 // random select one in the list
533 $randomId = $ids[mt_rand(0, \
count($ids) - 1)]['id'];
535 return $this->find($randomId);
539 * Return a query builder to be used by other getBuilderFor* method.
543 * @return QueryBuilder
545 private function getQueryBuilderByUser($userId)
547 return $this->createQueryBuilder('e')
548 ->andWhere('e.user = :userId')->setParameter('userId', $userId);
552 * Return a sorted query builder to be used by other getBuilderFor* method.
555 * @param string $sortBy
556 * @param string $direction
558 * @return QueryBuilder
560 private function getSortedQueryBuilderByUser($userId, $sortBy = 'createdAt', $direction = 'desc')
562 return $this->sortQueryBuilder($this->getQueryBuilderByUser($userId), $sortBy, $direction);
566 * Return the given QueryBuilder with an orderBy() call.
568 * @param QueryBuilder $qb
569 * @param string $sortBy
570 * @param string $direction
572 * @return QueryBuilder
574 private function sortQueryBuilder(QueryBuilder
$qb, $sortBy = 'createdAt', $direction = 'desc')
576 return $qb->orderBy(sprintf('e.%s', $sortBy), $direction);