]> git.immae.eu Git - github/wallabag/wallabag.git/blob - src/Wallabag/CoreBundle/Repository/EntryRepository.php
Add Wallabag\CoreBundle\Helper\UrlHasher
[github/wallabag/wallabag.git] / src / Wallabag / CoreBundle / Repository / EntryRepository.php
1 <?php
2
3 namespace Wallabag\CoreBundle\Repository;
4
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;
13
14 class EntryRepository extends EntityRepository
15 {
16 /**
17 * Retrieves all entries for a user.
18 *
19 * @param int $userId
20 *
21 * @return QueryBuilder
22 */
23 public function getBuilderForAllByUser($userId)
24 {
25 return $this
26 ->getSortedQueryBuilderByUser($userId)
27 ;
28 }
29
30 /**
31 * Retrieves unread entries for a user.
32 *
33 * @param int $userId
34 *
35 * @return QueryBuilder
36 */
37 public function getBuilderForUnreadByUser($userId)
38 {
39 return $this
40 ->getSortedQueryBuilderByUser($userId)
41 ->andWhere('e.isArchived = false')
42 ;
43 }
44
45 /**
46 * Retrieves read entries for a user.
47 *
48 * @param int $userId
49 *
50 * @return QueryBuilder
51 */
52 public function getBuilderForArchiveByUser($userId)
53 {
54 return $this
55 ->getSortedQueryBuilderByUser($userId, 'archivedAt', 'desc')
56 ->andWhere('e.isArchived = true')
57 ;
58 }
59
60 /**
61 * Retrieves starred entries for a user.
62 *
63 * @param int $userId
64 *
65 * @return QueryBuilder
66 */
67 public function getBuilderForStarredByUser($userId)
68 {
69 return $this
70 ->getSortedQueryBuilderByUser($userId, 'starredAt', 'desc')
71 ->andWhere('e.isStarred = true')
72 ;
73 }
74
75 /**
76 * Retrieves entries filtered with a search term for a user.
77 *
78 * @param int $userId
79 * @param string $term
80 * @param string $currentRoute
81 *
82 * @return QueryBuilder
83 */
84 public function getBuilderForSearchByUser($userId, $term, $currentRoute)
85 {
86 $qb = $this
87 ->getSortedQueryBuilderByUser($userId);
88
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');
95 }
96
97 // We lower() all parts here because PostgreSQL 'LIKE' verb is case-sensitive
98 $qb
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')
101 ->groupBy('e.id');
102
103 return $qb;
104 }
105
106 /**
107 * Retrieve a sorted list of untagged entries for a user.
108 *
109 * @param int $userId
110 *
111 * @return QueryBuilder
112 */
113 public function getBuilderForUntaggedByUser($userId)
114 {
115 return $this->sortQueryBuilder($this->getRawBuilderForUntaggedByUser($userId));
116 }
117
118 /**
119 * Retrieve untagged entries for a user.
120 *
121 * @param int $userId
122 *
123 * @return QueryBuilder
124 */
125 public function getRawBuilderForUntaggedByUser($userId)
126 {
127 return $this->getQueryBuilderByUser($userId)
128 ->leftJoin('e.tags', 't')
129 ->andWhere('t.id is null');
130 }
131
132 /**
133 * Find Entries.
134 *
135 * @param int $userId
136 * @param bool $isArchived
137 * @param bool $isStarred
138 * @param bool $isPublic
139 * @param string $sort
140 * @param string $order
141 * @param int $since
142 * @param string $tags
143 * @param string $detail 'metadata' or 'full'. Include content field if 'full'
144 *
145 * @todo Breaking change: replace default detail=full by detail=metadata in a future version
146 *
147 * @return Pagerfanta
148 */
149 public function findEntries($userId, $isArchived = null, $isStarred = null, $isPublic = null, $sort = 'created', $order = 'asc', $since = 0, $tags = '', $detail = 'full')
150 {
151 if (!\in_array(strtolower($detail), ['full', 'metadata'], true)) {
152 throw new \Exception('Detail "' . $detail . '" parameter is wrong, allowed: full or metadata');
153 }
154
155 $qb = $this->createQueryBuilder('e')
156 ->leftJoin('e.tags', 't')
157 ->where('e.user = :userId')->setParameter('userId', $userId);
158
159 if ('metadata' === $detail) {
160 $fieldNames = $this->getClassMetadata()->getFieldNames();
161 $fields = array_filter($fieldNames, function ($k) {
162 return 'content' !== $k;
163 });
164 $qb->select(sprintf('partial e.{%s}', implode(',', $fields)));
165 }
166
167 if (null !== $isArchived) {
168 $qb->andWhere('e.isArchived = :isArchived')->setParameter('isArchived', (bool) $isArchived);
169 }
170
171 if (null !== $isStarred) {
172 $qb->andWhere('e.isStarred = :isStarred')->setParameter('isStarred', (bool) $isStarred);
173 }
174
175 if (null !== $isPublic) {
176 $qb->andWhere('e.uid IS ' . (true === $isPublic ? 'NOT' : '') . ' NULL');
177 }
178
179 if ($since > 0) {
180 $qb->andWhere('e.updatedAt > :since')->setParameter('since', new \DateTime(date('Y-m-d H:i:s', $since)));
181 }
182
183 if (\is_string($tags) && '' !== $tags) {
184 foreach (explode(',', $tags) as $i => $tag) {
185 $entryAlias = 'e' . $i;
186 $tagAlias = 't' . $i;
187
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(
191 'e.id',
192 $this->createQueryBuilder($entryAlias)
193 ->select($entryAlias . '.id')
194 ->leftJoin($entryAlias . '.tags', $tagAlias)
195 ->where($tagAlias . '.label = :label' . $i)
196 ->getDQL()
197 ));
198
199 // bound parameter to the main query builder
200 $qb->setParameter('label' . $i, $tag);
201 }
202 }
203
204 if (!\in_array(strtolower($order), ['asc', 'desc'], true)) {
205 throw new \Exception('Order "' . $order . '" parameter is wrong, allowed: asc or desc');
206 }
207
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);
214 }
215
216 $pagerAdapter = new DoctrineORMAdapter($qb, true, false);
217
218 return new Pagerfanta($pagerAdapter);
219 }
220
221 /**
222 * Fetch an entry with a tag. Only used for tests.
223 *
224 * @param int $userId
225 *
226 * @return array
227 */
228 public function findOneWithTags($userId)
229 {
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)
235 ;
236
237 return $qb->getQuery()->getResult();
238 }
239
240 /**
241 * Find distinct language for a given user.
242 * Used to build the filter language list.
243 *
244 * @param int $userId User id
245 *
246 * @return array
247 */
248 public function findDistinctLanguageByUser($userId)
249 {
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')
256 ->getQuery()
257 ->getResult();
258
259 $languages = [];
260 foreach ($results as $result) {
261 $languages[$result['language']] = $result['language'];
262 }
263
264 return $languages;
265 }
266
267 /**
268 * Used only in test case to get the right entry associated to the right user.
269 *
270 * @param string $username
271 *
272 * @return Entry
273 */
274 public function findOneByUsernameAndNotArchived($username)
275 {
276 return $this->createQueryBuilder('e')
277 ->leftJoin('e.user', 'u')
278 ->where('u.username = :username')->setParameter('username', $username)
279 ->andWhere('e.isArchived = false')
280 ->setMaxResults(1)
281 ->getQuery()
282 ->getSingleResult();
283 }
284
285 /**
286 * Remove a tag from all user entries.
287 *
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:
290 *
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
292 *
293 * @param int $userId
294 * @param Tag $tag
295 */
296 public function removeTag($userId, Tag $tag)
297 {
298 $entries = $this->getSortedQueryBuilderByUser($userId)
299 ->innerJoin('e.tags', 't')
300 ->andWhere('t.id = :tagId')->setParameter('tagId', $tag->getId())
301 ->getQuery()
302 ->getResult();
303
304 foreach ($entries as $entry) {
305 $entry->removeTag($tag);
306 }
307
308 $this->getEntityManager()->flush();
309 }
310
311 /**
312 * Remove tags from all user entries.
313 *
314 * @param int $userId
315 * @param Array<Tag> $tags
316 */
317 public function removeTags($userId, $tags)
318 {
319 foreach ($tags as $tag) {
320 $this->removeTag($userId, $tag);
321 }
322 }
323
324 /**
325 * Find all entries that are attached to a give tag id.
326 *
327 * @param int $userId
328 * @param int $tagId
329 *
330 * @return array
331 */
332 public function findAllByTagId($userId, $tagId)
333 {
334 return $this->getSortedQueryBuilderByUser($userId)
335 ->innerJoin('e.tags', 't')
336 ->andWhere('t.id = :tagId')->setParameter('tagId', $tagId)
337 ->getQuery()
338 ->getResult();
339 }
340
341 /**
342 * Find an entry by its url and its owner.
343 * If it exists, return the entry otherwise return false.
344 *
345 * @param string $url
346 * @param int $userId
347 *
348 * @return Entry|bool
349 */
350 public function findByUrlAndUserId($url, $userId)
351 {
352 return $this->findByHashedUrlAndUserId(
353 UrlHasher::hashUrl($url),
354 $userId);
355 }
356
357 /**
358 * Find an entry by its hashed url and its owner.
359 * If it exists, return the entry otherwise return false.
360 *
361 * @param string $hashedUrl Url hashed using sha1
362 * @param int $userId
363 *
364 * @return Entry|bool
365 */
366 public function findByHashedUrlAndUserId($hashedUrl, $userId)
367 {
368 $res = $this->createQueryBuilder('e')
369 ->where('e.hashedUrl = :hashed_url')->setParameter('hashed_url', $hashedUrl)
370 ->andWhere('e.user = :user_id')->setParameter('user_id', $userId)
371 ->getQuery()
372 ->getResult();
373
374 if (\count($res)) {
375 return current($res);
376 }
377
378 return false;
379 }
380
381 /**
382 * Count all entries for a user.
383 *
384 * @param int $userId
385 *
386 * @return int
387 */
388 public function countAllEntriesByUser($userId)
389 {
390 $qb = $this->createQueryBuilder('e')
391 ->select('count(e)')
392 ->where('e.user = :userId')->setParameter('userId', $userId)
393 ;
394
395 return (int) $qb->getQuery()->getSingleScalarResult();
396 }
397
398 /**
399 * Remove all entries for a user id.
400 * Used when a user want to reset all informations.
401 *
402 * @param int $userId
403 */
404 public function removeAllByUserId($userId)
405 {
406 $this->getEntityManager()
407 ->createQuery('DELETE FROM Wallabag\CoreBundle\Entity\Entry e WHERE e.user = :userId')
408 ->setParameter('userId', $userId)
409 ->execute();
410 }
411
412 public function removeArchivedByUserId($userId)
413 {
414 $this->getEntityManager()
415 ->createQuery('DELETE FROM Wallabag\CoreBundle\Entity\Entry e WHERE e.user = :userId AND e.isArchived = TRUE')
416 ->setParameter('userId', $userId)
417 ->execute();
418 }
419
420 /**
421 * Get id and url from all entries
422 * Used for the clean-duplicates command.
423 */
424 public function findAllEntriesIdAndUrlByUserId($userId)
425 {
426 $qb = $this->createQueryBuilder('e')
427 ->select('e.id, e.url')
428 ->where('e.user = :userid')->setParameter(':userid', $userId);
429
430 return $qb->getQuery()->getArrayResult();
431 }
432
433 /**
434 * @param int $userId
435 *
436 * @return array
437 */
438 public function findAllEntriesIdByUserId($userId = null)
439 {
440 $qb = $this->createQueryBuilder('e')
441 ->select('e.id');
442
443 if (null !== $userId) {
444 $qb->where('e.user = :userid')->setParameter(':userid', $userId);
445 }
446
447 return $qb->getQuery()->getArrayResult();
448 }
449
450 /**
451 * Find all entries by url and owner.
452 *
453 * @param string $url
454 * @param int $userId
455 *
456 * @return array
457 */
458 public function findAllByUrlAndUserId($url, $userId)
459 {
460 return $this->createQueryBuilder('e')
461 ->where('e.url = :url')->setParameter('url', urldecode($url))
462 ->andWhere('e.user = :user_id')->setParameter('user_id', $userId)
463 ->getQuery()
464 ->getResult();
465 }
466
467 /**
468 * Returns a random entry, filtering by status.
469 *
470 * @param int $userId
471 * @param string $type Can be unread, archive, starred, etc
472 *
473 * @throws NoResultException
474 *
475 * @return Entry
476 */
477 public function getRandomEntry($userId, $type = '')
478 {
479 $qb = $this->getQueryBuilderByUser($userId)
480 ->select('e.id');
481
482 switch ($type) {
483 case 'unread':
484 $qb->andWhere('e.isArchived = false');
485 break;
486 case 'archive':
487 $qb->andWhere('e.isArchived = true');
488 break;
489 case 'starred':
490 $qb->andWhere('e.isStarred = true');
491 break;
492 case 'untagged':
493 $qb->leftJoin('e.tags', 't');
494 $qb->andWhere('t.id is null');
495 break;
496 }
497
498 $ids = $qb->getQuery()->getArrayResult();
499
500 if (empty($ids)) {
501 throw new NoResultException();
502 }
503
504 // random select one in the list
505 $randomId = $ids[mt_rand(0, \count($ids) - 1)]['id'];
506
507 return $this->find($randomId);
508 }
509
510 /**
511 * Inject a UrlHasher.
512 *
513 * @param UrlHasher $hasher
514 */
515 public function setUrlHasher(UrlHasher $hasher)
516 {
517 $this->urlHasher = $hasher;
518 }
519
520 /**
521 * Get the UrlHasher, or create a default one if not injected.
522 *
523 * XXX: the default uses the default hash algorithm
524 *
525 * @return UrlHasher
526 */
527 protected function getUrlHasher()
528 {
529 if (!isset($this->urlHasher)) {
530 $this->setUrlHasher(new UrlHasher());
531 }
532
533 return $this->urlHasher;
534 }
535
536 /**
537 * Return a query builder to be used by other getBuilderFor* method.
538 *
539 * @param int $userId
540 *
541 * @return QueryBuilder
542 */
543 private function getQueryBuilderByUser($userId)
544 {
545 return $this->createQueryBuilder('e')
546 ->andWhere('e.user = :userId')->setParameter('userId', $userId);
547 }
548
549 /**
550 * Return a sorted query builder to be used by other getBuilderFor* method.
551 *
552 * @param int $userId
553 * @param string $sortBy
554 * @param string $direction
555 *
556 * @return QueryBuilder
557 */
558 private function getSortedQueryBuilderByUser($userId, $sortBy = 'createdAt', $direction = 'desc')
559 {
560 return $this->sortQueryBuilder($this->getQueryBuilderByUser($userId), $sortBy, $direction);
561 }
562
563 /**
564 * Return the given QueryBuilder with an orderBy() call.
565 *
566 * @param QueryBuilder $qb
567 * @param string $sortBy
568 * @param string $direction
569 *
570 * @return QueryBuilder
571 */
572 private function sortQueryBuilder(QueryBuilder $qb, $sortBy = 'createdAt', $direction = 'desc')
573 {
574 return $qb->orderBy(sprintf('e.%s', $sortBy), $direction);
575 }
576 }