From ca9a83ee511a1e9c54d375b76509de699bd2164a Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Fri, 24 Feb 2017 11:31:31 +0100 Subject: return id of article instead of true if entry exists --- src/Wallabag/ApiBundle/Controller/EntryRestController.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/EntryRestController.php b/src/Wallabag/ApiBundle/Controller/EntryRestController.php index 2c2ec0c1..af5f7603 100644 --- a/src/Wallabag/ApiBundle/Controller/EntryRestController.php +++ b/src/Wallabag/ApiBundle/Controller/EntryRestController.php @@ -41,7 +41,7 @@ class EntryRestController extends WallabagRestController ->getRepository('WallabagCoreBundle:Entry') ->findByUrlAndUserId($url, $this->getUser()->getId()); - $results[$url] = false === $res ? false : true; + $results[$url] = $res instanceof Entry ? $res->getId() : false; } $json = $this->get('serializer')->serialize($results, 'json'); @@ -60,7 +60,7 @@ class EntryRestController extends WallabagRestController ->getRepository('WallabagCoreBundle:Entry') ->findByUrlAndUserId($url, $this->getUser()->getId()); - $exists = false === $res ? false : true; + $exists = $res instanceof Entry ? $res->getId() : false; $json = $this->get('serializer')->serialize(['exists' => $exists], 'json'); -- cgit v1.2.3 From fb9f100e8f4f3288b87536faff4b59cacc7b1efb Mon Sep 17 00:00:00 2001 From: FrenchHope Date: Sun, 19 Mar 2017 09:40:31 +0100 Subject: Scuttle sharing --- src/Wallabag/CoreBundle/Command/InstallCommand.php | 10 ++++++++++ src/Wallabag/CoreBundle/DataFixtures/ORM/LoadSettingData.php | 10 ++++++++++ .../Resources/views/themes/baggy/Entry/entry.html.twig | 1 + .../Resources/views/themes/material/Entry/entry.html.twig | 8 ++++++++ 4 files changed, 29 insertions(+) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Command/InstallCommand.php b/src/Wallabag/CoreBundle/Command/InstallCommand.php index f0738b91..f1179741 100644 --- a/src/Wallabag/CoreBundle/Command/InstallCommand.php +++ b/src/Wallabag/CoreBundle/Command/InstallCommand.php @@ -332,6 +332,16 @@ class InstallCommand extends ContainerAwareCommand 'value' => 'http://myshaarli.com', 'section' => 'entry', ], + [ + 'name' => 'share_scuttle', + 'value' => '1', + 'section' => 'entry', + ], + [ + 'name' => 'scuttle_url', + 'value' => 'http://scuttle.org', + 'section' => 'entry', + ], [ 'name' => 'share_mail', 'value' => '1', diff --git a/src/Wallabag/CoreBundle/DataFixtures/ORM/LoadSettingData.php b/src/Wallabag/CoreBundle/DataFixtures/ORM/LoadSettingData.php index a723656e..52941a64 100644 --- a/src/Wallabag/CoreBundle/DataFixtures/ORM/LoadSettingData.php +++ b/src/Wallabag/CoreBundle/DataFixtures/ORM/LoadSettingData.php @@ -50,11 +50,21 @@ class LoadSettingData extends AbstractFixture implements OrderedFixtureInterface 'value' => '1', 'section' => 'entry', ], + [ + 'name' => 'share_scuttle', + 'value' => '1', + 'section' => 'entry', + ], [ 'name' => 'shaarli_url', 'value' => 'http://myshaarli.com', 'section' => 'entry', ], + [ + 'name' => 'scuttle_url', + 'value' => 'http://scuttle.org', + 'section' => 'entry', + ], [ 'name' => 'share_mail', 'value' => '1', diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Entry/entry.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Entry/entry.html.twig index a555691d..5d5e6dd8 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Entry/entry.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Entry/entry.html.twig @@ -30,6 +30,7 @@ {% if craue_setting('share_twitter') %}
  • {% endif %} {% if craue_setting('share_mail') %}
  • {% endif %} {% if craue_setting('share_shaarli') %}
  • shaarli
  • {% endif %} + {% if craue_setting('share_scuttle') %}
  • scuttle
  • {% endif %} {% if craue_setting('share_diaspora') %}
  • diaspora
  • {% endif %} {% if craue_setting('share_unmark') %}
  • unmark.it
  • {% endif %} {% if craue_setting('carrot') %}
  • Carrot
  • {% endif %} diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entry.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entry.html.twig index c3508083..8e60e2b4 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entry.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entry.html.twig @@ -131,6 +131,14 @@ {% endif %} + {% if craue_setting('share_scuttle') %} +
  • + + + scuttle + +
  • + {% endif %} {% if craue_setting('share_diaspora') %}
  • -- cgit v1.2.3 From b5a5377af12048e05269fc490e588c1b777cde13 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20L=C5=93uillet?= Date: Mon, 27 Mar 2017 22:13:13 +0200 Subject: Added migration for Scuttle sharing --- src/Wallabag/CoreBundle/Command/InstallCommand.php | 2 +- src/Wallabag/CoreBundle/DataFixtures/ORM/LoadSettingData.php | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Command/InstallCommand.php b/src/Wallabag/CoreBundle/Command/InstallCommand.php index f1179741..3c4d3f25 100644 --- a/src/Wallabag/CoreBundle/Command/InstallCommand.php +++ b/src/Wallabag/CoreBundle/Command/InstallCommand.php @@ -341,7 +341,7 @@ class InstallCommand extends ContainerAwareCommand 'name' => 'scuttle_url', 'value' => 'http://scuttle.org', 'section' => 'entry', - ], + ], [ 'name' => 'share_mail', 'value' => '1', diff --git a/src/Wallabag/CoreBundle/DataFixtures/ORM/LoadSettingData.php b/src/Wallabag/CoreBundle/DataFixtures/ORM/LoadSettingData.php index 52941a64..aaeb9ee9 100644 --- a/src/Wallabag/CoreBundle/DataFixtures/ORM/LoadSettingData.php +++ b/src/Wallabag/CoreBundle/DataFixtures/ORM/LoadSettingData.php @@ -54,7 +54,7 @@ class LoadSettingData extends AbstractFixture implements OrderedFixtureInterface 'name' => 'share_scuttle', 'value' => '1', 'section' => 'entry', - ], + ], [ 'name' => 'shaarli_url', 'value' => 'http://myshaarli.com', @@ -64,7 +64,7 @@ class LoadSettingData extends AbstractFixture implements OrderedFixtureInterface 'name' => 'scuttle_url', 'value' => 'http://scuttle.org', 'section' => 'entry', - ], + ], [ 'name' => 'share_mail', 'value' => '1', -- cgit v1.2.3 From 273b6f06584092f3b596406bf4c0d57aa738e8bf Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Thu, 30 Mar 2017 16:07:48 +0200 Subject: Rename method from *username to *user Signed-off-by: Thomas Citharel --- src/Wallabag/CoreBundle/Controller/EntryController.php | 2 +- src/Wallabag/CoreBundle/Repository/EntryRepository.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Controller/EntryController.php b/src/Wallabag/CoreBundle/Controller/EntryController.php index f7398e69..8d2ac6d4 100644 --- a/src/Wallabag/CoreBundle/Controller/EntryController.php +++ b/src/Wallabag/CoreBundle/Controller/EntryController.php @@ -227,7 +227,7 @@ class EntryController extends Controller public function showUnreadAction(Request $request, $page) { // load the quickstart if no entry in database - if ($page == 1 && $this->get('wallabag_core.entry_repository')->countAllEntriesByUsername($this->getUser()->getId()) == 0) { + if ($page == 1 && $this->get('wallabag_core.entry_repository')->countAllEntriesByUser($this->getUser()->getId()) == 0) { return $this->redirect($this->generateUrl('quickstart')); } diff --git a/src/Wallabag/CoreBundle/Repository/EntryRepository.php b/src/Wallabag/CoreBundle/Repository/EntryRepository.php index 4071301d..9325d261 100644 --- a/src/Wallabag/CoreBundle/Repository/EntryRepository.php +++ b/src/Wallabag/CoreBundle/Repository/EntryRepository.php @@ -328,7 +328,7 @@ class EntryRepository extends EntityRepository * * @return int */ - public function countAllEntriesByUsername($userId) + public function countAllEntriesByUser($userId) { $qb = $this->createQueryBuilder('e') ->select('count(e)') -- cgit v1.2.3 From 6da1aebc946e6448dd0d5080ee88e79c2bae4666 Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Thu, 30 Mar 2017 16:24:59 +0200 Subject: Allow to remove all archived entries Since we still support fucking SQLite, we need to retrieve all tags & annotations for archived entries before deleting them. Signed-off-by: Thomas Citharel --- .../Repository/AnnotationRepository.php | 16 ++++++ .../CoreBundle/Controller/ConfigController.php | 59 +++++++++++++++++++++- .../CoreBundle/Repository/EntryRepository.php | 8 +++ .../CoreBundle/Repository/TagRepository.php | 20 ++++++++ .../Resources/translations/messages.da.yml | 2 + .../Resources/translations/messages.de.yml | 2 + .../Resources/translations/messages.en.yml | 2 + .../Resources/translations/messages.es.yml | 2 + .../Resources/translations/messages.fa.yml | 2 + .../Resources/translations/messages.fr.yml | 2 + .../Resources/translations/messages.it.yml | 2 + .../Resources/translations/messages.oc.yml | 2 + .../Resources/translations/messages.pl.yml | 2 + .../Resources/translations/messages.pt.yml | 2 + .../Resources/translations/messages.ro.yml | 2 + .../Resources/translations/messages.tr.yml | 2 + .../views/themes/material/Config/index.html.twig | 3 ++ 17 files changed, 129 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/Wallabag/AnnotationBundle/Repository/AnnotationRepository.php b/src/Wallabag/AnnotationBundle/Repository/AnnotationRepository.php index 8d3f07ee..23f21c3e 100644 --- a/src/Wallabag/AnnotationBundle/Repository/AnnotationRepository.php +++ b/src/Wallabag/AnnotationBundle/Repository/AnnotationRepository.php @@ -122,4 +122,20 @@ class AnnotationRepository extends EntityRepository ->setParameter('userId', $userId) ->execute(); } + + /** + * Find all annotations related to archived entries + * + * @param $userId + * @return mixed + */ + public function findAllByArchivedEntriesAndUserId($userId) + { + return $this->createQueryBuilder('a') + ->leftJoin('a.entry', 'e') + ->where('a.user = :userid')->setParameter(':userid', $userId) + ->andWhere('e.isArchived = true') + ->getQuery() + ->getResult(); + } } diff --git a/src/Wallabag/CoreBundle/Controller/ConfigController.php b/src/Wallabag/CoreBundle/Controller/ConfigController.php index 907bf78e..7dbe3f18 100644 --- a/src/Wallabag/CoreBundle/Controller/ConfigController.php +++ b/src/Wallabag/CoreBundle/Controller/ConfigController.php @@ -248,7 +248,7 @@ class ConfigController extends Controller break; case 'entries': - // SQLite doesn't care about cascading remove, so we need to manually remove associated stuf + // SQLite doesn't care about cascading remove, so we need to manually remove associated stuff // otherwise they won't be removed ... if ($this->get('doctrine')->getConnection()->getDriver() instanceof \Doctrine\DBAL\Driver\PDOSqlite\Driver) { $this->getDoctrine()->getRepository('WallabagAnnotationBundle:Annotation')->removeAllByUserId($this->getUser()->getId()); @@ -260,6 +260,19 @@ class ConfigController extends Controller $this->getDoctrine() ->getRepository('WallabagCoreBundle:Entry') ->removeAllByUserId($this->getUser()->getId()); + break; + case 'archived': + if ($this->get('doctrine')->getConnection()->getDriver() instanceof \Doctrine\DBAL\Driver\PDOSqlite\Driver) { + $this->removeAnnotationsForArchivedByUserId($this->getUser()->getId()); + } + + // manually remove tags to avoid orphan tag + $this->removeTagsForArchivedByUserId($this->getUser()->getId()); + + $this->getDoctrine() + ->getRepository('WallabagCoreBundle:Entry') + ->removeArchivedByUserId($this->getUser()->getId()); + break; } $this->get('session')->getFlashBag()->add( @@ -299,6 +312,50 @@ class ConfigController extends Controller $em->flush(); } + /** + * Remove all tags for a given user and cleanup orphan tags. + * + * @param int $userId + */ + private function removeTagsForArchivedByUserId($userId) + { + $tags = $this->getDoctrine()->getRepository('WallabagCoreBundle:Tag')->findTagsForArchivedArticles($userId); + + if (empty($tags)) { + return; + } + + $this->getDoctrine() + ->getRepository('WallabagCoreBundle:Entry') + ->removeTags($userId, $tags); + + // cleanup orphan tags + $em = $this->getDoctrine()->getManager(); + + foreach ($tags as $tag) { + if (count($tag->getEntries()) === 0) { + $em->remove($tag); + } + } + + $em->flush(); + } + + private function removeAnnotationsForArchivedByUserId($userId) + { + $em = $this->getDoctrine()->getManager(); + + $archivedEntriesAnnotations = $this->getDoctrine() + ->getRepository('WallabagAnnotationBundle:Annotation') + ->findAllByArchivedEntriesAndUserId($userId); + + foreach ($archivedEntriesAnnotations as $archivedEntriesAnnotation) { + $em->remove($archivedEntriesAnnotation); + } + + $em->flush(); + } + /** * Validate that a rule can be edited/deleted by the current user. * diff --git a/src/Wallabag/CoreBundle/Repository/EntryRepository.php b/src/Wallabag/CoreBundle/Repository/EntryRepository.php index 9325d261..1f22e901 100644 --- a/src/Wallabag/CoreBundle/Repository/EntryRepository.php +++ b/src/Wallabag/CoreBundle/Repository/EntryRepository.php @@ -371,4 +371,12 @@ class EntryRepository extends EntityRepository ->setParameter('userId', $userId) ->execute(); } + + public function removeArchivedByUserId($userId) + { + $this->getEntityManager() + ->createQuery('DELETE FROM Wallabag\CoreBundle\Entity\Entry e WHERE e.user = :userId AND e.isArchived = TRUE') + ->setParameter('userId', $userId) + ->execute(); + } } diff --git a/src/Wallabag/CoreBundle/Repository/TagRepository.php b/src/Wallabag/CoreBundle/Repository/TagRepository.php index 2182df25..b78e244e 100644 --- a/src/Wallabag/CoreBundle/Repository/TagRepository.php +++ b/src/Wallabag/CoreBundle/Repository/TagRepository.php @@ -76,4 +76,24 @@ class TagRepository extends EntityRepository ->getQuery() ->getSingleResult(); } + + public function findTagsForArchivedArticles($userId) + { + $ids = $this->createQueryBuilder('t') + ->select('t.id') + ->leftJoin('t.entries', 'e') + ->where('e.user = :userId')->setParameter('userId', $userId) + ->andWhere('e.isArchived = true') + ->groupBy('t.id') + ->orderBy('t.slug') + ->getQuery() + ->getArrayResult(); + + $tags = []; + foreach ($ids as $id) { + $tags[] = $this->find($id); + } + + return $tags; + } } diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml index 5d9e85e4..dfac7a65 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml @@ -110,6 +110,7 @@ config: # annotations: Remove ALL annotations # tags: Remove ALL tags # entries: Remove ALL entries + # archived: Remove ALL archived entries # confirm: Are you really really sure? (THIS CAN'T BE UNDONE) form_password: # description: "You can change your password here. Your new password should by at least 8 characters long." @@ -528,6 +529,7 @@ flashes: # annotations_reset: Annotations reset # tags_reset: Tags reset # entries_reset: Entries reset + # archived_reset: Archived entries deleted entry: notice: # entry_already_saved: 'Entry already saved on %date%' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml index f1952a3e..0b9df325 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml @@ -110,6 +110,7 @@ config: annotations: Entferne ALLE Annotationen tags: Entferne ALLE Tags entries: Entferne ALLE Einträge + # archived: Remove ALL archived entries confirm: Bist du wirklich sicher? (DIES KANN NICHT RÜCKGÄNGIG GEMACHT WERDEN) form_password: description: "Hier kannst du dein Kennwort ändern. Dieses sollte mindestens acht Zeichen enthalten." @@ -528,6 +529,7 @@ flashes: annotations_reset: Anmerkungen zurücksetzen tags_reset: Tags zurücksetzen entries_reset: Einträge zurücksetzen + # archived_reset: Archived entries deleted entry: notice: entry_already_saved: 'Eintrag bereits am %date% gespeichert' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml index 8e7e3c2c..2fa3192e 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml @@ -110,6 +110,7 @@ config: annotations: Remove ALL annotations tags: Remove ALL tags entries: Remove ALL entries + archived: Remove ALL archived entries confirm: Are you really sure? (THIS CAN'T BE UNDONE) form_password: description: "You can change your password here. Your new password should by at least 8 characters long." @@ -528,6 +529,7 @@ flashes: annotations_reset: Annotations reset tags_reset: Tags reset entries_reset: Entries reset + archived_reset: Archived entries deleted entry: notice: entry_already_saved: 'Entry already saved on %date%' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml index 3d65c311..ce581d89 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml @@ -110,6 +110,7 @@ config: annotations: Eliminar TODAS las anotaciones tags: Eliminar TODAS las etiquetas entries: Eliminar TODOS los artículos + # archived: Remove ALL archived entries confirm: ¿Estás completamente seguro? (NO SE PUEDE DESHACER) form_password: description: "Puedes cambiar la contraseña aquí. Tu nueva contraseña debe tener al menos 8 caracteres." @@ -528,6 +529,7 @@ flashes: annotations_reset: Anotaciones reiniciadas tags_reset: Etiquetas reiniciadas entries_reset: Artículos reiniciados + # archived_reset: Archived entries deleted entry: notice: entry_already_saved: 'Artículo ya guardado el %fecha%' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml index 80500d19..3e3ee12c 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml @@ -110,6 +110,7 @@ config: # annotations: Remove ALL annotations # tags: Remove ALL tags # entries: Remove ALL entries + # archived: Remove ALL archived entries # confirm: Are you really really sure? (THIS CAN'T BE UNDONE) form_password: # description: "You can change your password here. Your new password should by at least 8 characters long." @@ -528,6 +529,7 @@ flashes: # annotations_reset: Annotations reset # tags_reset: Tags reset # entries_reset: Entries reset + # archived_reset: Archived entries deleted entry: notice: entry_already_saved: 'این مقاله در تاریخ %date% ذخیره شده بود' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml index 4f49f777..074593a6 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml @@ -110,6 +110,7 @@ config: annotations: Supprimer TOUTES les annotations tags: Supprimer TOUS les tags entries: Supprimer TOUS les articles + archived: Supprimer TOUS les articles archivés confirm: Êtes-vous vraiment vraiment sûr ? (C'EST IRRÉVERSIBLE) form_password: description: "Vous pouvez changer ici votre mot de passe. Le mot de passe doit contenir au moins 8 caractères." @@ -528,6 +529,7 @@ flashes: annotations_reset: Annotations supprimées tags_reset: Tags supprimés entries_reset: Articles supprimés + archived_reset: Articles archivés supprimés entry: notice: entry_already_saved: "Article déjà sauvegardé le %date%" diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml index 992ff71c..0d86756a 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml @@ -110,6 +110,7 @@ config: # annotations: Remove ALL annotations # tags: Remove ALL tags # entries: Remove ALL entries + # archived: Remove ALL archived entries # confirm: Are you really really sure? (THIS CAN'T BE UNDONE) form_password: # description: "You can change your password here. Your new password should by at least 8 characters long." @@ -528,6 +529,7 @@ flashes: # annotations_reset: Annotations reset # tags_reset: Tags reset # entries_reset: Entries reset + # archived_reset: Archived entries deleted entry: notice: entry_already_saved: 'Contenuto già salvato in data %date%' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml index f6488565..d2949c50 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml @@ -110,6 +110,7 @@ config: annotations: Levar TOTAS las anotacions tags: Levar TOTAS las etiquetas entries: Levar TOTES los articles + # archived: Remove ALL archived entries confirm: Sètz vertadièrament segur ? (ES IRREVERSIBLE) form_password: description: "Podètz cambiar vòstre senhal aquí. Vòstre senhal deu èsser long d'almens 8 caractèrs." @@ -528,6 +529,7 @@ flashes: annotations_reset: Anotacions levadas tags_reset: Etiquetas levadas entries_reset: Articles levats + # archived_reset: Archived entries deleted entry: notice: entry_already_saved: 'Article ja salvargardat lo %date%' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml index eda9bbbf..1f512942 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml @@ -110,6 +110,7 @@ config: annotations: Usuń WSZYSTKIE adnotacje tags: Usuń WSZYSTKIE tagi entries: usuń WSZYTSTKIE wpisy + # archived: Remove ALL archived entries confirm: Jesteś pewien? (tej operacji NIE MOŻNA cofnąć) form_password: description: "Tutaj możesz zmienić swoje hasło. Twoje nowe hasło powinno mieć conajmniej 8 znaków." @@ -528,6 +529,7 @@ flashes: annotations_reset: Zresetuj adnotacje tags_reset: Zresetuj tagi entries_reset: Zresetuj wpisy + # archived_reset: Archived entries deleted entry: notice: entry_already_saved: 'Wpis już został dodany %date%' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml index 8a7cc6f8..2e815230 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml @@ -110,6 +110,7 @@ config: # annotations: Remove ALL annotations # tags: Remove ALL tags # entries: Remove ALL entries + # archived: Remove ALL archived entries # confirm: Are you really really sure? (THIS CAN'T BE UNDONE) form_password: # description: "You can change your password here. Your new password should by at least 8 characters long." @@ -528,6 +529,7 @@ flashes: # annotations_reset: Annotations reset # tags_reset: Tags reset # entries_reset: Entries reset + # archived_reset: Archived entries deleted entry: notice: entry_already_saved: 'Entrada já foi salva em %date%' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml index 52b6414f..16401efd 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml @@ -110,6 +110,7 @@ config: # annotations: Remove ALL annotations # tags: Remove ALL tags # entries: Remove ALL entries + # archived: Remove ALL archived entries # confirm: Are you really really sure? (THIS CAN'T BE UNDONE) form_password: # description: "You can change your password here. Your new password should by at least 8 characters long." @@ -528,6 +529,7 @@ flashes: # annotations_reset: Annotations reset # tags_reset: Tags reset # entries_reset: Entries reset + # archived_reset: Archived entries deleted entry: notice: # entry_already_saved: 'Entry already saved on %date%' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml index bfb7e206..a4bf7dfe 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml @@ -110,6 +110,7 @@ config: # annotations: Remove ALL annotations # tags: Remove ALL tags # entries: Remove ALL entries + # archived: Remove ALL archived entries # confirm: Are you really really sure? (THIS CAN'T BE UNDONE) form_password: # description: "You can change your password here. Your new password should by at least 8 characters long." @@ -528,6 +529,7 @@ flashes: # annotations_reset: Annotations reset # tags_reset: Tags reset # entries_reset: Entries reset + # archived_reset: Archived entries deleted entry: notice: entry_already_saved: 'Entry already saved on %date%' diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/material/Config/index.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/material/Config/index.html.twig index 5d411fdd..708ff951 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/material/Config/index.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/material/Config/index.html.twig @@ -229,6 +229,9 @@ {{ 'config.reset.tags'|trans }} + + {{ 'config.reset.archived'|trans }} + {{ 'config.reset.entries'|trans }} -- cgit v1.2.3 From 9102851f59d960869b210bb26ab0e9c266781c4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20L=C5=93uillet?= Date: Fri, 31 Mar 2017 10:53:23 +0200 Subject: Added delete button on Baggy theme --- src/Wallabag/AnnotationBundle/Repository/AnnotationRepository.php | 3 ++- .../CoreBundle/Resources/views/themes/baggy/Config/index.html.twig | 5 +++++ 2 files changed, 7 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/Wallabag/AnnotationBundle/Repository/AnnotationRepository.php b/src/Wallabag/AnnotationBundle/Repository/AnnotationRepository.php index 23f21c3e..3af53805 100644 --- a/src/Wallabag/AnnotationBundle/Repository/AnnotationRepository.php +++ b/src/Wallabag/AnnotationBundle/Repository/AnnotationRepository.php @@ -124,9 +124,10 @@ class AnnotationRepository extends EntityRepository } /** - * Find all annotations related to archived entries + * Find all annotations related to archived entries. * * @param $userId + * * @return mixed */ public function findAllByArchivedEntriesAndUserId($userId) diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Config/index.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Config/index.html.twig index 3548f590..01f63a7b 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Config/index.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Config/index.html.twig @@ -199,6 +199,11 @@ {{ 'config.reset.tags'|trans }}
  • +
  • + + {{ 'config.reset.archived'|trans }} + +
  • {{ 'config.reset.entries'|trans }} -- cgit v1.2.3 From e682a70f88338af66b8d47bfe078e32fd9c6520c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20L=C5=93uillet?= Date: Fri, 31 Mar 2017 11:04:18 +0200 Subject: Refactored code --- .../CoreBundle/Controller/ConfigController.php | 40 +++++++++------------- 1 file changed, 16 insertions(+), 24 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Controller/ConfigController.php b/src/Wallabag/CoreBundle/Controller/ConfigController.php index 7dbe3f18..b2814ade 100644 --- a/src/Wallabag/CoreBundle/Controller/ConfigController.php +++ b/src/Wallabag/CoreBundle/Controller/ConfigController.php @@ -284,14 +284,13 @@ class ConfigController extends Controller } /** - * Remove all tags for a given user and cleanup orphan tags. + * Remove all tags for given tags and a given user and cleanup orphan tags. * - * @param int $userId + * @param array $tags + * @param int $userId */ - private function removeAllTagsByUserId($userId) + private function removeAllTagsByStatusAndUserId($tags, $userId) { - $tags = $this->getDoctrine()->getRepository('WallabagCoreBundle:Tag')->findAllTags($userId); - if (empty($tags)) { return; } @@ -312,6 +311,17 @@ class ConfigController extends Controller $em->flush(); } + /** + * Remove all tags for a given user and cleanup orphan tags. + * + * @param int $userId + */ + private function removeAllTagsByUserId($userId) + { + $tags = $this->getDoctrine()->getRepository('WallabagCoreBundle:Tag')->findAllTags($userId); + $this->removeAllTagsByStatusAndUserId($tags, $userId); + } + /** * Remove all tags for a given user and cleanup orphan tags. * @@ -320,25 +330,7 @@ class ConfigController extends Controller private function removeTagsForArchivedByUserId($userId) { $tags = $this->getDoctrine()->getRepository('WallabagCoreBundle:Tag')->findTagsForArchivedArticles($userId); - - if (empty($tags)) { - return; - } - - $this->getDoctrine() - ->getRepository('WallabagCoreBundle:Entry') - ->removeTags($userId, $tags); - - // cleanup orphan tags - $em = $this->getDoctrine()->getManager(); - - foreach ($tags as $tag) { - if (count($tag->getEntries()) === 0) { - $em->remove($tag); - } - } - - $em->flush(); + $this->removeAllTagsByStatusAndUserId($tags, $userId); } private function removeAnnotationsForArchivedByUserId($userId) -- cgit v1.2.3 From 13a592a1288d7deb49211838368583c0109a5fbd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20L=C5=93uillet?= Date: Fri, 31 Mar 2017 17:03:08 +0200 Subject: Renamed methods --- src/Wallabag/AnnotationBundle/Repository/AnnotationRepository.php | 2 +- src/Wallabag/CoreBundle/Controller/ConfigController.php | 4 ++-- src/Wallabag/CoreBundle/Repository/TagRepository.php | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/Wallabag/AnnotationBundle/Repository/AnnotationRepository.php b/src/Wallabag/AnnotationBundle/Repository/AnnotationRepository.php index 3af53805..da361308 100644 --- a/src/Wallabag/AnnotationBundle/Repository/AnnotationRepository.php +++ b/src/Wallabag/AnnotationBundle/Repository/AnnotationRepository.php @@ -130,7 +130,7 @@ class AnnotationRepository extends EntityRepository * * @return mixed */ - public function findAllByArchivedEntriesAndUserId($userId) + public function findAllArchivedEntriesByUser($userId) { return $this->createQueryBuilder('a') ->leftJoin('a.entry', 'e') diff --git a/src/Wallabag/CoreBundle/Controller/ConfigController.php b/src/Wallabag/CoreBundle/Controller/ConfigController.php index b2814ade..1a80cc1a 100644 --- a/src/Wallabag/CoreBundle/Controller/ConfigController.php +++ b/src/Wallabag/CoreBundle/Controller/ConfigController.php @@ -329,7 +329,7 @@ class ConfigController extends Controller */ private function removeTagsForArchivedByUserId($userId) { - $tags = $this->getDoctrine()->getRepository('WallabagCoreBundle:Tag')->findTagsForArchivedArticles($userId); + $tags = $this->getDoctrine()->getRepository('WallabagCoreBundle:Tag')->findForArchivedArticlesByUser($userId); $this->removeAllTagsByStatusAndUserId($tags, $userId); } @@ -339,7 +339,7 @@ class ConfigController extends Controller $archivedEntriesAnnotations = $this->getDoctrine() ->getRepository('WallabagAnnotationBundle:Annotation') - ->findAllByArchivedEntriesAndUserId($userId); + ->findAllArchivedEntriesByUser($userId); foreach ($archivedEntriesAnnotations as $archivedEntriesAnnotation) { $em->remove($archivedEntriesAnnotation); diff --git a/src/Wallabag/CoreBundle/Repository/TagRepository.php b/src/Wallabag/CoreBundle/Repository/TagRepository.php index b78e244e..6c63a6a2 100644 --- a/src/Wallabag/CoreBundle/Repository/TagRepository.php +++ b/src/Wallabag/CoreBundle/Repository/TagRepository.php @@ -77,7 +77,7 @@ class TagRepository extends EntityRepository ->getSingleResult(); } - public function findTagsForArchivedArticles($userId) + public function findForArchivedArticlesByUser($userId) { $ids = $this->createQueryBuilder('t') ->select('t.id') -- cgit v1.2.3 From 5e9009ce86a366001616fad5b28cb59dc20ee4df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20L=C5=93uillet?= Date: Wed, 5 Apr 2017 22:22:16 +0200 Subject: Added publication date --- src/Wallabag/CoreBundle/Entity/Entry.php | 29 ++++++++++++++++++++++ src/Wallabag/CoreBundle/Helper/ContentProxy.php | 4 +++ .../Resources/translations/messages.da.yml | 1 + .../Resources/translations/messages.de.yml | 1 + .../Resources/translations/messages.en.yml | 1 + .../Resources/translations/messages.es.yml | 1 + .../Resources/translations/messages.fa.yml | 1 + .../Resources/translations/messages.fr.yml | 1 + .../Resources/translations/messages.it.yml | 1 + .../Resources/translations/messages.oc.yml | 1 + .../Resources/translations/messages.pl.yml | 1 + .../Resources/translations/messages.pt.yml | 1 + .../Resources/translations/messages.ro.yml | 1 + .../Resources/translations/messages.tr.yml | 1 + .../views/themes/baggy/Entry/entry.html.twig | 8 +++++- .../views/themes/material/Entry/entry.html.twig | 10 ++++++-- 16 files changed, 60 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Entity/Entry.php b/src/Wallabag/CoreBundle/Entity/Entry.php index 7276b437..54f74a14 100644 --- a/src/Wallabag/CoreBundle/Entity/Entry.php +++ b/src/Wallabag/CoreBundle/Entity/Entry.php @@ -121,6 +121,15 @@ class Entry */ private $updatedAt; + /** + * @var \DateTime + * + * @ORM\Column(name="published_at", type="datetime", nullable=true) + * + * @Groups({"entries_for_user", "export_all"}) + */ + private $publishedAt; + /** * @ORM\OneToMany(targetEntity="Wallabag\AnnotationBundle\Entity\Annotation", mappedBy="entry", cascade={"persist", "remove"}) * @ORM\JoinTable @@ -701,4 +710,24 @@ class Entry return $this; } + + /** + * @return \Datetime + */ + public function getPublishedAt() + { + return $this->publishedAt; + } + + /** + * @param \Datetime $publishedAt + * + * @return Entry + */ + public function setPublishedAt(\Datetime $publishedAt) + { + $this->publishedAt = $publishedAt; + + return $this; + } } diff --git a/src/Wallabag/CoreBundle/Helper/ContentProxy.php b/src/Wallabag/CoreBundle/Helper/ContentProxy.php index f222dd88..56358665 100644 --- a/src/Wallabag/CoreBundle/Helper/ContentProxy.php +++ b/src/Wallabag/CoreBundle/Helper/ContentProxy.php @@ -79,6 +79,10 @@ class ContentProxy $entry->setContent($html); $entry->setHttpStatus(isset($content['status']) ? $content['status'] : ''); + if (isset($content['date']) && null !== $content['date']) { + $entry->setPublishedAt(new \DateTime($content['date'])); + } + $entry->setLanguage(isset($content['language']) ? $content['language'] : ''); $entry->setMimetype(isset($content['content_type']) ? $content['content_type'] : ''); $entry->setReadingTime(Utils::getReadingTime($html)); diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml index dfac7a65..a8802efc 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml @@ -224,6 +224,7 @@ entry: original_article: 'original' # annotations_on_the_entry: '{0} No annotations|{1} One annotation|]1,Inf[ %count% annotations' created_at: 'Oprettelsesdato' + # published_at: 'Publication date' new: page_title: 'Gem ny artikel' placeholder: 'http://website.com' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml index 0b9df325..fa2b9fcb 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml @@ -224,6 +224,7 @@ entry: original_article: 'original' annotations_on_the_entry: '{0} Keine Anmerkungen|{1} Eine Anmerkung|]1,Inf[ %count% Anmerkungen' created_at: 'Erstellungsdatum' + # published_at: 'Publication date' new: page_title: 'Neuen Artikel speichern' placeholder: 'https://website.de' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml index 2fa3192e..bc2a90a5 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml @@ -224,6 +224,7 @@ entry: original_article: 'original' annotations_on_the_entry: '{0} No annotations|{1} One annotation|]1,Inf[ %count% annotations' created_at: 'Creation date' + published_at: 'Publication date' new: page_title: 'Save new entry' placeholder: 'http://website.com' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml index ce581d89..da516ee8 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml @@ -224,6 +224,7 @@ entry: original_article: 'original' annotations_on_the_entry: '{0} Sin anotaciones|{1} Una anotación|]1,Inf[ %count% anotaciones' created_at: 'Fecha de creación' + # published_at: 'Publication date' new: page_title: 'Guardar un nuevo artículo' placeholder: 'http://sitioweb.com' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml index 3e3ee12c..0a3bebe4 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml @@ -224,6 +224,7 @@ entry: original_article: 'اصلی' annotations_on_the_entry: '{0} بدون حاشیه|{1} یک حاشیه|]1,Inf[ %nbحاشیه% annotations' created_at: 'زمان ساخت' + # published_at: 'Publication date' new: page_title: 'ذخیرهٔ مقالهٔ تازه' placeholder: 'http://website.com' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml index 074593a6..468a9af9 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml @@ -224,6 +224,7 @@ entry: original_article: "original" annotations_on_the_entry: "{0} Aucune annotation|{1} Une annotation|]1,Inf[ %count% annotations" created_at: "Date de création" + published_at: "Date de publication" new: page_title: "Sauvegarder un nouvel article" placeholder: "http://website.com" diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml index 0d86756a..e7b0ea8a 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml @@ -224,6 +224,7 @@ entry: original_article: 'originale' annotations_on_the_entry: '{0} Nessuna annotazione|{1} Una annotazione|]1,Inf[ %count% annotazioni' created_at: 'Data di creazione' + # published_at: 'Publication date' new: page_title: 'Salva un nuovo contenuto' placeholder: 'http://website.com' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml index d2949c50..1937dfce 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml @@ -224,6 +224,7 @@ entry: original_article: 'original' annotations_on_the_entry: "{0} Pas cap d'anotacion|{1} Una anotacion|]1,Inf[ %count% anotacions" created_at: 'Data de creacion' + # published_at: 'Publication date' new: page_title: 'Enregistrar un novèl article' placeholder: 'http://website.com' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml index 1f512942..cb644045 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml @@ -224,6 +224,7 @@ entry: original_article: 'oryginalny' annotations_on_the_entry: '{0} Nie ma adnotacji |{1} Jedna adnotacja |]1,Inf[ %count% adnotacji' created_at: 'Czas stworzenia' + # published_at: 'Publication date' new: page_title: 'Zapisz nowy wpis' placeholder: 'http://website.com' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml index 2e815230..16803549 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml @@ -224,6 +224,7 @@ entry: original_article: 'original' annotations_on_the_entry: '{0} Sem anotações|{1} Uma anotação|]1,Inf[ %nbAnnotations% anotações' created_at: 'Data de criação' + # published_at: 'Publication date' new: page_title: 'Salvar nova entrada' placeholder: 'http://website.com' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml index 16401efd..539482f8 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml @@ -224,6 +224,7 @@ entry: original_article: 'original' # annotations_on_the_entry: '{0} No annotations|{1} One annotation|]1,Inf[ %count% annotations' created_at: 'Data creării' + # published_at: 'Publication date' new: page_title: 'Salvează un nou articol' placeholder: 'http://website.com' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml index a4bf7dfe..a3e1cca7 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml @@ -224,6 +224,7 @@ entry: original_article: 'orijinal' # annotations_on_the_entry: '{0} No annotations|{1} One annotation|]1,Inf[ %count% annotations' created_at: 'Oluşturulma tarihi' + # published_at: 'Publication date' new: page_title: 'Yeni makaleyi kaydet' placeholder: 'http://website.com' diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Entry/entry.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Entry/entry.html.twig index 5d5e6dd8..8bc7b54c 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Entry/entry.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Entry/entry.html.twig @@ -44,9 +44,15 @@
    - {{ entry.createdAt|date('Y-m-d') }} + {{ entry.createdAt|date('Y-m-d H:i') }} + {% if entry.publishedAt is not null %} + + {{ entry.publishedAt|date('Y-m-d H:i') }} + + {% endif %} + {% set readingTime = entry.readingTime / app.user.config.readingSpeed %} {% if readingTime > 0 %} diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entry.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entry.html.twig index 8e60e2b4..c72a22c0 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entry.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entry.html.twig @@ -138,7 +138,7 @@ scuttle
  • - {% endif %} + {% endif %} {% if craue_setting('share_diaspora') %}
  • @@ -226,8 +226,14 @@
  • today - {{ entry.createdAt|date('Y-m-d') }} + {{ entry.createdAt|date('Y-m-d H:i') }} +
  • + {% if entry.publishedAt is not null %} +
  • + create + {{ entry.publishedAt|date('Y-m-d H:i') }}
  • + {% endif %}
  • link -- cgit v1.2.3 From 7b0b3622ab2dd909028481b294c91f88a5682671 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20L=C5=93uillet?= Date: Thu, 6 Apr 2017 09:36:20 +0200 Subject: Added author of article --- src/Wallabag/CoreBundle/Entity/Entry.php | 29 ++++++++++++++++++++++ src/Wallabag/CoreBundle/Helper/ContentProxy.php | 6 ++++- .../Resources/translations/messages.da.yml | 1 + .../Resources/translations/messages.de.yml | 1 + .../Resources/translations/messages.en.yml | 1 + .../Resources/translations/messages.es.yml | 1 + .../Resources/translations/messages.fa.yml | 1 + .../Resources/translations/messages.fr.yml | 1 + .../Resources/translations/messages.it.yml | 1 + .../Resources/translations/messages.oc.yml | 1 + .../Resources/translations/messages.pl.yml | 1 + .../Resources/translations/messages.pt.yml | 1 + .../Resources/translations/messages.ro.yml | 1 + .../Resources/translations/messages.tr.yml | 1 + .../views/themes/baggy/Entry/entry.html.twig | 10 +++++++- .../views/themes/material/Entry/entry.html.twig | 10 +++++++- 16 files changed, 64 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Entity/Entry.php b/src/Wallabag/CoreBundle/Entity/Entry.php index 54f74a14..8d385eb4 100644 --- a/src/Wallabag/CoreBundle/Entity/Entry.php +++ b/src/Wallabag/CoreBundle/Entity/Entry.php @@ -130,6 +130,15 @@ class Entry */ private $publishedAt; + /** + * @var array + * + * @ORM\Column(name="published_by", type="json_array", nullable=true) + * + * @Groups({"entries_for_user", "export_all"}) + */ + private $publishedBy; + /** * @ORM\OneToMany(targetEntity="Wallabag\AnnotationBundle\Entity\Annotation", mappedBy="entry", cascade={"persist", "remove"}) * @ORM\JoinTable @@ -730,4 +739,24 @@ class Entry return $this; } + + /** + * @return string + */ + public function getPublishedBy() + { + return $this->publishedBy; + } + + /** + * @param string $publishedBy + * + * @return Entry + */ + public function setPublishedBy($publishedBy) + { + $this->publishedBy = $publishedBy; + + return $this; + } } diff --git a/src/Wallabag/CoreBundle/Helper/ContentProxy.php b/src/Wallabag/CoreBundle/Helper/ContentProxy.php index 56358665..d45aef88 100644 --- a/src/Wallabag/CoreBundle/Helper/ContentProxy.php +++ b/src/Wallabag/CoreBundle/Helper/ContentProxy.php @@ -79,10 +79,14 @@ class ContentProxy $entry->setContent($html); $entry->setHttpStatus(isset($content['status']) ? $content['status'] : ''); - if (isset($content['date']) && null !== $content['date']) { + if (isset($content['date']) && null !== $content['date'] && '' !== $content['date']) { $entry->setPublishedAt(new \DateTime($content['date'])); } + if (!empty($content['authors'])) { + $entry->setPublishedBy($content['authors']); + } + $entry->setLanguage(isset($content['language']) ? $content['language'] : ''); $entry->setMimetype(isset($content['content_type']) ? $content['content_type'] : ''); $entry->setReadingTime(Utils::getReadingTime($html)); diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml index a8802efc..3e841a18 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml @@ -225,6 +225,7 @@ entry: # annotations_on_the_entry: '{0} No annotations|{1} One annotation|]1,Inf[ %count% annotations' created_at: 'Oprettelsesdato' # published_at: 'Publication date' + # published_by: 'Published by' new: page_title: 'Gem ny artikel' placeholder: 'http://website.com' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml index fa2b9fcb..3358b5d3 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml @@ -225,6 +225,7 @@ entry: annotations_on_the_entry: '{0} Keine Anmerkungen|{1} Eine Anmerkung|]1,Inf[ %count% Anmerkungen' created_at: 'Erstellungsdatum' # published_at: 'Publication date' + # published_by: 'Published by' new: page_title: 'Neuen Artikel speichern' placeholder: 'https://website.de' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml index bc2a90a5..30f44350 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml @@ -225,6 +225,7 @@ entry: annotations_on_the_entry: '{0} No annotations|{1} One annotation|]1,Inf[ %count% annotations' created_at: 'Creation date' published_at: 'Publication date' + published_by: 'Published by' new: page_title: 'Save new entry' placeholder: 'http://website.com' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml index da516ee8..363c94fb 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml @@ -225,6 +225,7 @@ entry: annotations_on_the_entry: '{0} Sin anotaciones|{1} Una anotación|]1,Inf[ %count% anotaciones' created_at: 'Fecha de creación' # published_at: 'Publication date' + # published_by: 'Published by' new: page_title: 'Guardar un nuevo artículo' placeholder: 'http://sitioweb.com' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml index 0a3bebe4..972c2a5d 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml @@ -225,6 +225,7 @@ entry: annotations_on_the_entry: '{0} بدون حاشیه|{1} یک حاشیه|]1,Inf[ %nbحاشیه% annotations' created_at: 'زمان ساخت' # published_at: 'Publication date' + # published_by: 'Published by' new: page_title: 'ذخیرهٔ مقالهٔ تازه' placeholder: 'http://website.com' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml index 468a9af9..04b1eeef 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml @@ -225,6 +225,7 @@ entry: annotations_on_the_entry: "{0} Aucune annotation|{1} Une annotation|]1,Inf[ %count% annotations" created_at: "Date de création" published_at: "Date de publication" + published_by: "Publié par" new: page_title: "Sauvegarder un nouvel article" placeholder: "http://website.com" diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml index e7b0ea8a..7f6787c9 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml @@ -225,6 +225,7 @@ entry: annotations_on_the_entry: '{0} Nessuna annotazione|{1} Una annotazione|]1,Inf[ %count% annotazioni' created_at: 'Data di creazione' # published_at: 'Publication date' + # published_by: 'Published by' new: page_title: 'Salva un nuovo contenuto' placeholder: 'http://website.com' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml index 1937dfce..5a760b87 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml @@ -225,6 +225,7 @@ entry: annotations_on_the_entry: "{0} Pas cap d'anotacion|{1} Una anotacion|]1,Inf[ %count% anotacions" created_at: 'Data de creacion' # published_at: 'Publication date' + # published_by: 'Published by' new: page_title: 'Enregistrar un novèl article' placeholder: 'http://website.com' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml index cb644045..b2df8a0a 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml @@ -225,6 +225,7 @@ entry: annotations_on_the_entry: '{0} Nie ma adnotacji |{1} Jedna adnotacja |]1,Inf[ %count% adnotacji' created_at: 'Czas stworzenia' # published_at: 'Publication date' + # published_by: 'Published by' new: page_title: 'Zapisz nowy wpis' placeholder: 'http://website.com' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml index 16803549..fb8c4d29 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml @@ -225,6 +225,7 @@ entry: annotations_on_the_entry: '{0} Sem anotações|{1} Uma anotação|]1,Inf[ %nbAnnotations% anotações' created_at: 'Data de criação' # published_at: 'Publication date' + # published_by: 'Published by' new: page_title: 'Salvar nova entrada' placeholder: 'http://website.com' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml index 539482f8..d702159a 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml @@ -225,6 +225,7 @@ entry: # annotations_on_the_entry: '{0} No annotations|{1} One annotation|]1,Inf[ %count% annotations' created_at: 'Data creării' # published_at: 'Publication date' + # published_by: 'Published by' new: page_title: 'Salvează un nou articol' placeholder: 'http://website.com' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml index a3e1cca7..6525afac 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml @@ -225,6 +225,7 @@ entry: # annotations_on_the_entry: '{0} No annotations|{1} One annotation|]1,Inf[ %count% annotations' created_at: 'Oluşturulma tarihi' # published_at: 'Publication date' + # published_by: 'Published by' new: page_title: 'Yeni makaleyi kaydet' placeholder: 'http://website.com' diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Entry/entry.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Entry/entry.html.twig index 8bc7b54c..426ce91c 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Entry/entry.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Entry/entry.html.twig @@ -47,12 +47,20 @@ {{ entry.createdAt|date('Y-m-d H:i') }} - {% if entry.publishedAt is not null %} + {% if entry.publishedAt is not null %} {{ entry.publishedAt|date('Y-m-d H:i') }} {% endif %} + {% if entry.publishedBy is not empty %} + + {% for author in entry.publishedBy %} + {{ author }}{% if not loop.last %}, {% endif %} + {% endfor %} + + {% endif %} + {% set readingTime = entry.readingTime / app.user.config.readingSpeed %} {% if readingTime > 0 %} diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entry.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entry.html.twig index c72a22c0..8be5fd0d 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entry.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entry.html.twig @@ -228,12 +228,20 @@ today {{ entry.createdAt|date('Y-m-d H:i') }}
  • - {% if entry.publishedAt is not null %} + {% if entry.publishedAt is not null %}
  • create {{ entry.publishedAt|date('Y-m-d H:i') }}
  • {% endif %} + {% if entry.publishedBy is not empty %} +
  • + person + {% for author in entry.publishedBy %} + {{ author }}{% if not loop.last %}, {% endif %} + {% endfor %} +
  • + {% endif %}
  • link -- cgit v1.2.3 From 15e4aea67842ae83f98d9864c5bdafa056381248 Mon Sep 17 00:00:00 2001 From: Maxime Date: Fri, 7 Apr 2017 22:23:20 +0200 Subject: Remove isPublic from Entry entity fix #2598 --- src/Wallabag/CoreBundle/Entity/Entry.php | 25 ------------------------- 1 file changed, 25 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Entity/Entry.php b/src/Wallabag/CoreBundle/Entity/Entry.php index 7276b437..bbb1fb53 100644 --- a/src/Wallabag/CoreBundle/Entity/Entry.php +++ b/src/Wallabag/CoreBundle/Entity/Entry.php @@ -174,15 +174,6 @@ class Entry */ private $previewPicture; - /** - * @var bool - * - * @ORM\Column(name="is_public", type="boolean", nullable=true, options={"default" = false}) - * - * @Groups({"export_all"}) - */ - private $isPublic; - /** * @var string * @@ -531,22 +522,6 @@ class Entry $this->domainName = $domainName; } - /** - * @return bool - */ - public function isPublic() - { - return $this->isPublic; - } - - /** - * @param bool $isPublic - */ - public function setIsPublic($isPublic) - { - $this->isPublic = $isPublic; - } - /** * @return ArrayCollection */ -- cgit v1.2.3 From 01736b5a2ee2a48403a2462014886bf009f18786 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20L=C5=93uillet?= Date: Thu, 13 Apr 2017 12:57:31 +0200 Subject: Removed is_public in Entry edit form --- src/Wallabag/CoreBundle/Form/Type/EditEntryType.php | 5 ----- src/Wallabag/CoreBundle/Resources/translations/messages.da.yml | 1 - src/Wallabag/CoreBundle/Resources/translations/messages.de.yml | 1 - src/Wallabag/CoreBundle/Resources/translations/messages.en.yml | 1 - src/Wallabag/CoreBundle/Resources/translations/messages.es.yml | 1 - src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml | 1 - src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml | 1 - src/Wallabag/CoreBundle/Resources/translations/messages.it.yml | 1 - src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml | 1 - src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml | 1 - src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml | 1 - src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml | 1 - src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml | 1 - .../CoreBundle/Resources/views/themes/material/Entry/edit.html.twig | 5 ----- 14 files changed, 22 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Form/Type/EditEntryType.php b/src/Wallabag/CoreBundle/Form/Type/EditEntryType.php index 40e5b5b9..1627cc44 100644 --- a/src/Wallabag/CoreBundle/Form/Type/EditEntryType.php +++ b/src/Wallabag/CoreBundle/Form/Type/EditEntryType.php @@ -3,7 +3,6 @@ namespace Wallabag\CoreBundle\Form\Type; use Symfony\Component\Form\AbstractType; -use Symfony\Component\Form\Extension\Core\Type\CheckboxType; use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilderInterface; @@ -18,10 +17,6 @@ class EditEntryType extends AbstractType 'required' => true, 'label' => 'entry.edit.title_label', ]) - ->add('is_public', CheckboxType::class, [ - 'required' => false, - 'label' => 'entry.edit.is_public_label', - ]) ->add('url', TextType::class, [ 'disabled' => true, 'required' => false, diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml index dfac7a65..ff89a6d1 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml @@ -235,7 +235,6 @@ entry: # page_title: 'Edit an entry' # title_label: 'Title' url_label: 'Url' - # is_public_label: 'Public' save_label: 'Gem' public: # shared_by_wallabag: "This article has been shared by wallabag" diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml index 0b9df325..99b15b0d 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml @@ -235,7 +235,6 @@ entry: page_title: 'Eintrag bearbeiten' title_label: 'Titel' url_label: 'URL' - is_public_label: 'Öffentlich' save_label: 'Speichern' public: shared_by_wallabag: "Dieser Artikel wurde mittels wallabag geteilt" diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml index 2fa3192e..273ba25d 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml @@ -235,7 +235,6 @@ entry: page_title: 'Edit an entry' title_label: 'Title' url_label: 'Url' - is_public_label: 'Public' save_label: 'Save' public: shared_by_wallabag: "This article has been shared by wallabag" diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml index ce581d89..87c6954f 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml @@ -235,7 +235,6 @@ entry: page_title: 'Editar un artículo' title_label: 'Título' url_label: 'URL' - is_public_label: 'Es público' save_label: 'Guardar' public: shared_by_wallabag: "Este artículo se ha compartido con wallabag" diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml index 3e3ee12c..caafd6d7 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml @@ -235,7 +235,6 @@ entry: page_title: 'ویرایش مقاله' title_label: 'عنوان' url_label: 'نشانی' - is_public_label: 'عمومی' save_label: 'ذخیره' public: # shared_by_wallabag: "This article has been shared by wallabag" diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml index 074593a6..72366513 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml @@ -235,7 +235,6 @@ entry: page_title: "Éditer un article" title_label: "Titre" url_label: "Adresse" - is_public_label: "Public" save_label: "Enregistrer" public: shared_by_wallabag: "Cet article a été partagé par wallabag" diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml index 0d86756a..52f05b87 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml @@ -235,7 +235,6 @@ entry: page_title: 'Modifica voce' title_label: 'Titolo' url_label: 'Url' - is_public_label: 'Pubblico' save_label: 'Salva' public: # shared_by_wallabag: "This article has been shared by wallabag" diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml index d2949c50..c8b0e783 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml @@ -235,7 +235,6 @@ entry: page_title: 'Modificar un article' title_label: 'Títol' url_label: 'Url' - is_public_label: 'Public' save_label: 'Enregistrar' public: shared_by_wallabag: "Aqueste article es estat partejat per wallabag" diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml index 1f512942..e586ea84 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml @@ -235,7 +235,6 @@ entry: page_title: 'Edytuj wpis' title_label: 'Tytuł' url_label: 'Adres URL' - is_public_label: 'Publiczny' save_label: 'Zapisz' public: shared_by_wallabag: "Ten artykuł został udostępniony przez wallabag" diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml index 2e815230..09ddd7f8 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml @@ -235,7 +235,6 @@ entry: page_title: 'Editar uma entrada' title_label: 'Título' url_label: 'Url' - is_public_label: 'Público' save_label: 'Salvar' public: shared_by_wallabag: "Este artigo foi compartilhado pelo wallabag" diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml index 16401efd..cdd0be9f 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml @@ -235,7 +235,6 @@ entry: # page_title: 'Edit an entry' # title_label: 'Title' url_label: 'Url' - # is_public_label: 'Public' save_label: 'Salvează' public: # shared_by_wallabag: "This article has been shared by wallabag" diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml index a4bf7dfe..ae05e036 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml @@ -235,7 +235,6 @@ entry: page_title: 'Makaleyi düzenle' title_label: 'Başlık' url_label: 'Url' - is_public_label: 'Herkes tarafından erişime açık olsun mu?' save_label: 'Kaydet' public: # shared_by_wallabag: "This article has been shared by wallabag" diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/edit.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/edit.html.twig index 1c5e2aab..b9537975 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/edit.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/edit.html.twig @@ -27,11 +27,6 @@ {{ form_label(form.url) }} {{ form_widget(form.url) }} - -
    - {{ form_widget(form.is_public) }} - {{ form_label(form.is_public) }} -

    {{ form_widget(form.save, {'attr': {'class': 'btn waves-effect waves-light'}}) }} -- cgit v1.2.3 From fdd725f58cfe96d9bb9454d0347f6ff847fce69d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20L=C5=93uillet?= Date: Thu, 20 Apr 2017 14:58:20 +0200 Subject: Added notmatches operator for tagging rule --- .../DataFixtures/ORM/LoadTaggingRuleData.php | 7 ++++++ src/Wallabag/CoreBundle/Entity/TaggingRule.php | 4 ++-- .../CoreBundle/Operator/Doctrine/NotMatches.php | 25 ++++++++++++++++++++++ .../CoreBundle/Operator/PHP/NotMatches.php | 21 ++++++++++++++++++ .../CoreBundle/Resources/config/services.yml | 10 +++++++++ .../Resources/translations/messages.da.yml | 2 +- .../Resources/translations/messages.de.yml | 1 + .../Resources/translations/messages.en.yml | 1 + .../Resources/translations/messages.es.yml | 1 + .../Resources/translations/messages.fa.yml | 1 + .../Resources/translations/messages.fr.yml | 1 + .../Resources/translations/messages.it.yml | 1 + .../Resources/translations/messages.oc.yml | 1 + .../Resources/translations/messages.pl.yml | 1 + .../Resources/translations/messages.pt.yml | 1 + .../Resources/translations/messages.ro.yml | 1 + .../Resources/translations/messages.tr.yml | 1 + .../views/themes/material/Config/index.html.twig | 4 ++-- 18 files changed, 79 insertions(+), 5 deletions(-) create mode 100644 src/Wallabag/CoreBundle/Operator/Doctrine/NotMatches.php create mode 100644 src/Wallabag/CoreBundle/Operator/PHP/NotMatches.php (limited to 'src') diff --git a/src/Wallabag/CoreBundle/DataFixtures/ORM/LoadTaggingRuleData.php b/src/Wallabag/CoreBundle/DataFixtures/ORM/LoadTaggingRuleData.php index 7efe6356..55abd63c 100644 --- a/src/Wallabag/CoreBundle/DataFixtures/ORM/LoadTaggingRuleData.php +++ b/src/Wallabag/CoreBundle/DataFixtures/ORM/LoadTaggingRuleData.php @@ -36,6 +36,13 @@ class LoadTaggingRuleData extends AbstractFixture implements OrderedFixtureInter $manager->persist($tr3); + $tr4 = new TaggingRule(); + $tr4->setRule('content notmatches "basket"'); + $tr4->setTags(['foot']); + $tr4->setConfig($this->getReference('admin-config')); + + $manager->persist($tr4); + $manager->flush(); } diff --git a/src/Wallabag/CoreBundle/Entity/TaggingRule.php b/src/Wallabag/CoreBundle/Entity/TaggingRule.php index 72651b19..84e11e26 100644 --- a/src/Wallabag/CoreBundle/Entity/TaggingRule.php +++ b/src/Wallabag/CoreBundle/Entity/TaggingRule.php @@ -31,7 +31,7 @@ class TaggingRule * @Assert\Length(max=255) * @RulerZAssert\ValidRule( * allowed_variables={"title", "url", "isArchived", "isStared", "content", "language", "mimetype", "readingTime", "domainName"}, - * allowed_operators={">", "<", ">=", "<=", "=", "is", "!=", "and", "not", "or", "matches"} + * allowed_operators={">", "<", ">=", "<=", "=", "is", "!=", "and", "not", "or", "matches", "notmatches"} * ) * @ORM\Column(name="rule", type="string", nullable=false) */ @@ -87,7 +87,7 @@ class TaggingRule /** * Set tags. * - * @param array $tags + * @param array $tags * * @return TaggingRule */ diff --git a/src/Wallabag/CoreBundle/Operator/Doctrine/NotMatches.php b/src/Wallabag/CoreBundle/Operator/Doctrine/NotMatches.php new file mode 100644 index 00000000..090da77c --- /dev/null +++ b/src/Wallabag/CoreBundle/Operator/Doctrine/NotMatches.php @@ -0,0 +1,25 @@ +subject
    is matches a search (case-insensitive).
    Example: title matches "football"' - + # notmatches: 'Tests that a subject is not matches a search (case-insensitive).
    Example: title notmatches "football"' entry: page_titles: # unread: 'Unread entries' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml index dbad8b16..893a4564 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml @@ -155,6 +155,7 @@ config: or: 'Eine Regel ODER die andere' and: 'Eine Regel UND eine andere' matches: 'Testet, ob eine Variable auf eine Suche zutrifft (Groß- und Kleinschreibung wird nicht berücksichtigt).
    Beispiel: title matches "Fußball"' + # notmatches: 'Tests that a subject is not matches a search (case-insensitive).
    Example: title notmatches "football"' entry: page_titles: diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml index 7da9fe6b..29f9938c 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml @@ -155,6 +155,7 @@ config: or: 'One rule OR another' and: 'One rule AND another' matches: 'Tests that a subject is matches a search (case-insensitive).
    Example: title matches "football"' + notmatches: 'Tests that a subject is not matches a search (case-insensitive).
    Example: title notmatches "football"' entry: page_titles: diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml index 6e21614e..99d25859 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml @@ -155,6 +155,7 @@ config: or: 'Una regla U otra' and: 'Una regla Y la otra' matches: 'Prueba si un sujeto corresponde a una búsqueda (insensible a mayusculas).
    Ejemplo : title matches "fútbol"' + # notmatches: 'Tests that a subject is not matches a search (case-insensitive).
    Example: title notmatches "football"' entry: page_titles: diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml index b938c80a..ccd9d555 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml @@ -155,6 +155,7 @@ config: # or: 'One rule OR another' # and: 'One rule AND another' # matches: 'Tests that a subject is matches a search (case-insensitive).
    Example: title matches "football"' + # notmatches: 'Tests that a subject is not matches a search (case-insensitive).
    Example: title notmatches "football"' entry: page_titles: diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml index 9abcda45..a0f100f7 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml @@ -155,6 +155,7 @@ config: or: "Une règle OU l’autre" and: "Une règle ET l’autre" matches: "Teste si un sujet correspond à une recherche (non sensible à la casse).
    Exemple : title matches \"football\"" + notmatches: "Teste si un sujet ne correspond pas à une recherche (non sensible à la casse).
    Exemple : title notmatches \"football\"" entry: page_titles: diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml index 58d0962a..374071ce 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml @@ -155,6 +155,7 @@ config: or: "Una regola O un'altra" and: "Una regola E un'altra" matches: 'Verifica che un oggetto risulti in una ricerca (case-insensitive).
    Esempio: titolo contiene "football"' + # notmatches: 'Tests that a subject is not matches a search (case-insensitive).
    Example: title notmatches "football"' entry: page_titles: diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml index 825a0efd..b01c611b 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml @@ -155,6 +155,7 @@ config: or: "Una règla O l'autra" and: "Una règla E l'autra" matches: 'Teste se un subjècte correspond a una recerca (non sensibla a la cassa).
    Exemple : title matches \"football\"' + # notmatches: 'Tests that a subject is not matches a search (case-insensitive).
    Example: title notmatches "football"' entry: page_titles: diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml index b02aa4ec..d76ac328 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml @@ -155,6 +155,7 @@ config: or: 'Jedna reguła LUB inna' and: 'Jedna reguła I inna' matches: 'Sprawdź czy temat pasuje szukaj (duże lub małe litery).
    Przykład: tytuł zawiera "piłka nożna"' + # notmatches: 'Tests that a subject is not matches a search (case-insensitive).
    Example: title notmatches "football"' entry: page_titles: diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml index 8aa7e5af..98dfcd25 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml @@ -155,6 +155,7 @@ config: or: 'Uma regra OU outra' and: 'Uma regra E outra' matches: 'Testa que um assunto corresponde a uma pesquisa (maiúscula ou minúscula).
    Exemplo: título corresponde a "futebol"' + # notmatches: 'Tests that a subject is not matches a search (case-insensitive).
    Example: title notmatches "football"' entry: page_titles: diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml index ce8d8d52..8c07c13f 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml @@ -155,6 +155,7 @@ config: # or: 'One rule OR another' # and: 'One rule AND another' # matches: 'Tests that a subject is matches a search (case-insensitive).
    Example: title matches "football"' + # notmatches: 'Tests that a subject is not matches a search (case-insensitive).
    Example: title notmatches "football"' entry: page_titles: diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml index d8903608..bd21cb67 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml @@ -155,6 +155,7 @@ config: or: 'Bir kural veya birbaşkası' and: 'Bir kural ve diğeri' # matches: 'Tests that a subject is matches a search (case-insensitive).
    Example: title matches "football"' + # notmatches: 'Tests that a subject is not matches a search (case-insensitive).
    Example: title notmatches "football"' entry: page_titles: diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/material/Config/index.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/material/Config/index.html.twig index 708ff951..d6e414e9 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/material/Config/index.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/material/Config/index.html.twig @@ -413,8 +413,8 @@ domainName {{ 'config.form_rules.faq.variable_description.domainName'|trans }} - matches - {{ 'config.form_rules.faq.operator_description.matches'|trans|raw }} + matches
    notmaches + {{ 'config.form_rules.faq.operator_description.matches'|trans|raw }}
    {{ 'config.form_rules.faq.operator_description.notmatches'|trans|raw }} -- cgit v1.2.3 From a375fed7bf34c07f760e4f0cda11b2af30dcbcdc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20L=C5=93uillet?= Date: Sat, 22 Apr 2017 13:14:34 +0200 Subject: Fixed @j0k3r review --- src/Wallabag/CoreBundle/Operator/Doctrine/NotMatches.php | 2 +- src/Wallabag/CoreBundle/Operator/PHP/NotMatches.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Operator/Doctrine/NotMatches.php b/src/Wallabag/CoreBundle/Operator/Doctrine/NotMatches.php index 090da77c..b7f9da57 100644 --- a/src/Wallabag/CoreBundle/Operator/Doctrine/NotMatches.php +++ b/src/Wallabag/CoreBundle/Operator/Doctrine/NotMatches.php @@ -10,7 +10,7 @@ namespace Wallabag\CoreBundle\Operator\Doctrine; * * This operator will be used to compile tagging rules in DQL, usable * by Doctrine ORM. - * It's registered in RulerZ using a service (wallabag.operator.doctrine.matches); + * It's registered in RulerZ using a service (wallabag.operator.doctrine.notmatches); */ class NotMatches { diff --git a/src/Wallabag/CoreBundle/Operator/PHP/NotMatches.php b/src/Wallabag/CoreBundle/Operator/PHP/NotMatches.php index eecb43cc..68b2676f 100644 --- a/src/Wallabag/CoreBundle/Operator/PHP/NotMatches.php +++ b/src/Wallabag/CoreBundle/Operator/PHP/NotMatches.php @@ -10,7 +10,7 @@ namespace Wallabag\CoreBundle\Operator\PHP; * * This operator will be used to compile tagging rules in PHP, usable * directly on Entry objects for instance. - * It's registered in RulerZ using a service (wallabag.operator.array.matches); + * It's registered in RulerZ using a service (wallabag.operator.array.notmatches); */ class NotMatches { -- cgit v1.2.3 From d1fc590211b8dc7360bf5b7ee01c67ccff0577ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20L=C5=93uillet?= Date: Mon, 24 Apr 2017 11:12:41 +0200 Subject: Added API endpoint to handle a list of URL and to add/delete tags --- .../ApiBundle/Controller/EntryRestController.php | 68 ++++++++++++++++++++++ 1 file changed, 68 insertions(+) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/EntryRestController.php b/src/Wallabag/ApiBundle/Controller/EntryRestController.php index af5f7603..fc46e782 100644 --- a/src/Wallabag/ApiBundle/Controller/EntryRestController.php +++ b/src/Wallabag/ApiBundle/Controller/EntryRestController.php @@ -438,4 +438,72 @@ class EntryRestController extends WallabagRestController return (new JsonResponse())->setJson($json); } + + /** + * Handles an entries list and add / delete to them some tags. + * + * @ApiDoc( + * parameters={ + * {"name"="list", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...','tags': 'tag1, tag2','action': 'delete'}, {'url': 'http://...','tags': 'tag1, tag2','action': 'add'}]", "description"="Urls (as an array) to handle."} + * } + * ) + * + * @return JsonResponse + */ + public function postEntriesTagsListAction(Request $request) + { + $this->validateAuthentication(); + + $list = json_decode($request->query->get('list', [])); + $results = []; + + // handle multiple urls + if (!empty($list)) { + $results = []; + foreach ($list as $key => $element) { + $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId( + $element->url, + $this->getUser()->getId() + ); + + $results[$key]['url'] = $element->url; + $results[$key]['action'] = $element->action; + $results[$key]['entry'] = $entry instanceof Entry ? $entry->getId() : false; + + $tags = $element->tags; + + if (false !== $entry && !(empty($tags))) { + switch ($element->action) { + case 'delete': + $tags = explode(',', $tags); + foreach ($tags as $label) { + $label = trim($label); + + $tag = $this->getDoctrine() + ->getRepository('WallabagCoreBundle:Tag') + ->findOneByLabel($label); + + if (false !== $tag) { + $entry->removeTag($tag); + } + } + + break; + case 'add': + $this->get('wallabag_core.content_proxy')->assignTagsToEntry($entry, $tags); + + break; + } + + $em = $this->getDoctrine()->getManager(); + $em->persist($entry); + $em->flush(); + } + } + } + + $json = $this->get('serializer')->serialize($results, 'json'); + + return (new JsonResponse())->setJson($json); + } } -- cgit v1.2.3 From 80299ed282d4f18ef92a79f29f9346b96acde468 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20L=C5=93uillet?= Date: Mon, 24 Apr 2017 12:24:17 +0200 Subject: Added endpoint to handle URL list to add/delete tags --- .../ApiBundle/Controller/EntryRestController.php | 85 ++++++++++++++++------ .../ApiBundle/Controller/TagRestController.php | 4 +- 2 files changed, 63 insertions(+), 26 deletions(-) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/EntryRestController.php b/src/Wallabag/ApiBundle/Controller/EntryRestController.php index fc46e782..5ccaa4ef 100644 --- a/src/Wallabag/ApiBundle/Controller/EntryRestController.php +++ b/src/Wallabag/ApiBundle/Controller/EntryRestController.php @@ -440,17 +440,17 @@ class EntryRestController extends WallabagRestController } /** - * Handles an entries list and add / delete to them some tags. + * Handles an entries list delete tags from them. * * @ApiDoc( * parameters={ - * {"name"="list", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...','tags': 'tag1, tag2','action': 'delete'}, {'url': 'http://...','tags': 'tag1, tag2','action': 'add'}]", "description"="Urls (as an array) to handle."} + * {"name"="list", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...','tags': 'tag1, tag2'}, {'url': 'http://...','tags': 'tag1, tag2'}]", "description"="Urls (as an array) to handle."} * } * ) * * @return JsonResponse */ - public function postEntriesTagsListAction(Request $request) + public function deleteEntriesTagsListAction(Request $request) { $this->validateAuthentication(); @@ -467,32 +467,22 @@ class EntryRestController extends WallabagRestController ); $results[$key]['url'] = $element->url; - $results[$key]['action'] = $element->action; $results[$key]['entry'] = $entry instanceof Entry ? $entry->getId() : false; $tags = $element->tags; if (false !== $entry && !(empty($tags))) { - switch ($element->action) { - case 'delete': - $tags = explode(',', $tags); - foreach ($tags as $label) { - $label = trim($label); - - $tag = $this->getDoctrine() - ->getRepository('WallabagCoreBundle:Tag') - ->findOneByLabel($label); - - if (false !== $tag) { - $entry->removeTag($tag); - } - } - - break; - case 'add': - $this->get('wallabag_core.content_proxy')->assignTagsToEntry($entry, $tags); - - break; + $tags = explode(',', $tags); + foreach ($tags as $label) { + $label = trim($label); + + $tag = $this->getDoctrine() + ->getRepository('WallabagCoreBundle:Tag') + ->findOneByLabel($label); + + if (false !== $tag) { + $entry->removeTag($tag); + } } $em = $this->getDoctrine()->getManager(); @@ -506,4 +496,51 @@ class EntryRestController extends WallabagRestController return (new JsonResponse())->setJson($json); } + + /** + * Handles an entries list and add tags to them. + * + * @ApiDoc( + * parameters={ + * {"name"="list", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...','tags': 'tag1, tag2'}, {'url': 'http://...','tags': 'tag1, tag2'}]", "description"="Urls (as an array) to handle."} + * } + * ) + * + * @return JsonResponse + */ + public function postEntriesTagsListAction(Request $request) + { + $this->validateAuthentication(); + + $list = json_decode($request->query->get('list', [])); + $results = []; + + // handle multiple urls + if (!empty($list)) { + $results = []; + foreach ($list as $key => $element) { + $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId( + $element->url, + $this->getUser()->getId() + ); + + $results[$key]['url'] = $element->url; + $results[$key]['entry'] = $entry instanceof Entry ? $entry->getId() : false; + + $tags = $element->tags; + + if (false !== $entry && !(empty($tags))) { + $this->get('wallabag_core.content_proxy')->assignTagsToEntry($entry, $tags); + + $em = $this->getDoctrine()->getManager(); + $em->persist($entry); + $em->flush(); + } + } + } + + $json = $this->get('serializer')->serialize($results, 'json'); + + return (new JsonResponse())->setJson($json); + } } diff --git a/src/Wallabag/ApiBundle/Controller/TagRestController.php b/src/Wallabag/ApiBundle/Controller/TagRestController.php index bc6d4e64..47298d7e 100644 --- a/src/Wallabag/ApiBundle/Controller/TagRestController.php +++ b/src/Wallabag/ApiBundle/Controller/TagRestController.php @@ -31,7 +31,7 @@ class TagRestController extends WallabagRestController } /** - * Permanently remove one tag from **every** entry. + * Permanently remove one tag from **every** entry by passing the Tag label. * * @ApiDoc( * requirements={ @@ -106,7 +106,7 @@ class TagRestController extends WallabagRestController } /** - * Permanently remove one tag from **every** entry. + * Permanently remove one tag from **every** entry by passing the Tag ID. * * @ApiDoc( * requirements={ -- cgit v1.2.3 From dcbebc17aaa50ea16eb0b7e379c14ebbcf0a645a Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Sat, 29 Apr 2017 12:58:39 +0200 Subject: Fix tests --- src/Wallabag/ApiBundle/Controller/EntryRestController.php | 2 -- 1 file changed, 2 deletions(-) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/EntryRestController.php b/src/Wallabag/ApiBundle/Controller/EntryRestController.php index 5ccaa4ef..7590efbb 100644 --- a/src/Wallabag/ApiBundle/Controller/EntryRestController.php +++ b/src/Wallabag/ApiBundle/Controller/EntryRestController.php @@ -459,7 +459,6 @@ class EntryRestController extends WallabagRestController // handle multiple urls if (!empty($list)) { - $results = []; foreach ($list as $key => $element) { $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId( $element->url, @@ -517,7 +516,6 @@ class EntryRestController extends WallabagRestController // handle multiple urls if (!empty($list)) { - $results = []; foreach ($list as $key => $element) { $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId( $element->url, -- cgit v1.2.3 From 1eca7831a69b9470b92dcc72e1ce51b42b291338 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20L=C5=93uillet?= Date: Mon, 24 Apr 2017 10:22:57 +0200 Subject: Added API endpoint to handle a list of URL By passing an array, you can add / delete URL in mass (bulk request) --- .../ApiBundle/Controller/EntryRestController.php | 71 ++++++++++++++++++++++ 1 file changed, 71 insertions(+) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/EntryRestController.php b/src/Wallabag/ApiBundle/Controller/EntryRestController.php index 7590efbb..3833ce3c 100644 --- a/src/Wallabag/ApiBundle/Controller/EntryRestController.php +++ b/src/Wallabag/ApiBundle/Controller/EntryRestController.php @@ -172,6 +172,77 @@ class EntryRestController extends WallabagRestController ->exportAs($request->attributes->get('_format')); } + /** + * Handles an entries list and create or remove URL. + * + * @ApiDoc( + * parameters={ + * {"name"="list", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...', 'action': 'delete'}, {'url': 'http://...', 'action': 'add'}]", "description"="Urls (as an array) to handle."} + * } + * ) + * + * @return JsonResponse + */ + public function postEntriesListAction(Request $request) + { + $this->validateAuthentication(); + + $list = json_decode($request->query->get('list', [])); + $results = []; + + // handle multiple urls + if (!empty($list)) { + $results = []; + foreach ($list as $key => $element) { + $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId( + $element->url, + $this->getUser()->getId() + ); + + $results[$key]['url'] = $element->url; + $results[$key]['action'] = $element->action; + + switch ($element->action) { + case 'delete': + if (false !== $entry) { + $em = $this->getDoctrine()->getManager(); + $em->remove($entry); + $em->flush(); + + // entry deleted, dispatch event about it! + $this->get('event_dispatcher')->dispatch(EntryDeletedEvent::NAME, new EntryDeletedEvent($entry)); + } + + $results[$key]['entry'] = $entry instanceof Entry ? true : false; + + break; + case 'add': + if (false === $entry) { + $entry = $this->get('wallabag_core.content_proxy')->updateEntry( + new Entry($this->getUser()), + $element->url + ); + } + + $em = $this->getDoctrine()->getManager(); + $em->persist($entry); + $em->flush(); + + $results[$key]['entry'] = $entry instanceof Entry ? $entry->getId() : false; + + // entry saved, dispatch event about it! + $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry)); + + break; + } + } + } + + $json = $this->get('serializer')->serialize($results, 'json'); + + return (new JsonResponse())->setJson($json); + } + /** * Create an entry. * -- cgit v1.2.3 From a7abcc7b7a5e3417eff70e2a5993558f83fc5d5a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20L=C5=93uillet?= Date: Mon, 24 Apr 2017 11:31:00 +0200 Subject: Splitted the endpoint in two --- .../ApiBundle/Controller/EntryRestController.php | 96 ++++++++++++++-------- 1 file changed, 62 insertions(+), 34 deletions(-) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/EntryRestController.php b/src/Wallabag/ApiBundle/Controller/EntryRestController.php index 3833ce3c..0c98c242 100644 --- a/src/Wallabag/ApiBundle/Controller/EntryRestController.php +++ b/src/Wallabag/ApiBundle/Controller/EntryRestController.php @@ -173,68 +173,96 @@ class EntryRestController extends WallabagRestController } /** - * Handles an entries list and create or remove URL. + * Handles an entries list and delete URL. * * @ApiDoc( * parameters={ - * {"name"="list", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...', 'action': 'delete'}, {'url': 'http://...', 'action': 'add'}]", "description"="Urls (as an array) to handle."} + * {"name"="urls", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...'}, {'url': 'http://...'}]", "description"="Urls (as an array) to delete."} * } * ) * * @return JsonResponse */ - public function postEntriesListAction(Request $request) + public function deleteEntriesListAction(Request $request) { $this->validateAuthentication(); - $list = json_decode($request->query->get('list', [])); + $urls = json_decode($request->query->get('urls', [])); $results = []; // handle multiple urls - if (!empty($list)) { + if (!empty($urls)) { $results = []; - foreach ($list as $key => $element) { + foreach ($urls as $key => $url) { $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId( - $element->url, + $url, $this->getUser()->getId() ); - $results[$key]['url'] = $element->url; - $results[$key]['action'] = $element->action; + $results[$key]['url'] = $url; - switch ($element->action) { - case 'delete': - if (false !== $entry) { - $em = $this->getDoctrine()->getManager(); - $em->remove($entry); - $em->flush(); + if (false !== $entry) { + $em = $this->getDoctrine()->getManager(); + $em->remove($entry); + $em->flush(); - // entry deleted, dispatch event about it! - $this->get('event_dispatcher')->dispatch(EntryDeletedEvent::NAME, new EntryDeletedEvent($entry)); - } + // entry deleted, dispatch event about it! + $this->get('event_dispatcher')->dispatch(EntryDeletedEvent::NAME, new EntryDeletedEvent($entry)); + } - $results[$key]['entry'] = $entry instanceof Entry ? true : false; + $results[$key]['entry'] = $entry instanceof Entry ? true : false; + } + } - break; - case 'add': - if (false === $entry) { - $entry = $this->get('wallabag_core.content_proxy')->updateEntry( - new Entry($this->getUser()), - $element->url - ); - } + $json = $this->get('serializer')->serialize($results, 'json'); + + return (new JsonResponse())->setJson($json); + } + + /** + * Handles an entries list and create URL. + * + * @ApiDoc( + * parameters={ + * {"name"="urls", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...'}, {'url': 'http://...'}]", "description"="Urls (as an array) to create."} + * } + * ) + * + * @return JsonResponse + */ + public function postEntriesListAction(Request $request) + { + $this->validateAuthentication(); - $em = $this->getDoctrine()->getManager(); - $em->persist($entry); - $em->flush(); + $urls = json_decode($request->query->get('urls', [])); + $results = []; - $results[$key]['entry'] = $entry instanceof Entry ? $entry->getId() : false; + // handle multiple urls + if (!empty($urls)) { + $results = []; + foreach ($urls as $key => $url) { + $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId( + $url, + $this->getUser()->getId() + ); - // entry saved, dispatch event about it! - $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry)); + $results[$key]['url'] = $url; - break; + if (false === $entry) { + $entry = $this->get('wallabag_core.content_proxy')->updateEntry( + new Entry($this->getUser()), + $url + ); } + + $em = $this->getDoctrine()->getManager(); + $em->persist($entry); + $em->flush(); + + $results[$key]['entry'] = $entry instanceof Entry ? $entry->getId() : false; + + // entry saved, dispatch event about it! + $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry)); } } -- cgit v1.2.3 From 719ba257d3d6495eaa0f4ea749b5aa4740f94dda Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Sat, 29 Apr 2017 12:24:27 +0200 Subject: Fix tests --- src/Wallabag/ApiBundle/Controller/EntryRestController.php | 1 - 1 file changed, 1 deletion(-) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/EntryRestController.php b/src/Wallabag/ApiBundle/Controller/EntryRestController.php index 0c98c242..ae6f0e3f 100644 --- a/src/Wallabag/ApiBundle/Controller/EntryRestController.php +++ b/src/Wallabag/ApiBundle/Controller/EntryRestController.php @@ -239,7 +239,6 @@ class EntryRestController extends WallabagRestController // handle multiple urls if (!empty($urls)) { - $results = []; foreach ($urls as $key => $url) { $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId( $url, -- cgit v1.2.3 From efd351c98fa0caa4c8df9c7ff6965c537524f12a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20L=C5=93uillet?= Date: Mon, 1 May 2017 09:21:59 +0200 Subject: Added limit --- src/Wallabag/ApiBundle/Controller/EntryRestController.php | 9 +++++++++ src/Wallabag/CoreBundle/DependencyInjection/Configuration.php | 3 +++ .../CoreBundle/DependencyInjection/WallabagCoreExtension.php | 1 + 3 files changed, 13 insertions(+) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/EntryRestController.php b/src/Wallabag/ApiBundle/Controller/EntryRestController.php index ae6f0e3f..7c3e778e 100644 --- a/src/Wallabag/ApiBundle/Controller/EntryRestController.php +++ b/src/Wallabag/ApiBundle/Controller/EntryRestController.php @@ -5,6 +5,7 @@ namespace Wallabag\ApiBundle\Controller; use Hateoas\Configuration\Route; use Hateoas\Representation\Factory\PagerfantaFactory; use Nelmio\ApiDocBundle\Annotation\ApiDoc; +use Symfony\Component\Config\Definition\Exception\Exception; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; @@ -229,6 +230,8 @@ class EntryRestController extends WallabagRestController * ) * * @return JsonResponse + * + * @throws Symfony\Component\Config\Definition\Exception\Exception When limit is reached */ public function postEntriesListAction(Request $request) { @@ -237,6 +240,12 @@ class EntryRestController extends WallabagRestController $urls = json_decode($request->query->get('urls', [])); $results = []; + $limit = $this->container->getParameter('wallabag_core.api_limit_mass_actions'); + + if (count($urls) > $limit) { + throw new Exception('API limit reached'); + } + // handle multiple urls if (!empty($urls)) { foreach ($urls as $key => $url) { diff --git a/src/Wallabag/CoreBundle/DependencyInjection/Configuration.php b/src/Wallabag/CoreBundle/DependencyInjection/Configuration.php index 006a18c3..75b37729 100644 --- a/src/Wallabag/CoreBundle/DependencyInjection/Configuration.php +++ b/src/Wallabag/CoreBundle/DependencyInjection/Configuration.php @@ -47,6 +47,9 @@ class Configuration implements ConfigurationInterface ->scalarNode('list_mode') ->defaultValue(1) ->end() + ->scalarNode('api_limit_mass_actions') + ->defaultValue(10) + ->end() ->end() ; diff --git a/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php b/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php index aa9ee339..c075c19f 100644 --- a/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php +++ b/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php @@ -26,6 +26,7 @@ class WallabagCoreExtension extends Extension $container->setParameter('wallabag_core.action_mark_as_read', $config['action_mark_as_read']); $container->setParameter('wallabag_core.list_mode', $config['list_mode']); $container->setParameter('wallabag_core.fetching_error_message', $config['fetching_error_message']); + $container->setParameter('wallabag_core.api_limit_mass_actions', $config['api_limit_mass_actions']); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.yml'); -- cgit v1.2.3 From e2f3800ccb884682547769d9e4b5d6b7cafe4e07 Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Fri, 24 Feb 2017 11:27:03 +0100 Subject: Add Clean Duplicates Command --- .../CoreBundle/Command/CleanDuplicatesCommand.php | 119 +++++++++++++++++++++ .../CoreBundle/Repository/EntryRepository.php | 13 +++ 2 files changed, 132 insertions(+) create mode 100644 src/Wallabag/CoreBundle/Command/CleanDuplicatesCommand.php (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Command/CleanDuplicatesCommand.php b/src/Wallabag/CoreBundle/Command/CleanDuplicatesCommand.php new file mode 100644 index 00000000..65f35d8e --- /dev/null +++ b/src/Wallabag/CoreBundle/Command/CleanDuplicatesCommand.php @@ -0,0 +1,119 @@ +setName('wallabag:clean-duplicates') + ->setDescription('Cleans the database for duplicates') + ->setHelp('This command helps you to clean your articles list in case of duplicates') + ->addArgument( + 'username', + InputArgument::OPTIONAL, + 'User to clean' + ); + } + + protected function execute(InputInterface $input, OutputInterface $output) + { + $this->output = $output; + + $username = $input->getArgument('username'); + + if ($username) { + try { + $user = $this->getUser($username); + $this->cleanDuplicates($user); + } catch (NoResultException $e) { + $output->writeln(sprintf('User "%s" not found.', $username)); + + return 1; + } + } else { + $users = $this->getDoctrine()->getRepository('WallabagUserBundle:User')->findAll(); + + $output->writeln(sprintf('Cleaning through %d user accounts', count($users))); + + foreach ($users as $user) { + $output->writeln(sprintf('Processing user %s', $user->getUsername())); + $this->cleanDuplicates($user); + } + $output->writeln(sprintf('Finished cleaning. %d duplicates found in total', $this->duplicates)); + } + + return 0; + } + + /** + * @param User $user + */ + private function cleanDuplicates(User $user) + { + $em = $this->getContainer()->get('doctrine.orm.entity_manager'); + $repo = $this->getDoctrine()->getRepository('WallabagCoreBundle:Entry'); + + $entries = $repo->getAllEntriesIdAndUrl($user->getId()); + + $duplicatesCount = 0; + $urls = []; + foreach ($entries as $entry) { + $url = $this->similarUrl($entry['url']); + + /* @var $entry Entry */ + if (in_array($url, $urls)) { + ++$duplicatesCount; + + $em->remove($repo->find($entry['id'])); + $em->flush(); // Flushing at the end of the loop would require the instance not being online + } else { + $urls[] = $entry['url']; + } + } + + $this->duplicates += $duplicatesCount; + + $this->output->writeln(sprintf('Cleaned %d duplicates for user %s', $duplicatesCount, $user->getUserName())); + } + + private function similarUrl($url) + { + if (in_array(substr($url, -1), ['/', '#'])) { // get rid of "/" and "#" and the end of urls + return substr($url, 0, strlen($url)); + } + + return $url; + } + + /** + * Fetches a user from its username. + * + * @param string $username + * + * @return \Wallabag\UserBundle\Entity\User + */ + private function getUser($username) + { + return $this->getDoctrine()->getRepository('WallabagUserBundle:User')->findOneByUserName($username); + } + + private function getDoctrine() + { + return $this->getContainer()->get('doctrine'); + } +} diff --git a/src/Wallabag/CoreBundle/Repository/EntryRepository.php b/src/Wallabag/CoreBundle/Repository/EntryRepository.php index 1f22e901..5e7b0d3a 100644 --- a/src/Wallabag/CoreBundle/Repository/EntryRepository.php +++ b/src/Wallabag/CoreBundle/Repository/EntryRepository.php @@ -379,4 +379,17 @@ class EntryRepository extends EntityRepository ->setParameter('userId', $userId) ->execute(); } + + /** + * Get id and url from all entries + * Used for the clean-duplicates command. + */ + public function getAllEntriesIdAndUrl($userId) + { + $qb = $this->createQueryBuilder('e') + ->select('e.id, e.url') + ->where('e.user = :userid')->setParameter(':userid', $userId); + + return $qb->getQuery()->getArrayResult(); + } } -- cgit v1.2.3 From c37515f880bd05b86e3e848cc184018295ec1920 Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Thu, 27 Apr 2017 15:58:32 +0200 Subject: Add filter to users management page Signed-off-by: Thomas Citharel --- .../Resources/translations/messages.da.yml | 3 ++ .../Resources/translations/messages.de.yml | 3 ++ .../Resources/translations/messages.en.yml | 3 ++ .../Resources/translations/messages.es.yml | 3 ++ .../Resources/translations/messages.fa.yml | 3 ++ .../Resources/translations/messages.fr.yml | 3 ++ .../Resources/translations/messages.it.yml | 3 ++ .../Resources/translations/messages.oc.yml | 3 ++ .../Resources/translations/messages.pl.yml | 3 ++ .../Resources/translations/messages.pt.yml | 3 ++ .../Resources/translations/messages.ro.yml | 3 ++ .../Resources/translations/messages.tr.yml | 3 ++ .../UserBundle/Controller/ManageController.php | 42 +++++++++++++++ src/Wallabag/UserBundle/Form/SearchUserType.php | 29 ++++++++++ .../UserBundle/Repository/UserRepository.php | 15 ++++++ .../Resources/views/Manage/index.html.twig | 61 ++++++++++++---------- .../Resources/views/Manage/search_form.html.twig | 15 ++++++ 17 files changed, 170 insertions(+), 28 deletions(-) create mode 100644 src/Wallabag/UserBundle/Form/SearchUserType.php create mode 100644 src/Wallabag/UserBundle/Resources/views/Manage/search_form.html.twig (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml index 72493fe3..68fcec5c 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml @@ -512,6 +512,9 @@ user: # delete: Delete # delete_confirm: Are you sure? # back_to_list: Back to list + search: + # label: Filter + # placeholder: Filter by username or email error: # page_title: An error occurred diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml index dbad8b16..be117231 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml @@ -512,6 +512,9 @@ user: delete: Löschen delete_confirm: Bist du sicher? back_to_list: Zurück zur Liste + search: + # label: Filter + # placeholder: Filter by username or email error: page_title: Ein Fehler ist aufgetreten diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml index 42a12b2a..b3850893 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml @@ -512,6 +512,9 @@ user: delete: Delete delete_confirm: Are you sure? back_to_list: Back to list + search: + label: Filter + placeholder: Filter by username or email error: page_title: An error occurred diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml index 6e21614e..ebf6745a 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml @@ -512,6 +512,9 @@ user: delete: Eliminar delete_confirm: ¿Estás seguro? back_to_list: Volver a la lista + search: + # label: Filter + # placeholder: Filter by username or email error: page_title: Ha ocurrido un error diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml index b938c80a..46460e13 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml @@ -512,6 +512,9 @@ user: # delete: Delete # delete_confirm: Are you sure? # back_to_list: Back to list + search: + # label: Filter + # placeholder: Filter by username or email error: # page_title: An error occurred diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml index 9abcda45..c968f7ab 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml @@ -512,6 +512,9 @@ user: delete: "Supprimer" delete_confirm: "Voulez-vous vraiment ?" back_to_list: "Revenir à la liste" + search: + label: Filtrer + placeholder: Filtrer par nom d'utilisateur ou email error: page_title: Une erreur est survenue diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml index 58d0962a..53b5e1b9 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml @@ -512,6 +512,9 @@ user: # delete: Delete # delete_confirm: Are you sure? # back_to_list: Back to list + search: + # label: Filter + # placeholder: Filter by username or email error: # page_title: An error occurred diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml index 825a0efd..c6614a63 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml @@ -512,6 +512,9 @@ user: delete: 'Suprimir' delete_confirm: 'Sètz segur ?' back_to_list: 'Tornar a la lista' + search: + # label: Filter + # placeholder: Filter by username or email error: page_title: Una error s'es produsida diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml index b02aa4ec..b464d0f6 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml @@ -512,6 +512,9 @@ user: delete: Usuń delete_confirm: Jesteś pewien? back_to_list: Powrót do listy + search: + # label: Filter + # placeholder: Filter by username or email error: page_title: Wystąpił błąd diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml index 8aa7e5af..2b0b1686 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml @@ -512,6 +512,9 @@ user: delete: 'Apagar' delete_confirm: 'Tem certeza?' back_to_list: 'Voltar para a lista' + search: + # label: Filter + # placeholder: Filter by username or email error: # page_title: An error occurred diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml index ce8d8d52..210978d0 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml @@ -512,6 +512,9 @@ user: # delete: Delete # delete_confirm: Are you sure? # back_to_list: Back to list + search: + # label: Filter + # placeholder: Filter by username or email error: # page_title: An error occurred diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml index d8903608..5ff5e012 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml @@ -512,6 +512,9 @@ user: # delete: Delete # delete_confirm: Are you sure? # back_to_list: Back to list + search: + # label: Filter + # placeholder: Filter by username or email error: # page_title: An error occurred diff --git a/src/Wallabag/UserBundle/Controller/ManageController.php b/src/Wallabag/UserBundle/Controller/ManageController.php index 92ee2b41..f0e3d4de 100644 --- a/src/Wallabag/UserBundle/Controller/ManageController.php +++ b/src/Wallabag/UserBundle/Controller/ManageController.php @@ -10,6 +10,7 @@ use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Wallabag\UserBundle\Entity\User; use Wallabag\CoreBundle\Entity\Config; +use Wallabag\UserBundle\Form\SearchUserType; /** * User controller. @@ -146,4 +147,45 @@ class ManageController extends Controller ->getForm() ; } + + /** + * @param Request $request + * @param int $page + * + * @Route("/search/{page}", name="user-search", defaults={"page" = 1}) + * + * Default parameter for page is hardcoded (in duplication of the defaults from the Route) + * because this controller is also called inside the layout template without any page as argument + * + * @return \Symfony\Component\HttpFoundation\Response + */ + public function searchFormAction(Request $request, $page = 1, $currentRoute = null) + { + // fallback to retrieve currentRoute from query parameter instead of injected one (when using inside a template) + if (null === $currentRoute && $request->query->has('currentRoute')) { + $currentRoute = $request->query->get('currentRoute'); + } + + $form = $this->createForm(SearchUserType::class); + + $form->handleRequest($request); + + if ($form->isSubmitted() && $form->isValid()) { + $this->get('logger')->info('searching users'); + $em = $this->getDoctrine()->getManager(); + + $searchTerm = (isset($request->get('search_user')['term']) ? $request->get('search_user')['term'] : ''); + + $users = $em->getRepository('WallabagUserBundle:User')->getUsersForSearch($searchTerm); + + return $this->render('WallabagUserBundle:Manage:index.html.twig', array( + 'users' => $users, + )); + } + + return $this->render('WallabagUserBundle:Manage:search_form.html.twig', [ + 'form' => $form->createView(), + 'currentRoute' => $currentRoute, + ]); + } } diff --git a/src/Wallabag/UserBundle/Form/SearchUserType.php b/src/Wallabag/UserBundle/Form/SearchUserType.php new file mode 100644 index 00000000..9ce46ee1 --- /dev/null +++ b/src/Wallabag/UserBundle/Form/SearchUserType.php @@ -0,0 +1,29 @@ +setMethod('GET') + ->add('term', TextType::class, [ + 'required' => true, + 'label' => 'user.new.form_search.term_label', + ]) + ; + } + + public function configureOptions(OptionsResolver $resolver) + { + $resolver->setDefaults([ + 'csrf_protection' => false, + ]); + } +} diff --git a/src/Wallabag/UserBundle/Repository/UserRepository.php b/src/Wallabag/UserBundle/Repository/UserRepository.php index f913f52d..66bbab39 100644 --- a/src/Wallabag/UserBundle/Repository/UserRepository.php +++ b/src/Wallabag/UserBundle/Repository/UserRepository.php @@ -52,4 +52,19 @@ class UserRepository extends EntityRepository ->getQuery() ->getSingleScalarResult(); } + + /** + * Retrieves users filtered with a search term. + * + * @param string $term + * + * @return QueryBuilder + */ + public function getUsersForSearch($term) + { + return $this->createQueryBuilder('u') + ->andWhere('lower(u.username) LIKE lower(:term) OR lower(u.email) LIKE lower(:term) OR lower(u.name) LIKE lower(:term)')->setParameter('term', '%'.$term.'%') + ->getQuery() + ->getResult(); + } } diff --git a/src/Wallabag/UserBundle/Resources/views/Manage/index.html.twig b/src/Wallabag/UserBundle/Resources/views/Manage/index.html.twig index daba29e4..abc02852 100644 --- a/src/Wallabag/UserBundle/Resources/views/Manage/index.html.twig +++ b/src/Wallabag/UserBundle/Resources/views/Manage/index.html.twig @@ -8,36 +8,41 @@
    -
    +

    {{ 'user.description'|trans|raw }}

    - - - - - - - - - - - - {% for user in users %} - - - - - - - {% endfor %} - -
    {{ 'user.form.username_label'|trans }}{{ 'user.form.email_label'|trans }}{{ 'user.form.last_login_label'|trans }}{{ 'user.list.actions'|trans }}
    {{ user.username }}{{ user.email }}{% if user.lastLogin %}{{ user.lastLogin|date('Y-m-d H:i:s') }}{% endif %} - {{ 'user.list.edit_action'|trans }} -
    -
    -

    - {{ 'user.list.create_new_one'|trans }} -

    +
    +
    + {{ render(controller("WallabagUserBundle:Manage:searchForm", {'currentRoute': app.request.attributes.get('_route')})) }} +
    +
    + + + + + + + + + + + + {% for user in users %} + + + + + + + {% endfor %} + +
    {{ 'user.form.username_label'|trans }}{{ 'user.form.email_label'|trans }}{{ 'user.form2017-03-10 16:51:07.last_login_label'|trans }}{{ 'user.list.actions'|trans }}
    {{ user.username }}{{ user.email }}{% if user.lastLogin %}{{ user.lastLogin|date('Y-m-d H:i:s') }}{% endif %} + {{ 'user.list.edit_action'|trans }} +
    +
    +

    + {{ 'user.list.create_new_one'|trans }} +

    diff --git a/src/Wallabag/UserBundle/Resources/views/Manage/search_form.html.twig b/src/Wallabag/UserBundle/Resources/views/Manage/search_form.html.twig new file mode 100644 index 00000000..f59388d0 --- /dev/null +++ b/src/Wallabag/UserBundle/Resources/views/Manage/search_form.html.twig @@ -0,0 +1,15 @@ +
    + {% if form_errors(form) %} + {{ form_errors(form) }} + {% endif %} + + {% if form_errors(form.term) %} + {{ form_errors(form.term) }} + {% endif %} + + search + {{ form_widget(form.term, { 'attr': {'autocomplete': 'off', 'placeholder': 'user.search.placeholder'} }) }} + + + {{ form_rest(form) }} +
    -- cgit v1.2.3 From 50cfd8108b8e318fd28564d2e9d30943ab12aac0 Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Thu, 27 Apr 2017 16:23:54 +0200 Subject: Add pagination Signed-off-by: Thomas Citharel --- .../UserBundle/Controller/ManageController.php | 43 ++++++++++++++++++---- .../UserBundle/Repository/UserRepository.php | 6 +-- .../Resources/views/Manage/index.html.twig | 8 +++- 3 files changed, 45 insertions(+), 12 deletions(-) (limited to 'src') diff --git a/src/Wallabag/UserBundle/Controller/ManageController.php b/src/Wallabag/UserBundle/Controller/ManageController.php index f0e3d4de..86fcd431 100644 --- a/src/Wallabag/UserBundle/Controller/ManageController.php +++ b/src/Wallabag/UserBundle/Controller/ManageController.php @@ -4,12 +4,14 @@ namespace Wallabag\UserBundle\Controller; use FOS\UserBundle\Event\UserEvent; use FOS\UserBundle\FOSUserEvents; +use Pagerfanta\Adapter\DoctrineORMAdapter; +use Pagerfanta\Exception\OutOfRangeCurrentPageException; +use Pagerfanta\Pagerfanta; use Symfony\Component\HttpFoundation\Request; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Wallabag\UserBundle\Entity\User; -use Wallabag\CoreBundle\Entity\Config; use Wallabag\UserBundle\Form\SearchUserType; /** @@ -20,17 +22,32 @@ class ManageController extends Controller /** * Lists all User entities. * - * @Route("/", name="user_index") + * @Route("/index/{page}", name="user_index") * @Method("GET") + * + * @param int $page + * + * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response */ - public function indexAction() + public function indexAction($page = 1) { $em = $this->getDoctrine()->getManager(); - $users = $em->getRepository('WallabagUserBundle:User')->findAll(); + $qb = $em->getRepository('WallabagUserBundle:User')->createQueryBuilder('u'); + $pagerAdapter = new DoctrineORMAdapter($qb->getQuery(), true, false); + $pagerFanta = new Pagerfanta($pagerAdapter); + $pagerFanta->setMaxPerPage(50); + + try { + $pagerFanta->setCurrentPage($page); + } catch (OutOfRangeCurrentPageException $e) { + if ($page > 1) { + return $this->redirect($this->generateUrl('user_index', ['page' => $pagerFanta->getNbPages()]), 302); + } + } return $this->render('WallabagUserBundle:Manage:index.html.twig', array( - 'users' => $users, + 'users' => $pagerFanta, )); } @@ -176,10 +193,22 @@ class ManageController extends Controller $searchTerm = (isset($request->get('search_user')['term']) ? $request->get('search_user')['term'] : ''); - $users = $em->getRepository('WallabagUserBundle:User')->getUsersForSearch($searchTerm); + $qb = $em->getRepository('WallabagUserBundle:User')->getQueryBuilderForSearch($searchTerm); + + $pagerAdapter = new DoctrineORMAdapter($qb->getQuery(), true, false); + $pagerFanta = new Pagerfanta($pagerAdapter); + $pagerFanta->setMaxPerPage(50); + + try { + $pagerFanta->setCurrentPage($page); + } catch (OutOfRangeCurrentPageException $e) { + if ($page > 1) { + return $this->redirect($this->generateUrl('user_index', ['page' => $pagerFanta->getNbPages()]), 302); + } + } return $this->render('WallabagUserBundle:Manage:index.html.twig', array( - 'users' => $users, + 'users' => $pagerFanta, )); } diff --git a/src/Wallabag/UserBundle/Repository/UserRepository.php b/src/Wallabag/UserBundle/Repository/UserRepository.php index 66bbab39..6adbe329 100644 --- a/src/Wallabag/UserBundle/Repository/UserRepository.php +++ b/src/Wallabag/UserBundle/Repository/UserRepository.php @@ -60,11 +60,9 @@ class UserRepository extends EntityRepository * * @return QueryBuilder */ - public function getUsersForSearch($term) + public function getQueryBuilderForSearch($term) { return $this->createQueryBuilder('u') - ->andWhere('lower(u.username) LIKE lower(:term) OR lower(u.email) LIKE lower(:term) OR lower(u.name) LIKE lower(:term)')->setParameter('term', '%'.$term.'%') - ->getQuery() - ->getResult(); + ->andWhere('lower(u.username) LIKE lower(:term) OR lower(u.email) LIKE lower(:term) OR lower(u.name) LIKE lower(:term)')->setParameter('term', '%'.$term.'%'); } } diff --git a/src/Wallabag/UserBundle/Resources/views/Manage/index.html.twig b/src/Wallabag/UserBundle/Resources/views/Manage/index.html.twig index abc02852..7a76f157 100644 --- a/src/Wallabag/UserBundle/Resources/views/Manage/index.html.twig +++ b/src/Wallabag/UserBundle/Resources/views/Manage/index.html.twig @@ -7,6 +7,9 @@
    + {% if users.getNbPages > 1 %} + {{ pagerfanta(users, 'twitter_bootstrap_translated', {'proximity': 1}) }} + {% endif %}

    {{ 'user.description'|trans|raw }}

    @@ -22,7 +25,7 @@ {{ 'user.form.username_label'|trans }} {{ 'user.form.email_label'|trans }} - {{ 'user.form2017-03-10 16:51:07.last_login_label'|trans }} + {{ 'user.form.last_login_label'|trans }} {{ 'user.list.actions'|trans }} @@ -43,6 +46,9 @@

    {{ 'user.list.create_new_one'|trans }}

    + {% if users.getNbPages > 1 %} + {{ pagerfanta(users, 'twitter_bootstrap_translated', {'proximity': 1}) }} + {% endif %}
    -- cgit v1.2.3 From a2daa32d0c6f71aa8553aed3c6ed58d7aa861baa Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Thu, 27 Apr 2017 16:40:18 +0200 Subject: Fix tests Signed-off-by: Thomas Citharel --- src/Wallabag/UserBundle/Resources/views/Manage/search_form.html.twig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Wallabag/UserBundle/Resources/views/Manage/search_form.html.twig b/src/Wallabag/UserBundle/Resources/views/Manage/search_form.html.twig index f59388d0..1d4df204 100644 --- a/src/Wallabag/UserBundle/Resources/views/Manage/search_form.html.twig +++ b/src/Wallabag/UserBundle/Resources/views/Manage/search_form.html.twig @@ -1,4 +1,4 @@ -
    + {% if form_errors(form) %} {{ form_errors(form) }} {% endif %} -- cgit v1.2.3 From d01dc5a81e7fde37d98fe6b10b9329b53add5b6a Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Sat, 29 Apr 2017 19:39:51 +0200 Subject: rename index to list Signed-off-by: Thomas Citharel --- src/Wallabag/UserBundle/Controller/ManageController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Wallabag/UserBundle/Controller/ManageController.php b/src/Wallabag/UserBundle/Controller/ManageController.php index 86fcd431..3ea773ee 100644 --- a/src/Wallabag/UserBundle/Controller/ManageController.php +++ b/src/Wallabag/UserBundle/Controller/ManageController.php @@ -22,7 +22,7 @@ class ManageController extends Controller /** * Lists all User entities. * - * @Route("/index/{page}", name="user_index") + * @Route("/list/{page}", name="user_index") * @Method("GET") * * @param int $page -- cgit v1.2.3 From b5b6877976bc32f23e51c2fb0f3f973f0d571b10 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20L=C5=93uillet?= Date: Tue, 2 May 2017 15:27:58 +0200 Subject: Merged list and search methods --- .../Resources/translations/messages.da.yml | 1 - .../Resources/translations/messages.de.yml | 1 - .../Resources/translations/messages.en.yml | 1 - .../Resources/translations/messages.es.yml | 1 - .../Resources/translations/messages.fa.yml | 1 - .../Resources/translations/messages.fr.yml | 141 ++++++++++----------- .../Resources/translations/messages.it.yml | 1 - .../Resources/translations/messages.oc.yml | 1 - .../Resources/translations/messages.pl.yml | 1 - .../Resources/translations/messages.pt.yml | 1 - .../Resources/translations/messages.ro.yml | 1 - .../Resources/translations/messages.tr.yml | 1 - .../UserBundle/Controller/ManageController.php | 72 +++-------- .../Resources/views/Manage/index.html.twig | 14 +- .../Resources/views/Manage/search_form.html.twig | 15 --- 15 files changed, 99 insertions(+), 154 deletions(-) delete mode 100644 src/Wallabag/UserBundle/Resources/views/Manage/search_form.html.twig (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml index 68fcec5c..23390c12 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml @@ -513,7 +513,6 @@ user: # delete_confirm: Are you sure? # back_to_list: Back to list search: - # label: Filter # placeholder: Filter by username or email error: diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml index be117231..71c935c8 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml @@ -513,7 +513,6 @@ user: delete_confirm: Bist du sicher? back_to_list: Zurück zur Liste search: - # label: Filter # placeholder: Filter by username or email error: diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml index b3850893..a5540c86 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml @@ -513,7 +513,6 @@ user: delete_confirm: Are you sure? back_to_list: Back to list search: - label: Filter placeholder: Filter by username or email error: diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml index ebf6745a..ba8bdc5a 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml @@ -513,7 +513,6 @@ user: delete_confirm: ¿Estás seguro? back_to_list: Volver a la lista search: - # label: Filter # placeholder: Filter by username or email error: diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml index 46460e13..7ef39e40 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml @@ -513,7 +513,6 @@ user: # delete_confirm: Are you sure? # back_to_list: Back to list search: - # label: Filter # placeholder: Filter by username or email error: diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml index c968f7ab..48036cf7 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml @@ -46,7 +46,7 @@ footer: social: "Social" powered_by: "propulsé par" about: "À propos" - stats: Depuis le %user_creation%, vous avez lu %nb_archives% articles. Ce qui fait %per_day% par jour ! + stats: "Depuis le %user_creation%, vous avez lu %nb_archives% articles. Ce qui fait %per_day% par jour !" config: page_title: "Configuration" @@ -71,16 +71,16 @@ config: 300_word: "Je lis environ 300 mots par minute" 400_word: "Je lis environ 400 mots par minute" action_mark_as_read: - label: 'Où souhaitez-vous être redirigé après avoir marqué un article comme lu ?' - redirect_homepage: "À la page d'accueil" - redirect_current_page: 'À la page courante' - pocket_consumer_key_label: Clé d’authentification Pocket pour importer les données - android_configuration: Configurez votre application Android - help_theme: "L'affichage de wallabag est personnalisable. C'est ici que vous choisissez le thème que vous préférez." - help_items_per_page: "Vous pouvez définir le nombre d'articles affichés sur chaque page." + label: "Où souhaitez-vous être redirigé après avoir marqué un article comme lu ?" + redirect_homepage: "À la page d’accueil" + redirect_current_page: "À la page courante" + pocket_consumer_key_label: "Clé d’authentification Pocket pour importer les données" + android_configuration: "Configurez votre application Android" + help_theme: "L’affichage de wallabag est personnalisable. C’est ici que vous choisissez le thème que vous préférez." + help_items_per_page: "Vous pouvez définir le nombre d’articles affichés sur chaque page." help_reading_speed: "wallabag calcule une durée de lecture pour chaque article. Vous pouvez définir ici, grâce à cette liste déroulante, si vous lisez plus ou moins vite. wallabag recalculera la durée de lecture de chaque article." - help_language: "Vous pouvez définir la langue de l'interface de wallabag." - help_pocket_consumer_key: "Nécessaire pour l'import depuis Pocket. Vous pouvez le créer depuis votre compte Pocket." + help_language: "Vous pouvez définir la langue de l’interface de wallabag." + help_pocket_consumer_key: "Nécessaire pour l’import depuis Pocket. Vous pouvez le créer depuis votre compte Pocket." form_rss: description: "Les flux RSS fournis par wallabag vous permettent de lire vos articles sauvegardés dans votre lecteur de flux préféré. Pour pouvoir les utiliser, vous devez d’abord créer un jeton." token_label: "Jeton RSS" @@ -100,18 +100,18 @@ config: twoFactorAuthentication_label: "Double authentification" help_twoFactorAuthentication: "Si vous activez 2FA, à chaque tentative de connexion à wallabag, vous recevrez un code par email." delete: - title: Supprimer mon compte (attention danger !) - description: Si vous confirmez la suppression de votre compte, TOUS les articles, TOUS les tags, TOUTES les annotations et votre compte seront DÉFINITIVEMENT supprimé (c'est IRRÉVERSIBLE). Vous serez ensuite déconnecté. - confirm: Vous êtes vraiment sûr ? (C'EST IRRÉVERSIBLE) - button: 'Supprimer mon compte' + title: "Supprimer mon compte (attention danger !)" + description: "Si vous confirmez la suppression de votre compte, TOUS les articles, TOUS les tags, TOUTES les annotations et votre compte seront DÉFINITIVEMENT supprimé (c’est IRRÉVERSIBLE). Vous serez ensuite déconnecté." + confirm: "Vous êtes vraiment sûr ? (C’EST IRRÉVERSIBLE)" + button: "Supprimer mon compte" reset: - title: Réinitialisation (attention danger !) - description: En cliquant sur les boutons ci-dessous vous avez la possibilité de supprimer certaines informations de votre compte. Attention, ces actions sont IRRÉVERSIBLES ! - annotations: Supprimer TOUTES les annotations - tags: Supprimer TOUS les tags - entries: Supprimer TOUS les articles - archived: Supprimer TOUS les articles archivés - confirm: Êtes-vous vraiment vraiment sûr ? (C'EST IRRÉVERSIBLE) + title: "Réinitialisation (attention danger !)" + description: "En cliquant sur les boutons ci-dessous vous avez la possibilité de supprimer certaines informations de votre compte. Attention, ces actions sont IRRÉVERSIBLES !" + annotations: "Supprimer TOUTES les annotations" + tags: "Supprimer TOUS les tags" + entries: "Supprimer TOUS les articles" + archived: "Supprimer TOUS les articles archivés" + confirm: "Êtes-vous vraiment vraiment sûr ? (C’EST IRRÉVERSIBLE)" form_password: description: "Vous pouvez changer ici votre mot de passe. Le mot de passe doit contenir au moins 8 caractères." old_password_label: "Mot de passe actuel" @@ -163,7 +163,7 @@ entry: archived: "Articles lus" filtered: "Articles filtrés" filtered_tags: "Articles filtrés par tags :" - filtered_search: 'Articles filtrés par recherche :' + filtered_search: "Articles filtrés par recherche :" untagged: "Article sans tag" list: number_on_the_page: "{0} Il n’y a pas d’article.|{1} Il y a un article.|]1,Inf[ Il y a %count% articles." @@ -187,7 +187,7 @@ entry: preview_picture_label: "A une photo" preview_picture_help: "Photo" language_label: "Langue" - http_status_label: 'Statut HTTP' + http_status_label: "Statut HTTP" reading_time: label: "Durée de lecture en minutes" from: "de" @@ -297,32 +297,32 @@ howto: bookmarklet: description: "Glissez et déposez ce lien dans votre barre de favoris :" shortcuts: - page_description: Voici les raccourcis disponibles dans wallabag. - shortcut: Raccourci - action: Action - all_pages_title: Raccourcis disponibles dans toutes les pages - go_unread: Afficher les articles non lus - go_starred: Afficher les articles favoris - go_archive: Afficher les articles lus - go_all: Afficher tous les articles - go_tags: Afficher les tags - go_config: Aller à la configuration - go_import: Aller aux imports - go_developers: Aller à la section Développeurs - go_howto: Afficher l'aide (cette page !) - go_logout: Se déconnecter - list_title: Raccourcis disponibles dans les pages de liste - search: Afficher le formulaire de recherche - article_title: Raccourcis disponibles quand on affiche un article - open_original: Ouvrir l'URL originale de l'article - toggle_favorite: Changer le statut Favori de l'article - toggle_archive: Changer le status Lu de l'article - delete: Supprimer l'article - material_title: Raccourcis disponibles avec le thème Material uniquement - add_link: Ajouter un nouvel article - hide_form: Masquer le formulaire courant (recherche ou nouvel article) - arrows_navigation: Naviguer à travers les articles - open_article: Afficher l'article sélectionné + page_description: "Voici les raccourcis disponibles dans wallabag." + shortcut: "Raccourci" + action: "Action" + all_pages_title: "Raccourcis disponibles dans toutes les pages" + go_unread: "Afficher les articles non lus" + go_starred: "Afficher les articles favoris" + go_archive: "Afficher les articles lus" + go_all: "Afficher tous les articles" + go_tags: "Afficher les tags" + go_config: "Aller à la configuration" + go_import: "Aller aux imports" + go_developers: "Aller à la section Développeurs" + go_howto: "Afficher l’aide (cette page !)" + go_logout: "Se déconnecter" + list_title: "Raccourcis disponibles dans les pages de liste" + search: "Afficher le formulaire de recherche" + article_title: "Raccourcis disponibles quand on affiche un article" + open_original: "Ouvrir l’URL originale de l’article" + toggle_favorite: "Changer le statut Favori de l’article" + toggle_archive: "Changer le status Lu de l’article" + delete: "Supprimer l’article" + material_title: "Raccourcis disponibles avec le thème Material uniquement" + add_link: "Ajouter un nouvel article" + hide_form: "Masquer le formulaire courant (recherche ou nouvel article)" + arrows_navigation: "Naviguer à travers les articles" + open_article: "Afficher l’article sélectionné" quickstart: page_title: "Pour bien débuter" @@ -384,8 +384,8 @@ tag: number_on_the_page: "{0} Il n’y a pas de tag.|{1} Il y a un tag.|]1,Inf[ Il y a %count% tags." see_untagged_entries: "Voir les articles sans tag" new: - add: 'Ajouter' - placeholder: 'Vous pouvez ajouter plusieurs tags, séparés par une virgule.' + add: "Ajouter" + placeholder: "Vous pouvez ajouter plusieurs tags, séparés par une virgule." import: page_title: "Importer" @@ -419,7 +419,7 @@ import: how_to: "Choisissez le fichier de votre export Readability et cliquez sur le bouton ci-dessous pour l’importer." worker: enabled: "Les imports sont asynchrones. Une fois l’import commencé un worker externe traitera les messages un par un. Le service activé est :" - download_images_warning: "Vous avez configuré le téléchagement des images pour vos articles. Combiné à l'import classique, cette opération peut être très très longue (voire échouer). Nous vous conseillons vivement d'activer les imports asynchrones." + download_images_warning: "Vous avez configuré le téléchagement des images pour vos articles. Combiné à l’import classique, cette opération peut être très très longue (voire échouer). Nous vous conseillons vivement d’activer les imports asynchrones." firefox: page_title: "Import > Firefox" description: "Cet outil va vous permettre d’importer tous vos marques-pages de Firefox. Ouvrez le panneau des marques-pages (Ctrl+Maj+O), puis dans « Importation et sauvegarde », choisissez « Sauvegarde… ». Vous allez récupérer un fichier .json.

    " @@ -488,16 +488,16 @@ developer: back: "Retour" user: - page_title: Gestion des utilisateurs - new_user: Créer un nouvel utilisateur - edit_user: Éditer un utilisateur existant - description: Ici vous pouvez gérer vos utilisateurs (création, mise à jour et suppression) + page_title: "Gestion des utilisateurs" + new_user: "Créer un nouvel utilisateur" + edit_user: "Éditer un utilisateur existant" + description: "Ici vous pouvez gérer vos utilisateurs (création, mise à jour et suppression)" list: - actions: Actions - edit_action: Éditer - yes: Oui - no: Non - create_new_one: Créer un nouvel utilisateur + actions: "Actions" + edit_action: "Éditer" + yes: "Oui" + no: "Non" + create_new_one: "Créer un nouvel utilisateur" form: username_label: "Nom d’utilisateur" name_label: "Nom" @@ -513,11 +513,10 @@ user: delete_confirm: "Voulez-vous vraiment ?" back_to_list: "Revenir à la liste" search: - label: Filtrer - placeholder: Filtrer par nom d'utilisateur ou email + placeholder: "Filtrer par nom d’utilisateur ou email" error: - page_title: Une erreur est survenue + page_title: "Une erreur est survenue" flashes: config: @@ -530,10 +529,10 @@ flashes: tagging_rules_updated: "Règles mises à jour" tagging_rules_deleted: "Règle supprimée" rss_token_updated: "Jeton RSS mis à jour" - annotations_reset: Annotations supprimées - tags_reset: Tags supprimés - entries_reset: Articles supprimés - archived_reset: Articles archivés supprimés + annotations_reset: "Annotations supprimées" + tags_reset: "Tags supprimés" + entries_reset: "Articles supprimés" + archived_reset: "Articles archivés supprimés" entry: notice: entry_already_saved: "Article déjà sauvegardé le %date%" @@ -565,6 +564,6 @@ flashes: client_deleted: "Client %name% supprimé" user: notice: - added: 'Utilisateur "%username%" ajouté' - updated: 'Utilisateur "%username%" mis à jour' - deleted: 'Utilisateur "%username%" supprimé' + added: "Utilisateur \"%username%\" ajouté" + updated: "Utilisateur \"%username%\" mis à jour" + deleted: "Utilisateur \"%username%\" supprimé" diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml index 53b5e1b9..364e9a1f 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml @@ -513,7 +513,6 @@ user: # delete_confirm: Are you sure? # back_to_list: Back to list search: - # label: Filter # placeholder: Filter by username or email error: diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml index c6614a63..4877238e 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml @@ -513,7 +513,6 @@ user: delete_confirm: 'Sètz segur ?' back_to_list: 'Tornar a la lista' search: - # label: Filter # placeholder: Filter by username or email error: diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml index b464d0f6..9e61162a 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml @@ -513,7 +513,6 @@ user: delete_confirm: Jesteś pewien? back_to_list: Powrót do listy search: - # label: Filter # placeholder: Filter by username or email error: diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml index 2b0b1686..30705c0a 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml @@ -513,7 +513,6 @@ user: delete_confirm: 'Tem certeza?' back_to_list: 'Voltar para a lista' search: - # label: Filter # placeholder: Filter by username or email error: diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml index 210978d0..d3c5a0f8 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml @@ -513,7 +513,6 @@ user: # delete_confirm: Are you sure? # back_to_list: Back to list search: - # label: Filter # placeholder: Filter by username or email error: diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml index 5ff5e012..27b43606 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml @@ -513,7 +513,6 @@ user: # delete_confirm: Are you sure? # back_to_list: Back to list search: - # label: Filter # placeholder: Filter by username or email error: diff --git a/src/Wallabag/UserBundle/Controller/ManageController.php b/src/Wallabag/UserBundle/Controller/ManageController.php index 3ea773ee..1c5c86d4 100644 --- a/src/Wallabag/UserBundle/Controller/ManageController.php +++ b/src/Wallabag/UserBundle/Controller/ManageController.php @@ -19,38 +19,6 @@ use Wallabag\UserBundle\Form\SearchUserType; */ class ManageController extends Controller { - /** - * Lists all User entities. - * - * @Route("/list/{page}", name="user_index") - * @Method("GET") - * - * @param int $page - * - * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response - */ - public function indexAction($page = 1) - { - $em = $this->getDoctrine()->getManager(); - - $qb = $em->getRepository('WallabagUserBundle:User')->createQueryBuilder('u'); - $pagerAdapter = new DoctrineORMAdapter($qb->getQuery(), true, false); - $pagerFanta = new Pagerfanta($pagerAdapter); - $pagerFanta->setMaxPerPage(50); - - try { - $pagerFanta->setCurrentPage($page); - } catch (OutOfRangeCurrentPageException $e) { - if ($page > 1) { - return $this->redirect($this->generateUrl('user_index', ['page' => $pagerFanta->getNbPages()]), 302); - } - } - - return $this->render('WallabagUserBundle:Manage:index.html.twig', array( - 'users' => $pagerFanta, - )); - } - /** * Creates a new User entity. * @@ -169,52 +137,44 @@ class ManageController extends Controller * @param Request $request * @param int $page * - * @Route("/search/{page}", name="user-search", defaults={"page" = 1}) + * @Route("/list/{page}", name="user_index", defaults={"page" = 1}) * * Default parameter for page is hardcoded (in duplication of the defaults from the Route) * because this controller is also called inside the layout template without any page as argument * * @return \Symfony\Component\HttpFoundation\Response */ - public function searchFormAction(Request $request, $page = 1, $currentRoute = null) + public function searchFormAction(Request $request, $page = 1) { - // fallback to retrieve currentRoute from query parameter instead of injected one (when using inside a template) - if (null === $currentRoute && $request->query->has('currentRoute')) { - $currentRoute = $request->query->get('currentRoute'); - } + $em = $this->getDoctrine()->getManager(); + $qb = $em->getRepository('WallabagUserBundle:User')->createQueryBuilder('u'); $form = $this->createForm(SearchUserType::class); - $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $this->get('logger')->info('searching users'); - $em = $this->getDoctrine()->getManager(); $searchTerm = (isset($request->get('search_user')['term']) ? $request->get('search_user')['term'] : ''); $qb = $em->getRepository('WallabagUserBundle:User')->getQueryBuilderForSearch($searchTerm); + } - $pagerAdapter = new DoctrineORMAdapter($qb->getQuery(), true, false); - $pagerFanta = new Pagerfanta($pagerAdapter); - $pagerFanta->setMaxPerPage(50); + $pagerAdapter = new DoctrineORMAdapter($qb->getQuery(), true, false); + $pagerFanta = new Pagerfanta($pagerAdapter); + $pagerFanta->setMaxPerPage(50); - try { - $pagerFanta->setCurrentPage($page); - } catch (OutOfRangeCurrentPageException $e) { - if ($page > 1) { - return $this->redirect($this->generateUrl('user_index', ['page' => $pagerFanta->getNbPages()]), 302); - } + try { + $pagerFanta->setCurrentPage($page); + } catch (OutOfRangeCurrentPageException $e) { + if ($page > 1) { + return $this->redirect($this->generateUrl('user_index', ['page' => $pagerFanta->getNbPages()]), 302); } - - return $this->render('WallabagUserBundle:Manage:index.html.twig', array( - 'users' => $pagerFanta, - )); } - return $this->render('WallabagUserBundle:Manage:search_form.html.twig', [ - 'form' => $form->createView(), - 'currentRoute' => $currentRoute, + return $this->render('WallabagUserBundle:Manage:index.html.twig', [ + 'searchForm' => $form->createView(), + 'users' => $pagerFanta, ]); } } diff --git a/src/Wallabag/UserBundle/Resources/views/Manage/index.html.twig b/src/Wallabag/UserBundle/Resources/views/Manage/index.html.twig index 7a76f157..15002632 100644 --- a/src/Wallabag/UserBundle/Resources/views/Manage/index.html.twig +++ b/src/Wallabag/UserBundle/Resources/views/Manage/index.html.twig @@ -16,7 +16,19 @@
    - {{ render(controller("WallabagUserBundle:Manage:searchForm", {'currentRoute': app.request.attributes.get('_route')})) }} + + {% if form_errors(searchForm) %} + {{ form_errors(searchForm) }} + {% endif %} + + {% if form_errors(searchForm.term) %} + {{ form_errors(searchForm.term) }} + {% endif %} + + {{ form_widget(searchForm.term, { 'attr': {'autocomplete': 'off', 'placeholder': 'user.search.placeholder'} }) }} + + {{ form_rest(searchForm) }} +
    diff --git a/src/Wallabag/UserBundle/Resources/views/Manage/search_form.html.twig b/src/Wallabag/UserBundle/Resources/views/Manage/search_form.html.twig deleted file mode 100644 index 1d4df204..00000000 --- a/src/Wallabag/UserBundle/Resources/views/Manage/search_form.html.twig +++ /dev/null @@ -1,15 +0,0 @@ -
    - {% if form_errors(form) %} - {{ form_errors(form) }} - {% endif %} - - {% if form_errors(form.term) %} - {{ form_errors(form.term) }} - {% endif %} - - search - {{ form_widget(form.term, { 'attr': {'autocomplete': 'off', 'placeholder': 'user.search.placeholder'} }) }} - - - {{ form_rest(form) }} -
    -- cgit v1.2.3 From 96e4398072943a181d55947fa788f5ee2b8cbbe3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20L=C5=93uillet?= Date: Tue, 2 May 2017 15:40:15 +0200 Subject: Fixed sandwich menu position in entry view (material theme) --- .../Resources/views/themes/material/Entry/entry.html.twig | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entry.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entry.html.twig index 8be5fd0d..3c4ad024 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entry.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entry.html.twig @@ -11,6 +11,11 @@ -- cgit v1.2.3 From d1e5059ea0ccfbf8e224e71f8d233b01ddfbc92d Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Thu, 4 May 2017 11:53:44 +0200 Subject: Use username to import Signed-off-by: Thomas Citharel add docs Signed-off-by: Thomas Citharel use username as default Signed-off-by: Thomas Citharel rename user to username typo Signed-off-by: Thomas Citharel --- src/Wallabag/ImportBundle/Command/ImportCommand.php | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/Wallabag/ImportBundle/Command/ImportCommand.php b/src/Wallabag/ImportBundle/Command/ImportCommand.php index 28d01715..ce72837a 100644 --- a/src/Wallabag/ImportBundle/Command/ImportCommand.php +++ b/src/Wallabag/ImportBundle/Command/ImportCommand.php @@ -15,10 +15,11 @@ class ImportCommand extends ContainerAwareCommand $this ->setName('wallabag:import') ->setDescription('Import entries from a JSON export') - ->addArgument('userId', InputArgument::REQUIRED, 'User ID to populate') + ->addArgument('username', InputArgument::REQUIRED, 'User to populate') ->addArgument('filepath', InputArgument::REQUIRED, 'Path to the JSON file') ->addOption('importer', null, InputArgument::OPTIONAL, 'The importer to use: v1, v2, instapaper, pinboard, readability, firefox or chrome', 'v1') ->addOption('markAsRead', null, InputArgument::OPTIONAL, 'Mark all entries as read', false) + ->addOption('useUserId', null, InputArgument::OPTIONAL, 'Use user id instead of username to find account', false) ; } @@ -34,10 +35,14 @@ class ImportCommand extends ContainerAwareCommand // Turning off doctrine default logs queries for saving memory $em->getConnection()->getConfiguration()->setSQLLogger(null); - $user = $em->getRepository('WallabagUserBundle:User')->findOneById($input->getArgument('userId')); + if ($input->getOption('useUserId')) { + $user = $em->getRepository('WallabagUserBundle:User')->findOneById($input->getArgument('username')); + } else { + $user = $em->getRepository('WallabagUserBundle:User')->findOneByUsername($input->getArgument('username')); + } if (!is_object($user)) { - throw new Exception(sprintf('User with id "%s" not found', $input->getArgument('userId'))); + throw new Exception(sprintf('User "%s" not found', $input->getArgument('username'))); } switch ($input->getOption('importer')) { -- cgit v1.2.3 From 64f81bc31699ed239e4becec1cfa7ebc0bef2b5a Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Fri, 31 Mar 2017 20:21:41 +0200 Subject: Adds Webpack support and removes the use for Grunt Signed-off-by: Thomas Citharel use scss Signed-off-by: Thomas Citharel fix build, add babel, fix annotations fixes (and improvements !) for baggy add live reload & environments & eslint & theme fixes --- .../Resources/views/themes/baggy/Entry/entries.html.twig | 14 +++++++------- .../Resources/views/themes/baggy/Entry/entry.html.twig | 2 +- .../Resources/views/themes/baggy/layout.html.twig | 6 ++++-- .../views/themes/material/Entry/entries.html.twig | 4 ++-- .../Resources/views/themes/material/Entry/entry.html.twig | 15 ++++++--------- .../Resources/views/themes/material/layout.html.twig | 10 ++++++---- 6 files changed, 26 insertions(+), 25 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Entry/entries.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Entry/entries.html.twig index 859b166b..bdd44b54 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Entry/entries.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Entry/entries.html.twig @@ -17,9 +17,9 @@
    {{ 'entry.list.number_on_the_page'|transchoice(entries.count) }}
    {% if (entry.previewPicture is null or listMode == 1) %}
    -
  • {% for tag in entry.tags %} {% endfor %}
  • -- cgit v1.2.3 From 5b914b0422e08c4b4859050026823af677c97727 Mon Sep 17 00:00:00 2001 From: Bertrand Dunogier Date: Sat, 14 Jan 2017 16:42:03 +0100 Subject: Improved Guzzle subscribers extensibility Allows 3rd parties to register new guzzle subscribers by adding extra calls to the http_client_factory service. --- .../CoreBundle/Helper/HttpClientFactory.php | 26 +++++++++++++++------- .../CoreBundle/Resources/config/services.yml | 3 ++- 2 files changed, 20 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Helper/HttpClientFactory.php b/src/Wallabag/CoreBundle/Helper/HttpClientFactory.php index 1ac8feb1..09439dff 100644 --- a/src/Wallabag/CoreBundle/Helper/HttpClientFactory.php +++ b/src/Wallabag/CoreBundle/Helper/HttpClientFactory.php @@ -13,8 +13,8 @@ use Psr\Log\LoggerInterface; */ class HttpClientFactory { - /** @var \GuzzleHttp\Event\SubscriberInterface */ - private $authenticatorSubscriber; + /** @var [\GuzzleHttp\Event\SubscriberInterface] */ + private $subscribers = []; /** @var \GuzzleHttp\Cookie\CookieJar */ private $cookieJar; @@ -25,14 +25,12 @@ class HttpClientFactory /** * HttpClientFactory constructor. * - * @param \GuzzleHttp\Event\SubscriberInterface $authenticatorSubscriber - * @param \GuzzleHttp\Cookie\CookieJar $cookieJar - * @param string $restrictedAccess this param is a kind of boolean. Values: 0 or 1 + * @param \GuzzleHttp\Cookie\CookieJar $cookieJar + * @param string $restrictedAccess This param is a kind of boolean. Values: 0 or 1 * @param LoggerInterface $logger */ - public function __construct(SubscriberInterface $authenticatorSubscriber, CookieJar $cookieJar, $restrictedAccess, LoggerInterface $logger) + public function __construct(CookieJar $cookieJar, $restrictedAccess, LoggerInterface $logger) { - $this->authenticatorSubscriber = $authenticatorSubscriber; $this->cookieJar = $cookieJar; $this->restrictedAccess = $restrictedAccess; $this->logger = $logger; @@ -53,8 +51,20 @@ class HttpClientFactory $this->cookieJar->clear(); // need to set the (shared) cookie jar $client = new Client(['handler' => new SafeCurlHandler(), 'defaults' => ['cookies' => $this->cookieJar]]); - $client->getEmitter()->attach($this->authenticatorSubscriber); + foreach ($this->subscribers as $subscriber) { + $client->getEmitter()->attach($subscriber); + } return $client; } + + /** + * Adds a subscriber to the HTTP client. + * + * @param SubscriberInterface $subscriber + */ + public function addSubscriber(SubscriberInterface $subscriber) + { + $this->subscribers[] = $subscriber; + } } diff --git a/src/Wallabag/CoreBundle/Resources/config/services.yml b/src/Wallabag/CoreBundle/Resources/config/services.yml index bccb2e19..68f900a1 100644 --- a/src/Wallabag/CoreBundle/Resources/config/services.yml +++ b/src/Wallabag/CoreBundle/Resources/config/services.yml @@ -71,10 +71,11 @@ services: wallabag_core.guzzle.http_client_factory: class: Wallabag\CoreBundle\Helper\HttpClientFactory arguments: - - "@bd_guzzle_site_authenticator.authenticator_subscriber" - "@wallabag_core.guzzle.cookie_jar" - '@=service(''craue_config'').get(''restricted_access'')' - '@logger' + calls: + - ["addSubscriber", ["@bd_guzzle_site_authenticator.authenticator_subscriber"]] wallabag_core.guzzle.cookie_jar: class: GuzzleHttp\Cookie\FileCookieJar -- cgit v1.2.3 From 662db41baee404be3427b2b11b2d1fbf0aefcc8f Mon Sep 17 00:00:00 2001 From: Bertrand Dunogier Date: Sun, 22 Jan 2017 00:42:05 +0100 Subject: Changed parsing of login_extra_fields in guzzle auth --- .../GrabySiteConfigBuilder.php | 28 +++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php b/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php index 6d4129e8..1c866f17 100644 --- a/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php +++ b/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php @@ -54,7 +54,7 @@ class GrabySiteConfigBuilder implements SiteConfigBuilder 'loginUri' => $config->login_uri ?: null, 'usernameField' => $config->login_username_field ?: null, 'passwordField' => $config->login_password_field ?: null, - 'extraFields' => is_array($config->login_extra_fields) ? $config->login_extra_fields : [], + 'extraFields' => $this->processExtraFields($config->login_extra_fields), 'notLoggedInXpath' => $config->not_logged_in_xpath ?: null, ]; @@ -65,4 +65,30 @@ class GrabySiteConfigBuilder implements SiteConfigBuilder return new SiteConfig($parameters); } + + /** + * Processes login_extra_fields config, transforming an '=' separated array of strings + * into a key/value array. + * + * @param array|mixed $extraFieldsStrings + * + * @return array + */ + protected function processExtraFields($extraFieldsStrings) + { + if (!is_array($extraFieldsStrings)) { + return []; + } + + $extraFields = []; + foreach ($extraFieldsStrings as $extraField) { + if (strpos($extraField, '=') === false) { + continue; + } + list($fieldName, $fieldValue) = explode('=', $extraField, 2); + $extraFields[$fieldName] = $fieldValue; + } + + return $extraFields; + } } -- cgit v1.2.3 From 72db15ca5d7950a604f359056fc6a627f25e4ee4 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Fri, 5 May 2017 12:05:50 +0200 Subject: Little refacto and send 400 on reaching urls limit --- .../ApiBundle/Controller/EntryRestController.php | 196 ++++++++++----------- 1 file changed, 94 insertions(+), 102 deletions(-) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/EntryRestController.php b/src/Wallabag/ApiBundle/Controller/EntryRestController.php index 7c3e778e..dbff6065 100644 --- a/src/Wallabag/ApiBundle/Controller/EntryRestController.php +++ b/src/Wallabag/ApiBundle/Controller/EntryRestController.php @@ -5,7 +5,7 @@ namespace Wallabag\ApiBundle\Controller; use Hateoas\Configuration\Route; use Hateoas\Representation\Factory\PagerfantaFactory; use Nelmio\ApiDocBundle\Annotation\ApiDoc; -use Symfony\Component\Config\Definition\Exception\Exception; +use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; @@ -45,9 +45,7 @@ class EntryRestController extends WallabagRestController $results[$url] = $res instanceof Entry ? $res->getId() : false; } - $json = $this->get('serializer')->serialize($results, 'json'); - - return (new JsonResponse())->setJson($json); + return $this->sendResponse($results); } // let's see if it is a simple url? @@ -63,9 +61,7 @@ class EntryRestController extends WallabagRestController $exists = $res instanceof Entry ? $res->getId() : false; - $json = $this->get('serializer')->serialize(['exists' => $exists], 'json'); - - return (new JsonResponse())->setJson($json); + return $this->sendResponse(['exists' => $exists]); } /** @@ -125,9 +121,7 @@ class EntryRestController extends WallabagRestController ) ); - $json = $this->get('serializer')->serialize($paginatedCollection, 'json'); - - return (new JsonResponse())->setJson($json); + return $this->sendResponse($paginatedCollection); } /** @@ -146,9 +140,7 @@ class EntryRestController extends WallabagRestController $this->validateAuthentication(); $this->validateUserAccess($entry->getUser()->getId()); - $json = $this->get('serializer')->serialize($entry, 'json'); - - return (new JsonResponse())->setJson($json); + return $this->sendResponse($entry); } /** @@ -189,35 +181,35 @@ class EntryRestController extends WallabagRestController $this->validateAuthentication(); $urls = json_decode($request->query->get('urls', [])); + + if (empty($urls)) { + return $this->sendResponse([]); + } + $results = []; // handle multiple urls - if (!empty($urls)) { - $results = []; - foreach ($urls as $key => $url) { - $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId( - $url, - $this->getUser()->getId() - ); - - $results[$key]['url'] = $url; + foreach ($urls as $key => $url) { + $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId( + $url, + $this->getUser()->getId() + ); - if (false !== $entry) { - $em = $this->getDoctrine()->getManager(); - $em->remove($entry); - $em->flush(); + $results[$key]['url'] = $url; - // entry deleted, dispatch event about it! - $this->get('event_dispatcher')->dispatch(EntryDeletedEvent::NAME, new EntryDeletedEvent($entry)); - } + if (false !== $entry) { + $em = $this->getDoctrine()->getManager(); + $em->remove($entry); + $em->flush(); - $results[$key]['entry'] = $entry instanceof Entry ? true : false; + // entry deleted, dispatch event about it! + $this->get('event_dispatcher')->dispatch(EntryDeletedEvent::NAME, new EntryDeletedEvent($entry)); } - } - $json = $this->get('serializer')->serialize($results, 'json'); + $results[$key]['entry'] = $entry instanceof Entry ? true : false; + } - return (new JsonResponse())->setJson($json); + return $this->sendResponse($results); } /** @@ -231,7 +223,7 @@ class EntryRestController extends WallabagRestController * * @return JsonResponse * - * @throws Symfony\Component\Config\Definition\Exception\Exception When limit is reached + * @throws HttpException When limit is reached */ public function postEntriesListAction(Request $request) { @@ -243,7 +235,7 @@ class EntryRestController extends WallabagRestController $limit = $this->container->getParameter('wallabag_core.api_limit_mass_actions'); if (count($urls) > $limit) { - throw new Exception('API limit reached'); + throw new HttpException(400, 'API limit reached'); } // handle multiple urls @@ -274,9 +266,7 @@ class EntryRestController extends WallabagRestController } } - $json = $this->get('serializer')->serialize($results, 'json'); - - return (new JsonResponse())->setJson($json); + return $this->sendResponse($results); } /** @@ -336,9 +326,7 @@ class EntryRestController extends WallabagRestController // entry saved, dispatch event about it! $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry)); - $json = $this->get('serializer')->serialize($entry, 'json'); - - return (new JsonResponse())->setJson($json); + return $this->sendResponse($entry); } /** @@ -387,9 +375,7 @@ class EntryRestController extends WallabagRestController $em = $this->getDoctrine()->getManager(); $em->flush(); - $json = $this->get('serializer')->serialize($entry, 'json'); - - return (new JsonResponse())->setJson($json); + return $this->sendResponse($entry); } /** @@ -432,9 +418,7 @@ class EntryRestController extends WallabagRestController // entry saved, dispatch event about it! $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry)); - $json = $this->get('serializer')->serialize($entry, 'json'); - - return (new JsonResponse())->setJson($json); + return $this->sendResponse($entry); } /** @@ -460,9 +444,7 @@ class EntryRestController extends WallabagRestController // entry deleted, dispatch event about it! $this->get('event_dispatcher')->dispatch(EntryDeletedEvent::NAME, new EntryDeletedEvent($entry)); - $json = $this->get('serializer')->serialize($entry, 'json'); - - return (new JsonResponse())->setJson($json); + return $this->sendResponse($entry); } /** @@ -481,9 +463,7 @@ class EntryRestController extends WallabagRestController $this->validateAuthentication(); $this->validateUserAccess($entry->getUser()->getId()); - $json = $this->get('serializer')->serialize($entry->getTags(), 'json'); - - return (new JsonResponse())->setJson($json); + return $this->sendResponse($entry->getTags()); } /** @@ -514,9 +494,7 @@ class EntryRestController extends WallabagRestController $em->persist($entry); $em->flush(); - $json = $this->get('serializer')->serialize($entry, 'json'); - - return (new JsonResponse())->setJson($json); + return $this->sendResponse($entry); } /** @@ -541,9 +519,7 @@ class EntryRestController extends WallabagRestController $em->persist($entry); $em->flush(); - $json = $this->get('serializer')->serialize($entry, 'json'); - - return (new JsonResponse())->setJson($json); + return $this->sendResponse($entry); } /** @@ -562,45 +538,46 @@ class EntryRestController extends WallabagRestController $this->validateAuthentication(); $list = json_decode($request->query->get('list', [])); - $results = []; + + if (empty($list)) { + return $this->sendResponse([]); + } // handle multiple urls - if (!empty($list)) { - foreach ($list as $key => $element) { - $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId( - $element->url, - $this->getUser()->getId() - ); + $results = []; - $results[$key]['url'] = $element->url; - $results[$key]['entry'] = $entry instanceof Entry ? $entry->getId() : false; + foreach ($list as $key => $element) { + $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId( + $element->url, + $this->getUser()->getId() + ); - $tags = $element->tags; + $results[$key]['url'] = $element->url; + $results[$key]['entry'] = $entry instanceof Entry ? $entry->getId() : false; - if (false !== $entry && !(empty($tags))) { - $tags = explode(',', $tags); - foreach ($tags as $label) { - $label = trim($label); + $tags = $element->tags; - $tag = $this->getDoctrine() - ->getRepository('WallabagCoreBundle:Tag') - ->findOneByLabel($label); + if (false !== $entry && !(empty($tags))) { + $tags = explode(',', $tags); + foreach ($tags as $label) { + $label = trim($label); - if (false !== $tag) { - $entry->removeTag($tag); - } - } + $tag = $this->getDoctrine() + ->getRepository('WallabagCoreBundle:Tag') + ->findOneByLabel($label); - $em = $this->getDoctrine()->getManager(); - $em->persist($entry); - $em->flush(); + if (false !== $tag) { + $entry->removeTag($tag); + } } + + $em = $this->getDoctrine()->getManager(); + $em->persist($entry); + $em->flush(); } } - $json = $this->get('serializer')->serialize($results, 'json'); - - return (new JsonResponse())->setJson($json); + return $this->sendResponse($results); } /** @@ -619,32 +596,47 @@ class EntryRestController extends WallabagRestController $this->validateAuthentication(); $list = json_decode($request->query->get('list', [])); + + if (empty($list)) { + return $this->sendResponse([]); + } + $results = []; // handle multiple urls - if (!empty($list)) { - foreach ($list as $key => $element) { - $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId( - $element->url, - $this->getUser()->getId() - ); + foreach ($list as $key => $element) { + $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId( + $element->url, + $this->getUser()->getId() + ); - $results[$key]['url'] = $element->url; - $results[$key]['entry'] = $entry instanceof Entry ? $entry->getId() : false; + $results[$key]['url'] = $element->url; + $results[$key]['entry'] = $entry instanceof Entry ? $entry->getId() : false; - $tags = $element->tags; + $tags = $element->tags; - if (false !== $entry && !(empty($tags))) { - $this->get('wallabag_core.content_proxy')->assignTagsToEntry($entry, $tags); + if (false !== $entry && !(empty($tags))) { + $this->get('wallabag_core.content_proxy')->assignTagsToEntry($entry, $tags); - $em = $this->getDoctrine()->getManager(); - $em->persist($entry); - $em->flush(); - } + $em = $this->getDoctrine()->getManager(); + $em->persist($entry); + $em->flush(); } } - $json = $this->get('serializer')->serialize($results, 'json'); + return $this->sendResponse($results); + } + + /** + * Shortcut to send data serialized in json. + * + * @param mixed $data + * + * @return JsonResponse + */ + private function sendResponse($data) + { + $json = $this->get('serializer')->serialize($data, 'json'); return (new JsonResponse())->setJson($json); } -- cgit v1.2.3 From d09fe4d233477d5cb9bfc613799b05a7ca14e270 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20L=C5=93uillet?= Date: Fri, 5 May 2017 14:33:36 +0200 Subject: Added test for deduplication --- .../CoreBundle/Repository/EntryRepository.php | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Repository/EntryRepository.php b/src/Wallabag/CoreBundle/Repository/EntryRepository.php index 5e7b0d3a..2e03fa19 100644 --- a/src/Wallabag/CoreBundle/Repository/EntryRepository.php +++ b/src/Wallabag/CoreBundle/Repository/EntryRepository.php @@ -392,4 +392,23 @@ class EntryRepository extends EntityRepository return $qb->getQuery()->getArrayResult(); } + + /** + * Find all entries by url and owner. + * + * @param $url + * @param $userId + * + * @return array + */ + public function findAllByUrlAndUserId($url, $userId) + { + $res = $this->createQueryBuilder('e') + ->where('e.url = :url')->setParameter('url', urldecode($url)) + ->andWhere('e.user = :user_id')->setParameter('user_id', $userId) + ->getQuery() + ->getResult(); + + return $res; + } } -- cgit v1.2.3 From 89f108b45ae94cd827595461b39f869111092579 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20L=C5=93uillet?= Date: Fri, 5 May 2017 14:54:03 +0200 Subject: Fixed @j0k3r review --- src/Wallabag/CoreBundle/Repository/EntryRepository.php | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Repository/EntryRepository.php b/src/Wallabag/CoreBundle/Repository/EntryRepository.php index 2e03fa19..6972e974 100644 --- a/src/Wallabag/CoreBundle/Repository/EntryRepository.php +++ b/src/Wallabag/CoreBundle/Repository/EntryRepository.php @@ -403,12 +403,10 @@ class EntryRepository extends EntityRepository */ public function findAllByUrlAndUserId($url, $userId) { - $res = $this->createQueryBuilder('e') + return $this->createQueryBuilder('e') ->where('e.url = :url')->setParameter('url', urldecode($url)) ->andWhere('e.user = :user_id')->setParameter('user_id', $userId) ->getQuery() ->getResult(); - - return $res; } } -- cgit v1.2.3 From 7d2d1d685920e8b4975c3967c031ae0abb7098c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20L=C5=93uillet?= Date: Fri, 5 May 2017 15:14:58 +0200 Subject: Added migrations execution after fresh install --- src/Wallabag/CoreBundle/Command/InstallCommand.php | 23 +++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Command/InstallCommand.php b/src/Wallabag/CoreBundle/Command/InstallCommand.php index 3c4d3f25..0d9364f6 100644 --- a/src/Wallabag/CoreBundle/Command/InstallCommand.php +++ b/src/Wallabag/CoreBundle/Command/InstallCommand.php @@ -63,6 +63,7 @@ class InstallCommand extends ContainerAwareCommand ->setupDatabase() ->setupAdmin() ->setupConfig() + ->runMigrations() ; $output->writeln('wallabag has been successfully installed.'); @@ -71,7 +72,7 @@ class InstallCommand extends ContainerAwareCommand protected function checkRequirements() { - $this->defaultOutput->writeln('Step 1 of 4. Checking system requirements.'); + $this->defaultOutput->writeln('Step 1 of 5. Checking system requirements.'); $doctrineManager = $this->getContainer()->get('doctrine')->getManager(); $rows = []; @@ -175,11 +176,11 @@ class InstallCommand extends ContainerAwareCommand protected function setupDatabase() { - $this->defaultOutput->writeln('Step 2 of 4. Setting up database.'); + $this->defaultOutput->writeln('Step 2 of 5. Setting up database.'); // user want to reset everything? Don't care about what is already here if (true === $this->defaultInput->getOption('reset')) { - $this->defaultOutput->writeln('Droping database, creating database and schema, clearing the cache'); + $this->defaultOutput->writeln('Dropping database, creating database and schema, clearing the cache'); $this ->runCommand('doctrine:database:drop', ['--force' => true]) @@ -211,7 +212,7 @@ class InstallCommand extends ContainerAwareCommand $question = new ConfirmationQuestion('It appears that your database already exists. Would you like to reset it? (y/N)', false); if ($questionHelper->ask($this->defaultInput, $this->defaultOutput, $question)) { - $this->defaultOutput->writeln('Droping database, creating database and schema'); + $this->defaultOutput->writeln('Dropping database, creating database and schema'); $this ->runCommand('doctrine:database:drop', ['--force' => true]) @@ -221,7 +222,7 @@ class InstallCommand extends ContainerAwareCommand } elseif ($this->isSchemaPresent()) { $question = new ConfirmationQuestion('Seems like your database contains schema. Do you want to reset it? (y/N)', false); if ($questionHelper->ask($this->defaultInput, $this->defaultOutput, $question)) { - $this->defaultOutput->writeln('Droping schema and creating schema'); + $this->defaultOutput->writeln('Dropping schema and creating schema'); $this ->runCommand('doctrine:schema:drop', ['--force' => true]) @@ -246,7 +247,7 @@ class InstallCommand extends ContainerAwareCommand protected function setupAdmin() { - $this->defaultOutput->writeln('Step 3 of 4. Administration setup.'); + $this->defaultOutput->writeln('Step 3 of 5. Administration setup.'); $questionHelper = $this->getHelperSet()->get('question'); $question = new ConfirmationQuestion('Would you like to create a new admin user (recommended) ? (Y/n)', true); @@ -285,7 +286,7 @@ class InstallCommand extends ContainerAwareCommand protected function setupConfig() { - $this->defaultOutput->writeln('Step 4 of 4. Config setup.'); + $this->defaultOutput->writeln('Step 4 of 5. Config setup.'); $em = $this->getContainer()->get('doctrine.orm.entity_manager'); // cleanup before insert new stuff @@ -464,6 +465,14 @@ class InstallCommand extends ContainerAwareCommand return $this; } + protected function runMigrations() + { + $this->defaultOutput->writeln('Step 5 of 5. Run migrations.'); + + $this + ->runCommand('doctrine:migrations:migrate', ['--no-interaction' => true]); + } + /** * Run a command. * -- cgit v1.2.3 From 34806fab1b26eb626862d45402cb4e265cc0af5b Mon Sep 17 00:00:00 2001 From: Aline Date: Sun, 7 May 2017 15:07:50 +0200 Subject: Fix reviews Signed-off-by: Aline --- .../Resources/views/themes/material/Config/index.html.twig | 8 ++++---- .../Resources/views/themes/material/Entry/_reading_time.html.twig | 4 ++-- .../Resources/views/themes/material/Entry/entry.html.twig | 3 +-- 3 files changed, 7 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/material/Config/index.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/material/Config/index.html.twig index de1fca24..9b0816eb 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/material/Config/index.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/material/Config/index.html.twig @@ -132,8 +132,8 @@
    -
    - +
    +
    {{ 'config.form_rss.token_label'|trans }}
    {% if rss.token %} {{ rss.token }} @@ -151,8 +151,8 @@
    {% if rss.token %}
    -
    - +
    +
    {{ 'config.form_rss.rss_links'|trans }}
    • {{ 'config.form_rss.rss_link.unread'|trans }}
    • {{ 'config.form_rss.rss_link.starred'|trans }}
    • diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/_reading_time.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/_reading_time.html.twig index 1a932a9f..6ba18768 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/_reading_time.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/_reading_time.html.twig @@ -1,7 +1,7 @@ {% set readingTime = entry.readingTime / app.user.config.readingSpeed %} timer {% if readingTime > 0 %} - {{ 'entry.list.reading_time_minutes_short'|trans({'%readingTime%': readingTime|round}) }} + {{ 'entry.list.reading_time_minutes_short'|trans({'%readingTime%': readingTime|round}) }} {% else %} - {{ 'entry.list.reading_time_less_one_minute_short'|trans|raw }} + {{ 'entry.list.reading_time_less_one_minute_short'|trans|raw }} {% endif %} diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entry.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entry.html.twig index a796ed26..987329a5 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entry.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entry.html.twig @@ -132,8 +132,7 @@ {% endif %} {% if craue_setting('share_scuttle') %}
    • - - + scuttle
    • -- cgit v1.2.3 From 4c6ee89c9c70f24209f2bb86de2b3137ab2d801c Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Sun, 7 May 2017 17:13:08 +0200 Subject: Fix review again Signed-off-by: Thomas Citharel --- .../views/themes/material/Entry/entry.html.twig | 74 +++++++++++----------- 1 file changed, 38 insertions(+), 36 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entry.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entry.html.twig index 987329a5..47e6e8c3 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entry.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entry.html.twig @@ -216,46 +216,48 @@

      {{ entry.title|striptags|raw }}

    diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/_card_list.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/_card_list.html.twig index 3ba6253a..174b7b54 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/_card_list.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/_card_list.html.twig @@ -10,7 +10,7 @@
  • {% if entry.isArchived == 0 %}done{% else %}redo{% endif %} {% if entry.isStarred == 0 %}star_border{% else %}star{% endif %} - delete + delete
  • diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entry.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entry.html.twig index 58e08cbc..4cff7bf2 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entry.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entry.html.twig @@ -82,7 +82,7 @@
  • - + delete {{ 'entry.view.left_menu.delete'|trans }} @@ -253,7 +253,10 @@ @@ -279,7 +282,7 @@
  • -- cgit v1.2.3 From 6bc6fb1f60e7b81a21f844dca025671a2f4a4564 Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Sat, 27 May 2017 22:08:14 +0200 Subject: Move Tags assigner to a separate file Signed-off-by: Thomas Citharel --- .../ApiBundle/Controller/EntryRestController.php | 8 +-- .../CoreBundle/Controller/TagController.php | 2 +- src/Wallabag/CoreBundle/Helper/ContentProxy.php | 56 +--------------- src/Wallabag/CoreBundle/Helper/TagsAssigner.php | 76 ++++++++++++++++++++++ .../CoreBundle/Resources/config/services.yml | 6 +- .../ImportBundle/Import/AbstractImport.php | 5 +- src/Wallabag/ImportBundle/Import/BrowserImport.php | 2 +- .../ImportBundle/Import/PinboardImport.php | 2 +- src/Wallabag/ImportBundle/Import/PocketImport.php | 2 +- .../ImportBundle/Import/WallabagImport.php | 2 +- .../ImportBundle/Resources/config/services.yml | 8 +++ 11 files changed, 105 insertions(+), 64 deletions(-) create mode 100644 src/Wallabag/CoreBundle/Helper/TagsAssigner.php (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/EntryRestController.php b/src/Wallabag/ApiBundle/Controller/EntryRestController.php index 4801811d..31bb67fd 100644 --- a/src/Wallabag/ApiBundle/Controller/EntryRestController.php +++ b/src/Wallabag/ApiBundle/Controller/EntryRestController.php @@ -318,7 +318,7 @@ class EntryRestController extends WallabagRestController $tags = $request->request->get('tags', ''); if (!empty($tags)) { - $this->get('wallabag_core.content_proxy')->assignTagsToEntry($entry, $tags); + $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags); } if (!is_null($isStarred)) { @@ -379,7 +379,7 @@ class EntryRestController extends WallabagRestController $tags = $request->request->get('tags', ''); if (!empty($tags)) { - $this->get('wallabag_core.content_proxy')->assignTagsToEntry($entry, $tags); + $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags); } $em = $this->getDoctrine()->getManager(); @@ -497,7 +497,7 @@ class EntryRestController extends WallabagRestController $tags = $request->request->get('tags', ''); if (!empty($tags)) { - $this->get('wallabag_core.content_proxy')->assignTagsToEntry($entry, $tags); + $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags); } $em = $this->getDoctrine()->getManager(); @@ -626,7 +626,7 @@ class EntryRestController extends WallabagRestController $tags = $element->tags; if (false !== $entry && !(empty($tags))) { - $this->get('wallabag_core.content_proxy')->assignTagsToEntry($entry, $tags); + $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags); $em = $this->getDoctrine()->getManager(); $em->persist($entry); diff --git a/src/Wallabag/CoreBundle/Controller/TagController.php b/src/Wallabag/CoreBundle/Controller/TagController.php index 8a093289..fb6a720b 100644 --- a/src/Wallabag/CoreBundle/Controller/TagController.php +++ b/src/Wallabag/CoreBundle/Controller/TagController.php @@ -28,7 +28,7 @@ class TagController extends Controller $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { - $this->get('wallabag_core.content_proxy')->assignTagsToEntry( + $this->get('wallabag_core.tags_assigner')->assignTagsToEntry( $entry, $form->get('label')->getData() ); diff --git a/src/Wallabag/CoreBundle/Helper/ContentProxy.php b/src/Wallabag/CoreBundle/Helper/ContentProxy.php index 9a08db3d..076135c7 100644 --- a/src/Wallabag/CoreBundle/Helper/ContentProxy.php +++ b/src/Wallabag/CoreBundle/Helper/ContentProxy.php @@ -4,10 +4,9 @@ namespace Wallabag\CoreBundle\Helper; use Graby\Graby; use Psr\Log\LoggerInterface; +use Symfony\Component\EventDispatcher\EventDispatcher; use Wallabag\CoreBundle\Entity\Entry; -use Wallabag\CoreBundle\Entity\Tag; use Wallabag\CoreBundle\Tools\Utils; -use Wallabag\CoreBundle\Repository\TagRepository; use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeExtensionGuesser; /** @@ -19,16 +18,15 @@ class ContentProxy protected $graby; protected $tagger; protected $logger; - protected $tagRepository; protected $mimeGuesser; protected $fetchingErrorMessage; + protected $eventDispatcher; - public function __construct(Graby $graby, RuleBasedTagger $tagger, TagRepository $tagRepository, LoggerInterface $logger, $fetchingErrorMessage) + public function __construct(Graby $graby, RuleBasedTagger $tagger, LoggerInterface $logger, $fetchingErrorMessage) { $this->graby = $graby; $this->tagger = $tagger; $this->logger = $logger; - $this->tagRepository = $tagRepository; $this->mimeGuesser = new MimeTypeExtensionGuesser(); $this->fetchingErrorMessage = $fetchingErrorMessage; } @@ -121,54 +119,6 @@ class ContentProxy return $entry; } - /** - * Assign some tags to an entry. - * - * @param Entry $entry - * @param array|string $tags An array of tag or a string coma separated of tag - * @param array $entitiesReady Entities from the EntityManager which are persisted but not yet flushed - * It is mostly to fix duplicate tag on import @see http://stackoverflow.com/a/7879164/569101 - */ - public function assignTagsToEntry(Entry $entry, $tags, array $entitiesReady = []) - { - if (!is_array($tags)) { - $tags = explode(',', $tags); - } - - // keeps only Tag entity from the "not yet flushed entities" - $tagsNotYetFlushed = []; - foreach ($entitiesReady as $entity) { - if ($entity instanceof Tag) { - $tagsNotYetFlushed[$entity->getLabel()] = $entity; - } - } - - foreach ($tags as $label) { - $label = trim($label); - - // avoid empty tag - if (0 === strlen($label)) { - continue; - } - - if (isset($tagsNotYetFlushed[$label])) { - $tagEntity = $tagsNotYetFlushed[$label]; - } else { - $tagEntity = $this->tagRepository->findOneByLabel($label); - - if (is_null($tagEntity)) { - $tagEntity = new Tag(); - $tagEntity->setLabel($label); - } - } - - // only add the tag on the entry if the relation doesn't exist - if (false === $entry->getTags()->contains($tagEntity)) { - $entry->addTag($tagEntity); - } - } - } - /** * Validate that the given content as enough value to be used * instead of fetch the content from the url. diff --git a/src/Wallabag/CoreBundle/Helper/TagsAssigner.php b/src/Wallabag/CoreBundle/Helper/TagsAssigner.php new file mode 100644 index 00000000..ae712d77 --- /dev/null +++ b/src/Wallabag/CoreBundle/Helper/TagsAssigner.php @@ -0,0 +1,76 @@ +tagRepository = $tagRepository; + } + + /** + * Assign some tags to an entry. + * + * @param Entry $entry + * @param array|string $tags An array of tag or a string coma separated of tag + * @param array $entitiesReady Entities from the EntityManager which are persisted but not yet flushed + * It is mostly to fix duplicate tag on import @see http://stackoverflow.com/a/7879164/569101 + * + * @return Tag[] + */ + public function assignTagsToEntry(Entry $entry, $tags, array $entitiesReady = []) + { + $tagsEntities = []; + + if (!is_array($tags)) { + $tags = explode(',', $tags); + } + + // keeps only Tag entity from the "not yet flushed entities" + $tagsNotYetFlushed = []; + foreach ($entitiesReady as $entity) { + if ($entity instanceof Tag) { + $tagsNotYetFlushed[$entity->getLabel()] = $entity; + } + } + + foreach ($tags as $label) { + $label = trim($label); + + // avoid empty tag + if (0 === strlen($label)) { + continue; + } + + if (isset($tagsNotYetFlushed[$label])) { + $tagEntity = $tagsNotYetFlushed[$label]; + } else { + $tagEntity = $this->tagRepository->findOneByLabel($label); + + if (null === $tagEntity) { + $tagEntity = new Tag(); + $tagEntity->setLabel($label); + } + } + + // only add the tag on the entry if the relation doesn't exist + if (false === $entry->getTags()->contains($tagEntity)) { + $entry->addTag($tagEntity); + $tagsEntities[] = $tagEntity; + } + } + + return $tagsEntities; + } +} diff --git a/src/Wallabag/CoreBundle/Resources/config/services.yml b/src/Wallabag/CoreBundle/Resources/config/services.yml index a9134ac3..a68b2fdc 100644 --- a/src/Wallabag/CoreBundle/Resources/config/services.yml +++ b/src/Wallabag/CoreBundle/Resources/config/services.yml @@ -89,10 +89,14 @@ services: arguments: - "@wallabag_core.graby" - "@wallabag_core.rule_based_tagger" - - "@wallabag_core.tag_repository" - "@logger" - '%wallabag_core.fetching_error_message%' + wallabag_core.tags_assigner: + class: Wallabag\CoreBundle\Helper\TagsAssigner + arguments: + - "@wallabag_core.tag_repository" + wallabag_core.rule_based_tagger: class: Wallabag\CoreBundle\Helper\RuleBasedTagger arguments: diff --git a/src/Wallabag/ImportBundle/Import/AbstractImport.php b/src/Wallabag/ImportBundle/Import/AbstractImport.php index 1d4a6e27..a61388c0 100644 --- a/src/Wallabag/ImportBundle/Import/AbstractImport.php +++ b/src/Wallabag/ImportBundle/Import/AbstractImport.php @@ -8,6 +8,7 @@ use Doctrine\ORM\EntityManager; use Wallabag\CoreBundle\Helper\ContentProxy; use Wallabag\CoreBundle\Entity\Entry; use Wallabag\CoreBundle\Entity\Tag; +use Wallabag\CoreBundle\Helper\TagsAssigner; use Wallabag\UserBundle\Entity\User; use OldSound\RabbitMqBundle\RabbitMq\ProducerInterface; use Symfony\Component\EventDispatcher\EventDispatcherInterface; @@ -18,6 +19,7 @@ abstract class AbstractImport implements ImportInterface protected $em; protected $logger; protected $contentProxy; + protected $tagsAssigner; protected $eventDispatcher; protected $producer; protected $user; @@ -26,11 +28,12 @@ abstract class AbstractImport implements ImportInterface protected $importedEntries = 0; protected $queuedEntries = 0; - public function __construct(EntityManager $em, ContentProxy $contentProxy, EventDispatcherInterface $eventDispatcher) + public function __construct(EntityManager $em, ContentProxy $contentProxy, TagsAssigner $tagsAssigner, EventDispatcherInterface $eventDispatcher) { $this->em = $em; $this->logger = new NullLogger(); $this->contentProxy = $contentProxy; + $this->tagsAssigner = $tagsAssigner; $this->eventDispatcher = $eventDispatcher; } diff --git a/src/Wallabag/ImportBundle/Import/BrowserImport.php b/src/Wallabag/ImportBundle/Import/BrowserImport.php index 8bf7d92e..c8a9b4e6 100644 --- a/src/Wallabag/ImportBundle/Import/BrowserImport.php +++ b/src/Wallabag/ImportBundle/Import/BrowserImport.php @@ -205,7 +205,7 @@ abstract class BrowserImport extends AbstractImport $entry = $this->fetchContent($entry, $data['url'], $data); if (array_key_exists('tags', $data)) { - $this->contentProxy->assignTagsToEntry( + $this->tagsAssigner->assignTagsToEntry( $entry, $data['tags'] ); diff --git a/src/Wallabag/ImportBundle/Import/PinboardImport.php b/src/Wallabag/ImportBundle/Import/PinboardImport.php index d9865534..489b9257 100644 --- a/src/Wallabag/ImportBundle/Import/PinboardImport.php +++ b/src/Wallabag/ImportBundle/Import/PinboardImport.php @@ -112,7 +112,7 @@ class PinboardImport extends AbstractImport $entry = $this->fetchContent($entry, $data['url'], $data); if (!empty($data['tags'])) { - $this->contentProxy->assignTagsToEntry( + $this->tagsAssigner->assignTagsToEntry( $entry, $data['tags'], $this->em->getUnitOfWork()->getScheduledEntityInsertions() diff --git a/src/Wallabag/ImportBundle/Import/PocketImport.php b/src/Wallabag/ImportBundle/Import/PocketImport.php index 33093480..1171d452 100644 --- a/src/Wallabag/ImportBundle/Import/PocketImport.php +++ b/src/Wallabag/ImportBundle/Import/PocketImport.php @@ -216,7 +216,7 @@ class PocketImport extends AbstractImport } if (isset($importedEntry['tags']) && !empty($importedEntry['tags'])) { - $this->contentProxy->assignTagsToEntry( + $this->tagsAssigner->assignTagsToEntry( $entry, array_keys($importedEntry['tags']), $this->em->getUnitOfWork()->getScheduledEntityInsertions() diff --git a/src/Wallabag/ImportBundle/Import/WallabagImport.php b/src/Wallabag/ImportBundle/Import/WallabagImport.php index 702da057..0e5382cf 100644 --- a/src/Wallabag/ImportBundle/Import/WallabagImport.php +++ b/src/Wallabag/ImportBundle/Import/WallabagImport.php @@ -111,7 +111,7 @@ abstract class WallabagImport extends AbstractImport $entry = $this->fetchContent($entry, $data['url'], $data); if (array_key_exists('tags', $data)) { - $this->contentProxy->assignTagsToEntry( + $this->tagsAssigner->assignTagsToEntry( $entry, $data['tags'], $this->em->getUnitOfWork()->getScheduledEntityInsertions() diff --git a/src/Wallabag/ImportBundle/Resources/config/services.yml b/src/Wallabag/ImportBundle/Resources/config/services.yml index c4fe3f92..661dc7e1 100644 --- a/src/Wallabag/ImportBundle/Resources/config/services.yml +++ b/src/Wallabag/ImportBundle/Resources/config/services.yml @@ -20,6 +20,7 @@ services: arguments: - "@doctrine.orm.entity_manager" - "@wallabag_core.content_proxy" + - "@wallabag_core.tags_assigner" - "@event_dispatcher" calls: - [ setClient, [ "@wallabag_import.pocket.client" ] ] @@ -32,6 +33,7 @@ services: arguments: - "@doctrine.orm.entity_manager" - "@wallabag_core.content_proxy" + - "@wallabag_core.tags_assigner" - "@event_dispatcher" calls: - [ setLogger, [ "@logger" ]] @@ -43,6 +45,7 @@ services: arguments: - "@doctrine.orm.entity_manager" - "@wallabag_core.content_proxy" + - "@wallabag_core.tags_assigner" - "@event_dispatcher" calls: - [ setLogger, [ "@logger" ]] @@ -54,6 +57,7 @@ services: arguments: - "@doctrine.orm.entity_manager" - "@wallabag_core.content_proxy" + - "@wallabag_core.tags_assigner" - "@event_dispatcher" calls: - [ setLogger, [ "@logger" ]] @@ -65,6 +69,7 @@ services: arguments: - "@doctrine.orm.entity_manager" - "@wallabag_core.content_proxy" + - "@wallabag_core.tags_assigner" - "@event_dispatcher" calls: - [ setLogger, [ "@logger" ]] @@ -76,6 +81,7 @@ services: arguments: - "@doctrine.orm.entity_manager" - "@wallabag_core.content_proxy" + - "@wallabag_core.tags_assigner" - "@event_dispatcher" calls: - [ setLogger, [ "@logger" ]] @@ -87,6 +93,7 @@ services: arguments: - "@doctrine.orm.entity_manager" - "@wallabag_core.content_proxy" + - "@wallabag_core.tags_assigner" - "@event_dispatcher" calls: - [ setLogger, [ "@logger" ]] @@ -97,6 +104,7 @@ services: arguments: - "@doctrine.orm.entity_manager" - "@wallabag_core.content_proxy" + - "@wallabag_core.tags_assigner" - "@event_dispatcher" calls: - [ setLogger, [ "@logger" ]] -- cgit v1.2.3 From 5d3deafd3efc04df53fc24ee82a49988f72756dd Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Sun, 28 May 2017 01:16:01 +0200 Subject: CS Signed-off-by: Thomas Citharel --- src/Wallabag/CoreBundle/Helper/ContentProxy.php | 1 - src/Wallabag/CoreBundle/Helper/TagsAssigner.php | 3 +-- src/Wallabag/ImportBundle/Import/BrowserImport.php | 1 - src/Wallabag/ImportBundle/Import/PocketImport.php | 1 - 4 files changed, 1 insertion(+), 5 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Helper/ContentProxy.php b/src/Wallabag/CoreBundle/Helper/ContentProxy.php index 076135c7..4b3e6fbb 100644 --- a/src/Wallabag/CoreBundle/Helper/ContentProxy.php +++ b/src/Wallabag/CoreBundle/Helper/ContentProxy.php @@ -4,7 +4,6 @@ namespace Wallabag\CoreBundle\Helper; use Graby\Graby; use Psr\Log\LoggerInterface; -use Symfony\Component\EventDispatcher\EventDispatcher; use Wallabag\CoreBundle\Entity\Entry; use Wallabag\CoreBundle\Tools\Utils; use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeExtensionGuesser; diff --git a/src/Wallabag/CoreBundle/Helper/TagsAssigner.php b/src/Wallabag/CoreBundle/Helper/TagsAssigner.php index ae712d77..a2fb0b9a 100644 --- a/src/Wallabag/CoreBundle/Helper/TagsAssigner.php +++ b/src/Wallabag/CoreBundle/Helper/TagsAssigner.php @@ -8,9 +8,8 @@ use Wallabag\CoreBundle\Repository\TagRepository; class TagsAssigner { - /** - * @var TagRepository $tagRepository + * @var TagRepository */ protected $tagRepository; diff --git a/src/Wallabag/ImportBundle/Import/BrowserImport.php b/src/Wallabag/ImportBundle/Import/BrowserImport.php index c8a9b4e6..ef0eeb7e 100644 --- a/src/Wallabag/ImportBundle/Import/BrowserImport.php +++ b/src/Wallabag/ImportBundle/Import/BrowserImport.php @@ -4,7 +4,6 @@ namespace Wallabag\ImportBundle\Import; use Wallabag\CoreBundle\Entity\Entry; use Wallabag\UserBundle\Entity\User; -use Wallabag\CoreBundle\Helper\ContentProxy; use Wallabag\CoreBundle\Event\EntrySavedEvent; abstract class BrowserImport extends AbstractImport diff --git a/src/Wallabag/ImportBundle/Import/PocketImport.php b/src/Wallabag/ImportBundle/Import/PocketImport.php index 1171d452..8835161b 100644 --- a/src/Wallabag/ImportBundle/Import/PocketImport.php +++ b/src/Wallabag/ImportBundle/Import/PocketImport.php @@ -5,7 +5,6 @@ namespace Wallabag\ImportBundle\Import; use GuzzleHttp\Client; use GuzzleHttp\Exception\RequestException; use Wallabag\CoreBundle\Entity\Entry; -use Wallabag\CoreBundle\Helper\ContentProxy; class PocketImport extends AbstractImport { -- cgit v1.2.3 From 2251045901875aa815dee43ec467fb1af8d416d0 Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Sat, 29 Apr 2017 19:22:50 +0200 Subject: WIP Signed-off-by: Thomas Citharel --- .../ApiBundle/Controller/UserRestController.php | 98 ++++++++++++++++++++++ .../ApiBundle/Resources/config/routing_rest.yml | 5 ++ src/Wallabag/UserBundle/Entity/User.php | 5 ++ 3 files changed, 108 insertions(+) create mode 100644 src/Wallabag/ApiBundle/Controller/UserRestController.php (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/UserRestController.php b/src/Wallabag/ApiBundle/Controller/UserRestController.php new file mode 100644 index 00000000..c5ffbdf1 --- /dev/null +++ b/src/Wallabag/ApiBundle/Controller/UserRestController.php @@ -0,0 +1,98 @@ +validateAuthentication(); + + $serializationContext = SerializationContext::create()->setGroups(['user_api']); + $json = $this->get('serializer')->serialize($this->getUser(), 'json', $serializationContext); + + return (new JsonResponse())->setJson($json); + } + + /** + * Register an user + * + * @ApiDoc( + * requirements={ + * {"name"="username", "dataType"="string", "required"=true, "description"="The user's username"}, + * {"name"="password", "dataType"="string", "required"=true, "description"="The user's password"} + * {"name"="email", "dataType"="string", "required"=true, "description"="The user's email"} + * } + * ) + * @return JsonResponse + */ + // TODO : Make this method (or the whole API) accessible only through https + public function putUserAction($username, $password, $email) + { + if (!$this->container->getParameter('fosuser_registration')) { + $json = $this->get('serializer')->serialize(['error' => "Server doesn't allow registrations"], 'json'); + return (new JsonResponse())->setJson($json)->setStatusCode(403); + } + + if ($password === '') { // TODO : might be a good idea to enforce restrictions here + $json = $this->get('serializer')->serialize(['error' => 'Password is blank'], 'json'); + return (new JsonResponse())->setJson($json)->setStatusCode(400); + } + + + // TODO : Make only one call to database by using a custom repository method + if ($this->getDoctrine() + ->getRepository('WallabagUserBundle:User') + ->findOneByUserName($username)) { + $json = $this->get('serializer')->serialize(['error' => 'Username is already taken'], 'json'); + return (new JsonResponse())->setJson($json)->setStatusCode(409); + } + + if ($this->getDoctrine() + ->getRepository('WallabagUserBundle:User') + ->findOneByEmail($email)) { + $json = $this->get('serializer')->serialize(['error' => 'An account with this email already exists'], 'json'); + return (new JsonResponse())->setJson($json)->setStatusCode(409); + } + + $em = $this->get('doctrine.orm.entity_manager'); + + $userManager = $this->get('fos_user.user_manager'); + $user = $userManager->createUser(); + + $user->setUsername($username); + + $user->setPlainPassword($password); + + $user->setEmail($email); + + $user->setEnabled(true); + $user->addRole('ROLE_USER'); + + $em->persist($user); + + // dispatch a created event so the associated config will be created + $event = new UserEvent($user); + $this->get('event_dispatcher')->dispatch(FOSUserEvents::USER_CREATED, $event); + + $serializationContext = SerializationContext::create()->setGroups(['user_api']); + $json = $this->get('serializer')->serialize($user, 'json', $serializationContext); + + return (new JsonResponse())->setJson($json); + + } + +} diff --git a/src/Wallabag/ApiBundle/Resources/config/routing_rest.yml b/src/Wallabag/ApiBundle/Resources/config/routing_rest.yml index 57d37f4b..c0283e71 100644 --- a/src/Wallabag/ApiBundle/Resources/config/routing_rest.yml +++ b/src/Wallabag/ApiBundle/Resources/config/routing_rest.yml @@ -17,3 +17,8 @@ misc: type: rest resource: "WallabagApiBundle:WallabagRest" name_prefix: api_ + +user: + type: rest + resource: "WallabagApiBundle:UserRest" + name_prefix: api_ diff --git a/src/Wallabag/UserBundle/Entity/User.php b/src/Wallabag/UserBundle/Entity/User.php index 3a167de7..1863c966 100644 --- a/src/Wallabag/UserBundle/Entity/User.php +++ b/src/Wallabag/UserBundle/Entity/User.php @@ -4,6 +4,7 @@ namespace Wallabag\UserBundle\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; +use JMS\Serializer\Annotation\Groups; use Scheb\TwoFactorBundle\Model\Email\TwoFactorInterface; use Scheb\TwoFactorBundle\Model\TrustedComputerInterface; use FOS\UserBundle\Model\User as BaseUser; @@ -35,6 +36,7 @@ class User extends BaseUser implements TwoFactorInterface, TrustedComputerInterf * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") + * @Groups({"user_api"}) */ protected $id; @@ -42,6 +44,7 @@ class User extends BaseUser implements TwoFactorInterface, TrustedComputerInterf * @var string * * @ORM\Column(name="name", type="text", nullable=true) + * @Groups({"user_api"}) */ protected $name; @@ -49,6 +52,7 @@ class User extends BaseUser implements TwoFactorInterface, TrustedComputerInterf * @var date * * @ORM\Column(name="created_at", type="datetime") + * @Groups({"user_api"}) */ protected $createdAt; @@ -56,6 +60,7 @@ class User extends BaseUser implements TwoFactorInterface, TrustedComputerInterf * @var date * * @ORM\Column(name="updated_at", type="datetime") + * @Groups({"user_api"}) */ protected $updatedAt; -- cgit v1.2.3 From 2740fc525eaada73734aa62e99e9a2ddb158a6da Mon Sep 17 00:00:00 2001 From: Sven Fischer Date: Mon, 29 May 2017 21:10:00 +0200 Subject: update :de: messages.de.yml --- .../CoreBundle/Resources/translations/messages.de.yml | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml index 6472e64b..00468575 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml @@ -110,7 +110,7 @@ config: annotations: Entferne ALLE Annotationen tags: Entferne ALLE Tags entries: Entferne ALLE Einträge - # archived: Remove ALL archived entries + archived: Entferne ALLE archivierten Einträge confirm: Bist du wirklich sicher? (DIES KANN NICHT RÜCKGÄNGIG GEMACHT WERDEN) form_password: description: "Hier kannst du dein Kennwort ändern. Dieses sollte mindestens acht Zeichen enthalten." @@ -155,7 +155,7 @@ config: or: 'Eine Regel ODER die andere' and: 'Eine Regel UND eine andere' matches: 'Testet, ob eine Variable auf eine Suche zutrifft (Groß- und Kleinschreibung wird nicht berücksichtigt).
    Beispiel: title matches "Fußball"' - # notmatches: 'Tests that a subject is not matches a search (case-insensitive).
    Example: title notmatches "football"' + notmatches: 'Testet, ob ein Titel nicht auf eine Suche zutrifft (Groß- und Kleinschreibung wird nicht berücksichtigt).
    Beispiel: title notmatches "Fußball"' entry: page_titles: @@ -225,8 +225,8 @@ entry: original_article: 'original' annotations_on_the_entry: '{0} Keine Anmerkungen|{1} Eine Anmerkung|]1,Inf[ %count% Anmerkungen' created_at: 'Erstellungsdatum' - # published_at: 'Publication date' - # published_by: 'Published by' + published_at: 'Erscheinungsdatum' + published_by: 'Veröffentlicht von' new: page_title: 'Neuen Artikel speichern' placeholder: 'https://website.de' @@ -242,8 +242,8 @@ entry: public: shared_by_wallabag: "Dieser Artikel wurde mittels wallabag geteilt" confirm: - # delete: "Are you sure you want to remove that article?" - # delete_tag: "Are you sure you want to remove that tag from that article?" + delete: "Bist du sicher, dass du diesen Artikel löschen möchtest?" + delete_tag: "Bist du sicher, dass du diesen Tag vom Artikel entfernen möchtest?" about: page_title: 'Über' @@ -517,7 +517,7 @@ user: delete_confirm: Bist du sicher? back_to_list: Zurück zur Liste search: - # placeholder: Filter by username or email + placeholder: Filtere nach Benutzer oder E-Mail-Adresse error: page_title: Ein Fehler ist aufgetreten @@ -536,7 +536,7 @@ flashes: annotations_reset: Anmerkungen zurücksetzen tags_reset: Tags zurücksetzen entries_reset: Einträge zurücksetzen - # archived_reset: Archived entries deleted + archived_reset: Archiverte Einträge zurücksetzen entry: notice: entry_already_saved: 'Eintrag bereits am %date% gespeichert' -- cgit v1.2.3 From 6eb463c4abf0c06fc03f3d0c961bfd217f00046f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Rumi=C5=84ski?= Date: Mon, 29 May 2017 23:47:00 +0200 Subject: Update messages.pl.yml add missing translation --- .../CoreBundle/Resources/translations/messages.pl.yml | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml index c338e63f..fa672387 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml @@ -110,7 +110,7 @@ config: annotations: Usuń WSZYSTKIE adnotacje tags: Usuń WSZYSTKIE tagi entries: usuń WSZYTSTKIE wpisy - # archived: Remove ALL archived entries + archived: usuń WSZYSTKIE zarchiwizowane wpisy confirm: Jesteś pewien? (tej operacji NIE MOŻNA cofnąć) form_password: description: "Tutaj możesz zmienić swoje hasło. Twoje nowe hasło powinno mieć conajmniej 8 znaków." @@ -155,7 +155,7 @@ config: or: 'Jedna reguła LUB inna' and: 'Jedna reguła I inna' matches: 'Sprawdź czy temat pasuje szukaj (duże lub małe litery).
    Przykład: tytuł zawiera "piłka nożna"' - # notmatches: 'Tests that a subject is not matches a search (case-insensitive).
    Example: title notmatches "football"' + notmatches: 'Sprawdź czy temat nie zawiera szukaj (duże lub małe litery).
    Przykład: tytuł nie zawiera "piłka nożna"' entry: page_titles: @@ -225,8 +225,8 @@ entry: original_article: 'oryginalny' annotations_on_the_entry: '{0} Nie ma adnotacji |{1} Jedna adnotacja |]1,Inf[ %count% adnotacji' created_at: 'Czas stworzenia' - # published_at: 'Publication date' - # published_by: 'Published by' + published_at: 'Data publikacji' + published_by: 'Opublikowane przez' new: page_title: 'Zapisz nowy wpis' placeholder: 'http://website.com' @@ -242,8 +242,8 @@ entry: public: shared_by_wallabag: "Ten artykuł został udostępniony przez wallabag" confirm: - # delete: "Are you sure you want to remove that article?" - # delete_tag: "Are you sure you want to remove that tag from that article?" + delete: "Czy jesteś pewien, że chcesz usunąć ten artykuł?" + delete_tag: "Czy jesteś pewien, że chcesz usunąć ten tag, z tego artykułu?" about: page_title: 'O nas' @@ -517,7 +517,7 @@ user: delete_confirm: Jesteś pewien? back_to_list: Powrót do listy search: - # placeholder: Filter by username or email + placeholder: Filtruj po nazwie użytkownika lub adresie e-mail error: page_title: Wystąpił błąd @@ -536,7 +536,7 @@ flashes: annotations_reset: Zresetuj adnotacje tags_reset: Zresetuj tagi entries_reset: Zresetuj wpisy - # archived_reset: Archived entries deleted + archived_reset: Zarchiwizowane wpisy usunięte entry: notice: entry_already_saved: 'Wpis już został dodany %date%' -- cgit v1.2.3 From 5709ecb36809fb009446a11a758232bbe8f264e4 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Tue, 30 May 2017 07:56:01 +0200 Subject: Re-use `NewUserType` to validate registration MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The only ugly things is how we handle error by generating the view and then parse the content to retrieve all errors… Fix exposition fields in User entity --- .../ApiBundle/Controller/UserRestController.php | 119 ++++++++++++++------- src/Wallabag/UserBundle/Entity/User.php | 25 ++++- 2 files changed, 101 insertions(+), 43 deletions(-) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/UserRestController.php b/src/Wallabag/ApiBundle/Controller/UserRestController.php index c5ffbdf1..a1b78e3f 100644 --- a/src/Wallabag/ApiBundle/Controller/UserRestController.php +++ b/src/Wallabag/ApiBundle/Controller/UserRestController.php @@ -6,12 +6,14 @@ use FOS\UserBundle\Event\UserEvent; use FOS\UserBundle\FOSUserEvents; use JMS\Serializer\SerializationContext; use Nelmio\ApiDocBundle\Annotation\ApiDoc; +use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\JsonResponse; +use Wallabag\UserBundle\Entity\User; class UserRestController extends WallabagRestController { /** - * Retrieve user informations + * Retrieve current logged in user informations. * * @ApiDoc() * @@ -21,78 +23,117 @@ class UserRestController extends WallabagRestController { $this->validateAuthentication(); - $serializationContext = SerializationContext::create()->setGroups(['user_api']); - $json = $this->get('serializer')->serialize($this->getUser(), 'json', $serializationContext); - - return (new JsonResponse())->setJson($json); + return $this->sendUser($this->getUser()); } /** - * Register an user + * Register an user. * * @ApiDoc( * requirements={ * {"name"="username", "dataType"="string", "required"=true, "description"="The user's username"}, - * {"name"="password", "dataType"="string", "required"=true, "description"="The user's password"} + * {"name"="password", "dataType"="string", "required"=true, "description"="The user's password"}, * {"name"="email", "dataType"="string", "required"=true, "description"="The user's email"} * } * ) + * + * @todo Make this method (or the whole API) accessible only through https + * * @return JsonResponse */ - // TODO : Make this method (or the whole API) accessible only through https - public function putUserAction($username, $password, $email) + public function putUserAction(Request $request) { if (!$this->container->getParameter('fosuser_registration')) { $json = $this->get('serializer')->serialize(['error' => "Server doesn't allow registrations"], 'json'); + return (new JsonResponse())->setJson($json)->setStatusCode(403); } - if ($password === '') { // TODO : might be a good idea to enforce restrictions here - $json = $this->get('serializer')->serialize(['error' => 'Password is blank'], 'json'); - return (new JsonResponse())->setJson($json)->setStatusCode(400); - } + $userManager = $this->get('fos_user.user_manager'); + $user = $userManager->createUser(); + // enable created user by default + $user->setEnabled(true); + $form = $this->createForm('Wallabag\UserBundle\Form\NewUserType', $user, [ + 'csrf_protection' => false, + ]); - // TODO : Make only one call to database by using a custom repository method - if ($this->getDoctrine() - ->getRepository('WallabagUserBundle:User') - ->findOneByUserName($username)) { - $json = $this->get('serializer')->serialize(['error' => 'Username is already taken'], 'json'); - return (new JsonResponse())->setJson($json)->setStatusCode(409); - } + // simulate form submission + $form->submit([ + 'username' => $request->request->get('username'), + 'plainPassword' => [ + 'first' => $request->request->get('password'), + 'second' => $request->request->get('password'), + ], + 'email' => $request->request->get('email'), + ]); - if ($this->getDoctrine() - ->getRepository('WallabagUserBundle:User') - ->findOneByEmail($email)) { - $json = $this->get('serializer')->serialize(['error' => 'An account with this email already exists'], 'json'); - return (new JsonResponse())->setJson($json)->setStatusCode(409); - } + if ($form->isSubmitted() && false === $form->isValid()) { + $view = $this->view($form, 400); + $view->setFormat('json'); - $em = $this->get('doctrine.orm.entity_manager'); + // handle errors in a more beautiful way than the default view + $data = json_decode($this->handleView($view)->getContent(), true)['children']; + $errors = []; - $userManager = $this->get('fos_user.user_manager'); - $user = $userManager->createUser(); + if (isset($data['username']['errors'])) { + $errors['username'] = $this->translateErrors($data['username']['errors']); + } - $user->setUsername($username); + if (isset($data['email']['errors'])) { + $errors['email'] = $this->translateErrors($data['email']['errors']); + } - $user->setPlainPassword($password); + if (isset($data['plainPassword']['children']['first']['errors'])) { + $errors['password'] = $this->translateErrors($data['plainPassword']['children']['first']['errors']); + } - $user->setEmail($email); + $json = $this->get('serializer')->serialize(['error' => $errors], 'json'); - $user->setEnabled(true); - $user->addRole('ROLE_USER'); + return (new JsonResponse())->setJson($json)->setStatusCode(400); + } - $em->persist($user); + $userManager->updateUser($user); // dispatch a created event so the associated config will be created - $event = new UserEvent($user); + $event = new UserEvent($user, $request); $this->get('event_dispatcher')->dispatch(FOSUserEvents::USER_CREATED, $event); - $serializationContext = SerializationContext::create()->setGroups(['user_api']); - $json = $this->get('serializer')->serialize($user, 'json', $serializationContext); + return $this->sendUser($user); + } - return (new JsonResponse())->setJson($json); + /** + * Send user response. + * + * @param User $user + * + * @return JsonResponse + */ + private function sendUser(User $user) + { + $json = $this->get('serializer')->serialize( + $user, + 'json', + SerializationContext::create()->setGroups(['user_api']) + ); + return (new JsonResponse())->setJson($json); } + /** + * Translate errors message. + * + * @param array $errors + * + * @return array + */ + private function translateErrors($errors) + { + $translatedErrors = []; + foreach ($errors as $error) { + $translatedErrors[] = $this->get('translator')->trans($error); + } + + return $translatedErrors; + } } diff --git a/src/Wallabag/UserBundle/Entity/User.php b/src/Wallabag/UserBundle/Entity/User.php index 1863c966..1ff3046a 100644 --- a/src/Wallabag/UserBundle/Entity/User.php +++ b/src/Wallabag/UserBundle/Entity/User.php @@ -5,11 +5,10 @@ namespace Wallabag\UserBundle\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; use JMS\Serializer\Annotation\Groups; +use JMS\Serializer\Annotation\XmlRoot; use Scheb\TwoFactorBundle\Model\Email\TwoFactorInterface; use Scheb\TwoFactorBundle\Model\TrustedComputerInterface; use FOS\UserBundle\Model\User as BaseUser; -use JMS\Serializer\Annotation\ExclusionPolicy; -use JMS\Serializer\Annotation\Expose; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; use Symfony\Component\Security\Core\User\UserInterface; use Wallabag\ApiBundle\Entity\Client; @@ -19,23 +18,24 @@ use Wallabag\CoreBundle\Entity\Entry; /** * User. * + * @XmlRoot("user") * @ORM\Entity(repositoryClass="Wallabag\UserBundle\Repository\UserRepository") * @ORM\Table(name="`user`") * @ORM\HasLifecycleCallbacks() - * @ExclusionPolicy("all") * * @UniqueEntity("email") * @UniqueEntity("username") */ class User extends BaseUser implements TwoFactorInterface, TrustedComputerInterface { + /** @Serializer\XmlAttribute */ /** * @var int * - * @Expose * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") + * * @Groups({"user_api"}) */ protected $id; @@ -44,14 +44,30 @@ class User extends BaseUser implements TwoFactorInterface, TrustedComputerInterf * @var string * * @ORM\Column(name="name", type="text", nullable=true) + * * @Groups({"user_api"}) */ protected $name; + /** + * @var string + * + * @Groups({"user_api"}) + */ + protected $username; + + /** + * @var string + * + * @Groups({"user_api"}) + */ + protected $email; + /** * @var date * * @ORM\Column(name="created_at", type="datetime") + * * @Groups({"user_api"}) */ protected $createdAt; @@ -60,6 +76,7 @@ class User extends BaseUser implements TwoFactorInterface, TrustedComputerInterf * @var date * * @ORM\Column(name="updated_at", type="datetime") + * * @Groups({"user_api"}) */ protected $updatedAt; -- cgit v1.2.3 From d069bff4f606be75c47a3415f2a5af13d6f04865 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Tue, 30 May 2017 07:56:41 +0200 Subject: Remove unknown validation_groups The Profile validation_groups does not exist and then for validation to be skipped (like password length) --- src/Wallabag/UserBundle/Controller/ManageController.php | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) (limited to 'src') diff --git a/src/Wallabag/UserBundle/Controller/ManageController.php b/src/Wallabag/UserBundle/Controller/ManageController.php index 1c5c86d4..084f2c67 100644 --- a/src/Wallabag/UserBundle/Controller/ManageController.php +++ b/src/Wallabag/UserBundle/Controller/ManageController.php @@ -33,9 +33,7 @@ class ManageController extends Controller // enable created user by default $user->setEnabled(true); - $form = $this->createForm('Wallabag\UserBundle\Form\NewUserType', $user, [ - 'validation_groups' => ['Profile'], - ]); + $form = $this->createForm('Wallabag\UserBundle\Form\NewUserType', $user); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { -- cgit v1.2.3 From 21242a02a170208bcdd3ffbdb351f0929f708c5a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20L=C5=93uillet?= Date: Wed, 3 May 2017 11:48:43 +0200 Subject: Added tags on list view --- .../Resources/views/themes/material/Entry/_card_list.html.twig | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/_card_list.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/_card_list.html.twig index 174b7b54..24d76a05 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/_card_list.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/_card_list.html.twig @@ -6,13 +6,20 @@ {{ entry.title| striptags | truncate(120, true, '…') | raw }} -
    -- cgit v1.2.3 From 5fe65baee5910c887ba148b1163a1a53654dc324 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Tue, 30 May 2017 11:39:15 +0200 Subject: Fix some Scrutinizer issues --- src/Wallabag/CoreBundle/Entity/Entry.php | 6 +++--- .../CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php | 8 +------- src/Wallabag/CoreBundle/Helper/RuleBasedTagger.php | 1 + 3 files changed, 5 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Entity/Entry.php b/src/Wallabag/CoreBundle/Entity/Entry.php index 08a67c34..29ca9feb 100644 --- a/src/Wallabag/CoreBundle/Entity/Entry.php +++ b/src/Wallabag/CoreBundle/Entity/Entry.php @@ -550,7 +550,7 @@ class Entry } /** - * @return ArrayCollection + * @return array */ public function getTags() { @@ -685,7 +685,7 @@ class Entry } /** - * @return int + * @return string */ public function getHttpStatus() { @@ -693,7 +693,7 @@ class Entry } /** - * @param int $httpStatus + * @param string $httpStatus * * @return Entry */ diff --git a/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php b/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php index c712bb26..15aa0317 100644 --- a/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php +++ b/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php @@ -38,13 +38,7 @@ class GrabySiteConfigBuilder implements SiteConfigBuilder } /** - * Builds the SiteConfig for a host. - * - * @param string $host The "www." prefix is ignored - * - * @return SiteConfig - * - * @throws OutOfRangeException If there is no config for $host + * {@inheritdoc} */ public function buildForHost($host) { diff --git a/src/Wallabag/CoreBundle/Helper/RuleBasedTagger.php b/src/Wallabag/CoreBundle/Helper/RuleBasedTagger.php index add27db2..509d0dec 100644 --- a/src/Wallabag/CoreBundle/Helper/RuleBasedTagger.php +++ b/src/Wallabag/CoreBundle/Helper/RuleBasedTagger.php @@ -15,6 +15,7 @@ class RuleBasedTagger private $rulerz; private $tagRepository; private $entryRepository; + private $logger; public function __construct(RulerZ $rulerz, TagRepository $tagRepository, EntryRepository $entryRepository, LoggerInterface $logger) { -- cgit v1.2.3 From 26650fdbf8af8d716e712e9c9c8474b42f90722d Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Tue, 30 May 2017 12:47:25 +0200 Subject: Use a better way to set input for command Actually use the correct to way handle that http://symfony.com/doc/current/components/console/helpers/questionhelper.html#testing-a-command-that-expects-input --- .../CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php | 1 - 1 file changed, 1 deletion(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php b/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php index 15aa0317..1c56fa9f 100644 --- a/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php +++ b/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php @@ -5,7 +5,6 @@ namespace Wallabag\CoreBundle\GuzzleSiteAuthenticator; use BD\GuzzleSiteAuthenticator\SiteConfig\SiteConfig; use BD\GuzzleSiteAuthenticator\SiteConfig\SiteConfigBuilder; use Graby\SiteConfig\ConfigBuilder; -use OutOfRangeException; use Psr\Log\LoggerInterface; class GrabySiteConfigBuilder implements SiteConfigBuilder -- cgit v1.2.3 From 4ec53ab74c82796a5b3e4bb3ad86ab3f994827cb Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Tue, 30 May 2017 13:01:25 +0200 Subject: CS --- src/Wallabag/CoreBundle/Entity/Entry.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Entity/Entry.php b/src/Wallabag/CoreBundle/Entity/Entry.php index 29ca9feb..9a7dd4e7 100644 --- a/src/Wallabag/CoreBundle/Entity/Entry.php +++ b/src/Wallabag/CoreBundle/Entity/Entry.php @@ -550,7 +550,7 @@ class Entry } /** - * @return array + * @return ArrayCollection */ public function getTags() { -- cgit v1.2.3 From ff24cf9c1d8ebaa6f5458835c431f86b7bd92b6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Benoist?= Date: Tue, 30 May 2017 14:06:38 +0200 Subject: Update :it: translation --- src/Wallabag/CoreBundle/Resources/translations/messages.it.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml index 70e9575a..460675d1 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml @@ -242,8 +242,8 @@ entry: public: # shared_by_wallabag: "This article has been shared by wallabag" confirm: - # delete: "Are you sure you want to remove that article?" - # delete_tag: "Are you sure you want to remove that tag from that article?" + delete: "Vuoi veramente rimuovere quell'articolo?" + delete_tag: "Vuoi veramente rimuovere quell'etichetta da quell'articolo?" about: page_title: 'About' -- cgit v1.2.3 From 047fdc767aed03a92f37273eae2206f3d61fedc5 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Tue, 30 May 2017 20:15:41 +0200 Subject: Add tests --- src/Wallabag/ImportBundle/Import/WallabagV2Import.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Wallabag/ImportBundle/Import/WallabagV2Import.php b/src/Wallabag/ImportBundle/Import/WallabagV2Import.php index 2603503c..3e085ecf 100644 --- a/src/Wallabag/ImportBundle/Import/WallabagV2Import.php +++ b/src/Wallabag/ImportBundle/Import/WallabagV2Import.php @@ -36,8 +36,8 @@ class WallabagV2Import extends WallabagImport return [ 'html' => $entry['content'], 'content_type' => $entry['mimetype'], - 'is_archived' => (int) ($entry['is_archived'] || $this->markAsRead), - 'is_starred' => (int) $entry['is_starred'], + 'is_archived' => (bool) ($entry['is_archived'] || $this->markAsRead), + 'is_starred' => (bool) $entry['is_starred'], ] + $entry; } -- cgit v1.2.3 From 5dbf3f2326c4054782304b9a41d773a1100acf48 Mon Sep 17 00:00:00 2001 From: Kevin Decherf Date: Sun, 21 May 2017 16:35:06 +0200 Subject: TagController: ignore ActionMarkAsRead when removing tag from entry Fixes #2835 Signed-off-by: Kevin Decherf --- src/Wallabag/CoreBundle/Controller/TagController.php | 2 +- src/Wallabag/CoreBundle/Helper/Redirect.php | 10 ++++++---- 2 files changed, 7 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Controller/TagController.php b/src/Wallabag/CoreBundle/Controller/TagController.php index fb6a720b..736eb1dc 100644 --- a/src/Wallabag/CoreBundle/Controller/TagController.php +++ b/src/Wallabag/CoreBundle/Controller/TagController.php @@ -70,7 +70,7 @@ class TagController extends Controller $em->flush(); } - $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers->get('referer')); + $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers->get('referer'), '', true); return $this->redirect($redirectUrl); } diff --git a/src/Wallabag/CoreBundle/Helper/Redirect.php b/src/Wallabag/CoreBundle/Helper/Redirect.php index f78b7fe0..abc84d08 100644 --- a/src/Wallabag/CoreBundle/Helper/Redirect.php +++ b/src/Wallabag/CoreBundle/Helper/Redirect.php @@ -21,12 +21,13 @@ class Redirect } /** - * @param string $url URL to redirect - * @param string $fallback Fallback URL if $url is null + * @param string $url URL to redirect + * @param string $fallback Fallback URL if $url is null + * @param bool $ignoreActionMarkAsRead Ignore configured action when mark as read * * @return string */ - public function to($url, $fallback = '') + public function to($url, $fallback = '', $ignoreActionMarkAsRead = false) { $user = $this->tokenStorage->getToken() ? $this->tokenStorage->getToken()->getUser() : null; @@ -34,7 +35,8 @@ class Redirect return $url; } - if (Config::REDIRECT_TO_HOMEPAGE === $user->getConfig()->getActionMarkAsRead()) { + if (!$ignoreActionMarkAsRead && + Config::REDIRECT_TO_HOMEPAGE === $user->getConfig()->getActionMarkAsRead()) { return $this->router->generate('homepage'); } -- cgit v1.2.3 From 7a8ed3cee1003aae56400e18509980e2695ea622 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Wed, 31 May 2017 10:38:00 +0200 Subject: Add support for tag in Instapaper import --- src/Wallabag/ImportBundle/Import/InstapaperImport.php | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) (limited to 'src') diff --git a/src/Wallabag/ImportBundle/Import/InstapaperImport.php b/src/Wallabag/ImportBundle/Import/InstapaperImport.php index 70a53f1a..c8e0cd5b 100644 --- a/src/Wallabag/ImportBundle/Import/InstapaperImport.php +++ b/src/Wallabag/ImportBundle/Import/InstapaperImport.php @@ -68,6 +68,14 @@ class InstapaperImport extends AbstractImport continue; } + // last element in the csv is the folder where the content belong + // BUT it can also be the status (since status = folder in Instapaper) + // and we don't want archive, unread & starred to become a tag + $tags = null; + if (false === in_array($data[3], ['Archive', 'Unread', 'Starred'])) { + $tags = [$data[3]]; + } + $entries[] = [ 'url' => $data[0], 'title' => $data[1], @@ -75,6 +83,7 @@ class InstapaperImport extends AbstractImport 'is_archived' => $data[3] === 'Archive' || $data[3] === 'Starred', 'is_starred' => $data[3] === 'Starred', 'html' => false, + 'tags' => $tags, ]; } fclose($handle); @@ -118,6 +127,14 @@ class InstapaperImport extends AbstractImport // update entry with content (in case fetching failed, the given entry will be return) $entry = $this->fetchContent($entry, $importedEntry['url'], $importedEntry); + if (!empty($importedEntry['tags'])) { + $this->tagsAssigner->assignTagsToEntry( + $entry, + $importedEntry['tags'], + $this->em->getUnitOfWork()->getScheduledEntityInsertions() + ); + } + $entry->setArchived($importedEntry['is_archived']); $entry->setStarred($importedEntry['is_starred']); -- cgit v1.2.3 From 812c980fa5ea03b9282e32a93723e459eee763a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20L=C5=93uillet?= Date: Mon, 29 May 2017 10:59:30 +0200 Subject: Fixed tags display on grid view --- .../themes/material/Entry/_card_list.html.twig | 47 ++++++++++++---------- .../views/themes/material/Entry/entries.html.twig | 4 +- 2 files changed, 28 insertions(+), 23 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/_card_list.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/_card_list.html.twig index 24d76a05..8a22f0c8 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/_card_list.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/_card_list.html.twig @@ -1,25 +1,30 @@ -
    -
    -
    - - - {{ entry.title| striptags | truncate(120, true, '…') | raw }} - + diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entries.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entries.html.twig index b2d91c9c..6f657b18 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entries.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entries.html.twig @@ -24,9 +24,9 @@

    -
      +
        {% for entry in entries %} -
      • +
      • {% if listMode == 1 %} {% include "@WallabagCore/themes/material/Entry/_card_list.html.twig" with {'entry': entry} only %} {% elseif entry.previewPicture is null %} -- cgit v1.2.3 From e668a8124c46d47add4248963d77f3b29b37b3ce Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Thu, 11 May 2017 08:14:29 +0200 Subject: Allow other fields to be send using API MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Entry API can now have these new fields: - content - language - preview_picture - published_at Re-use the ContentProxy to be able to do the same using the web UI (in the future). htmLawed is used to clean stuff from content, I hope it’ll be enough to avoid security breach. Lower content validation when we want to update an entry with content already defined. Before, language & content_type were required. If there weren’t provided, we re-fetched the content using graby. I think these fields aren’t required for an entry to be created. So I removed them. Which means some import from the v1 export won’t be re-fetched since they provide content, url & title. Also, remove liberation link from Readability import to avoid overlaping import (from wallabag v1, which had the same link) --- .../ApiBundle/Controller/EntryRestController.php | 46 +++++++++++++++------- src/Wallabag/CoreBundle/Helper/ContentProxy.php | 30 ++++++++++---- 2 files changed, 54 insertions(+), 22 deletions(-) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/EntryRestController.php b/src/Wallabag/ApiBundle/Controller/EntryRestController.php index 31bb67fd..dfd04fb4 100644 --- a/src/Wallabag/ApiBundle/Controller/EntryRestController.php +++ b/src/Wallabag/ApiBundle/Controller/EntryRestController.php @@ -280,6 +280,10 @@ class EntryRestController extends WallabagRestController * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."}, * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="entry already starred"}, * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="entry already archived"}, + * {"name"="content", "dataType"="string", "required"=false, "description"="Content of the entry"}, + * {"name"="language", "dataType"="string", "required"=false, "description"="Language of the entry"}, + * {"name"="preview_picture", "dataType"="string", "required"=false, "description"="Preview picture of the entry"}, + * {"name"="published_at", "dataType"="datetime", "format"="YYYY-MM-DDTHH:II:SS+TZ", "required"=false, "description"="Published date of the entry"}, * } * ) * @@ -293,30 +297,42 @@ class EntryRestController extends WallabagRestController $title = $request->request->get('title'); $isArchived = $request->request->get('archive'); $isStarred = $request->request->get('starred'); + $content = $request->request->get('content'); + $language = $request->request->get('language'); + $picture = $request->request->get('preview_picture'); + $publishedAt = $request->request->get('published_at'); $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId($url, $this->getUser()->getId()); if (false === $entry) { $entry = new Entry($this->getUser()); - try { - $entry = $this->get('wallabag_core.content_proxy')->updateEntry( - $entry, - $url - ); - } catch (\Exception $e) { - $this->get('logger')->error('Error while saving an entry', [ - 'exception' => $e, - 'entry' => $entry, - ]); - $entry->setUrl($url); - } } - if (!is_null($title)) { - $entry->setTitle($title); + try { + $entry = $this->get('wallabag_core.content_proxy')->updateEntry( + $entry, + $url, + [ + 'title' => $title, + 'html' => $content, + 'url' => $url, + 'language' => $language, + 'date' => $publishedAt, + // faking the preview picture + 'open_graph' => [ + 'og_image' => $picture, + ], + ] + ); + } catch (\Exception $e) { + $this->get('logger')->error('Error while saving an entry', [ + 'exception' => $e, + 'entry' => $entry, + ]); + $entry->setUrl($url); } - $tags = $request->request->get('tags', ''); + $tags = $request->request->get('tags', []); if (!empty($tags)) { $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags); } diff --git a/src/Wallabag/CoreBundle/Helper/ContentProxy.php b/src/Wallabag/CoreBundle/Helper/ContentProxy.php index 4b3e6fbb..e06ad3d6 100644 --- a/src/Wallabag/CoreBundle/Helper/ContentProxy.php +++ b/src/Wallabag/CoreBundle/Helper/ContentProxy.php @@ -45,6 +45,18 @@ class ContentProxy */ public function updateEntry(Entry $entry, $url, array $content = []) { + // ensure content is a bit cleaned up + if (!empty($content['html'])) { + $content['html'] = htmLawed($content['html'], [ + 'safe' => 1, + // which means: do not remove iframe elements + 'elements' => '*+iframe', + 'deny_attribute' => 'style', + 'comment' => 1, + 'cdata' => 1, + ]); + } + // do we have to fetch the content or the provided one is ok? if (empty($content) || false === $this->validateContent($content)) { $fetchedContent = $this->graby->fetchContent($url); @@ -57,7 +69,7 @@ class ContentProxy } $title = $content['title']; - if (!$title && isset($content['open_graph']['og_title'])) { + if (!$title && !empty($content['open_graph']['og_title'])) { $title = $content['open_graph']['og_title']; } @@ -65,7 +77,7 @@ class ContentProxy if (false === $html) { $html = $this->fetchingErrorMessage; - if (isset($content['open_graph']['og_description'])) { + if (!empty($content['open_graph']['og_description'])) { $html .= '

        But we found a short description:

        '; $html .= $content['open_graph']['og_description']; } @@ -76,8 +88,12 @@ class ContentProxy $entry->setContent($html); $entry->setHttpStatus(isset($content['status']) ? $content['status'] : ''); - if (isset($content['date']) && null !== $content['date'] && '' !== $content['date']) { - $entry->setPublishedAt(new \DateTime($content['date'])); + if (!empty($content['date'])) { + try { + $entry->setPublishedAt(new \DateTime($content['date'])); + } catch (\Exception $e) { + $this->logger->warn('Error while defining date', ['e' => $e, 'url' => $url, 'date' => $content['date']]); + } } if (!empty($content['authors'])) { @@ -97,12 +113,12 @@ class ContentProxy $entry->setDomainName($domainName); } - if (isset($content['open_graph']['og_image']) && $content['open_graph']['og_image']) { + if (!empty($content['open_graph']['og_image'])) { $entry->setPreviewPicture($content['open_graph']['og_image']); } // if content is an image define as a preview too - if (isset($content['content_type']) && in_array($this->mimeGuesser->guess($content['content_type']), ['jpeg', 'jpg', 'gif', 'png'], true)) { + if (!empty($content['content_type']) && in_array($this->mimeGuesser->guess($content['content_type']), ['jpeg', 'jpg', 'gif', 'png'], true)) { $entry->setPreviewPicture($content['url']); } @@ -128,6 +144,6 @@ class ContentProxy */ private function validateContent(array $content) { - return isset($content['title']) && isset($content['html']) && isset($content['url']) && isset($content['language']) && isset($content['content_type']); + return !empty($content['title']) && !empty($content['html']) && !empty($content['url']); } } -- cgit v1.2.3 From fb436e8ca0c7468b9698050df0b78447e2d0854f Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Thu, 11 May 2017 20:10:22 +0200 Subject: Add support for authors --- src/Wallabag/ApiBundle/Controller/EntryRestController.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/EntryRestController.php b/src/Wallabag/ApiBundle/Controller/EntryRestController.php index dfd04fb4..e6bbe552 100644 --- a/src/Wallabag/ApiBundle/Controller/EntryRestController.php +++ b/src/Wallabag/ApiBundle/Controller/EntryRestController.php @@ -284,6 +284,7 @@ class EntryRestController extends WallabagRestController * {"name"="language", "dataType"="string", "required"=false, "description"="Language of the entry"}, * {"name"="preview_picture", "dataType"="string", "required"=false, "description"="Preview picture of the entry"}, * {"name"="published_at", "dataType"="datetime", "format"="YYYY-MM-DDTHH:II:SS+TZ", "required"=false, "description"="Published date of the entry"}, + * {"name"="authors", "dataType"="string", "format"="Name Firstname,author2,author3", "required"=false, "description"="Authors of the entry"}, * } * ) * @@ -295,12 +296,14 @@ class EntryRestController extends WallabagRestController $url = $request->request->get('url'); $title = $request->request->get('title'); + $tags = $request->request->get('tags', []); $isArchived = $request->request->get('archive'); $isStarred = $request->request->get('starred'); $content = $request->request->get('content'); $language = $request->request->get('language'); $picture = $request->request->get('preview_picture'); $publishedAt = $request->request->get('published_at'); + $authors = $request->request->get('authors', ''); $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId($url, $this->getUser()->getId()); @@ -322,6 +325,7 @@ class EntryRestController extends WallabagRestController 'open_graph' => [ 'og_image' => $picture, ], + 'authors' => explode(',', $authors), ] ); } catch (\Exception $e) { @@ -332,7 +336,7 @@ class EntryRestController extends WallabagRestController $entry->setUrl($url); } - $tags = $request->request->get('tags', []); + if (!empty($tags)) { $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags); } -- cgit v1.2.3 From 74a75f7d430eb7a69cd377194e52012db34d39b4 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Fri, 12 May 2017 07:53:21 +0200 Subject: Use graby ContentExtractor to clean html It might be better to re-use some graby functionalities to clean html instead of building a new system. --- src/Wallabag/ApiBundle/Controller/EntryRestController.php | 1 - src/Wallabag/CoreBundle/Helper/ContentProxy.php | 10 ++++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/EntryRestController.php b/src/Wallabag/ApiBundle/Controller/EntryRestController.php index e6bbe552..0930c109 100644 --- a/src/Wallabag/ApiBundle/Controller/EntryRestController.php +++ b/src/Wallabag/ApiBundle/Controller/EntryRestController.php @@ -336,7 +336,6 @@ class EntryRestController extends WallabagRestController $entry->setUrl($url); } - if (!empty($tags)) { $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags); } diff --git a/src/Wallabag/CoreBundle/Helper/ContentProxy.php b/src/Wallabag/CoreBundle/Helper/ContentProxy.php index e06ad3d6..a1df16d8 100644 --- a/src/Wallabag/CoreBundle/Helper/ContentProxy.php +++ b/src/Wallabag/CoreBundle/Helper/ContentProxy.php @@ -47,6 +47,16 @@ class ContentProxy { // ensure content is a bit cleaned up if (!empty($content['html'])) { + $extractor = $this->graby->getExtractor(); + $contentExtracted = $extractor->process($content['html'], $url); + + if ($contentExtracted) { + $contentBlock = $extractor->getContent(); + $contentBlock->normalize(); + + $content['html'] = trim($contentBlock->innerHTML); + } + $content['html'] = htmLawed($content['html'], [ 'safe' => 1, // which means: do not remove iframe elements -- cgit v1.2.3 From 0d6cfb884c8ef75e4dc5fd667fb9d29702523a2a Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Tue, 16 May 2017 23:11:20 +0200 Subject: Remove htmlawed and use graby instead Instead of using htmlawed (which is already used in graby) use graby directly (which require some refacto on graby side). Still needs some tests. --- src/Wallabag/CoreBundle/Helper/ContentProxy.php | 19 +------------------ 1 file changed, 1 insertion(+), 18 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Helper/ContentProxy.php b/src/Wallabag/CoreBundle/Helper/ContentProxy.php index a1df16d8..66d72fe6 100644 --- a/src/Wallabag/CoreBundle/Helper/ContentProxy.php +++ b/src/Wallabag/CoreBundle/Helper/ContentProxy.php @@ -47,24 +47,7 @@ class ContentProxy { // ensure content is a bit cleaned up if (!empty($content['html'])) { - $extractor = $this->graby->getExtractor(); - $contentExtracted = $extractor->process($content['html'], $url); - - if ($contentExtracted) { - $contentBlock = $extractor->getContent(); - $contentBlock->normalize(); - - $content['html'] = trim($contentBlock->innerHTML); - } - - $content['html'] = htmLawed($content['html'], [ - 'safe' => 1, - // which means: do not remove iframe elements - 'elements' => '*+iframe', - 'deny_attribute' => 'style', - 'comment' => 1, - 'cdata' => 1, - ]); + $content['html'] = $this->graby->cleanupHtml($content['html'], $url); } // do we have to fetch the content or the provided one is ok? -- cgit v1.2.3 From 9e349f08a651c43c6d5dd890303ed529c38c4fde Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Wed, 24 May 2017 16:02:49 +0200 Subject: Improve docs --- src/Wallabag/ApiBundle/Controller/EntryRestController.php | 3 +++ src/Wallabag/CoreBundle/Helper/ContentProxy.php | 6 +++--- 2 files changed, 6 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/EntryRestController.php b/src/Wallabag/ApiBundle/Controller/EntryRestController.php index 0930c109..cc2cca64 100644 --- a/src/Wallabag/ApiBundle/Controller/EntryRestController.php +++ b/src/Wallabag/ApiBundle/Controller/EntryRestController.php @@ -273,6 +273,9 @@ class EntryRestController extends WallabagRestController /** * Create an entry. * + * If you want to provide the HTML content (which means wallabag won't fetch it from the url), you must provide `content`, `title` & `url` fields **non-empty**. + * Otherwise, content will be fetched as normal from the url and values will be overwritten. + * * @ApiDoc( * parameters={ * {"name"="url", "dataType"="string", "required"=true, "format"="http://www.test.com/article.html", "description"="Url for the entry."}, diff --git a/src/Wallabag/CoreBundle/Helper/ContentProxy.php b/src/Wallabag/CoreBundle/Helper/ContentProxy.php index 66d72fe6..90d0c50d 100644 --- a/src/Wallabag/CoreBundle/Helper/ContentProxy.php +++ b/src/Wallabag/CoreBundle/Helper/ContentProxy.php @@ -31,7 +31,7 @@ class ContentProxy } /** - * Fetch content using graby and hydrate given entry with results information. + * Fetch content using graby and hydrate given $entry with results information. * In case we couldn't find content, we'll try to use Open Graph data. * * We can also force the content, in case of an import from the v1 for example, so the function won't @@ -39,7 +39,7 @@ class ContentProxy * * @param Entry $entry Entry to update * @param string $url Url to grab content for - * @param array $content An array with AT LEAST keys title, html, url, language & content_type to skip the fetchContent from the url + * @param array $content An array with AT LEAST keys title, html, url to skip the fetchContent from the url * * @return Entry */ @@ -85,7 +85,7 @@ class ContentProxy try { $entry->setPublishedAt(new \DateTime($content['date'])); } catch (\Exception $e) { - $this->logger->warn('Error while defining date', ['e' => $e, 'url' => $url, 'date' => $content['date']]); + $this->logger->warning('Error while defining date', ['e' => $e, 'url' => $url, 'date' => $content['date']]); } } -- cgit v1.2.3 From f0378b4d7c7b8c971239445f3a2a1535abab7d00 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Wed, 24 May 2017 16:44:03 +0200 Subject: Forced date can now be a timestamp too Add adding more tests for forced content --- src/Wallabag/ApiBundle/Controller/EntryRestController.php | 2 +- src/Wallabag/CoreBundle/Helper/ContentProxy.php | 9 ++++++++- 2 files changed, 9 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/EntryRestController.php b/src/Wallabag/ApiBundle/Controller/EntryRestController.php index cc2cca64..c3ba1858 100644 --- a/src/Wallabag/ApiBundle/Controller/EntryRestController.php +++ b/src/Wallabag/ApiBundle/Controller/EntryRestController.php @@ -286,7 +286,7 @@ class EntryRestController extends WallabagRestController * {"name"="content", "dataType"="string", "required"=false, "description"="Content of the entry"}, * {"name"="language", "dataType"="string", "required"=false, "description"="Language of the entry"}, * {"name"="preview_picture", "dataType"="string", "required"=false, "description"="Preview picture of the entry"}, - * {"name"="published_at", "dataType"="datetime", "format"="YYYY-MM-DDTHH:II:SS+TZ", "required"=false, "description"="Published date of the entry"}, + * {"name"="published_at", "dataType"="datetime|integer", "format"="YYYY-MM-DDTHH:II:SS+TZ or a timestamp", "required"=false, "description"="Published date of the entry"}, * {"name"="authors", "dataType"="string", "format"="Name Firstname,author2,author3", "required"=false, "description"="Authors of the entry"}, * } * ) diff --git a/src/Wallabag/CoreBundle/Helper/ContentProxy.php b/src/Wallabag/CoreBundle/Helper/ContentProxy.php index 90d0c50d..8ba77ca9 100644 --- a/src/Wallabag/CoreBundle/Helper/ContentProxy.php +++ b/src/Wallabag/CoreBundle/Helper/ContentProxy.php @@ -82,8 +82,15 @@ class ContentProxy $entry->setHttpStatus(isset($content['status']) ? $content['status'] : ''); if (!empty($content['date'])) { + $date = $content['date']; + + // is it a timestamp? + if (filter_var($date, FILTER_VALIDATE_INT) !== false) { + $date = '@'.$content['date']; + } + try { - $entry->setPublishedAt(new \DateTime($content['date'])); + $entry->setPublishedAt(new \DateTime($date)); } catch (\Exception $e) { $this->logger->warning('Error while defining date', ['e' => $e, 'url' => $url, 'date' => $content['date']]); } -- cgit v1.2.3 From 91775f36fee13c5e1fd77abf27555e6c77fa93da Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Wed, 31 May 2017 14:34:46 +0200 Subject: Add some flex magic Signed-off-by: Thomas Citharel --- .../themes/material/Entry/_card_list.html.twig | 34 ++++++++++------------ 1 file changed, 16 insertions(+), 18 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/_card_list.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/_card_list.html.twig index 8a22f0c8..b64e1436 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/_card_list.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/_card_list.html.twig @@ -1,30 +1,28 @@
        +
        {% if entry.previewPicture is not null %}{% endif %}
        -- cgit v1.2.3 From 7ab5eb9508921d84b4b4ec84a59135d536da748e Mon Sep 17 00:00:00 2001 From: adev Date: Mon, 15 May 2017 20:47:59 +0200 Subject: Isolated tests Use https://github.com/dmaicher/doctrine-test-bundle to have test isolation. --- src/Wallabag/CoreBundle/Command/InstallCommand.php | 16 +++++++--------- src/Wallabag/CoreBundle/Controller/ConfigController.php | 4 ++-- .../Event/Subscriber/SQLiteCascadeDeleteSubscriber.php | 5 ++--- 3 files changed, 11 insertions(+), 14 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Command/InstallCommand.php b/src/Wallabag/CoreBundle/Command/InstallCommand.php index 0d9364f6..d9608246 100644 --- a/src/Wallabag/CoreBundle/Command/InstallCommand.php +++ b/src/Wallabag/CoreBundle/Command/InstallCommand.php @@ -499,20 +499,18 @@ class InstallCommand extends ContainerAwareCommand $output = new BufferedOutput(); $exitCode = $this->getApplication()->run(new ArrayInput($parameters), $output); + // PDO does not always close the connection after Doctrine commands. + // See https://github.com/symfony/symfony/issues/11750. + $this->getContainer()->get('doctrine')->getManager()->getConnection()->close(); + if (0 !== $exitCode) { $this->getApplication()->setAutoExit(true); - $this->defaultOutput->writeln(''); - $this->defaultOutput->writeln('The command "'.$command.'" generates some errors: '); - $this->defaultOutput->writeln($output->fetch()); - - die(); + throw new \RuntimeException( + 'The command "'.$command."\" generates some errors: \n\n" + .$output->fetch()); } - // PDO does not always close the connection after Doctrine commands. - // See https://github.com/symfony/symfony/issues/11750. - $this->getContainer()->get('doctrine')->getManager()->getConnection()->close(); - return $this; } diff --git a/src/Wallabag/CoreBundle/Controller/ConfigController.php b/src/Wallabag/CoreBundle/Controller/ConfigController.php index 1a80cc1a..0e61c642 100644 --- a/src/Wallabag/CoreBundle/Controller/ConfigController.php +++ b/src/Wallabag/CoreBundle/Controller/ConfigController.php @@ -250,7 +250,7 @@ class ConfigController extends Controller case 'entries': // SQLite doesn't care about cascading remove, so we need to manually remove associated stuff // otherwise they won't be removed ... - if ($this->get('doctrine')->getConnection()->getDriver() instanceof \Doctrine\DBAL\Driver\PDOSqlite\Driver) { + if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) { $this->getDoctrine()->getRepository('WallabagAnnotationBundle:Annotation')->removeAllByUserId($this->getUser()->getId()); } @@ -262,7 +262,7 @@ class ConfigController extends Controller ->removeAllByUserId($this->getUser()->getId()); break; case 'archived': - if ($this->get('doctrine')->getConnection()->getDriver() instanceof \Doctrine\DBAL\Driver\PDOSqlite\Driver) { + if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) { $this->removeAnnotationsForArchivedByUserId($this->getUser()->getId()); } diff --git a/src/Wallabag/CoreBundle/Event/Subscriber/SQLiteCascadeDeleteSubscriber.php b/src/Wallabag/CoreBundle/Event/Subscriber/SQLiteCascadeDeleteSubscriber.php index 3b4c4cf9..5e6af8cc 100644 --- a/src/Wallabag/CoreBundle/Event/Subscriber/SQLiteCascadeDeleteSubscriber.php +++ b/src/Wallabag/CoreBundle/Event/Subscriber/SQLiteCascadeDeleteSubscriber.php @@ -45,9 +45,8 @@ class SQLiteCascadeDeleteSubscriber implements EventSubscriber public function preRemove(LifecycleEventArgs $args) { $entity = $args->getEntity(); - - if (!$this->doctrine->getConnection()->getDriver() instanceof \Doctrine\DBAL\Driver\PDOSqlite\Driver || - !$entity instanceof Entry) { + if (!$this->doctrine->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform + || !$entity instanceof Entry) { return; } -- cgit v1.2.3 From 2e05858e1a4b1acf49aa47fe3f1dc708239718a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20L=C5=93uillet?= Date: Wed, 31 May 2017 22:20:44 +0200 Subject: Updated :it: translations Thank you @matteocoder --- .../Resources/translations/messages.it.yml | 26 +++++++++++----------- 1 file changed, 13 insertions(+), 13 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml index 460675d1..d8281fda 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml @@ -24,7 +24,7 @@ menu: tags: 'Tags' internal_settings: 'Strumenti' import: 'Importa' - howto: 'How to' + howto: 'Come fare' # developer: 'API clients management' logout: 'Logout' about: 'About' @@ -44,8 +44,8 @@ footer: wallabag: elsewhere: 'Porta wallabag con te' social: 'Social' - powered_by: 'powered by' - about: 'About' + powered_by: 'Offerto da' + about: 'A proposito' # stats: Since %user_creation% you read %nb_archives% articles. That is about %per_day% a day! config: @@ -55,7 +55,7 @@ config: rss: 'RSS' user_info: 'Informazioni utente' password: 'Password' - rules: 'Regole di tagging' + rules: 'Regole di etichettatura' new_user: 'Aggiungi utente' form: save: 'Salva' @@ -83,7 +83,7 @@ config: # help_pocket_consumer_key: "Required for Pocket import. You can create it in your Pocket account." form_rss: description: 'I feed RSS generati da wallabag ti permettono di leggere i tuoi contenuti salvati con il tuo lettore di RSS preferito. Prima, devi generare un token.' - token_label: 'RSS token' + token_label: 'Token RSS' no_token: 'Nessun token' token_create: 'Crea il tuo token' token_reset: 'Rigenera il tuo token' @@ -94,10 +94,10 @@ config: archive: 'archiviati' rss_limit: 'Numero di elementi nel feed' form_user: - two_factor_description: "Abilitando la two factor authentication riceverai una e-mail con un codice per ogni nuova connesione non verificata" + two_factor_description: "Abilitando l'\autenticazione a due fattori riceverai una e-mail con un codice per ogni nuova connesione non verificata" name_label: 'Nome' email_label: 'E-mail' - twoFactorAuthentication_label: 'Two factor authentication' + twoFactorAuthentication_label: 'Autenticazione a due fattori' # help_twoFactorAuthentication: "If you enable 2FA, each time you want to login to wallabag, you'll receive a code by email." delete: # title: Delete my account (a.k.a danger zone) @@ -119,19 +119,19 @@ config: repeat_new_password_label: 'Ripeti la nuova password' form_rules: if_label: 'se' - then_tag_as_label: 'allora tagga come' + then_tag_as_label: 'allora etichetta come' delete_rule_label: 'elimina' # edit_rule_label: 'edit' rule_label: 'Regola' - tags_label: 'Tag' + tags_label: 'Etichetta' faq: title: 'FAQ' - tagging_rules_definition_title: 'Cosa significa « regole di tagging » ?' - tagging_rules_definition_description: 'Sono regole utilizzate da wallabag per taggare automaticamente i contenuti.
        Ogni volta che viene aggiunto un contenuto, tutte le regole di tagging rules vengono utilizzate per aggiungere i tag configurati, risparmiandoti il lavoro di classificare i contenuti manualmente.' + tagging_rules_definition_title: 'Cosa significa « regole di etichettatura» ?' + tagging_rules_definition_description: 'Sono regole utilizzate da wallabag per etichettare automaticamente i contenuti.
        Ogni volta che viene aggiunto un contenuto, tutte le regole di etichettatura vengono utilizzate per aggiungere le etichette configurate, risparmiandoti il lavoro di classificare i contenuti manualmente.' how_to_use_them_title: 'Come si usano?' - how_to_use_them_description: 'Diciamo che vuoi taggare un contenuto come « lettura veloce » quando il tempo di lettura è inferiore ai 3 minuti.
        In questo case, devi mettere « readingTime <= 3 » nel campo Regola e « lettura veloce » nel campo Tag.
        Molti tag si possono aggiungere contemporanemente separandoli con una virgola: « lettura veloce, da leggere »
        Regole complesse possono essere scritte utilizzando gli operatori predefiniti: se « readingTime >= 5 AND domainName = "github.com" » allora tagga « lettura lunga, github »' + how_to_use_them_description: 'Diciamo che vuoi etichettare un contenuto come « lettura veloce » quando il tempo di lettura è inferiore ai 3 minuti.
        In questo case, devi mettere « readingTime <= 3 » nel campo Regola e « lettura veloce » nel campo Etichette.
        Molte etichette si possono aggiungere contemporanemente separandole con una virgola: « lettura veloce, da leggere »
        Regole complesse possono essere scritte utilizzando gli operatori predefiniti: se « readingTime >= 5 AND domainName = "github.com" » allora etichetta « lettura lunga, github »' variables_available_title: 'Quali operatori e variabili posso utilizzare per scrivere delle regole?' - variables_available_description: 'I seguenti operatori e variabili posso essere utilizzati per scrivere regole di tagging:' + variables_available_description: 'I seguenti operatori e variabili posso essere utilizzati per scrivere regole di etichettatura:' meaning: 'Significato' variable_description: label: 'Variabile' -- cgit v1.2.3 From 53da8ad844b379ab9d82f2497cc5de91da9a1388 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Thu, 1 Jun 2017 09:29:16 +0200 Subject: Page parameter was never used in the function It could have been used if we set the current page inside PreparePagerForEntries. But we did that in each controller because we can have an OutOfRangeCurrentPageException --- src/Wallabag/CoreBundle/Controller/EntryController.php | 3 +-- src/Wallabag/CoreBundle/Controller/TagController.php | 3 +-- src/Wallabag/CoreBundle/Helper/PreparePagerForEntries.php | 5 ++--- 3 files changed, 4 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Controller/EntryController.php b/src/Wallabag/CoreBundle/Controller/EntryController.php index 8d2ac6d4..9fe3e693 100644 --- a/src/Wallabag/CoreBundle/Controller/EntryController.php +++ b/src/Wallabag/CoreBundle/Controller/EntryController.php @@ -321,8 +321,7 @@ class EntryController extends Controller $pagerAdapter = new DoctrineORMAdapter($qb->getQuery(), true, false); - $entries = $this->get('wallabag_core.helper.prepare_pager_for_entries') - ->prepare($pagerAdapter, $page); + $entries = $this->get('wallabag_core.helper.prepare_pager_for_entries')->prepare($pagerAdapter); try { $entries->setCurrentPage($page); diff --git a/src/Wallabag/CoreBundle/Controller/TagController.php b/src/Wallabag/CoreBundle/Controller/TagController.php index 736eb1dc..9422bae4 100644 --- a/src/Wallabag/CoreBundle/Controller/TagController.php +++ b/src/Wallabag/CoreBundle/Controller/TagController.php @@ -125,8 +125,7 @@ class TagController extends Controller $pagerAdapter = new ArrayAdapter($entriesByTag); - $entries = $this->get('wallabag_core.helper.prepare_pager_for_entries') - ->prepare($pagerAdapter, $page); + $entries = $this->get('wallabag_core.helper.prepare_pager_for_entries')->prepare($pagerAdapter); try { $entries->setCurrentPage($page); diff --git a/src/Wallabag/CoreBundle/Helper/PreparePagerForEntries.php b/src/Wallabag/CoreBundle/Helper/PreparePagerForEntries.php index 7d3798b9..df579ebd 100644 --- a/src/Wallabag/CoreBundle/Helper/PreparePagerForEntries.php +++ b/src/Wallabag/CoreBundle/Helper/PreparePagerForEntries.php @@ -20,16 +20,15 @@ class PreparePagerForEntries /** * @param AdapterInterface $adapter - * @param int $page * * @return null|Pagerfanta */ - public function prepare(AdapterInterface $adapter, $page = 1) + public function prepare(AdapterInterface $adapter) { $user = $this->tokenStorage->getToken() ? $this->tokenStorage->getToken()->getUser() : null; if (null === $user || !is_object($user)) { - return null; + return; } $entries = new Pagerfanta($adapter); -- cgit v1.2.3 From c3f7a2ca707dbd43a8798cb3fcefe01333305d8b Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Thu, 1 Jun 2017 09:30:20 +0200 Subject: Set the right variable type --- src/Wallabag/UserBundle/Entity/User.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Wallabag/UserBundle/Entity/User.php b/src/Wallabag/UserBundle/Entity/User.php index 1ff3046a..6cc962b8 100644 --- a/src/Wallabag/UserBundle/Entity/User.php +++ b/src/Wallabag/UserBundle/Entity/User.php @@ -64,7 +64,7 @@ class User extends BaseUser implements TwoFactorInterface, TrustedComputerInterf protected $email; /** - * @var date + * @var \DateTime * * @ORM\Column(name="created_at", type="datetime") * @@ -73,7 +73,7 @@ class User extends BaseUser implements TwoFactorInterface, TrustedComputerInterf protected $createdAt; /** - * @var date + * @var \DateTime * * @ORM\Column(name="updated_at", type="datetime") * -- cgit v1.2.3 From 10bf812a9ed6364902eb0382fe261f3ec0ae7254 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Thu, 1 Jun 2017 09:30:38 +0200 Subject: Both parameter wasn't used in the function, removing them --- src/Wallabag/UserBundle/EventListener/CreateConfigListener.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'src') diff --git a/src/Wallabag/UserBundle/EventListener/CreateConfigListener.php b/src/Wallabag/UserBundle/EventListener/CreateConfigListener.php index 0bdd1cae..e4d55c19 100644 --- a/src/Wallabag/UserBundle/EventListener/CreateConfigListener.php +++ b/src/Wallabag/UserBundle/EventListener/CreateConfigListener.php @@ -5,7 +5,6 @@ namespace Wallabag\UserBundle\EventListener; use Doctrine\ORM\EntityManager; use FOS\UserBundle\Event\UserEvent; use FOS\UserBundle\FOSUserEvents; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Wallabag\CoreBundle\Entity\Config; @@ -47,7 +46,7 @@ class CreateConfigListener implements EventSubscriberInterface ]; } - public function createConfig(UserEvent $event, $eventName = null, EventDispatcherInterface $eventDispatcher = null) + public function createConfig(UserEvent $event) { $config = new Config($event->getUser()); $config->setTheme($this->theme); -- cgit v1.2.3 From 3a6af6c580b686593045a8f0cfbfc478aa93943c Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Thu, 1 Jun 2017 09:36:01 +0200 Subject: fixup! Set the right variable type --- src/Wallabag/UserBundle/Entity/User.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Wallabag/UserBundle/Entity/User.php b/src/Wallabag/UserBundle/Entity/User.php index 6cc962b8..ed6ce331 100644 --- a/src/Wallabag/UserBundle/Entity/User.php +++ b/src/Wallabag/UserBundle/Entity/User.php @@ -157,7 +157,7 @@ class User extends BaseUser implements TwoFactorInterface, TrustedComputerInterf } /** - * @return string + * @return \DateTime */ public function getCreatedAt() { @@ -165,7 +165,7 @@ class User extends BaseUser implements TwoFactorInterface, TrustedComputerInterf } /** - * @return string + * @return \DateTime */ public function getUpdatedAt() { -- cgit v1.2.3 From 7aba665e484c5c36ee029219a999a427d864ff22 Mon Sep 17 00:00:00 2001 From: Jerome Charaoui Date: Tue, 6 Dec 2016 22:17:44 -0500 Subject: Avoid returning objects passed by reference. Objects are always passed by reference, so it doesn't make sense to return an object which is passed by reference as it will always be the same object. This change makes the code a bit more readable. --- src/Wallabag/ApiBundle/Controller/EntryRestController.php | 4 ++-- src/Wallabag/CoreBundle/Controller/EntryController.php | 8 ++------ src/Wallabag/CoreBundle/Helper/ContentProxy.php | 4 ---- src/Wallabag/ImportBundle/Import/AbstractImport.php | 4 +--- src/Wallabag/ImportBundle/Import/BrowserImport.php | 2 +- src/Wallabag/ImportBundle/Import/InstapaperImport.php | 2 +- src/Wallabag/ImportBundle/Import/PinboardImport.php | 2 +- src/Wallabag/ImportBundle/Import/PocketImport.php | 2 +- src/Wallabag/ImportBundle/Import/ReadabilityImport.php | 2 +- src/Wallabag/ImportBundle/Import/WallabagImport.php | 2 +- 10 files changed, 11 insertions(+), 21 deletions(-) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/EntryRestController.php b/src/Wallabag/ApiBundle/Controller/EntryRestController.php index c3ba1858..d154c18b 100644 --- a/src/Wallabag/ApiBundle/Controller/EntryRestController.php +++ b/src/Wallabag/ApiBundle/Controller/EntryRestController.php @@ -315,7 +315,7 @@ class EntryRestController extends WallabagRestController } try { - $entry = $this->get('wallabag_core.content_proxy')->updateEntry( + $this->get('wallabag_core.content_proxy')->updateEntry( $entry, $url, [ @@ -428,7 +428,7 @@ class EntryRestController extends WallabagRestController $this->validateUserAccess($entry->getUser()->getId()); try { - $entry = $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl()); + $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl()); } catch (\Exception $e) { $this->get('logger')->error('Error while saving an entry', [ 'exception' => $e, diff --git a/src/Wallabag/CoreBundle/Controller/EntryController.php b/src/Wallabag/CoreBundle/Controller/EntryController.php index 8d2ac6d4..6018dfac 100644 --- a/src/Wallabag/CoreBundle/Controller/EntryController.php +++ b/src/Wallabag/CoreBundle/Controller/EntryController.php @@ -53,12 +53,10 @@ class EntryController extends Controller /** * Fetch content and update entry. - * In case it fails, entry will return to avod loosing the data. + * In case it fails, $entry->getContent will return an error message. * * @param Entry $entry * @param string $prefixMessage Should be the translation key: entry_saved or entry_reloaded - * - * @return Entry */ private function updateEntry(Entry $entry, $prefixMessage = 'entry_saved') { @@ -68,7 +66,7 @@ class EntryController extends Controller $message = 'flashes.entry.notice.'.$prefixMessage; try { - $entry = $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl()); + $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl()); } catch (\Exception $e) { $this->get('logger')->error('Error while saving an entry', [ 'exception' => $e, @@ -79,8 +77,6 @@ class EntryController extends Controller } $this->get('session')->getFlashBag()->add('notice', $message); - - return $entry; } /** diff --git a/src/Wallabag/CoreBundle/Helper/ContentProxy.php b/src/Wallabag/CoreBundle/Helper/ContentProxy.php index 8ba77ca9..c73b8eaf 100644 --- a/src/Wallabag/CoreBundle/Helper/ContentProxy.php +++ b/src/Wallabag/CoreBundle/Helper/ContentProxy.php @@ -40,8 +40,6 @@ class ContentProxy * @param Entry $entry Entry to update * @param string $url Url to grab content for * @param array $content An array with AT LEAST keys title, html, url to skip the fetchContent from the url - * - * @return Entry */ public function updateEntry(Entry $entry, $url, array $content = []) { @@ -130,8 +128,6 @@ class ContentProxy 'error_msg' => $e->getMessage(), ]); } - - return $entry; } /** diff --git a/src/Wallabag/ImportBundle/Import/AbstractImport.php b/src/Wallabag/ImportBundle/Import/AbstractImport.php index a61388c0..fc462c4c 100644 --- a/src/Wallabag/ImportBundle/Import/AbstractImport.php +++ b/src/Wallabag/ImportBundle/Import/AbstractImport.php @@ -91,13 +91,11 @@ abstract class AbstractImport implements ImportInterface * @param Entry $entry Entry to update * @param string $url Url to grab content for * @param array $content An array with AT LEAST keys title, html, url, language & content_type to skip the fetchContent from the url - * - * @return Entry */ protected function fetchContent(Entry $entry, $url, array $content = []) { try { - return $this->contentProxy->updateEntry($entry, $url, $content); + $this->contentProxy->updateEntry($entry, $url, $content); } catch (\Exception $e) { return $entry; } diff --git a/src/Wallabag/ImportBundle/Import/BrowserImport.php b/src/Wallabag/ImportBundle/Import/BrowserImport.php index ef0eeb7e..71e65e59 100644 --- a/src/Wallabag/ImportBundle/Import/BrowserImport.php +++ b/src/Wallabag/ImportBundle/Import/BrowserImport.php @@ -201,7 +201,7 @@ abstract class BrowserImport extends AbstractImport $entry->setTitle($data['title']); // update entry with content (in case fetching failed, the given entry will be return) - $entry = $this->fetchContent($entry, $data['url'], $data); + $this->fetchContent($entry, $data['url'], $data); if (array_key_exists('tags', $data)) { $this->tagsAssigner->assignTagsToEntry( diff --git a/src/Wallabag/ImportBundle/Import/InstapaperImport.php b/src/Wallabag/ImportBundle/Import/InstapaperImport.php index c8e0cd5b..3aa12f6f 100644 --- a/src/Wallabag/ImportBundle/Import/InstapaperImport.php +++ b/src/Wallabag/ImportBundle/Import/InstapaperImport.php @@ -125,7 +125,7 @@ class InstapaperImport extends AbstractImport $entry->setTitle($importedEntry['title']); // update entry with content (in case fetching failed, the given entry will be return) - $entry = $this->fetchContent($entry, $importedEntry['url'], $importedEntry); + $this->fetchContent($entry, $importedEntry['url'], $importedEntry); if (!empty($importedEntry['tags'])) { $this->tagsAssigner->assignTagsToEntry( diff --git a/src/Wallabag/ImportBundle/Import/PinboardImport.php b/src/Wallabag/ImportBundle/Import/PinboardImport.php index 489b9257..110b0464 100644 --- a/src/Wallabag/ImportBundle/Import/PinboardImport.php +++ b/src/Wallabag/ImportBundle/Import/PinboardImport.php @@ -109,7 +109,7 @@ class PinboardImport extends AbstractImport $entry->setTitle($data['title']); // update entry with content (in case fetching failed, the given entry will be return) - $entry = $this->fetchContent($entry, $data['url'], $data); + $this->fetchContent($entry, $data['url'], $data); if (!empty($data['tags'])) { $this->tagsAssigner->assignTagsToEntry( diff --git a/src/Wallabag/ImportBundle/Import/PocketImport.php b/src/Wallabag/ImportBundle/Import/PocketImport.php index 8835161b..c1d5b6da 100644 --- a/src/Wallabag/ImportBundle/Import/PocketImport.php +++ b/src/Wallabag/ImportBundle/Import/PocketImport.php @@ -192,7 +192,7 @@ class PocketImport extends AbstractImport $entry->setUrl($url); // update entry with content (in case fetching failed, the given entry will be return) - $entry = $this->fetchContent($entry, $url); + $this->fetchContent($entry, $url); // 0, 1, 2 - 1 if the item is archived - 2 if the item should be deleted $entry->setArchived($importedEntry['status'] == 1 || $this->markAsRead); diff --git a/src/Wallabag/ImportBundle/Import/ReadabilityImport.php b/src/Wallabag/ImportBundle/Import/ReadabilityImport.php index de320d23..002b27f4 100644 --- a/src/Wallabag/ImportBundle/Import/ReadabilityImport.php +++ b/src/Wallabag/ImportBundle/Import/ReadabilityImport.php @@ -109,7 +109,7 @@ class ReadabilityImport extends AbstractImport $entry->setTitle($data['title']); // update entry with content (in case fetching failed, the given entry will be return) - $entry = $this->fetchContent($entry, $data['url'], $data); + $this->fetchContent($entry, $data['url'], $data); $entry->setArchived($data['is_archived']); $entry->setStarred($data['is_starred']); diff --git a/src/Wallabag/ImportBundle/Import/WallabagImport.php b/src/Wallabag/ImportBundle/Import/WallabagImport.php index 0e5382cf..c64ccd64 100644 --- a/src/Wallabag/ImportBundle/Import/WallabagImport.php +++ b/src/Wallabag/ImportBundle/Import/WallabagImport.php @@ -108,7 +108,7 @@ abstract class WallabagImport extends AbstractImport $entry->setTitle($data['title']); // update entry with content (in case fetching failed, the given entry will be return) - $entry = $this->fetchContent($entry, $data['url'], $data); + $this->fetchContent($entry, $data['url'], $data); if (array_key_exists('tags', $data)) { $this->tagsAssigner->assignTagsToEntry( -- cgit v1.2.3 From 1c5da417e4ddb14223f9af6e5cea6778e5c0fd08 Mon Sep 17 00:00:00 2001 From: Jerome Charaoui Date: Tue, 6 Dec 2016 22:27:08 -0500 Subject: Put default fetching error title in global config --- src/Wallabag/CoreBundle/Controller/EntryController.php | 3 --- src/Wallabag/CoreBundle/DependencyInjection/Configuration.php | 2 ++ src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php | 1 + src/Wallabag/CoreBundle/Resources/config/services.yml | 1 + 4 files changed, 4 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Controller/EntryController.php b/src/Wallabag/CoreBundle/Controller/EntryController.php index 6018dfac..4b2bc7da 100644 --- a/src/Wallabag/CoreBundle/Controller/EntryController.php +++ b/src/Wallabag/CoreBundle/Controller/EntryController.php @@ -60,9 +60,6 @@ class EntryController extends Controller */ private function updateEntry(Entry $entry, $prefixMessage = 'entry_saved') { - // put default title in case of fetching content failed - $entry->setTitle('No title found'); - $message = 'flashes.entry.notice.'.$prefixMessage; try { diff --git a/src/Wallabag/CoreBundle/DependencyInjection/Configuration.php b/src/Wallabag/CoreBundle/DependencyInjection/Configuration.php index 75b37729..8b5b5744 100644 --- a/src/Wallabag/CoreBundle/DependencyInjection/Configuration.php +++ b/src/Wallabag/CoreBundle/DependencyInjection/Configuration.php @@ -41,6 +41,8 @@ class Configuration implements ConfigurationInterface ->end() ->scalarNode('fetching_error_message') ->end() + ->scalarNode('fetching_error_message_title') + ->end() ->scalarNode('action_mark_as_read') ->defaultValue(1) ->end() diff --git a/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php b/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php index c075c19f..a2a703cb 100644 --- a/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php +++ b/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php @@ -26,6 +26,7 @@ class WallabagCoreExtension extends Extension $container->setParameter('wallabag_core.action_mark_as_read', $config['action_mark_as_read']); $container->setParameter('wallabag_core.list_mode', $config['list_mode']); $container->setParameter('wallabag_core.fetching_error_message', $config['fetching_error_message']); + $container->setParameter('wallabag_core.fetching_error_message_title', $config['fetching_error_message_title']); $container->setParameter('wallabag_core.api_limit_mass_actions', $config['api_limit_mass_actions']); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); diff --git a/src/Wallabag/CoreBundle/Resources/config/services.yml b/src/Wallabag/CoreBundle/Resources/config/services.yml index a68b2fdc..a9b0d2d5 100644 --- a/src/Wallabag/CoreBundle/Resources/config/services.yml +++ b/src/Wallabag/CoreBundle/Resources/config/services.yml @@ -41,6 +41,7 @@ services: arguments: - error_message: '%wallabag_core.fetching_error_message%' + error_message_title: '%wallabag_core.fetching_error_message_title%' - "@wallabag_core.guzzle.http_client" - "@wallabag_core.graby.config_builder" calls: -- cgit v1.2.3 From d0e9b3d640acce49068d1a2c5603b92c1bda363e Mon Sep 17 00:00:00 2001 From: Jerome Charaoui Date: Wed, 7 Dec 2016 15:16:49 -0500 Subject: Add disableContentUpdate import option This commit also decouples the "import" and "update" functions inside ContentProxy. If a content array is available, it must be passed to the new importEntry method. --- src/Wallabag/CoreBundle/Helper/ContentProxy.php | 76 +++++++++++++++------- .../ImportBundle/Command/ImportCommand.php | 4 +- .../ImportBundle/Import/AbstractImport.php | 29 ++++++++- 3 files changed, 84 insertions(+), 25 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Helper/ContentProxy.php b/src/Wallabag/CoreBundle/Helper/ContentProxy.php index c73b8eaf..88873bd5 100644 --- a/src/Wallabag/CoreBundle/Helper/ContentProxy.php +++ b/src/Wallabag/CoreBundle/Helper/ContentProxy.php @@ -7,6 +7,7 @@ use Psr\Log\LoggerInterface; use Wallabag\CoreBundle\Entity\Entry; use Wallabag\CoreBundle\Tools\Utils; use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeExtensionGuesser; +use Symfony\Component\Config\Definition\Exception\Exception; /** * This kind of proxy class take care of getting the content from an url @@ -31,34 +32,58 @@ class ContentProxy } /** - * Fetch content using graby and hydrate given $entry with results information. - * In case we couldn't find content, we'll try to use Open Graph data. - * - * We can also force the content, in case of an import from the v1 for example, so the function won't - * fetch the content from the website but rather use information given with the $content parameter. + * Update existing entry by fetching from URL using Graby. * * @param Entry $entry Entry to update * @param string $url Url to grab content for - * @param array $content An array with AT LEAST keys title, html, url to skip the fetchContent from the url */ - public function updateEntry(Entry $entry, $url, array $content = []) + public function updateEntry(Entry $entry, $url) { - // ensure content is a bit cleaned up - if (!empty($content['html'])) { - $content['html'] = $this->graby->cleanupHtml($content['html'], $url); - } + $content = $this->graby->fetchContent($url); + + $this->stockEntry($entry, $content); + } + + /** + * Import entry using either fetched or provided content. + * + * @param Entry $entry Entry to update + * @param array $content Array with content provided for import with AT LEAST keys title, html, url to skip the fetchContent from the url + * @param bool $disableContentUpdate Whether to skip trying to fetch content using Graby + */ + public function importEntry(Entry $entry, array $content, $disableContentUpdate = false) + { + $this->validateContent($content); - // do we have to fetch the content or the provided one is ok? - if (empty($content) || false === $this->validateContent($content)) { - $fetchedContent = $this->graby->fetchContent($url); + if (false === $disableContentUpdate) { + try { + $fetchedContent = $this->graby->fetchContent($content['url']); + } catch (\Exception $e) { + $this->logger->error('Error while trying to fetch content from URL.', [ + 'entry_url' => $content['url'], + 'error_msg' => $e->getMessage(), + ]); + } // when content is imported, we have information in $content // in case fetching content goes bad, we'll keep the imported information instead of overriding them - if (empty($content) || $fetchedContent['html'] !== $this->fetchingErrorMessage) { + if ($fetchedContent['html'] !== $this->fetchingErrorMessage) { $content = $fetchedContent; } } + $this->stockEntry($entry, $content); + } + + /** + * Stock entry with fetched or imported content. + * Will fall back to OpenGraph data if available. + * + * @param Entry $entry Entry to stock + * @param array $content Array with at least title and URL + */ + private function stockEntry(Entry $entry, array $content) + { $title = $content['title']; if (!$title && !empty($content['open_graph']['og_title'])) { $title = $content['open_graph']['og_title']; @@ -74,7 +99,7 @@ class ContentProxy } } - $entry->setUrl($content['url'] ?: $url); + $entry->setUrl($content['url']); $entry->setTitle($title); $entry->setContent($html); $entry->setHttpStatus(isset($content['status']) ? $content['status'] : ''); @@ -124,22 +149,29 @@ class ContentProxy $this->tagger->tag($entry); } catch (\Exception $e) { $this->logger->error('Error while trying to automatically tag an entry.', [ - 'entry_url' => $url, + 'entry_url' => $content['url'], 'error_msg' => $e->getMessage(), ]); } } /** - * Validate that the given content as enough value to be used - * instead of fetch the content from the url. + * Validate that the given content has at least a title, an html and a url. * * @param array $content - * - * @return bool true if valid otherwise false */ private function validateContent(array $content) { - return !empty($content['title']) && !empty($content['html']) && !empty($content['url']); + if (!empty($content['title']))) { + throw new Exception('Missing title from imported entry!'); + } + + if (!empty($content['url']))) { + throw new Exception('Missing URL from imported entry!'); + } + + if (!empty($content['html']))) { + throw new Exception('Missing html from imported entry!'); + } } } diff --git a/src/Wallabag/ImportBundle/Command/ImportCommand.php b/src/Wallabag/ImportBundle/Command/ImportCommand.php index ce72837a..bca800e6 100644 --- a/src/Wallabag/ImportBundle/Command/ImportCommand.php +++ b/src/Wallabag/ImportBundle/Command/ImportCommand.php @@ -5,6 +5,7 @@ namespace Wallabag\ImportBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Config\Definition\Exception\Exception; use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; @@ -19,7 +20,7 @@ class ImportCommand extends ContainerAwareCommand ->addArgument('filepath', InputArgument::REQUIRED, 'Path to the JSON file') ->addOption('importer', null, InputArgument::OPTIONAL, 'The importer to use: v1, v2, instapaper, pinboard, readability, firefox or chrome', 'v1') ->addOption('markAsRead', null, InputArgument::OPTIONAL, 'Mark all entries as read', false) - ->addOption('useUserId', null, InputArgument::OPTIONAL, 'Use user id instead of username to find account', false) + ->addOption('disableContentUpdate', null, InputOption::VALUE_NONE, 'Disable fetching updated content from URL') ; } @@ -69,6 +70,7 @@ class ImportCommand extends ContainerAwareCommand } $import->setMarkAsRead($input->getOption('markAsRead')); + $import->setDisableContentUpdate($input->getOption('disableContentUpdate')); $import->setUser($user); $res = $import diff --git a/src/Wallabag/ImportBundle/Import/AbstractImport.php b/src/Wallabag/ImportBundle/Import/AbstractImport.php index fc462c4c..167853aa 100644 --- a/src/Wallabag/ImportBundle/Import/AbstractImport.php +++ b/src/Wallabag/ImportBundle/Import/AbstractImport.php @@ -24,6 +24,7 @@ abstract class AbstractImport implements ImportInterface protected $producer; protected $user; protected $markAsRead; + protected $disableContentUpdate; protected $skippedEntries = 0; protected $importedEntries = 0; protected $queuedEntries = 0; @@ -84,6 +85,27 @@ abstract class AbstractImport implements ImportInterface return $this->markAsRead; } + /** + * Set whether articles should be fetched for updated content. + * + * @param bool $markAsRead + */ + public function setDisableContentUpdate($disableContentUpdate) + { + $this->disableContentUpdate = $disableContentUpdate; + + return $this; + } + + /** + * Get whether articles should be fetched for updated content. + */ + public function getDisableContentUpdate() + { + return $this->disableContentUpdate; + } + + /** * Fetch content from the ContentProxy (using graby). * If it fails return the given entry to be saved in all case (to avoid user to loose the content). @@ -95,9 +117,12 @@ abstract class AbstractImport implements ImportInterface protected function fetchContent(Entry $entry, $url, array $content = []) { try { - $this->contentProxy->updateEntry($entry, $url, $content); + $this->contentProxy->importEntry($entry, $content, $this->disableContentUpdate); } catch (\Exception $e) { - return $entry; + $this->logger->error('Error trying to import an entry.', [ + 'entry_url' => $content['url'], + 'error_msg' => $e->getMessage(), + ]); } } -- cgit v1.2.3 From 704803e182068923eba16f3dc451e9231f15ecb5 Mon Sep 17 00:00:00 2001 From: Jerome Charaoui Date: Fri, 16 Dec 2016 09:46:21 -0500 Subject: Replace Wallabag v1 error strings with v2 strings --- src/Wallabag/ImportBundle/Import/WallabagV1Import.php | 18 +++++++++++++++--- .../ImportBundle/Resources/config/services.yml | 2 ++ 2 files changed, 17 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/Wallabag/ImportBundle/Import/WallabagV1Import.php b/src/Wallabag/ImportBundle/Import/WallabagV1Import.php index 59e3ce02..872fd642 100644 --- a/src/Wallabag/ImportBundle/Import/WallabagV1Import.php +++ b/src/Wallabag/ImportBundle/Import/WallabagV1Import.php @@ -4,6 +4,17 @@ namespace Wallabag\ImportBundle\Import; class WallabagV1Import extends WallabagImport { + protected $fetchingErrorMessage; + protected $fetchingErrorMessageTitle; + + public function __construct($em, $contentProxy, $eventDispatcher, $fetchingErrorMessageTitle, $fetchingErrorMessage) + { + $this->fetchingErrorMessageTitle = $fetchingErrorMessageTitle; + $this->fetchingErrorMessage = $fetchingErrorMessage; + + parent::__construct($em, $contentProxy, $eventDispatcher); + } + /** * {@inheritdoc} */ @@ -43,10 +54,11 @@ class WallabagV1Import extends WallabagImport 'created_at' => '', ]; - // force content to be refreshed in case on bad fetch in the v1 installation + // In case of a bad fetch in v1, replace title and content with v2 error strings + // If fetching fails again, they will get this instead of the v1 strings if (in_array($entry['title'], $this->untitled)) { - $data['title'] = ''; - $data['html'] = ''; + $data['title'] = $this->fetchingErrorMessageTitle; + $data['html'] = $this->fetchingErrorMessage; } if (array_key_exists('tags', $entry) && $entry['tags'] != '') { diff --git a/src/Wallabag/ImportBundle/Resources/config/services.yml b/src/Wallabag/ImportBundle/Resources/config/services.yml index 661dc7e1..b224a6a2 100644 --- a/src/Wallabag/ImportBundle/Resources/config/services.yml +++ b/src/Wallabag/ImportBundle/Resources/config/services.yml @@ -35,6 +35,8 @@ services: - "@wallabag_core.content_proxy" - "@wallabag_core.tags_assigner" - "@event_dispatcher" + - "%wallabag_core.fetching_error_message_title%" + - "%wallabag_core.fetching_error_message%" calls: - [ setLogger, [ "@logger" ]] tags: -- cgit v1.2.3 From 432a24f5028446f1bc5c184905f8406bbef8bf05 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Tue, 30 May 2017 16:21:25 +0200 Subject: CS --- src/Wallabag/ImportBundle/Import/AbstractImport.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'src') diff --git a/src/Wallabag/ImportBundle/Import/AbstractImport.php b/src/Wallabag/ImportBundle/Import/AbstractImport.php index 167853aa..1f904292 100644 --- a/src/Wallabag/ImportBundle/Import/AbstractImport.php +++ b/src/Wallabag/ImportBundle/Import/AbstractImport.php @@ -88,7 +88,7 @@ abstract class AbstractImport implements ImportInterface /** * Set whether articles should be fetched for updated content. * - * @param bool $markAsRead + * @param bool $disableContentUpdate */ public function setDisableContentUpdate($disableContentUpdate) { @@ -105,7 +105,6 @@ abstract class AbstractImport implements ImportInterface return $this->disableContentUpdate; } - /** * Fetch content from the ContentProxy (using graby). * If it fails return the given entry to be saved in all case (to avoid user to loose the content). -- cgit v1.2.3 From d5c2cc54b5490b0bec46f39d7706d5d46869e872 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Tue, 30 May 2017 17:48:24 +0200 Subject: Fix tests --- .../ApiBundle/Controller/EntryRestController.php | 45 +++++++++++----------- src/Wallabag/CoreBundle/Helper/ContentProxy.php | 27 +++++++++---- .../ImportBundle/Command/ImportCommand.php | 1 + .../ImportBundle/Import/AbstractImport.php | 5 ++- .../ImportBundle/Import/WallabagV1Import.php | 4 +- 5 files changed, 49 insertions(+), 33 deletions(-) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/EntryRestController.php b/src/Wallabag/ApiBundle/Controller/EntryRestController.php index d154c18b..93c8157e 100644 --- a/src/Wallabag/ApiBundle/Controller/EntryRestController.php +++ b/src/Wallabag/ApiBundle/Controller/EntryRestController.php @@ -231,7 +231,6 @@ class EntryRestController extends WallabagRestController $this->validateAuthentication(); $urls = json_decode($request->query->get('urls', [])); - $results = []; $limit = $this->container->getParameter('wallabag_core.api_limit_mass_actions'); @@ -239,32 +238,34 @@ class EntryRestController extends WallabagRestController throw new HttpException(400, 'API limit reached'); } + $results = []; + if (empty($urls)) { + return $this->sendResponse($results); + } + // handle multiple urls - if (!empty($urls)) { - foreach ($urls as $key => $url) { - $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId( - $url, - $this->getUser()->getId() - ); - - $results[$key]['url'] = $url; - - if (false === $entry) { - $entry = $this->get('wallabag_core.content_proxy')->updateEntry( - new Entry($this->getUser()), - $url - ); - } + foreach ($urls as $key => $url) { + $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId( + $url, + $this->getUser()->getId() + ); - $em = $this->getDoctrine()->getManager(); - $em->persist($entry); - $em->flush(); + $results[$key]['url'] = $url; - $results[$key]['entry'] = $entry instanceof Entry ? $entry->getId() : false; + if (false === $entry) { + $entry = new Entry($this->getUser()); - // entry saved, dispatch event about it! - $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry)); + $this->get('wallabag_core.content_proxy')->updateEntry($entry, $url); } + + $em = $this->getDoctrine()->getManager(); + $em->persist($entry); + $em->flush(); + + $results[$key]['entry'] = $entry instanceof Entry ? $entry->getId() : false; + + // entry saved, dispatch event about it! + $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry)); } return $this->sendResponse($results); diff --git a/src/Wallabag/CoreBundle/Helper/ContentProxy.php b/src/Wallabag/CoreBundle/Helper/ContentProxy.php index 88873bd5..cd18c668 100644 --- a/src/Wallabag/CoreBundle/Helper/ContentProxy.php +++ b/src/Wallabag/CoreBundle/Helper/ContentProxy.php @@ -34,13 +34,17 @@ class ContentProxy /** * Update existing entry by fetching from URL using Graby. * - * @param Entry $entry Entry to update - * @param string $url Url to grab content for + * @param Entry $entry Entry to update + * @param string $url Url to grab content for */ public function updateEntry(Entry $entry, $url) { $content = $this->graby->fetchContent($url); + // be sure to keep the url in case of error + // so we'll be able to refetch it in the future + $content['url'] = $content['url'] ?: $url; + $this->stockEntry($entry, $content); } @@ -53,7 +57,14 @@ class ContentProxy */ public function importEntry(Entry $entry, array $content, $disableContentUpdate = false) { - $this->validateContent($content); + try { + $this->validateContent($content); + } catch (\Exception $e) { + // validation failed but do we want to disable updating content? + if (true === $disableContentUpdate) { + throw $e; + } + } if (false === $disableContentUpdate) { try { @@ -79,8 +90,8 @@ class ContentProxy * Stock entry with fetched or imported content. * Will fall back to OpenGraph data if available. * - * @param Entry $entry Entry to stock - * @param array $content Array with at least title and URL + * @param Entry $entry Entry to stock + * @param array $content Array with at least title and URL */ private function stockEntry(Entry $entry, array $content) { @@ -162,15 +173,15 @@ class ContentProxy */ private function validateContent(array $content) { - if (!empty($content['title']))) { + if (empty($content['title'])) { throw new Exception('Missing title from imported entry!'); } - if (!empty($content['url']))) { + if (empty($content['url'])) { throw new Exception('Missing URL from imported entry!'); } - if (!empty($content['html']))) { + if (empty($content['html'])) { throw new Exception('Missing html from imported entry!'); } } diff --git a/src/Wallabag/ImportBundle/Command/ImportCommand.php b/src/Wallabag/ImportBundle/Command/ImportCommand.php index bca800e6..0829a1da 100644 --- a/src/Wallabag/ImportBundle/Command/ImportCommand.php +++ b/src/Wallabag/ImportBundle/Command/ImportCommand.php @@ -20,6 +20,7 @@ class ImportCommand extends ContainerAwareCommand ->addArgument('filepath', InputArgument::REQUIRED, 'Path to the JSON file') ->addOption('importer', null, InputArgument::OPTIONAL, 'The importer to use: v1, v2, instapaper, pinboard, readability, firefox or chrome', 'v1') ->addOption('markAsRead', null, InputArgument::OPTIONAL, 'Mark all entries as read', false) + ->addOption('useUserId', null, InputArgument::OPTIONAL, 'Use user id instead of username to find account', false) ->addOption('disableContentUpdate', null, InputOption::VALUE_NONE, 'Disable fetching updated content from URL') ; } diff --git a/src/Wallabag/ImportBundle/Import/AbstractImport.php b/src/Wallabag/ImportBundle/Import/AbstractImport.php index 1f904292..bf568a1a 100644 --- a/src/Wallabag/ImportBundle/Import/AbstractImport.php +++ b/src/Wallabag/ImportBundle/Import/AbstractImport.php @@ -24,7 +24,7 @@ abstract class AbstractImport implements ImportInterface protected $producer; protected $user; protected $markAsRead; - protected $disableContentUpdate; + protected $disableContentUpdate = false; protected $skippedEntries = 0; protected $importedEntries = 0; protected $queuedEntries = 0; @@ -115,6 +115,9 @@ abstract class AbstractImport implements ImportInterface */ protected function fetchContent(Entry $entry, $url, array $content = []) { + // be sure to set at least the given url + $content['url'] = isset($content['url']) ? $content['url'] : $url; + try { $this->contentProxy->importEntry($entry, $content, $this->disableContentUpdate); } catch (\Exception $e) { diff --git a/src/Wallabag/ImportBundle/Import/WallabagV1Import.php b/src/Wallabag/ImportBundle/Import/WallabagV1Import.php index 872fd642..1f0df646 100644 --- a/src/Wallabag/ImportBundle/Import/WallabagV1Import.php +++ b/src/Wallabag/ImportBundle/Import/WallabagV1Import.php @@ -7,12 +7,12 @@ class WallabagV1Import extends WallabagImport protected $fetchingErrorMessage; protected $fetchingErrorMessageTitle; - public function __construct($em, $contentProxy, $eventDispatcher, $fetchingErrorMessageTitle, $fetchingErrorMessage) + public function __construct($em, $contentProxy, $tagsAssigner, $eventDispatcher, $fetchingErrorMessageTitle, $fetchingErrorMessage) { $this->fetchingErrorMessageTitle = $fetchingErrorMessageTitle; $this->fetchingErrorMessage = $fetchingErrorMessage; - parent::__construct($em, $contentProxy, $eventDispatcher); + parent::__construct($em, $contentProxy, $tagsAssigner, $eventDispatcher); } /** -- cgit v1.2.3 From 843182c7cf428b5f6b8a1ff7057adc703c1e816e Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Thu, 1 Jun 2017 09:52:09 +0200 Subject: CS --- src/Wallabag/CoreBundle/Helper/ContentProxy.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Helper/ContentProxy.php b/src/Wallabag/CoreBundle/Helper/ContentProxy.php index cd18c668..e6292744 100644 --- a/src/Wallabag/CoreBundle/Helper/ContentProxy.php +++ b/src/Wallabag/CoreBundle/Helper/ContentProxy.php @@ -51,9 +51,9 @@ class ContentProxy /** * Import entry using either fetched or provided content. * - * @param Entry $entry Entry to update - * @param array $content Array with content provided for import with AT LEAST keys title, html, url to skip the fetchContent from the url - * @param bool $disableContentUpdate Whether to skip trying to fetch content using Graby + * @param Entry $entry Entry to update + * @param array $content Array with content provided for import with AT LEAST keys title, html, url to skip the fetchContent from the url + * @param bool $disableContentUpdate Whether to skip trying to fetch content using Graby */ public function importEntry(Entry $entry, array $content, $disableContentUpdate = false) { -- cgit v1.2.3 From 6acadf8e98cf6021a9019773df75bdb151865687 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Thu, 1 Jun 2017 11:31:45 +0200 Subject: Rewrote code & fix tests --- src/Wallabag/CoreBundle/Helper/ContentProxy.php | 66 +++++++--------------- .../ImportBundle/Import/AbstractImport.php | 7 +-- 2 files changed, 22 insertions(+), 51 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Helper/ContentProxy.php b/src/Wallabag/CoreBundle/Helper/ContentProxy.php index e6292744..3024fdc5 100644 --- a/src/Wallabag/CoreBundle/Helper/ContentProxy.php +++ b/src/Wallabag/CoreBundle/Helper/ContentProxy.php @@ -7,7 +7,6 @@ use Psr\Log\LoggerInterface; use Wallabag\CoreBundle\Entity\Entry; use Wallabag\CoreBundle\Tools\Utils; use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeExtensionGuesser; -use Symfony\Component\Config\Definition\Exception\Exception; /** * This kind of proxy class take care of getting the content from an url @@ -32,57 +31,40 @@ class ContentProxy } /** - * Update existing entry by fetching from URL using Graby. + * Update entry using either fetched or provided content. * - * @param Entry $entry Entry to update - * @param string $url Url to grab content for + * @param Entry $entry Entry to update + * @param string $url Url of the content + * @param array $content Array with content provided for import with AT LEAST keys title, html, url to skip the fetchContent from the url + * @param bool $disableContentUpdate Whether to skip trying to fetch content using Graby */ - public function updateEntry(Entry $entry, $url) + public function updateEntry(Entry $entry, $url, array $content = [], $disableContentUpdate = false) { - $content = $this->graby->fetchContent($url); - - // be sure to keep the url in case of error - // so we'll be able to refetch it in the future - $content['url'] = $content['url'] ?: $url; - - $this->stockEntry($entry, $content); - } - - /** - * Import entry using either fetched or provided content. - * - * @param Entry $entry Entry to update - * @param array $content Array with content provided for import with AT LEAST keys title, html, url to skip the fetchContent from the url - * @param bool $disableContentUpdate Whether to skip trying to fetch content using Graby - */ - public function importEntry(Entry $entry, array $content, $disableContentUpdate = false) - { - try { - $this->validateContent($content); - } catch (\Exception $e) { - // validation failed but do we want to disable updating content? - if (true === $disableContentUpdate) { - throw $e; - } + if (!empty($content['html'])) { + $content['html'] = $this->graby->cleanupHtml($content['html'], $url); } - if (false === $disableContentUpdate) { + if ((empty($content) || false === $this->validateContent($content)) && false === $disableContentUpdate) { try { - $fetchedContent = $this->graby->fetchContent($content['url']); + $fetchedContent = $this->graby->fetchContent($url); } catch (\Exception $e) { $this->logger->error('Error while trying to fetch content from URL.', [ - 'entry_url' => $content['url'], + 'entry_url' => $url, 'error_msg' => $e->getMessage(), ]); } // when content is imported, we have information in $content // in case fetching content goes bad, we'll keep the imported information instead of overriding them - if ($fetchedContent['html'] !== $this->fetchingErrorMessage) { + if (empty($content) || $fetchedContent['html'] !== $this->fetchingErrorMessage) { $content = $fetchedContent; } } + // be sure to keep the url in case of error + // so we'll be able to refetch it in the future + $content['url'] = !empty($content['url']) ? $content['url'] : $url; + $this->stockEntry($entry, $content); } @@ -126,7 +108,7 @@ class ContentProxy try { $entry->setPublishedAt(new \DateTime($date)); } catch (\Exception $e) { - $this->logger->warning('Error while defining date', ['e' => $e, 'url' => $url, 'date' => $content['date']]); + $this->logger->warning('Error while defining date', ['e' => $e, 'url' => $content['url'], 'date' => $content['date']]); } } @@ -170,19 +152,11 @@ class ContentProxy * Validate that the given content has at least a title, an html and a url. * * @param array $content + * + * @return bool true if valid otherwise false */ private function validateContent(array $content) { - if (empty($content['title'])) { - throw new Exception('Missing title from imported entry!'); - } - - if (empty($content['url'])) { - throw new Exception('Missing URL from imported entry!'); - } - - if (empty($content['html'])) { - throw new Exception('Missing html from imported entry!'); - } + return !empty($content['title']) && !empty($content['html']) && !empty($content['url']); } } diff --git a/src/Wallabag/ImportBundle/Import/AbstractImport.php b/src/Wallabag/ImportBundle/Import/AbstractImport.php index bf568a1a..9f3d822a 100644 --- a/src/Wallabag/ImportBundle/Import/AbstractImport.php +++ b/src/Wallabag/ImportBundle/Import/AbstractImport.php @@ -115,14 +115,11 @@ abstract class AbstractImport implements ImportInterface */ protected function fetchContent(Entry $entry, $url, array $content = []) { - // be sure to set at least the given url - $content['url'] = isset($content['url']) ? $content['url'] : $url; - try { - $this->contentProxy->importEntry($entry, $content, $this->disableContentUpdate); + $this->contentProxy->updateEntry($entry, $url, $content, $this->disableContentUpdate); } catch (\Exception $e) { $this->logger->error('Error trying to import an entry.', [ - 'entry_url' => $content['url'], + 'entry_url' => $url, 'error_msg' => $e->getMessage(), ]); } -- cgit v1.2.3 From ec970721525d9a4761a30ee417406cf8ad8bb171 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Thu, 1 Jun 2017 11:45:02 +0200 Subject: No need to catch that Exception --- src/Wallabag/CoreBundle/Helper/ContentProxy.php | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Helper/ContentProxy.php b/src/Wallabag/CoreBundle/Helper/ContentProxy.php index 3024fdc5..bfaa1976 100644 --- a/src/Wallabag/CoreBundle/Helper/ContentProxy.php +++ b/src/Wallabag/CoreBundle/Helper/ContentProxy.php @@ -45,14 +45,7 @@ class ContentProxy } if ((empty($content) || false === $this->validateContent($content)) && false === $disableContentUpdate) { - try { - $fetchedContent = $this->graby->fetchContent($url); - } catch (\Exception $e) { - $this->logger->error('Error while trying to fetch content from URL.', [ - 'entry_url' => $url, - 'error_msg' => $e->getMessage(), - ]); - } + $fetchedContent = $this->graby->fetchContent($url); // when content is imported, we have information in $content // in case fetching content goes bad, we'll keep the imported information instead of overriding them @@ -73,7 +66,7 @@ class ContentProxy * Will fall back to OpenGraph data if available. * * @param Entry $entry Entry to stock - * @param array $content Array with at least title and URL + * @param array $content Array with at least title, url & html */ private function stockEntry(Entry $entry, array $content) { -- cgit v1.2.3 From 701d3066fbac504beb25ab7a13546ad155e65488 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Thu, 1 Jun 2017 12:46:07 +0200 Subject: We don't need that getter --- src/Wallabag/ImportBundle/Import/AbstractImport.php | 8 -------- 1 file changed, 8 deletions(-) (limited to 'src') diff --git a/src/Wallabag/ImportBundle/Import/AbstractImport.php b/src/Wallabag/ImportBundle/Import/AbstractImport.php index 9f3d822a..9b624296 100644 --- a/src/Wallabag/ImportBundle/Import/AbstractImport.php +++ b/src/Wallabag/ImportBundle/Import/AbstractImport.php @@ -97,14 +97,6 @@ abstract class AbstractImport implements ImportInterface return $this; } - /** - * Get whether articles should be fetched for updated content. - */ - public function getDisableContentUpdate() - { - return $this->disableContentUpdate; - } - /** * Fetch content from the ContentProxy (using graby). * If it fails return the given entry to be saved in all case (to avoid user to loose the content). -- cgit v1.2.3 From f5924e954730efdb7b9fadf23c0b73b3f5a0a434 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Thu, 1 Jun 2017 15:44:36 +0200 Subject: Fix option attributes --- src/Wallabag/ImportBundle/Command/ImportCommand.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/Wallabag/ImportBundle/Command/ImportCommand.php b/src/Wallabag/ImportBundle/Command/ImportCommand.php index 0829a1da..5f1ab0af 100644 --- a/src/Wallabag/ImportBundle/Command/ImportCommand.php +++ b/src/Wallabag/ImportBundle/Command/ImportCommand.php @@ -18,9 +18,9 @@ class ImportCommand extends ContainerAwareCommand ->setDescription('Import entries from a JSON export') ->addArgument('username', InputArgument::REQUIRED, 'User to populate') ->addArgument('filepath', InputArgument::REQUIRED, 'Path to the JSON file') - ->addOption('importer', null, InputArgument::OPTIONAL, 'The importer to use: v1, v2, instapaper, pinboard, readability, firefox or chrome', 'v1') - ->addOption('markAsRead', null, InputArgument::OPTIONAL, 'Mark all entries as read', false) - ->addOption('useUserId', null, InputArgument::OPTIONAL, 'Use user id instead of username to find account', false) + ->addOption('importer', null, InputOption::VALUE_OPTIONAL, 'The importer to use: v1, v2, instapaper, pinboard, readability, firefox or chrome', 'v1') + ->addOption('markAsRead', null, InputOption::VALUE_OPTIONAL, 'Mark all entries as read', false) + ->addOption('useUserId', null, InputOption::VALUE_NONE, 'Use user id instead of username to find account') ->addOption('disableContentUpdate', null, InputOption::VALUE_NONE, 'Disable fetching updated content from URL') ; } -- cgit v1.2.3 From fcad69a427de7ce4f65cbf53bcf778e561959807 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Thu, 1 Jun 2017 22:50:33 +0200 Subject: Replace images with & MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Images with `&` in the path weren’t well replaced because they might be with `&` in the html instead. Replacing `&` with `&` fix the problem. --- src/Wallabag/CoreBundle/Helper/DownloadImages.php | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Helper/DownloadImages.php b/src/Wallabag/CoreBundle/Helper/DownloadImages.php index 0d330d2a..f7c26a38 100644 --- a/src/Wallabag/CoreBundle/Helper/DownloadImages.php +++ b/src/Wallabag/CoreBundle/Helper/DownloadImages.php @@ -66,6 +66,12 @@ class DownloadImages continue; } + // if image contains "&"" and we can't find it in the html + // it might be because it's encoded as & + if (false !== stripos($image, '&') && false === stripos($html, $image)) { + $image = str_replace('&', '&', $image); + } + $html = str_replace($image, $imagePath, $html); } @@ -114,7 +120,7 @@ class DownloadImages $ext = $this->mimeGuesser->guess($res->getHeader('content-type')); $this->logger->debug('DownloadImages: Checking extension', ['ext' => $ext, 'header' => $res->getHeader('content-type')]); if (!in_array($ext, ['jpeg', 'jpg', 'gif', 'png'], true)) { - $this->logger->error('DownloadImages: Processed image with not allowed extension. Skipping '.$imagePath); + $this->logger->error('DownloadImages: Processed image with not allowed extension. Skipping: '.$imagePath); return false; } -- cgit v1.2.3 From 9bf7752f73ebfbfea0adbdb0d562a3cfa85039f3 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Thu, 1 Jun 2017 22:58:38 +0200 Subject: CS --- src/Wallabag/CoreBundle/Helper/DownloadImages.php | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Helper/DownloadImages.php b/src/Wallabag/CoreBundle/Helper/DownloadImages.php index f7c26a38..54e23a05 100644 --- a/src/Wallabag/CoreBundle/Helper/DownloadImages.php +++ b/src/Wallabag/CoreBundle/Helper/DownloadImages.php @@ -54,7 +54,7 @@ class DownloadImages $crawler = new Crawler($html); $result = $crawler ->filterXpath('//img') - ->extract(array('src')); + ->extract(['src']); $relativePath = $this->getRelativePath($entryId); @@ -66,8 +66,7 @@ class DownloadImages continue; } - // if image contains "&"" and we can't find it in the html - // it might be because it's encoded as & + // if image contains "&" and we can't find it in the html it might be because it's encoded as & if (false !== stripos($image, '&') && false === stripos($html, $image)) { $image = str_replace('&', '&', $image); } -- cgit v1.2.3 From d06a1ebdfb6f70adea935c727799798f2b8ea3f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Benoist?= Date: Fri, 2 Jun 2017 09:17:45 +0200 Subject: Update messages.it.yml --- .../Resources/translations/messages.it.yml | 46 +++++++++++----------- 1 file changed, 23 insertions(+), 23 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml index d8281fda..16e8072b 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml @@ -211,7 +211,7 @@ entry: view_original_article: 'Contenuto originale' re_fetch_content: 'Ri-ottieni pagina' delete: 'Elimina' - add_a_tag: 'Aggiungi un tag' + add_a_tag: 'Aggiungi un''etichetta' share_content: 'Condividi' share_email_label: 'E-mail' # public_link: 'public link' @@ -222,7 +222,7 @@ entry: label: 'Problemi?' description: 'Questo contenuto viene visualizzato male?' edit_title: 'Modifica titolo' - original_article: 'originale' + original_article: 'Originale' annotations_on_the_entry: '{0} Nessuna annotazione|{1} Una annotazione|]1,Inf[ %count% annotazioni' created_at: 'Data di creazione' # published_at: 'Publication date' @@ -246,7 +246,7 @@ entry: delete_tag: "Vuoi veramente rimuovere quell'etichetta da quell'articolo?" about: - page_title: 'About' + page_title: 'A proposito' top_menu: who_behind_wallabag: "Chi c'è dietro a wallabag" getting_help: 'Ottieni aiuto' @@ -265,7 +265,7 @@ about: bug_reports: 'Bug reports' support: 'su GitHub' helping: - description: 'wallabag è gratuito opensource. Puoi aiutarci:' + description: 'wallabag è gratuito ed OpenSource. Puoi aiutarci:' by_contributing: 'per contribuire al progetto:' by_contributing_2: 'un elenco delle attività richieste' by_paypal: 'via Paypal' @@ -273,7 +273,7 @@ about: description: 'Un grazie ai collaboratori di wallabag web application' third_party: description: 'Ecco un elenco delle librerie di terze parti utilizzate in wallabag (con le rispettive licenze):' - package: 'Package' + package: 'Pacchetto' license: 'Licenza' howto: @@ -299,7 +299,7 @@ howto: ios: 'sullo store di iTunes' windows: 'sullo store di Microsoft' bookmarklet: - description: 'Trascinando e rilasciando questo link sulla barra dei bookmark del tuo browser:' + description: 'Trascinando e rilasciando questo link sulla barra dei preferiti del tuo browser:' shortcuts: # page_description: Here are the shortcuts available in wallabag. # shortcut: Shortcut @@ -333,7 +333,7 @@ quickstart: # more: 'More…' intro: title: 'Benvenuto su wallabag!' - paragraph_1: "Un tour in cui ti guideremo per scoprire e che ti mostrerà delle funzionalità che potrebbero interessarti." + paragraph_1: "Ti accompagneremo alla scoperta di wallabag e ti mostreremo delle funzionalità che potrebbero interessarti." paragraph_2: 'Seguici!' configure: title: "Configura l'applicazione" @@ -383,9 +383,9 @@ quickstart: gitter: 'Su Gitter' tag: - page_title: 'Tags' + page_title: 'Etichette' list: - number_on_the_page: "{0} Non ci sono tag.|{1} C'è un tag.|]1,Inf[ ci sono %count% tag." + number_on_the_page: "{0} Non ci sono etichette.|{1} C'è un'etichetta.|]1,Inf[ ci sono %count% etichette." # see_untagged_entries: 'See untagged entries' new: # add: 'Add' @@ -403,20 +403,20 @@ import: save_label: 'Carica file' pocket: page_title: 'Importa da > Pocket' - description: "Questo importatore copierà tutti i tuoi dati da Pocket. Pocket non ci consente di ottenere contenuti dal loro servzio, così il contenuto leggibile di ogni articolo verrà ri-ottenuto da wallabag." + description: "Questo importatore copierà tutti i tuoi dati da Pocket. Pocket non ci consente di ottenere contenuti dal loro servizio, così il contenuto leggibile di ogni articolo verrà ri-ottenuto da wallabag." config_missing: description: "Importazione da Pocket non configurata." admin_message: 'Devi definire %keyurls% una pocket_consumer_key %keyurle%.' - user_message: 'Il tuo amministratore di server deve define una API Key per Pocket.' + user_message: 'Il tuo amministratore del server deve definire una API Key per Pocket.' authorize_message: 'Puoi importare dati dal tuo account Pocket. Devi solo cliccare sul pulsante sottostante e autorizzare la connessione a getpocket.com.' connect_to_pocket: 'Connetti a Pocket and importa i dati' wallabag_v1: page_title: 'Importa da > Wallabag v1' - description: 'Questo importatore copierà tutti i tuoi dati da un wallabag v1. Nella tua pagina di configurazione, clicca su "JSON export" nella sezione "Esport i tuoi dati di wallabag". Otterrai un file "wallabag-export-1-xxxx-xx-xx.json".' + description: 'Questo importatore copierà tutti i tuoi dati da un wallabag v1. Nella tua pagina di configurazione, clicca su "JSON export" nella sezione "Esporta i tuoi dati di wallabag". Otterrai un file "wallabag-export-1-xxxx-xx-xx.json".' how_to: 'Seleziona la tua esportazione di wallabag e clicca sul pulsante sottostante caricare il file e importare i dati.' wallabag_v2: page_title: 'Importa da > Wallabag v2' - description: 'Questo importatore copierà tutti i tuoi dati da un wallabag v2. Vai in "Tutti i contenuti", e, nella sidebar di esportazione, clicca su "JSON". Otterrai un file "Tutti i contenuti.json".' + description: 'Questo importatore copierà tutti i tuoi dati da un wallabag v2. Vai in "Tutti i contenuti", e, nella barra laterale di esportazione, clicca su "JSON". Otterrai un file "Tutti i contenuti.json' readability: page_title: 'Importa da > Readability' # description: 'This importer will import all your Readability articles. On the tools (https://www.readability.com/tools/) page, click on "Export your data" in the "Data Export" section. You will received an email to download a json (which does not end with .json in fact).' @@ -455,19 +455,19 @@ developer: title: 'Client esistenti' field_id: 'Client ID' field_secret: 'Client secret' - field_uris: 'Redirect URI' - field_grant_types: 'Tipi di grant permessi' + field_uris: 'URI di reindirizzamento' + field_grant_types: 'Tipi di permessi concessi' no_client: 'Ancora nessun client.' remove: - warn_message_1: "Hai la possibilitò di rimuovere questo client.L'operazione è IRREVERSIBILE!" + warn_message_1: "Hai la possibilità di rimuovere questo client. L'operazione è IRREVERSIBILE!" warn_message_2: "Se lo rimuovi, ogni app configurata con questo client non sarà più in grado di autenticarsi." action: 'Rimuovi questo client' client: # page_title: 'API clients management > Nuovo client' - page_description: 'Stai per creare un nuovo client. Compila i campi sottostanti per il redirect URI della tua applicazione.' + page_description: 'Stai per creare un nuovo client. Compila i campi sottostanti per lo URI di reindirizzamento della tua applicazione.' form: # name_label: 'Name of the client' - redirect_uris_label: 'Redirect URI' + redirect_uris_label: 'URI di reindirizzamento' save_label: 'Crea un nuovo client' action_back: 'Indietro' client_parameter: @@ -477,7 +477,7 @@ developer: field_id: 'Client ID' field_secret: 'Client secret' back: 'Indietro' - read_howto: 'Leggi howto "Come creare la mia prima applicazione"' + read_howto: 'Leggi "Come creare la mia prima applicazione"' howto: # page_title: 'API clients management > Come creare la mia prima applicazione' description: @@ -530,9 +530,9 @@ flashes: password_not_updated_demo: "In modalità demo, non puoi cambiare la password dell'utente." user_updated: 'Informazioni aggiornate' rss_updated: 'Informazioni RSS aggiornate' - tagging_rules_updated: 'Regole di tagging aggiornate' - tagging_rules_deleted: 'Regola di tagging aggiornate' - rss_token_updated: 'RSS token aggiornato' + tagging_rules_updated: 'Regole di etichettatura aggiornate' + tagging_rules_deleted: 'Regole di etichettatura eliminate' + rss_token_updated: 'Token RSS aggiornato' # annotations_reset: Annotations reset # tags_reset: Tags reset # entries_reset: Entries reset @@ -552,7 +552,7 @@ flashes: entry_deleted: 'Contenuto eliminato' tag: notice: - tag_added: 'Tag aggiunto' + tag_added: 'Etichetta aggiunta' import: notice: failed: 'Importazione fallita, riprova.' -- cgit v1.2.3 From 426bb453d295900fb3e35dce2f9081a42639cf27 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Fri, 2 Jun 2017 10:19:33 +0200 Subject: API user creation behing a toggle I've added a toggle feature (in internal settings) so that user api creation can be disabled while form registration still can be enabled. Also, the /api/user endpoint shouldn't require authentication. Even if we check the authentication when sending a GET request, to retrieve current user information. I've moved all the internal settings definition to config to avoid duplicated place to define them. I don't know why we didn't did that earlier. --- .../ApiBundle/Controller/UserRestController.php | 6 +- src/Wallabag/CoreBundle/Command/InstallCommand.php | 160 +------------------ .../DataFixtures/ORM/LoadSettingData.php | 174 ++------------------- .../DependencyInjection/Configuration.php | 11 ++ .../DependencyInjection/WallabagCoreExtension.php | 1 + 5 files changed, 30 insertions(+), 322 deletions(-) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/UserRestController.php b/src/Wallabag/ApiBundle/Controller/UserRestController.php index a1b78e3f..1fc67d00 100644 --- a/src/Wallabag/ApiBundle/Controller/UserRestController.php +++ b/src/Wallabag/ApiBundle/Controller/UserRestController.php @@ -43,7 +43,7 @@ class UserRestController extends WallabagRestController */ public function putUserAction(Request $request) { - if (!$this->container->getParameter('fosuser_registration')) { + if (!$this->getParameter('fosuser_registration') || !$this->get('craue_config')->get('api_user_registration')) { $json = $this->get('serializer')->serialize(['error' => "Server doesn't allow registrations"], 'json'); return (new JsonResponse())->setJson($json)->setStatusCode(403); @@ -51,8 +51,8 @@ class UserRestController extends WallabagRestController $userManager = $this->get('fos_user.user_manager'); $user = $userManager->createUser(); - // enable created user by default - $user->setEnabled(true); + // user will be disabled BY DEFAULT to avoid spamming account to be created + $user->setEnabled(false); $form = $this->createForm('Wallabag\UserBundle\Form\NewUserType', $user, [ 'csrf_protection' => false, diff --git a/src/Wallabag/CoreBundle/Command/InstallCommand.php b/src/Wallabag/CoreBundle/Command/InstallCommand.php index d9608246..0f119377 100644 --- a/src/Wallabag/CoreBundle/Command/InstallCommand.php +++ b/src/Wallabag/CoreBundle/Command/InstallCommand.php @@ -292,165 +292,7 @@ class InstallCommand extends ContainerAwareCommand // cleanup before insert new stuff $em->createQuery('DELETE FROM CraueConfigBundle:Setting')->execute(); - $settings = [ - [ - 'name' => 'share_public', - 'value' => '1', - 'section' => 'entry', - ], - [ - 'name' => 'carrot', - 'value' => '1', - 'section' => 'entry', - ], - [ - 'name' => 'share_diaspora', - 'value' => '1', - 'section' => 'entry', - ], - [ - 'name' => 'diaspora_url', - 'value' => 'http://diasporapod.com', - 'section' => 'entry', - ], - [ - 'name' => 'share_unmark', - 'value' => '1', - 'section' => 'entry', - ], - [ - 'name' => 'unmark_url', - 'value' => 'https://unmark.it', - 'section' => 'entry', - ], - [ - 'name' => 'share_shaarli', - 'value' => '1', - 'section' => 'entry', - ], - [ - 'name' => 'shaarli_url', - 'value' => 'http://myshaarli.com', - 'section' => 'entry', - ], - [ - 'name' => 'share_scuttle', - 'value' => '1', - 'section' => 'entry', - ], - [ - 'name' => 'scuttle_url', - 'value' => 'http://scuttle.org', - 'section' => 'entry', - ], - [ - 'name' => 'share_mail', - 'value' => '1', - 'section' => 'entry', - ], - [ - 'name' => 'share_twitter', - 'value' => '1', - 'section' => 'entry', - ], - [ - 'name' => 'export_epub', - 'value' => '1', - 'section' => 'export', - ], - [ - 'name' => 'export_mobi', - 'value' => '1', - 'section' => 'export', - ], - [ - 'name' => 'export_pdf', - 'value' => '1', - 'section' => 'export', - ], - [ - 'name' => 'export_csv', - 'value' => '1', - 'section' => 'export', - ], - [ - 'name' => 'export_json', - 'value' => '1', - 'section' => 'export', - ], - [ - 'name' => 'export_txt', - 'value' => '1', - 'section' => 'export', - ], - [ - 'name' => 'export_xml', - 'value' => '1', - 'section' => 'export', - ], - [ - 'name' => 'import_with_redis', - 'value' => '0', - 'section' => 'import', - ], - [ - 'name' => 'import_with_rabbitmq', - 'value' => '0', - 'section' => 'import', - ], - [ - 'name' => 'show_printlink', - 'value' => '1', - 'section' => 'entry', - ], - [ - 'name' => 'wallabag_support_url', - 'value' => 'https://www.wallabag.org/pages/support.html', - 'section' => 'misc', - ], - [ - 'name' => 'wallabag_url', - 'value' => '', - 'section' => 'misc', - ], - [ - 'name' => 'piwik_enabled', - 'value' => '0', - 'section' => 'analytics', - ], - [ - 'name' => 'piwik_host', - 'value' => 'v2.wallabag.org', - 'section' => 'analytics', - ], - [ - 'name' => 'piwik_site_id', - 'value' => '1', - 'section' => 'analytics', - ], - [ - 'name' => 'demo_mode_enabled', - 'value' => '0', - 'section' => 'misc', - ], - [ - 'name' => 'demo_mode_username', - 'value' => 'wallabag', - 'section' => 'misc', - ], - [ - 'name' => 'download_images_enabled', - 'value' => '0', - 'section' => 'misc', - ], - [ - 'name' => 'restricted_access', - 'value' => '0', - 'section' => 'entry', - ], - ]; - - foreach ($settings as $setting) { + foreach ($this->getContainer()->getParameter('wallabag_core.default_internal_settings') as $setting) { $newSetting = new Setting(); $newSetting->setName($setting['name']); $newSetting->setValue($setting['value']); diff --git a/src/Wallabag/CoreBundle/DataFixtures/ORM/LoadSettingData.php b/src/Wallabag/CoreBundle/DataFixtures/ORM/LoadSettingData.php index aaeb9ee9..a52288e6 100644 --- a/src/Wallabag/CoreBundle/DataFixtures/ORM/LoadSettingData.php +++ b/src/Wallabag/CoreBundle/DataFixtures/ORM/LoadSettingData.php @@ -6,173 +6,27 @@ use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\OrderedFixtureInterface; use Doctrine\Common\Persistence\ObjectManager; use Craue\ConfigBundle\Entity\Setting; +use Symfony\Component\DependencyInjection\ContainerAwareInterface; +use Symfony\Component\DependencyInjection\ContainerInterface; -class LoadSettingData extends AbstractFixture implements OrderedFixtureInterface +class LoadSettingData extends AbstractFixture implements OrderedFixtureInterface, ContainerAwareInterface { + /** + * @var ContainerInterface + */ + private $container; + + public function setContainer(ContainerInterface $container = null) + { + $this->container = $container; + } + /** * {@inheritdoc} */ public function load(ObjectManager $manager) { - $settings = [ - [ - 'name' => 'share_public', - 'value' => '1', - 'section' => 'entry', - ], - [ - 'name' => 'carrot', - 'value' => '1', - 'section' => 'entry', - ], - [ - 'name' => 'share_diaspora', - 'value' => '1', - 'section' => 'entry', - ], - [ - 'name' => 'diaspora_url', - 'value' => 'http://diasporapod.com', - 'section' => 'entry', - ], - [ - 'name' => 'share_unmark', - 'value' => '1', - 'section' => 'entry', - ], - [ - 'name' => 'unmark_url', - 'value' => 'https://unmark.it', - 'section' => 'entry', - ], - [ - 'name' => 'share_shaarli', - 'value' => '1', - 'section' => 'entry', - ], - [ - 'name' => 'share_scuttle', - 'value' => '1', - 'section' => 'entry', - ], - [ - 'name' => 'shaarli_url', - 'value' => 'http://myshaarli.com', - 'section' => 'entry', - ], - [ - 'name' => 'scuttle_url', - 'value' => 'http://scuttle.org', - 'section' => 'entry', - ], - [ - 'name' => 'share_mail', - 'value' => '1', - 'section' => 'entry', - ], - [ - 'name' => 'share_twitter', - 'value' => '1', - 'section' => 'entry', - ], - [ - 'name' => 'export_epub', - 'value' => '1', - 'section' => 'export', - ], - [ - 'name' => 'export_mobi', - 'value' => '1', - 'section' => 'export', - ], - [ - 'name' => 'export_pdf', - 'value' => '1', - 'section' => 'export', - ], - [ - 'name' => 'export_csv', - 'value' => '1', - 'section' => 'export', - ], - [ - 'name' => 'export_json', - 'value' => '1', - 'section' => 'export', - ], - [ - 'name' => 'export_txt', - 'value' => '1', - 'section' => 'export', - ], - [ - 'name' => 'export_xml', - 'value' => '1', - 'section' => 'export', - ], - [ - 'name' => 'import_with_redis', - 'value' => '0', - 'section' => 'import', - ], - [ - 'name' => 'import_with_rabbitmq', - 'value' => '0', - 'section' => 'import', - ], - [ - 'name' => 'show_printlink', - 'value' => '1', - 'section' => 'entry', - ], - [ - 'name' => 'wallabag_support_url', - 'value' => 'https://www.wallabag.org/pages/support.html', - 'section' => 'misc', - ], - [ - 'name' => 'wallabag_url', - 'value' => 'http://v2.wallabag.org', - 'section' => 'misc', - ], - [ - 'name' => 'piwik_enabled', - 'value' => '0', - 'section' => 'analytics', - ], - [ - 'name' => 'piwik_host', - 'value' => 'v2.wallabag.org', - 'section' => 'analytics', - ], - [ - 'name' => 'piwik_site_id', - 'value' => '1', - 'section' => 'analytics', - ], - [ - 'name' => 'demo_mode_enabled', - 'value' => '0', - 'section' => 'misc', - ], - [ - 'name' => 'demo_mode_username', - 'value' => 'wallabag', - 'section' => 'misc', - ], - [ - 'name' => 'download_images_enabled', - 'value' => '0', - 'section' => 'misc', - ], - [ - 'name' => 'restricted_access', - 'value' => '0', - 'section' => 'entry', - ], - ]; - - foreach ($settings as $setting) { + foreach ($this->container->getParameter('wallabag_core.default_internal_settings') as $setting) { $newSetting = new Setting(); $newSetting->setName($setting['name']); $newSetting->setValue($setting['value']); diff --git a/src/Wallabag/CoreBundle/DependencyInjection/Configuration.php b/src/Wallabag/CoreBundle/DependencyInjection/Configuration.php index 8b5b5744..33df92d3 100644 --- a/src/Wallabag/CoreBundle/DependencyInjection/Configuration.php +++ b/src/Wallabag/CoreBundle/DependencyInjection/Configuration.php @@ -52,6 +52,17 @@ class Configuration implements ConfigurationInterface ->scalarNode('api_limit_mass_actions') ->defaultValue(10) ->end() + ->arrayNode('default_internal_settings') + ->prototype('array') + ->children() + ->scalarNode('name')->end() + ->scalarNode('value')->end() + ->enumNode('section') + ->values(['entry', 'misc', 'api', 'analytics', 'export', 'import']) + ->end() + ->end() + ->end() + ->end() ->end() ; diff --git a/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php b/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php index a2a703cb..b4d8a386 100644 --- a/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php +++ b/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php @@ -28,6 +28,7 @@ class WallabagCoreExtension extends Extension $container->setParameter('wallabag_core.fetching_error_message', $config['fetching_error_message']); $container->setParameter('wallabag_core.fetching_error_message_title', $config['fetching_error_message_title']); $container->setParameter('wallabag_core.api_limit_mass_actions', $config['api_limit_mass_actions']); + $container->setParameter('wallabag_core.default_internal_settings', $config['default_internal_settings']); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.yml'); -- cgit v1.2.3 From 1b9cd91782ed8341d2e608371201348c59986f23 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Fri, 2 Jun 2017 10:27:15 +0200 Subject: Add translation --- src/Wallabag/ApiBundle/Controller/UserRestController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/UserRestController.php b/src/Wallabag/ApiBundle/Controller/UserRestController.php index 1fc67d00..a1d7c1ff 100644 --- a/src/Wallabag/ApiBundle/Controller/UserRestController.php +++ b/src/Wallabag/ApiBundle/Controller/UserRestController.php @@ -51,7 +51,7 @@ class UserRestController extends WallabagRestController $userManager = $this->get('fos_user.user_manager'); $user = $userManager->createUser(); - // user will be disabled BY DEFAULT to avoid spamming account to be created + // user will be disabled BY DEFAULT to avoid spamming account to be enabled $user->setEnabled(false); $form = $this->createForm('Wallabag\UserBundle\Form\NewUserType', $user, [ -- cgit v1.2.3 From d143fa243df6112c9df7c6e7e408b66da40c8fce Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Fri, 2 Jun 2017 16:53:03 +0200 Subject: Add show user command Signed-off-by: Thomas Citharel --- .../CoreBundle/Command/ShowUserCommand.php | 77 ++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 src/Wallabag/CoreBundle/Command/ShowUserCommand.php (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Command/ShowUserCommand.php b/src/Wallabag/CoreBundle/Command/ShowUserCommand.php new file mode 100644 index 00000000..10428c4b --- /dev/null +++ b/src/Wallabag/CoreBundle/Command/ShowUserCommand.php @@ -0,0 +1,77 @@ +setName('wallabag:user:show') + ->setDescription('Show user details') + ->setHelp('This command shows the details for an user') + ->addArgument( + 'username', + InputArgument::REQUIRED, + 'User to show details for' + ); + } + + protected function execute(InputInterface $input, OutputInterface $output) + { + $this->output = $output; + + $username = $input->getArgument('username'); + + try { + $user = $this->getUser($username); + $this->showUser($user); + } catch (NoResultException $e) { + $output->writeln(sprintf('User "%s" not found.', $username)); + + return 1; + } + + return 0; + } + + /** + * @param User $user + */ + private function showUser(User $user) + { + $this->output->writeln(sprintf('Username : %s', $user->getUsername())); + $this->output->writeln(sprintf('Email : %s', $user->getEmail())); + $this->output->writeln(sprintf('Display name : %s', $user->getName())); + $this->output->writeln(sprintf('Creation date : %s', $user->getCreatedAt() !== null ? $user->getCreatedAt()->format('Y-m-d H:i:s') : 'false')); + $this->output->writeln(sprintf('Last login : %s', $user->getLastLogin() !== null ? $user->getLastLogin()->format('Y-m-d H:i:s') : 'false')); + $this->output->writeln(sprintf('2FA activated: %s', $user->isTwoFactorAuthentication() ? 'true' : 'false')); + } + + /** + * Fetches a user from its username. + * + * @param string $username + * + * @return \Wallabag\UserBundle\Entity\User + */ + private function getUser($username) + { + return $this->getDoctrine()->getRepository('WallabagUserBundle:User')->findOneByUserName($username); + } + + private function getDoctrine() + { + return $this->getContainer()->get('doctrine'); + } +} -- cgit v1.2.3 From a1e6187406289b6b54f8044ba1f209979454204b Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Fri, 2 Jun 2017 20:03:25 +0200 Subject: Return 201 on user creation --- .../ApiBundle/Controller/UserRestController.php | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/UserRestController.php b/src/Wallabag/ApiBundle/Controller/UserRestController.php index a1d7c1ff..8f675b8d 100644 --- a/src/Wallabag/ApiBundle/Controller/UserRestController.php +++ b/src/Wallabag/ApiBundle/Controller/UserRestController.php @@ -46,7 +46,9 @@ class UserRestController extends WallabagRestController if (!$this->getParameter('fosuser_registration') || !$this->get('craue_config')->get('api_user_registration')) { $json = $this->get('serializer')->serialize(['error' => "Server doesn't allow registrations"], 'json'); - return (new JsonResponse())->setJson($json)->setStatusCode(403); + return (new JsonResponse()) + ->setJson($json) + ->setStatusCode(JsonResponse::HTTP_FORBIDDEN); } $userManager = $this->get('fos_user.user_manager'); @@ -90,7 +92,9 @@ class UserRestController extends WallabagRestController $json = $this->get('serializer')->serialize(['error' => $errors], 'json'); - return (new JsonResponse())->setJson($json)->setStatusCode(400); + return (new JsonResponse()) + ->setJson($json) + ->setStatusCode(JsonResponse::HTTP_BAD_REQUEST); } $userManager->updateUser($user); @@ -99,17 +103,18 @@ class UserRestController extends WallabagRestController $event = new UserEvent($user, $request); $this->get('event_dispatcher')->dispatch(FOSUserEvents::USER_CREATED, $event); - return $this->sendUser($user); + return $this->sendUser($user, JsonResponse::HTTP_CREATED); } /** * Send user response. * * @param User $user + * @param int $status HTTP Status code to send * * @return JsonResponse */ - private function sendUser(User $user) + private function sendUser(User $user, $status = JsonResponse::HTTP_OK) { $json = $this->get('serializer')->serialize( $user, @@ -117,7 +122,9 @@ class UserRestController extends WallabagRestController SerializationContext::create()->setGroups(['user_api']) ); - return (new JsonResponse())->setJson($json); + return (new JsonResponse()) + ->setJson($json) + ->setStatusCode($status); } /** -- cgit v1.2.3 From 645291e8feb0f3e977b9518da7d731fda8cf1f30 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Fri, 2 Jun 2017 20:52:49 +0200 Subject: Add ability to patch an entry with more fields Like when we create an entry, we can now patch an entry with new fields: - content - language - preview_picture - published_at - authors --- .../ApiBundle/Controller/EntryRestController.php | 38 ++++++++++++++++++++-- src/Wallabag/CoreBundle/Helper/ContentProxy.php | 2 +- 2 files changed, 36 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/EntryRestController.php b/src/Wallabag/ApiBundle/Controller/EntryRestController.php index 93c8157e..7135e616 100644 --- a/src/Wallabag/ApiBundle/Controller/EntryRestController.php +++ b/src/Wallabag/ApiBundle/Controller/EntryRestController.php @@ -374,6 +374,11 @@ class EntryRestController extends WallabagRestController * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."}, * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="archived the entry."}, * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="starred the entry."}, + * {"name"="content", "dataType"="string", "required"=false, "description"="Content of the entry"}, + * {"name"="language", "dataType"="string", "required"=false, "description"="Language of the entry"}, + * {"name"="preview_picture", "dataType"="string", "required"=false, "description"="Preview picture of the entry"}, + * {"name"="published_at", "dataType"="datetime|integer", "format"="YYYY-MM-DDTHH:II:SS+TZ or a timestamp", "required"=false, "description"="Published date of the entry"}, + * {"name"="authors", "dataType"="string", "format"="Name Firstname,author2,author3", "required"=false, "description"="Authors of the entry"}, * } * ) * @@ -385,11 +390,39 @@ class EntryRestController extends WallabagRestController $this->validateUserAccess($entry->getUser()->getId()); $title = $request->request->get('title'); + $tags = $request->request->get('tags', ''); $isArchived = $request->request->get('archive'); $isStarred = $request->request->get('starred'); + $content = $request->request->get('content'); + $language = $request->request->get('language'); + $picture = $request->request->get('preview_picture'); + $publishedAt = $request->request->get('published_at'); + $authors = $request->request->get('authors', ''); - if (!is_null($title)) { - $entry->setTitle($title); + try { + $this->get('wallabag_core.content_proxy')->updateEntry( + $entry, + $entry->getUrl(), + [ + 'title' => !empty($title) ? $title : $entry->getTitle(), + 'html' => !empty($content) ? $content : $entry->getContent(), + 'url' => $entry->getUrl(), + 'language' => $language, + 'date' => $publishedAt, + // faking the preview picture + 'open_graph' => [ + 'og_image' => $picture, + ], + 'authors' => is_string($authors) ? explode(',', $authors) : [], + ], + // we don't want the content to be update by fetching the url + true + ); + } catch (\Exception $e) { + $this->get('logger')->error('Error while saving an entry', [ + 'exception' => $e, + 'entry' => $entry, + ]); } if (!is_null($isArchived)) { @@ -400,7 +433,6 @@ class EntryRestController extends WallabagRestController $entry->setStarred((bool) $isStarred); } - $tags = $request->request->get('tags', ''); if (!empty($tags)) { $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags); } diff --git a/src/Wallabag/CoreBundle/Helper/ContentProxy.php b/src/Wallabag/CoreBundle/Helper/ContentProxy.php index bfaa1976..d5820e66 100644 --- a/src/Wallabag/CoreBundle/Helper/ContentProxy.php +++ b/src/Wallabag/CoreBundle/Helper/ContentProxy.php @@ -105,7 +105,7 @@ class ContentProxy } } - if (!empty($content['authors'])) { + if (!empty($content['authors']) && is_array($content['authors'])) { $entry->setPublishedBy($content['authors']); } -- cgit v1.2.3 From 2c3e148b0029a094431622feac79fafcd0d43fc8 Mon Sep 17 00:00:00 2001 From: adev Date: Sun, 7 May 2017 17:21:30 +0200 Subject: Displays an error with an annotation with a too long quote Fix #2762 --- .../Controller/WallabagAnnotationController.php | 49 +++++++++++++--------- .../AnnotationBundle/Entity/Annotation.php | 7 +++- .../AnnotationBundle/Form/EditAnnotationType.php | 18 ++++++++ .../AnnotationBundle/Form/NewAnnotationType.php | 35 ++++++++++++++++ src/Wallabag/AnnotationBundle/Form/RangeType.php | 19 +++++++++ .../Resources/translations/validators.da.yml | 1 + .../Resources/translations/validators.de.yml | 1 + .../Resources/translations/validators.en.yml | 1 + .../Resources/translations/validators.es.yml | 1 + .../Resources/translations/validators.fa.yml | 1 + .../Resources/translations/validators.fr.yml | 1 + .../Resources/translations/validators.it.yml | 1 + .../Resources/translations/validators.oc.yml | 1 + .../Resources/translations/validators.pl.yml | 1 + .../Resources/translations/validators.pt.yml | 1 + .../Resources/translations/validators.ro.yml | 1 + .../Resources/translations/validators.tr.yml | 1 + 17 files changed, 119 insertions(+), 21 deletions(-) create mode 100644 src/Wallabag/AnnotationBundle/Form/EditAnnotationType.php create mode 100644 src/Wallabag/AnnotationBundle/Form/NewAnnotationType.php create mode 100644 src/Wallabag/AnnotationBundle/Form/RangeType.php (limited to 'src') diff --git a/src/Wallabag/AnnotationBundle/Controller/WallabagAnnotationController.php b/src/Wallabag/AnnotationBundle/Controller/WallabagAnnotationController.php index c13a034f..2b4b0e8d 100644 --- a/src/Wallabag/AnnotationBundle/Controller/WallabagAnnotationController.php +++ b/src/Wallabag/AnnotationBundle/Controller/WallabagAnnotationController.php @@ -7,6 +7,8 @@ use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; use Wallabag\AnnotationBundle\Entity\Annotation; +use Wallabag\AnnotationBundle\Form\EditAnnotationType; +use Wallabag\AnnotationBundle\Form\NewAnnotationType; use Wallabag\CoreBundle\Entity\Entry; class WallabagAnnotationController extends FOSRestController @@ -49,25 +51,25 @@ class WallabagAnnotationController extends FOSRestController $data = json_decode($request->getContent(), true); $em = $this->getDoctrine()->getManager(); - $annotation = new Annotation($this->getUser()); + $annotation->setEntry($entry); - $annotation->setText($data['text']); - if (array_key_exists('quote', $data)) { - $annotation->setQuote($data['quote']); - } - if (array_key_exists('ranges', $data)) { - $annotation->setRanges($data['ranges']); - } + $form = $this->get('form.factory')->createNamed('', NewAnnotationType::class, $annotation, [ + 'csrf_protection' => false, + 'allow_extra_fields' => true, + ]); + $form->submit($data); - $annotation->setEntry($entry); + if ($form->isValid()) { + $em->persist($annotation); + $em->flush(); - $em->persist($annotation); - $em->flush(); + $json = $this->get('serializer')->serialize($annotation, 'json'); - $json = $this->get('serializer')->serialize($annotation, 'json'); + return JsonResponse::fromJsonString($json); + } - return (new JsonResponse())->setJson($json); + return $form; } /** @@ -86,16 +88,23 @@ class WallabagAnnotationController extends FOSRestController { $data = json_decode($request->getContent(), true); - if (!is_null($data['text'])) { - $annotation->setText($data['text']); - } + $form = $this->get('form.factory')->createNamed('', EditAnnotationType::class, $annotation, [ + 'csrf_protection' => false, + 'allow_extra_fields' => true, + ]); + $form->submit($data); - $em = $this->getDoctrine()->getManager(); - $em->flush(); + if ($form->isValid()) { + $em = $this->getDoctrine()->getManager(); + $em->persist($annotation); + $em->flush(); - $json = $this->get('serializer')->serialize($annotation, 'json'); + $json = $this->get('serializer')->serialize($annotation, 'json'); - return (new JsonResponse())->setJson($json); + return JsonResponse::fromJsonString($json); + } + + return $form; } /** diff --git a/src/Wallabag/AnnotationBundle/Entity/Annotation.php b/src/Wallabag/AnnotationBundle/Entity/Annotation.php index 0838f5aa..c8e41649 100644 --- a/src/Wallabag/AnnotationBundle/Entity/Annotation.php +++ b/src/Wallabag/AnnotationBundle/Entity/Annotation.php @@ -8,6 +8,7 @@ use JMS\Serializer\Annotation\Exclude; use JMS\Serializer\Annotation\VirtualProperty; use JMS\Serializer\Annotation\SerializedName; use JMS\Serializer\Annotation\Groups; +use Symfony\Component\Validator\Constraints as Assert; use Wallabag\UserBundle\Entity\User; use Wallabag\CoreBundle\Entity\Entry; @@ -56,7 +57,11 @@ class Annotation /** * @var string * - * @ORM\Column(name="quote", type="string") + * @Assert\Length( + * max = 10000, + * maxMessage = "validator.quote_length_too_high" + * ) + * @ORM\Column(name="quote", type="text") * * @Groups({"entries_for_user", "export_all"}) */ diff --git a/src/Wallabag/AnnotationBundle/Form/EditAnnotationType.php b/src/Wallabag/AnnotationBundle/Form/EditAnnotationType.php new file mode 100644 index 00000000..3b587478 --- /dev/null +++ b/src/Wallabag/AnnotationBundle/Form/EditAnnotationType.php @@ -0,0 +1,18 @@ +add('text', null, [ + 'empty_data' => '', + ]) + ; + } +} diff --git a/src/Wallabag/AnnotationBundle/Form/NewAnnotationType.php b/src/Wallabag/AnnotationBundle/Form/NewAnnotationType.php new file mode 100644 index 00000000..c73c3ded --- /dev/null +++ b/src/Wallabag/AnnotationBundle/Form/NewAnnotationType.php @@ -0,0 +1,35 @@ +add('text', null, [ + 'empty_data' => '', + ]) + ->add('quote', null, [ + 'empty_data' => null, + ]) + ->add('ranges', CollectionType::class, [ + 'entry_type' => RangeType::class, + 'allow_add' => true, + ]) + ; + } + + public function configureOptions(OptionsResolver $resolver) + { + $resolver->setDefaults([ + 'data_class' => Annotation::class, + ]); + } +} diff --git a/src/Wallabag/AnnotationBundle/Form/RangeType.php b/src/Wallabag/AnnotationBundle/Form/RangeType.php new file mode 100644 index 00000000..0647375e --- /dev/null +++ b/src/Wallabag/AnnotationBundle/Form/RangeType.php @@ -0,0 +1,19 @@ +add('start') + ->add('startOffset') + ->add('end') + ->add('endOffset') + ; + } +} diff --git a/src/Wallabag/CoreBundle/Resources/translations/validators.da.yml b/src/Wallabag/CoreBundle/Resources/translations/validators.da.yml index 32a8b4a8..c6a84209 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/validators.da.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/validators.da.yml @@ -4,3 +4,4 @@ validator: # password_wrong_value: 'Wrong value for your current password' # item_per_page_too_high: 'This will certainly kill the app' # rss_limit_too_high: 'This will certainly kill the app' + # quote_length_too_high: 'The quote is too long. It should have {{ limit }} characters or less.' diff --git a/src/Wallabag/CoreBundle/Resources/translations/validators.de.yml b/src/Wallabag/CoreBundle/Resources/translations/validators.de.yml index 37b9888f..c74c00ca 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/validators.de.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/validators.de.yml @@ -4,3 +4,4 @@ validator: password_wrong_value: 'Falscher Wert für dein aktuelles Kennwort' item_per_page_too_high: 'Dies wird die Anwendung möglicherweise beenden' rss_limit_too_high: 'Dies wird die Anwendung möglicherweise beenden' + # quote_length_too_high: 'The quote is too long. It should have {{ limit }} characters or less.' diff --git a/src/Wallabag/CoreBundle/Resources/translations/validators.en.yml b/src/Wallabag/CoreBundle/Resources/translations/validators.en.yml index 29217497..8cc117fe 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/validators.en.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/validators.en.yml @@ -4,3 +4,4 @@ validator: password_wrong_value: 'Wrong value for your current password' item_per_page_too_high: 'This will certainly kill the app' rss_limit_too_high: 'This will certainly kill the app' + quote_length_too_high: 'The quote is too long. It should have {{ limit }} characters or less.' diff --git a/src/Wallabag/CoreBundle/Resources/translations/validators.es.yml b/src/Wallabag/CoreBundle/Resources/translations/validators.es.yml index 57ddaa5a..97a8edfa 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/validators.es.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/validators.es.yml @@ -4,3 +4,4 @@ validator: password_wrong_value: 'Entrada equivocada para su contraseña actual' item_per_page_too_high: 'Esto matará la aplicación' rss_limit_too_high: 'Esto matará la aplicación' + # quote_length_too_high: 'The quote is too long. It should have {{ limit }} characters or less.' diff --git a/src/Wallabag/CoreBundle/Resources/translations/validators.fa.yml b/src/Wallabag/CoreBundle/Resources/translations/validators.fa.yml index e0536d18..ef677525 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/validators.fa.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/validators.fa.yml @@ -4,3 +4,4 @@ validator: password_wrong_value: 'رمز فعلی را اشتباه وارد کرده‌اید' item_per_page_too_high: 'با این تعداد برنامه به فنا می‌رود' rss_limit_too_high: 'با این تعداد برنامه به فنا می‌رود' + # quote_length_too_high: 'The quote is too long. It should have {{ limit }} characters or less.' diff --git a/src/Wallabag/CoreBundle/Resources/translations/validators.fr.yml b/src/Wallabag/CoreBundle/Resources/translations/validators.fr.yml index 64574709..f31b4ed2 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/validators.fr.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/validators.fr.yml @@ -4,3 +4,4 @@ validator: password_wrong_value: "Votre mot de passe actuel est faux" item_per_page_too_high: "Ça ne va pas plaire à l’application" rss_limit_too_high: "Ça ne va pas plaire à l’application" + quote_length_too_high: "La citation est trop longue. Elle doit avoir au maximum {{ limit }} caractères." diff --git a/src/Wallabag/CoreBundle/Resources/translations/validators.it.yml b/src/Wallabag/CoreBundle/Resources/translations/validators.it.yml index d9beb54f..d949cc3b 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/validators.it.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/validators.it.yml @@ -4,3 +4,4 @@ validator: password_wrong_value: 'Valore inserito per la password corrente errato' item_per_page_too_high: 'Questo valore è troppo alto' rss_limit_too_high: 'Questo valore è troppo alto' + # quote_length_too_high: 'The quote is too long. It should have {{ limit }} characters or less.' diff --git a/src/Wallabag/CoreBundle/Resources/translations/validators.oc.yml b/src/Wallabag/CoreBundle/Resources/translations/validators.oc.yml index f92c2708..fb4aa592 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/validators.oc.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/validators.oc.yml @@ -4,3 +4,4 @@ validator: password_wrong_value: 'Vòstre senhal actual es pas bon' item_per_page_too_high: "Aquò li agradarà pas a l'aplicacion" rss_limit_too_high: "Aquò li agradarà pas a l'aplicacion" + # quote_length_too_high: 'The quote is too long. It should have {{ limit }} characters or less.' diff --git a/src/Wallabag/CoreBundle/Resources/translations/validators.pl.yml b/src/Wallabag/CoreBundle/Resources/translations/validators.pl.yml index ffcd5e7f..58d19cc9 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/validators.pl.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/validators.pl.yml @@ -4,3 +4,4 @@ validator: password_wrong_value: 'Twoje obecne hasło jest błędne' item_per_page_too_high: 'To może spowodować problemy z aplikacją' rss_limit_too_high: 'To może spowodować problemy z aplikacją' + # quote_length_too_high: 'The quote is too long. It should have {{ limit }} characters or less.' diff --git a/src/Wallabag/CoreBundle/Resources/translations/validators.pt.yml b/src/Wallabag/CoreBundle/Resources/translations/validators.pt.yml index 4eddff10..a8c1f9de 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/validators.pt.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/validators.pt.yml @@ -4,3 +4,4 @@ validator: password_wrong_value: 'A senha atual informada está errada' item_per_page_too_high: 'Certamente isso pode matar a aplicação' rss_limit_too_high: 'Certamente isso pode matar a aplicação' + # quote_length_too_high: 'The quote is too long. It should have {{ limit }} characters or less.' diff --git a/src/Wallabag/CoreBundle/Resources/translations/validators.ro.yml b/src/Wallabag/CoreBundle/Resources/translations/validators.ro.yml index 59a8cdd8..6840cf11 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/validators.ro.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/validators.ro.yml @@ -4,3 +4,4 @@ validator: # password_wrong_value: 'Wrong value for your current password' # item_per_page_too_high: 'This will certainly kill the app' # rss_limit_too_high: 'This will certainly kill the app' + # quote_length_too_high: 'The quote is too long. It should have {{ limit }} characters or less.' diff --git a/src/Wallabag/CoreBundle/Resources/translations/validators.tr.yml b/src/Wallabag/CoreBundle/Resources/translations/validators.tr.yml index 01388771..e1e7317f 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/validators.tr.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/validators.tr.yml @@ -4,3 +4,4 @@ validator: # password_wrong_value: 'Wrong value for your current password' # item_per_page_too_high: 'This will certainly kill the app' # rss_limit_too_high: 'This will certainly kill the app' + # quote_length_too_high: 'The quote is too long. It should have {{ limit }} characters or less.' -- cgit v1.2.3 From 0d8ecb82a32fcb7e87d99316b00c827c8aa71eee Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Sun, 4 Jun 2017 17:57:40 +0200 Subject: Fix review Signed-off-by: Thomas Citharel --- src/Wallabag/CoreBundle/Command/ShowUserCommand.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Command/ShowUserCommand.php b/src/Wallabag/CoreBundle/Command/ShowUserCommand.php index 10428c4b..0eeaabc4 100644 --- a/src/Wallabag/CoreBundle/Command/ShowUserCommand.php +++ b/src/Wallabag/CoreBundle/Command/ShowUserCommand.php @@ -53,9 +53,9 @@ class ShowUserCommand extends ContainerAwareCommand $this->output->writeln(sprintf('Username : %s', $user->getUsername())); $this->output->writeln(sprintf('Email : %s', $user->getEmail())); $this->output->writeln(sprintf('Display name : %s', $user->getName())); - $this->output->writeln(sprintf('Creation date : %s', $user->getCreatedAt() !== null ? $user->getCreatedAt()->format('Y-m-d H:i:s') : 'false')); - $this->output->writeln(sprintf('Last login : %s', $user->getLastLogin() !== null ? $user->getLastLogin()->format('Y-m-d H:i:s') : 'false')); - $this->output->writeln(sprintf('2FA activated: %s', $user->isTwoFactorAuthentication() ? 'true' : 'false')); + $this->output->writeln(sprintf('Creation date : %s', $user->getCreatedAt()->format('Y-m-d H:i:s'))); + $this->output->writeln(sprintf('Last login : %s', $user->getLastLogin() !== null ? $user->getLastLogin()->format('Y-m-d H:i:s') : 'never')); + $this->output->writeln(sprintf('2FA activated: %s', $user->isTwoFactorAuthentication() ? 'yes' : 'no')); } /** -- cgit v1.2.3 From 577c0b6dd82c421c377c37295c59dee147068132 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Mon, 5 Jun 2017 22:54:02 +0200 Subject: Use an alternative way to detect image MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When parsing content to retrieve images to save locally, we only check for the content-type of the image response. In some case, that value is empty. Now we’re also checking for the first few bytes of the content as an alternative to detect if it’s an image wallabag can handle. We might get higher image supports using that alternative method. --- src/Wallabag/CoreBundle/Helper/DownloadImages.php | 50 ++++++++++++++++++++--- 1 file changed, 45 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Helper/DownloadImages.php b/src/Wallabag/CoreBundle/Helper/DownloadImages.php index 54e23a05..ed888cdb 100644 --- a/src/Wallabag/CoreBundle/Helper/DownloadImages.php +++ b/src/Wallabag/CoreBundle/Helper/DownloadImages.php @@ -5,6 +5,7 @@ namespace Wallabag\CoreBundle\Helper; use Psr\Log\LoggerInterface; use Symfony\Component\DomCrawler\Crawler; use GuzzleHttp\Client; +use GuzzleHttp\Message\Response; use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeExtensionGuesser; use Symfony\Component\Finder\Finder; @@ -116,13 +117,11 @@ class DownloadImages return false; } - $ext = $this->mimeGuesser->guess($res->getHeader('content-type')); - $this->logger->debug('DownloadImages: Checking extension', ['ext' => $ext, 'header' => $res->getHeader('content-type')]); - if (!in_array($ext, ['jpeg', 'jpg', 'gif', 'png'], true)) { - $this->logger->error('DownloadImages: Processed image with not allowed extension. Skipping: '.$imagePath); - + $ext = $this->getExtensionFromResponse($res, $imagePath); + if (false === $res) { return false; } + $hashImage = hash('crc32', $absolutePath); $localPath = $folderPath.'/'.$hashImage.'.'.$ext; @@ -237,4 +236,45 @@ class DownloadImages return false; } + + /** + * Retrieve and validate the extension from the response of the url of the image. + * + * @param Response $res Guzzle Response + * @param string $imagePath Path from the src image from the content (used for log only) + * + * @return string|false Extension name or false if validation failed + */ + private function getExtensionFromResponse(Response $res, $imagePath) + { + $ext = $this->mimeGuesser->guess($res->getHeader('content-type')); + $this->logger->debug('DownloadImages: Checking extension', ['ext' => $ext, 'header' => $res->getHeader('content-type')]); + + // ok header doesn't have the extension, try a different way + if (empty($ext)) { + $types = [ + 'jpeg' => "\xFF\xD8\xFF", + 'gif' => 'GIF', + 'png' => "\x89\x50\x4e\x47\x0d\x0a", + ]; + $bytes = substr((string) $res->getBody(), 0, 8); + + foreach ($types as $type => $header) { + if (0 === strpos($bytes, $header)) { + $ext = $type; + break; + } + } + + $this->logger->debug('DownloadImages: Checking extension (alternative)', ['ext' => $ext]); + } + + if (!in_array($ext, ['jpeg', 'jpg', 'gif', 'png'], true)) { + $this->logger->error('DownloadImages: Processed image with not allowed extension. Skipping: '.$imagePath); + + return false; + } + + return $ext; + } } -- cgit v1.2.3 From be9d693e74e41fdcdb18bf80aa1aff614154bcce Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Thu, 1 Jun 2017 10:42:19 +0200 Subject: remove craueconfig domain name setting and add a proper one in parameters --- src/Wallabag/CoreBundle/Controller/ConfigController.php | 2 +- src/Wallabag/CoreBundle/DependencyInjection/Configuration.php | 1 + src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php | 1 + src/Wallabag/CoreBundle/Resources/config/services.yml | 2 +- src/Wallabag/UserBundle/Resources/config/services.yml | 2 +- 5 files changed, 5 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Controller/ConfigController.php b/src/Wallabag/CoreBundle/Controller/ConfigController.php index 0e61c642..89d27425 100644 --- a/src/Wallabag/CoreBundle/Controller/ConfigController.php +++ b/src/Wallabag/CoreBundle/Controller/ConfigController.php @@ -151,7 +151,7 @@ class ConfigController extends Controller 'token' => $config->getRssToken(), ], 'twofactor_auth' => $this->getParameter('twofactor_auth'), - 'wallabag_url' => $this->get('craue_config')->get('wallabag_url'), + 'wallabag_url' => $this->getParameter('domain_name'), 'enabled_users' => $this->getDoctrine() ->getRepository('WallabagUserBundle:User') ->getSumEnabledUsers(), diff --git a/src/Wallabag/CoreBundle/DependencyInjection/Configuration.php b/src/Wallabag/CoreBundle/DependencyInjection/Configuration.php index 33df92d3..37f7c761 100644 --- a/src/Wallabag/CoreBundle/DependencyInjection/Configuration.php +++ b/src/Wallabag/CoreBundle/DependencyInjection/Configuration.php @@ -62,6 +62,7 @@ class Configuration implements ConfigurationInterface ->end() ->end() ->end() + ->scalarNode('domain_name') ->end() ->end() ; diff --git a/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php b/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php index b4d8a386..d0b4351e 100644 --- a/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php +++ b/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php @@ -29,6 +29,7 @@ class WallabagCoreExtension extends Extension $container->setParameter('wallabag_core.fetching_error_message_title', $config['fetching_error_message_title']); $container->setParameter('wallabag_core.api_limit_mass_actions', $config['api_limit_mass_actions']); $container->setParameter('wallabag_core.default_internal_settings', $config['default_internal_settings']); + $container->setParameter('wallabag_core.domain_name', $config['domain_name']); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.yml'); diff --git a/src/Wallabag/CoreBundle/Resources/config/services.yml b/src/Wallabag/CoreBundle/Resources/config/services.yml index a9b0d2d5..a82f36ce 100644 --- a/src/Wallabag/CoreBundle/Resources/config/services.yml +++ b/src/Wallabag/CoreBundle/Resources/config/services.yml @@ -122,7 +122,7 @@ services: wallabag_core.helper.entries_export: class: Wallabag\CoreBundle\Helper\EntriesExport arguments: - - '@=service(''craue_config'').get(''wallabag_url'')' + - '%domain_name%' - src/Wallabag/CoreBundle/Resources/public/themes/_global/img/appicon/apple-touch-icon-152.png wallabag.operator.array.matches: diff --git a/src/Wallabag/UserBundle/Resources/config/services.yml b/src/Wallabag/UserBundle/Resources/config/services.yml index 72f6f12c..bfba6010 100644 --- a/src/Wallabag/UserBundle/Resources/config/services.yml +++ b/src/Wallabag/UserBundle/Resources/config/services.yml @@ -7,7 +7,7 @@ services: - "%scheb_two_factor.email.sender_email%" - "%scheb_two_factor.email.sender_name%" - '@=service(''craue_config'').get(''wallabag_support_url'')' - - '@=service(''craue_config'').get(''wallabag_url'')' + - '%domain_name%' wallabag_user.password_resetting: class: Wallabag\UserBundle\EventListener\PasswordResettingListener -- cgit v1.2.3 From d6c4c484c46706f9eecf81af3f64649f014418e1 Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Tue, 6 Jun 2017 16:04:51 +0200 Subject: add migration --- src/Wallabag/CoreBundle/DependencyInjection/Configuration.php | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/DependencyInjection/Configuration.php b/src/Wallabag/CoreBundle/DependencyInjection/Configuration.php index 37f7c761..a6f53714 100644 --- a/src/Wallabag/CoreBundle/DependencyInjection/Configuration.php +++ b/src/Wallabag/CoreBundle/DependencyInjection/Configuration.php @@ -62,6 +62,7 @@ class Configuration implements ConfigurationInterface ->end() ->end() ->end() + ->end() ->scalarNode('domain_name') ->end() ->end() -- cgit v1.2.3 From e48b238a3e2c387be1f897e6f2c3c481d25f5203 Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Tue, 6 Jun 2017 16:18:25 +0200 Subject: fix tests --- src/Wallabag/CoreBundle/Resources/config/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Resources/config/services.yml b/src/Wallabag/CoreBundle/Resources/config/services.yml index a82f36ce..6e2c9761 100644 --- a/src/Wallabag/CoreBundle/Resources/config/services.yml +++ b/src/Wallabag/CoreBundle/Resources/config/services.yml @@ -195,7 +195,7 @@ services: arguments: - "@wallabag_core.entry.download_images.client" - "%kernel.root_dir%/../web/assets/images" - - '@=service(''craue_config'').get(''wallabag_url'')' + - '%wallabag_core.domain_name%' - "@logger" wallabag_core.entry.download_images.client: -- cgit v1.2.3 From db0c48af361eb20fbfcac625869de6f26112d3f7 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Wed, 7 Jun 2017 15:07:55 +0200 Subject: Refactorize the way to save an Entry in the API --- .../ApiBundle/Controller/EntryRestController.php | 172 +++++++++------------ 1 file changed, 70 insertions(+), 102 deletions(-) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/EntryRestController.php b/src/Wallabag/ApiBundle/Controller/EntryRestController.php index 7135e616..09b73ccb 100644 --- a/src/Wallabag/ApiBundle/Controller/EntryRestController.php +++ b/src/Wallabag/ApiBundle/Controller/EntryRestController.php @@ -299,65 +299,18 @@ class EntryRestController extends WallabagRestController $this->validateAuthentication(); $url = $request->request->get('url'); - $title = $request->request->get('title'); - $tags = $request->request->get('tags', []); - $isArchived = $request->request->get('archive'); - $isStarred = $request->request->get('starred'); - $content = $request->request->get('content'); - $language = $request->request->get('language'); - $picture = $request->request->get('preview_picture'); - $publishedAt = $request->request->get('published_at'); - $authors = $request->request->get('authors', ''); - $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId($url, $this->getUser()->getId()); + $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId( + $url, + $this->getUser()->getId() + ); if (false === $entry) { $entry = new Entry($this->getUser()); - } - - try { - $this->get('wallabag_core.content_proxy')->updateEntry( - $entry, - $url, - [ - 'title' => $title, - 'html' => $content, - 'url' => $url, - 'language' => $language, - 'date' => $publishedAt, - // faking the preview picture - 'open_graph' => [ - 'og_image' => $picture, - ], - 'authors' => explode(',', $authors), - ] - ); - } catch (\Exception $e) { - $this->get('logger')->error('Error while saving an entry', [ - 'exception' => $e, - 'entry' => $entry, - ]); $entry->setUrl($url); } - if (!empty($tags)) { - $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags); - } - - if (!is_null($isStarred)) { - $entry->setStarred((bool) $isStarred); - } - - if (!is_null($isArchived)) { - $entry->setArchived((bool) $isArchived); - } - - $em = $this->getDoctrine()->getManager(); - $em->persist($entry); - $em->flush(); - - // entry saved, dispatch event about it! - $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry)); + $this->upsertEntry($entry, $request); return $this->sendResponse($entry); } @@ -389,56 +342,7 @@ class EntryRestController extends WallabagRestController $this->validateAuthentication(); $this->validateUserAccess($entry->getUser()->getId()); - $title = $request->request->get('title'); - $tags = $request->request->get('tags', ''); - $isArchived = $request->request->get('archive'); - $isStarred = $request->request->get('starred'); - $content = $request->request->get('content'); - $language = $request->request->get('language'); - $picture = $request->request->get('preview_picture'); - $publishedAt = $request->request->get('published_at'); - $authors = $request->request->get('authors', ''); - - try { - $this->get('wallabag_core.content_proxy')->updateEntry( - $entry, - $entry->getUrl(), - [ - 'title' => !empty($title) ? $title : $entry->getTitle(), - 'html' => !empty($content) ? $content : $entry->getContent(), - 'url' => $entry->getUrl(), - 'language' => $language, - 'date' => $publishedAt, - // faking the preview picture - 'open_graph' => [ - 'og_image' => $picture, - ], - 'authors' => is_string($authors) ? explode(',', $authors) : [], - ], - // we don't want the content to be update by fetching the url - true - ); - } catch (\Exception $e) { - $this->get('logger')->error('Error while saving an entry', [ - 'exception' => $e, - 'entry' => $entry, - ]); - } - - if (!is_null($isArchived)) { - $entry->setArchived((bool) $isArchived); - } - - if (!is_null($isStarred)) { - $entry->setStarred((bool) $isStarred); - } - - if (!empty($tags)) { - $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags); - } - - $em = $this->getDoctrine()->getManager(); - $em->flush(); + $this->upsertEntry($entry, $request, true); return $this->sendResponse($entry); } @@ -705,4 +609,68 @@ class EntryRestController extends WallabagRestController return (new JsonResponse())->setJson($json); } + + /** + * Update or Insert a new entry. + * + * @param Entry $entry + * @param Request $request + * @param bool $disableContentUpdate If we don't want the content to be update by fetching the url (used when patching instead of posting) + */ + private function upsertEntry(Entry $entry, Request $request, $disableContentUpdate = false) + { + $title = $request->request->get('title'); + $tags = $request->request->get('tags', []); + $isArchived = $request->request->get('archive'); + $isStarred = $request->request->get('starred'); + $content = $request->request->get('content'); + $language = $request->request->get('language'); + $picture = $request->request->get('preview_picture'); + $publishedAt = $request->request->get('published_at'); + $authors = $request->request->get('authors', ''); + + try { + $this->get('wallabag_core.content_proxy')->updateEntry( + $entry, + $entry->getUrl(), + [ + 'title' => !empty($title) ? $title : $entry->getTitle(), + 'html' => !empty($content) ? $content : $entry->getContent(), + 'url' => $entry->getUrl(), + 'language' => !empty($language) ? $language : $entry->getLanguage(), + 'date' => !empty($publishedAt) ? $publishedAt : $entry->getPublishedAt(), + // faking the open graph preview picture + 'open_graph' => [ + 'og_image' => !empty($picture) ? $picture : $entry->getPreviewPicture(), + ], + 'authors' => is_string($authors) ? explode(',', $authors) : $entry->getPublishedBy(), + ], + $disableContentUpdate + ); + } catch (\Exception $e) { + $this->get('logger')->error('Error while saving an entry', [ + 'exception' => $e, + 'entry' => $entry, + ]); + } + + if (!is_null($isArchived)) { + $entry->setArchived((bool) $isArchived); + } + + if (!is_null($isStarred)) { + $entry->setStarred((bool) $isStarred); + } + + if (!empty($tags)) { + $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags); + } + + $em = $this->getDoctrine()->getManager(); + $em->persist($entry); + $em->flush(); + + // entry saved, dispatch event about it! + $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry)); + } } -- cgit v1.2.3 From 0c00e5251671c3648eabb8888271c09137ad902d Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Wed, 7 Jun 2017 23:23:28 +0200 Subject: Create a client when creating a user using the api MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit While creating a new user using the API, we also create a new client for the current user. So the app which just create the user can use its newly created client to configure the app. That new client is only return after creating the user. When calling the endpoint /api/user to get user information, the new client information won’t be return. --- .../ApiBundle/Controller/UserRestController.php | 20 +++++++++--- src/Wallabag/ApiBundle/Entity/Client.php | 23 +++++++++++++ .../views/themes/common/Developer/index.html.twig | 2 +- src/Wallabag/UserBundle/Entity/User.php | 38 ++++++++++++++++++---- 4 files changed, 70 insertions(+), 13 deletions(-) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/UserRestController.php b/src/Wallabag/ApiBundle/Controller/UserRestController.php index 8f675b8d..becbbb9e 100644 --- a/src/Wallabag/ApiBundle/Controller/UserRestController.php +++ b/src/Wallabag/ApiBundle/Controller/UserRestController.php @@ -9,6 +9,7 @@ use Nelmio\ApiDocBundle\Annotation\ApiDoc; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\JsonResponse; use Wallabag\UserBundle\Entity\User; +use Wallabag\ApiBundle\Entity\Client; class UserRestController extends WallabagRestController { @@ -97,29 +98,38 @@ class UserRestController extends WallabagRestController ->setStatusCode(JsonResponse::HTTP_BAD_REQUEST); } + // create a default client + $client = new Client($user); + $client->setName('Default client'); + + $this->getDoctrine()->getManager()->persist($client); + + $user->addClient($client); + $userManager->updateUser($user); // dispatch a created event so the associated config will be created $event = new UserEvent($user, $request); $this->get('event_dispatcher')->dispatch(FOSUserEvents::USER_CREATED, $event); - return $this->sendUser($user, JsonResponse::HTTP_CREATED); + return $this->sendUser($user, 'user_api_with_client', JsonResponse::HTTP_CREATED); } /** * Send user response. * - * @param User $user - * @param int $status HTTP Status code to send + * @param User $user + * @param string $group Used to define with serialized group might be used + * @param int $status HTTP Status code to send * * @return JsonResponse */ - private function sendUser(User $user, $status = JsonResponse::HTTP_OK) + private function sendUser(User $user, $group = 'user_api', $status = JsonResponse::HTTP_OK) { $json = $this->get('serializer')->serialize( $user, 'json', - SerializationContext::create()->setGroups(['user_api']) + SerializationContext::create()->setGroups([$group]) ); return (new JsonResponse()) diff --git a/src/Wallabag/ApiBundle/Entity/Client.php b/src/Wallabag/ApiBundle/Entity/Client.php index 9ed9f980..c15fd3fa 100644 --- a/src/Wallabag/ApiBundle/Entity/Client.php +++ b/src/Wallabag/ApiBundle/Entity/Client.php @@ -5,6 +5,9 @@ namespace Wallabag\ApiBundle\Entity; use Doctrine\ORM\Mapping as ORM; use FOS\OAuthServerBundle\Entity\Client as BaseClient; use Wallabag\UserBundle\Entity\User; +use JMS\Serializer\Annotation\Groups; +use JMS\Serializer\Annotation\SerializedName; +use JMS\Serializer\Annotation\VirtualProperty; /** * @ORM\Table("oauth2_clients") @@ -23,6 +26,8 @@ class Client extends BaseClient * @var string * * @ORM\Column(name="name", type="text", nullable=false) + * + * @Groups({"user_api_with_client"}) */ protected $name; @@ -36,6 +41,14 @@ class Client extends BaseClient */ protected $accessTokens; + /** + * @var string + * + * @SerializedName("client_secret") + * @Groups({"user_api_with_client"}) + */ + protected $secret; + /** * @ORM\ManyToOne(targetEntity="Wallabag\UserBundle\Entity\User", inversedBy="clients") */ @@ -78,4 +91,14 @@ class Client extends BaseClient { return $this->user; } + + /** + * @VirtualProperty + * @SerializedName("client_id") + * @Groups({"user_api_with_client"}) + */ + public function getClientId() + { + return $this->getId().'_'.$this->getRandomId(); + } } diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/common/Developer/index.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/common/Developer/index.html.twig index b3f0affb..528b055c 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/common/Developer/index.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/common/Developer/index.html.twig @@ -33,7 +33,7 @@ - + diff --git a/src/Wallabag/UserBundle/Entity/User.php b/src/Wallabag/UserBundle/Entity/User.php index ed6ce331..5c75846f 100644 --- a/src/Wallabag/UserBundle/Entity/User.php +++ b/src/Wallabag/UserBundle/Entity/User.php @@ -6,6 +6,7 @@ use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; use JMS\Serializer\Annotation\Groups; use JMS\Serializer\Annotation\XmlRoot; +use JMS\Serializer\Annotation\Accessor; use Scheb\TwoFactorBundle\Model\Email\TwoFactorInterface; use Scheb\TwoFactorBundle\Model\TrustedComputerInterface; use FOS\UserBundle\Model\User as BaseUser; @@ -36,7 +37,7 @@ class User extends BaseUser implements TwoFactorInterface, TrustedComputerInterf * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") * - * @Groups({"user_api"}) + * @Groups({"user_api", "user_api_with_client"}) */ protected $id; @@ -45,21 +46,21 @@ class User extends BaseUser implements TwoFactorInterface, TrustedComputerInterf * * @ORM\Column(name="name", type="text", nullable=true) * - * @Groups({"user_api"}) + * @Groups({"user_api", "user_api_with_client"}) */ protected $name; /** * @var string * - * @Groups({"user_api"}) + * @Groups({"user_api", "user_api_with_client"}) */ protected $username; /** * @var string * - * @Groups({"user_api"}) + * @Groups({"user_api", "user_api_with_client"}) */ protected $email; @@ -68,7 +69,7 @@ class User extends BaseUser implements TwoFactorInterface, TrustedComputerInterf * * @ORM\Column(name="created_at", type="datetime") * - * @Groups({"user_api"}) + * @Groups({"user_api", "user_api_with_client"}) */ protected $createdAt; @@ -77,7 +78,7 @@ class User extends BaseUser implements TwoFactorInterface, TrustedComputerInterf * * @ORM\Column(name="updated_at", type="datetime") * - * @Groups({"user_api"}) + * @Groups({"user_api", "user_api_with_client"}) */ protected $updatedAt; @@ -97,7 +98,8 @@ class User extends BaseUser implements TwoFactorInterface, TrustedComputerInterf private $authCode; /** - * @var bool Enabled yes/no + * @var bool + * * @ORM\Column(type="boolean") */ private $twoFactorAuthentication = false; @@ -112,6 +114,14 @@ class User extends BaseUser implements TwoFactorInterface, TrustedComputerInterf */ protected $clients; + /** + * @see getFirstClient() below + * + * @Groups({"user_api_with_client"}) + * @Accessor(getter="getFirstClient") + */ + protected $default_client; + public function __construct() { parent::__construct(); @@ -288,4 +298,18 @@ class User extends BaseUser implements TwoFactorInterface, TrustedComputerInterf { return $this->clients; } + + /** + * Only used by the API when creating a new user it'll also return the first client (which was also created at the same time). + * + * @return Client + */ + public function getFirstClient() + { + if (empty($this->clients)) { + return $this->clients; + } + + return $this->clients->first(); + } } -- cgit v1.2.3 From eb570e49c8e3ba12638fac600bb5527191c2aaa2 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Wed, 7 Jun 2017 23:23:34 +0200 Subject: CS --- src/Wallabag/UserBundle/Entity/User.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/Wallabag/UserBundle/Entity/User.php b/src/Wallabag/UserBundle/Entity/User.php index 5c75846f..aba76ca7 100644 --- a/src/Wallabag/UserBundle/Entity/User.php +++ b/src/Wallabag/UserBundle/Entity/User.php @@ -110,6 +110,8 @@ class User extends BaseUser implements TwoFactorInterface, TrustedComputerInterf private $trusted; /** + * @var ArrayCollection + * * @ORM\OneToMany(targetEntity="Wallabag\ApiBundle\Entity\Client", mappedBy="user", cascade={"remove"}) */ protected $clients; @@ -306,10 +308,8 @@ class User extends BaseUser implements TwoFactorInterface, TrustedComputerInterf */ public function getFirstClient() { - if (empty($this->clients)) { - return $this->clients; + if (!empty($this->clients)) { + return $this->clients->first(); } - - return $this->clients->first(); } } -- cgit v1.2.3 From a8d3fe50df52ec486add5691a3b67fe5205a032e Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Thu, 8 Jun 2017 14:25:44 +0200 Subject: Add ability to name the client --- src/Wallabag/ApiBundle/Controller/UserRestController.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/UserRestController.php b/src/Wallabag/ApiBundle/Controller/UserRestController.php index becbbb9e..7471f5f6 100644 --- a/src/Wallabag/ApiBundle/Controller/UserRestController.php +++ b/src/Wallabag/ApiBundle/Controller/UserRestController.php @@ -28,13 +28,14 @@ class UserRestController extends WallabagRestController } /** - * Register an user. + * Register an user and create a client. * * @ApiDoc( * requirements={ * {"name"="username", "dataType"="string", "required"=true, "description"="The user's username"}, * {"name"="password", "dataType"="string", "required"=true, "description"="The user's password"}, - * {"name"="email", "dataType"="string", "required"=true, "description"="The user's email"} + * {"name"="email", "dataType"="string", "required"=true, "description"="The user's email"}, + * {"name"="client_name", "dataType"="string", "required"=true, "description"="The client name (to be used by your app)"} * } * ) * @@ -100,7 +101,7 @@ class UserRestController extends WallabagRestController // create a default client $client = new Client($user); - $client->setName('Default client'); + $client->setName($request->request->get('client_name', 'Default client')); $this->getDoctrine()->getManager()->persist($client); -- cgit v1.2.3 From 80f4d85ac92ab4dc490c51f2d831ac7fa3853826 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Thu, 8 Jun 2017 19:15:33 +0200 Subject: Review --- src/Wallabag/CoreBundle/DependencyInjection/Configuration.php | 2 -- src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php | 1 - src/Wallabag/CoreBundle/Resources/config/services.yml | 2 +- 3 files changed, 1 insertion(+), 4 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/DependencyInjection/Configuration.php b/src/Wallabag/CoreBundle/DependencyInjection/Configuration.php index a6f53714..33df92d3 100644 --- a/src/Wallabag/CoreBundle/DependencyInjection/Configuration.php +++ b/src/Wallabag/CoreBundle/DependencyInjection/Configuration.php @@ -63,8 +63,6 @@ class Configuration implements ConfigurationInterface ->end() ->end() ->end() - ->scalarNode('domain_name') - ->end() ->end() ; diff --git a/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php b/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php index d0b4351e..b4d8a386 100644 --- a/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php +++ b/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php @@ -29,7 +29,6 @@ class WallabagCoreExtension extends Extension $container->setParameter('wallabag_core.fetching_error_message_title', $config['fetching_error_message_title']); $container->setParameter('wallabag_core.api_limit_mass_actions', $config['api_limit_mass_actions']); $container->setParameter('wallabag_core.default_internal_settings', $config['default_internal_settings']); - $container->setParameter('wallabag_core.domain_name', $config['domain_name']); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.yml'); diff --git a/src/Wallabag/CoreBundle/Resources/config/services.yml b/src/Wallabag/CoreBundle/Resources/config/services.yml index 6e2c9761..8b00700f 100644 --- a/src/Wallabag/CoreBundle/Resources/config/services.yml +++ b/src/Wallabag/CoreBundle/Resources/config/services.yml @@ -195,7 +195,7 @@ services: arguments: - "@wallabag_core.entry.download_images.client" - "%kernel.root_dir%/../web/assets/images" - - '%wallabag_core.domain_name%' + - '%domain_name%' - "@logger" wallabag_core.entry.download_images.client: -- cgit v1.2.3 From 0d349ea67073c535e1aa7f19f3cf842a54458bfe Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Thu, 8 Jun 2017 21:51:46 +0200 Subject: Validate language & preview picture fields Instead of saving the value of each field right into the content without any validation, it seems better to validate them. This might sounds obvious now we say that. --- src/Wallabag/CoreBundle/Helper/ContentProxy.php | 78 +++++++++++++++++++--- .../CoreBundle/Resources/config/services.yml | 1 + 2 files changed, 68 insertions(+), 11 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Helper/ContentProxy.php b/src/Wallabag/CoreBundle/Helper/ContentProxy.php index d5820e66..dd9170ad 100644 --- a/src/Wallabag/CoreBundle/Helper/ContentProxy.php +++ b/src/Wallabag/CoreBundle/Helper/ContentProxy.php @@ -7,6 +7,9 @@ use Psr\Log\LoggerInterface; use Wallabag\CoreBundle\Entity\Entry; use Wallabag\CoreBundle\Tools\Utils; use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeExtensionGuesser; +use Symfony\Component\Validator\Constraints\Language as LanguageConstraint; +use Symfony\Component\Validator\Constraints\Url as UrlConstraint; +use Symfony\Component\Validator\Validator\ValidatorInterface; /** * This kind of proxy class take care of getting the content from an url @@ -21,10 +24,11 @@ class ContentProxy protected $fetchingErrorMessage; protected $eventDispatcher; - public function __construct(Graby $graby, RuleBasedTagger $tagger, LoggerInterface $logger, $fetchingErrorMessage) + public function __construct(Graby $graby, RuleBasedTagger $tagger, ValidatorInterface $validator, LoggerInterface $logger, $fetchingErrorMessage) { $this->graby = $graby; $this->tagger = $tagger; + $this->validator = $validator; $this->logger = $logger; $this->mimeGuesser = new MimeTypeExtensionGuesser(); $this->fetchingErrorMessage = $fetchingErrorMessage; @@ -113,7 +117,24 @@ class ContentProxy $entry->setHeaders($content['all_headers']); } - $entry->setLanguage(isset($content['language']) ? $content['language'] : ''); + $this->validateAndSetLanguage( + $entry, + isset($content['language']) ? $content['language'] : '' + ); + + $this->validateAndSetPreviewPicture( + $entry, + isset($content['open_graph']['og_image']) ? $content['open_graph']['og_image'] : '' + ); + + // if content is an image define as a preview too + if (!empty($content['content_type']) && in_array($this->mimeGuesser->guess($content['content_type']), ['jpeg', 'jpg', 'gif', 'png'], true)) { + $this->validateAndSetPreviewPicture( + $entry, + $content['url'] + ); + } + $entry->setMimetype(isset($content['content_type']) ? $content['content_type'] : ''); $entry->setReadingTime(Utils::getReadingTime($html)); @@ -122,15 +143,6 @@ class ContentProxy $entry->setDomainName($domainName); } - if (!empty($content['open_graph']['og_image'])) { - $entry->setPreviewPicture($content['open_graph']['og_image']); - } - - // if content is an image define as a preview too - if (!empty($content['content_type']) && in_array($this->mimeGuesser->guess($content['content_type']), ['jpeg', 'jpg', 'gif', 'png'], true)) { - $entry->setPreviewPicture($content['url']); - } - try { $this->tagger->tag($entry); } catch (\Exception $e) { @@ -152,4 +164,48 @@ class ContentProxy { return !empty($content['title']) && !empty($content['html']) && !empty($content['url']); } + + /** + * Use a Symfony validator to ensure the language is well formatted. + * + * @param Entry $entry + * @param string $value Language to validate + */ + private function validateAndSetLanguage($entry, $value) + { + $errors = $this->validator->validate( + $value, + (new LanguageConstraint()) + ); + + if (0 === count($errors)) { + $entry->setLanguage($value); + + return; + } + + $this->logger->warning('Language validation failed. '.(string) $errors); + } + + /** + * Use a Symfony validator to ensure the preview picture is a real url. + * + * @param Entry $entry + * @param string $value URL to validate + */ + private function validateAndSetPreviewPicture($entry, $value) + { + $errors = $this->validator->validate( + $value, + (new UrlConstraint()) + ); + + if (0 === count($errors)) { + $entry->setPreviewPicture($value); + + return; + } + + $this->logger->warning('PreviewPicture validation failed. '.(string) $errors); + } } diff --git a/src/Wallabag/CoreBundle/Resources/config/services.yml b/src/Wallabag/CoreBundle/Resources/config/services.yml index a9b0d2d5..2ae5d27f 100644 --- a/src/Wallabag/CoreBundle/Resources/config/services.yml +++ b/src/Wallabag/CoreBundle/Resources/config/services.yml @@ -90,6 +90,7 @@ services: arguments: - "@wallabag_core.graby" - "@wallabag_core.rule_based_tagger" + - "@validator" - "@logger" - '%wallabag_core.fetching_error_message%' -- cgit v1.2.3 From be54dfe4e67b90bf6d94139fe968584871ca0f59 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Thu, 8 Jun 2017 21:56:20 +0200 Subject: CS --- src/Wallabag/CoreBundle/Helper/ContentProxy.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Helper/ContentProxy.php b/src/Wallabag/CoreBundle/Helper/ContentProxy.php index dd9170ad..f752d37e 100644 --- a/src/Wallabag/CoreBundle/Helper/ContentProxy.php +++ b/src/Wallabag/CoreBundle/Helper/ContentProxy.php @@ -19,6 +19,7 @@ class ContentProxy { protected $graby; protected $tagger; + protected $validator; protected $logger; protected $mimeGuesser; protected $fetchingErrorMessage; @@ -127,7 +128,7 @@ class ContentProxy isset($content['open_graph']['og_image']) ? $content['open_graph']['og_image'] : '' ); - // if content is an image define as a preview too + // if content is an image, define it as a preview too if (!empty($content['content_type']) && in_array($this->mimeGuesser->guess($content['content_type']), ['jpeg', 'jpg', 'gif', 'png'], true)) { $this->validateAndSetPreviewPicture( $entry, -- cgit v1.2.3 From 63f9f22fa37b14171c6f92d24f99ccf01ae7af00 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Thu, 8 Jun 2017 22:24:49 +0200 Subject: Log an error level message when user auth fail MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When a user login using the form we know log an error level information with information about the user: - username used - IP - User agent For example: > Authentication failure for user "eza", from IP "127.0.0.1", with UA: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36". It’ll allows server admin using fail2ban to configure it to block these people if they generate too much failure authentication. --- .../UserBundle/Resources/config/services.yml | 8 +++ .../CustomAuthenticationFailureHandler.php | 62 ++++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 src/Wallabag/UserBundle/Security/CustomAuthenticationFailureHandler.php (limited to 'src') diff --git a/src/Wallabag/UserBundle/Resources/config/services.yml b/src/Wallabag/UserBundle/Resources/config/services.yml index 72f6f12c..6ab463e3 100644 --- a/src/Wallabag/UserBundle/Resources/config/services.yml +++ b/src/Wallabag/UserBundle/Resources/config/services.yml @@ -35,3 +35,11 @@ services: - "%wallabag_core.list_mode%" tags: - { name: kernel.event_subscriber } + + wallabag_user.security.custom_auth_failure_handler: + class: Wallabag\UserBundle\Security\CustomAuthenticationFailureHandler + arguments: + - "@http_kernel" + - "@security.http_utils" + - { } + - "@logger" diff --git a/src/Wallabag/UserBundle/Security/CustomAuthenticationFailureHandler.php b/src/Wallabag/UserBundle/Security/CustomAuthenticationFailureHandler.php new file mode 100644 index 00000000..93e2d17b --- /dev/null +++ b/src/Wallabag/UserBundle/Security/CustomAuthenticationFailureHandler.php @@ -0,0 +1,62 @@ +options['failure_path_parameter'])) { + $this->options['failure_path'] = $failureUrl; + } + + if (null === $this->options['failure_path']) { + $this->options['failure_path'] = $this->options['login_path']; + } + + if ($this->options['failure_forward']) { + $this->logger->debug('Authentication failure, forward triggered.', ['failure_path' => $this->options['failure_path']]); + + $this->logError($request); + + $subRequest = $this->httpUtils->createRequest($request, $this->options['failure_path']); + $subRequest->attributes->set(Security::AUTHENTICATION_ERROR, $exception); + + return $this->httpKernel->handle($subRequest, HttpKernelInterface::SUB_REQUEST); + } + + $this->logger->debug('Authentication failure, redirect triggered.', ['failure_path' => $this->options['failure_path']]); + + $this->logError($request); + + $request->getSession()->set(Security::AUTHENTICATION_ERROR, $exception); + + return $this->httpUtils->createRedirectResponse($request, $this->options['failure_path']); + } + + /** + * Log error information about fialure + * + * @param Request $request + */ + private function logError(Request $request) + { + $this->logger->error('Authentication failure for user "'.$request->request->get('_username').'", from IP "'.$request->getClientIp().'", with UA: "'.$request->server->get('HTTP_USER_AGENT').'".'); + } +} -- cgit v1.2.3 From fa1c9d7cc7f3c4d2f9167a5b62bbc8cd1f9df59b Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Thu, 8 Jun 2017 22:52:26 +0200 Subject: CS --- .../UserBundle/Security/CustomAuthenticationFailureHandler.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Wallabag/UserBundle/Security/CustomAuthenticationFailureHandler.php b/src/Wallabag/UserBundle/Security/CustomAuthenticationFailureHandler.php index 93e2d17b..2d4ea0ea 100644 --- a/src/Wallabag/UserBundle/Security/CustomAuthenticationFailureHandler.php +++ b/src/Wallabag/UserBundle/Security/CustomAuthenticationFailureHandler.php @@ -51,9 +51,9 @@ class CustomAuthenticationFailureHandler extends DefaultAuthenticationFailureHan } /** - * Log error information about fialure + * Log error information about fialure. * - * @param Request $request + * @param Request $request */ private function logError(Request $request) { -- cgit v1.2.3 From f81a34e37929a822755d120215d2f18f042ff713 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Fri, 9 Jun 2017 09:45:43 +0200 Subject: Use a listener to catch auth failure --- .../AuthenticationFailureListener.php | 40 ++++++++++++++ .../UserBundle/Resources/config/services.yml | 10 ++-- .../CustomAuthenticationFailureHandler.php | 62 ---------------------- 3 files changed, 45 insertions(+), 67 deletions(-) create mode 100644 src/Wallabag/UserBundle/EventListener/AuthenticationFailureListener.php delete mode 100644 src/Wallabag/UserBundle/Security/CustomAuthenticationFailureHandler.php (limited to 'src') diff --git a/src/Wallabag/UserBundle/EventListener/AuthenticationFailureListener.php b/src/Wallabag/UserBundle/EventListener/AuthenticationFailureListener.php new file mode 100644 index 00000000..10f13233 --- /dev/null +++ b/src/Wallabag/UserBundle/EventListener/AuthenticationFailureListener.php @@ -0,0 +1,40 @@ +requestStack = $requestStack; + $this->logger = $logger; + } + + /** + * {@inheritdoc} + */ + public static function getSubscribedEvents() + { + return [ + AuthenticationEvents::AUTHENTICATION_FAILURE => 'onAuthenticationFailure', + ]; + } + + /** + * On failure, add a custom error in log so server admin can configure fail2ban to block IP from people who try to login too much. + */ + public function onAuthenticationFailure() + { + $request = $this->requestStack->getMasterRequest(); + + $this->logger->error('Authentication failure for user "'.$request->request->get('_username').'", from IP "'.$request->getClientIp().'", with UA: "'.$request->server->get('HTTP_USER_AGENT').'".'); + } +} diff --git a/src/Wallabag/UserBundle/Resources/config/services.yml b/src/Wallabag/UserBundle/Resources/config/services.yml index 6ab463e3..f2cd6e01 100644 --- a/src/Wallabag/UserBundle/Resources/config/services.yml +++ b/src/Wallabag/UserBundle/Resources/config/services.yml @@ -36,10 +36,10 @@ services: tags: - { name: kernel.event_subscriber } - wallabag_user.security.custom_auth_failure_handler: - class: Wallabag\UserBundle\Security\CustomAuthenticationFailureHandler + wallabag_user.listener.authentication_failure_event_listener: + class: Wallabag\UserBundle\EventListener\AuthenticationFailureListener arguments: - - "@http_kernel" - - "@security.http_utils" - - { } + - "@request_stack" - "@logger" + tags: + - { name: kernel.event_listener, event: security.authentication.failure, method: onAuthenticationFailure } diff --git a/src/Wallabag/UserBundle/Security/CustomAuthenticationFailureHandler.php b/src/Wallabag/UserBundle/Security/CustomAuthenticationFailureHandler.php deleted file mode 100644 index 2d4ea0ea..00000000 --- a/src/Wallabag/UserBundle/Security/CustomAuthenticationFailureHandler.php +++ /dev/null @@ -1,62 +0,0 @@ -options['failure_path_parameter'])) { - $this->options['failure_path'] = $failureUrl; - } - - if (null === $this->options['failure_path']) { - $this->options['failure_path'] = $this->options['login_path']; - } - - if ($this->options['failure_forward']) { - $this->logger->debug('Authentication failure, forward triggered.', ['failure_path' => $this->options['failure_path']]); - - $this->logError($request); - - $subRequest = $this->httpUtils->createRequest($request, $this->options['failure_path']); - $subRequest->attributes->set(Security::AUTHENTICATION_ERROR, $exception); - - return $this->httpKernel->handle($subRequest, HttpKernelInterface::SUB_REQUEST); - } - - $this->logger->debug('Authentication failure, redirect triggered.', ['failure_path' => $this->options['failure_path']]); - - $this->logError($request); - - $request->getSession()->set(Security::AUTHENTICATION_ERROR, $exception); - - return $this->httpUtils->createRedirectResponse($request, $this->options['failure_path']); - } - - /** - * Log error information about fialure. - * - * @param Request $request - */ - private function logError(Request $request) - { - $this->logger->error('Authentication failure for user "'.$request->request->get('_username').'", from IP "'.$request->getClientIp().'", with UA: "'.$request->server->get('HTTP_USER_AGENT').'".'); - } -} -- cgit v1.2.3 From 42f3bb2c6346e04d2837f980bf685f7e32a61a21 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Fri, 9 Jun 2017 11:28:04 +0200 Subject: Use Locale instead of Language --- src/Wallabag/CoreBundle/Helper/ContentProxy.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Helper/ContentProxy.php b/src/Wallabag/CoreBundle/Helper/ContentProxy.php index f752d37e..e4e7fb31 100644 --- a/src/Wallabag/CoreBundle/Helper/ContentProxy.php +++ b/src/Wallabag/CoreBundle/Helper/ContentProxy.php @@ -7,7 +7,7 @@ use Psr\Log\LoggerInterface; use Wallabag\CoreBundle\Entity\Entry; use Wallabag\CoreBundle\Tools\Utils; use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeExtensionGuesser; -use Symfony\Component\Validator\Constraints\Language as LanguageConstraint; +use Symfony\Component\Validator\Constraints\Locale as LocaleConstraint; use Symfony\Component\Validator\Constraints\Url as UrlConstraint; use Symfony\Component\Validator\Validator\ValidatorInterface; @@ -176,7 +176,7 @@ class ContentProxy { $errors = $this->validator->validate( $value, - (new LanguageConstraint()) + (new LocaleConstraint()) ); if (0 === count($errors)) { -- cgit v1.2.3 From 80e49ba7b0320a5c4278c01f3d7851a9218e0919 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Fri, 9 Jun 2017 11:42:04 +0200 Subject: Convert - to _ in language Mostly to increase language supports --- src/Wallabag/CoreBundle/Helper/ContentProxy.php | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Helper/ContentProxy.php b/src/Wallabag/CoreBundle/Helper/ContentProxy.php index e4e7fb31..0c971863 100644 --- a/src/Wallabag/CoreBundle/Helper/ContentProxy.php +++ b/src/Wallabag/CoreBundle/Helper/ContentProxy.php @@ -174,6 +174,10 @@ class ContentProxy */ private function validateAndSetLanguage($entry, $value) { + // some lang are defined as fr-FR, es-ES. + // replacing - by _ might increase language support + $value = str_replace('-', '_', $value); + $errors = $this->validator->validate( $value, (new LocaleConstraint()) -- cgit v1.2.3 From a9b984feeef84474add8a7c4a8e741816bf8f0e0 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Sat, 10 Jun 2017 11:21:47 +0200 Subject: Fix tags count in tags list on baggy --- src/Wallabag/CoreBundle/Resources/views/themes/baggy/Tag/tags.html.twig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Tag/tags.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Tag/tags.html.twig index 1e2c6b42..7509918e 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Tag/tags.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Tag/tags.html.twig @@ -9,7 +9,7 @@ -- cgit v1.2.3 From 8da86b3f93b0cbe03cab5efedf0baa56c0371720 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Rumi=C5=84ski?= Date: Sat, 10 Jun 2017 12:40:40 +0200 Subject: Update validators.pl.yml add "quote_length_too_high" translation --- src/Wallabag/CoreBundle/Resources/translations/validators.pl.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Resources/translations/validators.pl.yml b/src/Wallabag/CoreBundle/Resources/translations/validators.pl.yml index 58d19cc9..e4165c14 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/validators.pl.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/validators.pl.yml @@ -4,4 +4,4 @@ validator: password_wrong_value: 'Twoje obecne hasło jest błędne' item_per_page_too_high: 'To może spowodować problemy z aplikacją' rss_limit_too_high: 'To może spowodować problemy z aplikacją' - # quote_length_too_high: 'The quote is too long. It should have {{ limit }} characters or less.' + quote_length_too_high: 'Cytat jest zbyt długi. powinien mieć {{ limit }} znaków lub mniej.' -- cgit v1.2.3 From e8911f7c09fa9d8009d7c7ee9fb0c181d2ffbc31 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Sat, 10 Jun 2017 15:00:52 +0200 Subject: Add isPublic filter on entries --- src/Wallabag/CoreBundle/Entity/Entry.php | 10 ++++++++++ src/Wallabag/CoreBundle/Form/Type/EntryFilterType.php | 14 ++++++++++++++ .../CoreBundle/Resources/translations/messages.da.yml | 2 ++ .../CoreBundle/Resources/translations/messages.de.yml | 2 ++ .../CoreBundle/Resources/translations/messages.en.yml | 2 ++ .../CoreBundle/Resources/translations/messages.es.yml | 2 ++ .../CoreBundle/Resources/translations/messages.fa.yml | 2 ++ .../CoreBundle/Resources/translations/messages.fr.yml | 2 ++ .../CoreBundle/Resources/translations/messages.it.yml | 2 ++ .../CoreBundle/Resources/translations/messages.oc.yml | 2 ++ .../CoreBundle/Resources/translations/messages.pl.yml | 2 ++ .../CoreBundle/Resources/translations/messages.pt.yml | 2 ++ .../CoreBundle/Resources/translations/messages.ro.yml | 2 ++ .../Resources/views/themes/baggy/Entry/entries.html.twig | 5 +++++ .../views/themes/material/Entry/entries.html.twig | 11 +++++++++++ 15 files changed, 62 insertions(+) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Entity/Entry.php b/src/Wallabag/CoreBundle/Entity/Entry.php index 9a7dd4e7..365030c7 100644 --- a/src/Wallabag/CoreBundle/Entity/Entry.php +++ b/src/Wallabag/CoreBundle/Entity/Entry.php @@ -684,6 +684,16 @@ class Entry $this->uid = null; } + /** + * Used in the entries filter so it's more explicit for the end user than the uid. + * + * @return bool + */ + public function isPublic() + { + return null !== $this->uid; + } + /** * @return string */ diff --git a/src/Wallabag/CoreBundle/Form/Type/EntryFilterType.php b/src/Wallabag/CoreBundle/Form/Type/EntryFilterType.php index 556578d1..6a4c485f 100644 --- a/src/Wallabag/CoreBundle/Form/Type/EntryFilterType.php +++ b/src/Wallabag/CoreBundle/Form/Type/EntryFilterType.php @@ -150,6 +150,20 @@ class EntryFilterType extends AbstractType }, 'label' => 'entry.filters.preview_picture_label', ]) + ->add('isPublic', CheckboxFilterType::class, [ + 'apply_filter' => function (QueryInterface $filterQuery, $field, $values) { + if (false === $values['value']) { + return; + } + + // is_public isn't a real field + // we should use the "uid" field to determine if the entry has been made public + $expression = $filterQuery->getExpr()->isNotNull($values['alias'].'.uid'); + + return $filterQuery->createCondition($expression); + }, + 'label' => 'entry.filters.is_public_label', + ]) ->add('language', ChoiceFilterType::class, [ 'choices' => array_flip($this->repository->findDistinctLanguageByUser($this->user->getId())), 'label' => 'entry.filters.language_label', diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml index 5e7afe27..02dd04f2 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml @@ -186,6 +186,8 @@ entry: unread_label: 'Ulæst' preview_picture_label: 'Har et vist billede' preview_picture_help: 'Forhåndsvis billede' + # is_public_label: 'Has a public link' + # is_public_help: 'Public link' language_label: 'Sprog' # http_status_label: 'HTTP status' reading_time: diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml index 00468575..f6ccdae0 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml @@ -187,6 +187,8 @@ entry: unread_label: 'Ungelesene' preview_picture_label: 'Vorschaubild vorhanden' preview_picture_help: 'Vorschaubild' + # is_public_label: 'Has a public link' + # is_public_help: 'Public link' language_label: 'Sprache' http_status_label: 'HTTP-Status' reading_time: diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml index 572084c1..902c3046 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml @@ -187,6 +187,8 @@ entry: unread_label: 'Unread' preview_picture_label: 'Has a preview picture' preview_picture_help: 'Preview picture' + is_public_label: 'Has a public link' + is_public_help: 'Public link' language_label: 'Language' http_status_label: 'HTTP status' reading_time: diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml index 0f2a4a7b..afd6a7b1 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml @@ -187,6 +187,8 @@ entry: unread_label: 'Sin leer' preview_picture_label: 'Tiene imagen de previsualización' preview_picture_help: 'Imagen de previsualización' + # is_public_label: 'Has a public link' + # is_public_help: 'Public link' language_label: 'Idioma' http_status_label: 'Código de estado HTTP' reading_time: diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml index a8900489..545514b3 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml @@ -187,6 +187,8 @@ entry: unread_label: 'خوانده‌نشده' preview_picture_label: 'دارای عکس پیش‌نمایش' preview_picture_help: 'پیش‌نمایش عکس' + # is_public_label: 'Has a public link' + # is_public_help: 'Public link' language_label: 'زبان' # http_status_label: 'HTTP status' reading_time: diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml index 6969b67b..e9e75efa 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml @@ -187,6 +187,8 @@ entry: unread_label: "Non lus" preview_picture_label: "A une photo" preview_picture_help: "Photo" + is_public_label: 'A une lien public' + is_public_help: 'Lien public' language_label: "Langue" http_status_label: "Statut HTTP" reading_time: diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml index c2007057..0597d3e3 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml @@ -187,6 +187,8 @@ entry: # unread_label: 'Unread' preview_picture_label: "Ha un'immagine di anteprima" preview_picture_help: 'Immagine di anteprima' + # is_public_label: 'Has a public link' + # is_public_help: 'Public link' language_label: 'Lingua' # http_status_label: 'HTTP status' reading_time: diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml index 3ac472d0..c172a0f6 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml @@ -187,6 +187,8 @@ entry: unread_label: 'Pas legits' preview_picture_label: 'A un imatge' preview_picture_help: 'Imatge' + # is_public_label: 'Has a public link' + # is_public_help: 'Public link' language_label: 'Lenga' http_status_label: 'Estatut HTTP' reading_time: diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml index fa672387..82d16767 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml @@ -187,6 +187,8 @@ entry: unread_label: 'Nieprzeczytane' preview_picture_label: 'Posiada podgląd obrazu' preview_picture_help: 'Podgląd obrazu' + # is_public_label: 'Has a public link' + # is_public_help: 'Public link' language_label: 'Język' http_status_label: 'Status HTTP' reading_time: diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml index 896ccb04..b75567d6 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml @@ -187,6 +187,8 @@ entry: unread_label: 'Não Lido' preview_picture_label: 'Possui uma imagem de preview' preview_picture_help: 'Imagem de preview' + # is_public_label: 'Has a public link' + # is_public_help: 'Public link' language_label: 'Idioma' # http_status_label: 'HTTP status' reading_time: diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml index c447dc9b..95df573d 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml @@ -187,6 +187,8 @@ entry: unread_label: 'Necitite' preview_picture_label: 'Are o imagine de previzualizare' preview_picture_help: 'Previzualizare imagine' + # is_public_label: 'Has a public link' + # is_public_help: 'Public link' language_label: 'Limbă' # http_status_label: 'HTTP status' reading_time: diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Entry/entries.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Entry/entries.html.twig index 0ba6f4f4..6c26d5bf 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Entry/entries.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Entry/entries.html.twig @@ -127,6 +127,11 @@ {{ form_widget(form.previewPicture) }} {{ form_label(form.previewPicture) }} + +
        + {{ form_widget(form.isPublic) }} + {{ form_label(form.isPublic) }} +
        diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entries.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entries.html.twig index 6f657b18..5ba42057 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entries.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entries.html.twig @@ -102,6 +102,15 @@ {{ form_label(form.previewPicture) }}
        +
        + +
        + +
        + {{ form_widget(form.isPublic) }} + {{ form_label(form.isPublic) }} +
        +
        {{ form_label(form.language) }}
        @@ -121,10 +130,12 @@
        {{ form_label(form.readingTime) }}
        +
        {{ form_widget(form.readingTime.left_number, {'type': 'number'}) }}
        +
        {{ form_widget(form.readingTime.right_number, {'type': 'number'}) }} -- cgit v1.2.3 From 1112e54772c9308ee3d7417869b5b8ef9b2b9812 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Sat, 10 Jun 2017 15:31:57 +0200 Subject: Add public filter/field in the API MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Listing entries can now be filtered by “public”. Creating or patching an entry can now set is to public or remove the public. Entry response now include “is_public” boolean field --- .../ApiBundle/Controller/EntryRestController.php | 27 +++++++++++++++++++--- src/Wallabag/CoreBundle/Entity/Entry.php | 4 ++++ .../CoreBundle/Repository/EntryRepository.php | 11 ++++++--- 3 files changed, 36 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/EntryRestController.php b/src/Wallabag/ApiBundle/Controller/EntryRestController.php index 09b73ccb..ae9a93aa 100644 --- a/src/Wallabag/ApiBundle/Controller/EntryRestController.php +++ b/src/Wallabag/ApiBundle/Controller/EntryRestController.php @@ -77,6 +77,7 @@ class EntryRestController extends WallabagRestController * {"name"="perPage", "dataType"="integer", "required"=false, "format"="default'30'", "description"="results per page."}, * {"name"="tags", "dataType"="string", "required"=false, "format"="api,rest", "description"="a list of tags url encoded. Will returns entries that matches ALL tags."}, * {"name"="since", "dataType"="integer", "required"=false, "format"="default '0'", "description"="The timestamp since when you want entries updated."}, + * {"name"="public", "dataType"="integer", "required"=false, "format"="1 or 0, all entries by default", "description"="filter by entries with a public link"}, * } * ) * @@ -88,6 +89,7 @@ class EntryRestController extends WallabagRestController $isArchived = (null === $request->query->get('archive')) ? null : (bool) $request->query->get('archive'); $isStarred = (null === $request->query->get('starred')) ? null : (bool) $request->query->get('starred'); + $isPublic = (null === $request->query->get('public')) ? null : (bool) $request->query->get('public'); $sort = $request->query->get('sort', 'created'); $order = $request->query->get('order', 'desc'); $page = (int) $request->query->get('page', 1); @@ -96,9 +98,16 @@ class EntryRestController extends WallabagRestController $since = $request->query->get('since', 0); /** @var \Pagerfanta\Pagerfanta $pager */ - $pager = $this->getDoctrine() - ->getRepository('WallabagCoreBundle:Entry') - ->findEntries($this->getUser()->getId(), $isArchived, $isStarred, $sort, $order, $since, $tags); + $pager = $this->get('wallabag_core.entry_repository')->findEntries( + $this->getUser()->getId(), + $isArchived, + $isStarred, + $isPublic, + $sort, + $order, + $since, + $tags + ); $pager->setMaxPerPage($perPage); $pager->setCurrentPage($page); @@ -111,6 +120,7 @@ class EntryRestController extends WallabagRestController [ 'archive' => $isArchived, 'starred' => $isStarred, + 'public' => $isPublic, 'sort' => $sort, 'order' => $order, 'page' => $page, @@ -289,6 +299,7 @@ class EntryRestController extends WallabagRestController * {"name"="preview_picture", "dataType"="string", "required"=false, "description"="Preview picture of the entry"}, * {"name"="published_at", "dataType"="datetime|integer", "format"="YYYY-MM-DDTHH:II:SS+TZ or a timestamp", "required"=false, "description"="Published date of the entry"}, * {"name"="authors", "dataType"="string", "format"="Name Firstname,author2,author3", "required"=false, "description"="Authors of the entry"}, + * {"name"="public", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="will generate a public link for the entry"}, * } * ) * @@ -332,6 +343,7 @@ class EntryRestController extends WallabagRestController * {"name"="preview_picture", "dataType"="string", "required"=false, "description"="Preview picture of the entry"}, * {"name"="published_at", "dataType"="datetime|integer", "format"="YYYY-MM-DDTHH:II:SS+TZ or a timestamp", "required"=false, "description"="Published date of the entry"}, * {"name"="authors", "dataType"="string", "format"="Name Firstname,author2,author3", "required"=false, "description"="Authors of the entry"}, + * {"name"="public", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="will generate a public link for the entry"}, * } * ) * @@ -623,6 +635,7 @@ class EntryRestController extends WallabagRestController $tags = $request->request->get('tags', []); $isArchived = $request->request->get('archive'); $isStarred = $request->request->get('starred'); + $isPublic = $request->request->get('public'); $content = $request->request->get('content'); $language = $request->request->get('language'); $picture = $request->request->get('preview_picture'); @@ -666,6 +679,14 @@ class EntryRestController extends WallabagRestController $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags); } + if (!is_null($isPublic)) { + $entry->cleanUid(); + + if (true === (bool) $isPublic && null === $entry->getUid()) { + $entry->generateUid(); + } + } + $em = $this->getDoctrine()->getManager(); $em->persist($entry); $em->flush(); diff --git a/src/Wallabag/CoreBundle/Entity/Entry.php b/src/Wallabag/CoreBundle/Entity/Entry.php index 365030c7..07d41ed8 100644 --- a/src/Wallabag/CoreBundle/Entity/Entry.php +++ b/src/Wallabag/CoreBundle/Entity/Entry.php @@ -687,6 +687,10 @@ class Entry /** * Used in the entries filter so it's more explicit for the end user than the uid. * + * @VirtualProperty + * @SerializedName("is_public") + * @Groups({"entries_for_user"}) + * * @return bool */ public function isPublic() diff --git a/src/Wallabag/CoreBundle/Repository/EntryRepository.php b/src/Wallabag/CoreBundle/Repository/EntryRepository.php index 6972e974..9bda4e15 100644 --- a/src/Wallabag/CoreBundle/Repository/EntryRepository.php +++ b/src/Wallabag/CoreBundle/Repository/EntryRepository.php @@ -135,6 +135,7 @@ class EntryRepository extends EntityRepository * @param int $userId * @param bool $isArchived * @param bool $isStarred + * @param bool $isPublic * @param string $sort * @param string $order * @param int $since @@ -142,18 +143,22 @@ class EntryRepository extends EntityRepository * * @return array */ - public function findEntries($userId, $isArchived = null, $isStarred = null, $sort = 'created', $order = 'ASC', $since = 0, $tags = '') + public function findEntries($userId, $isArchived = null, $isStarred = null, $isPublic = null, $sort = 'created', $order = 'ASC', $since = 0, $tags = '') { $qb = $this->createQueryBuilder('e') ->leftJoin('e.tags', 't') ->where('e.user =:userId')->setParameter('userId', $userId); if (null !== $isArchived) { - $qb->andWhere('e.isArchived =:isArchived')->setParameter('isArchived', (bool) $isArchived); + $qb->andWhere('e.isArchived = :isArchived')->setParameter('isArchived', (bool) $isArchived); } if (null !== $isStarred) { - $qb->andWhere('e.isStarred =:isStarred')->setParameter('isStarred', (bool) $isStarred); + $qb->andWhere('e.isStarred = :isStarred')->setParameter('isStarred', (bool) $isStarred); + } + + if (null !== $isPublic) { + $qb->andWhere('e.uid IS '.(true === $isPublic ? 'NOT' : '').' NULL'); } if ($since > 0) { -- cgit v1.2.3 From a9c6577f0c51dd4282e022fa4b41cbb7b0e201b3 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Sat, 10 Jun 2017 15:37:25 +0200 Subject: Few fixes --- src/Wallabag/ApiBundle/Controller/EntryRestController.php | 4 ++-- src/Wallabag/CoreBundle/Entity/Entry.php | 1 + src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/EntryRestController.php b/src/Wallabag/ApiBundle/Controller/EntryRestController.php index ae9a93aa..afd708e6 100644 --- a/src/Wallabag/ApiBundle/Controller/EntryRestController.php +++ b/src/Wallabag/ApiBundle/Controller/EntryRestController.php @@ -680,10 +680,10 @@ class EntryRestController extends WallabagRestController } if (!is_null($isPublic)) { - $entry->cleanUid(); - if (true === (bool) $isPublic && null === $entry->getUid()) { $entry->generateUid(); + } else if (false === (bool) $isPublic) { + $entry->cleanUid(); } } diff --git a/src/Wallabag/CoreBundle/Entity/Entry.php b/src/Wallabag/CoreBundle/Entity/Entry.php index 07d41ed8..a0503c39 100644 --- a/src/Wallabag/CoreBundle/Entity/Entry.php +++ b/src/Wallabag/CoreBundle/Entity/Entry.php @@ -686,6 +686,7 @@ class Entry /** * Used in the entries filter so it's more explicit for the end user than the uid. + * Also used in the API. * * @VirtualProperty * @SerializedName("is_public") diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml index e9e75efa..e9e79c67 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml @@ -187,7 +187,7 @@ entry: unread_label: "Non lus" preview_picture_label: "A une photo" preview_picture_help: "Photo" - is_public_label: 'A une lien public' + is_public_label: 'A un lien public' is_public_help: 'Lien public' language_label: "Langue" http_status_label: "Statut HTTP" -- cgit v1.2.3 From d9da186fb8427ca82d1fd7c4e2ef3f5032781f23 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Sat, 10 Jun 2017 16:08:24 +0200 Subject: CS --- src/Wallabag/ApiBundle/Controller/EntryRestController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/EntryRestController.php b/src/Wallabag/ApiBundle/Controller/EntryRestController.php index afd708e6..768c4fdc 100644 --- a/src/Wallabag/ApiBundle/Controller/EntryRestController.php +++ b/src/Wallabag/ApiBundle/Controller/EntryRestController.php @@ -682,7 +682,7 @@ class EntryRestController extends WallabagRestController if (!is_null($isPublic)) { if (true === (bool) $isPublic && null === $entry->getUid()) { $entry->generateUid(); - } else if (false === (bool) $isPublic) { + } elseif (false === (bool) $isPublic) { $entry->cleanUid(); } } -- cgit v1.2.3 From 41d45c6122f61e01a370233d26a2633836094d5c Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Mon, 12 Jun 2017 16:46:33 +0200 Subject: Fix empty language and preview pics --- src/Wallabag/CoreBundle/Helper/ContentProxy.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Helper/ContentProxy.php b/src/Wallabag/CoreBundle/Helper/ContentProxy.php index 0c971863..51bb2ca2 100644 --- a/src/Wallabag/CoreBundle/Helper/ContentProxy.php +++ b/src/Wallabag/CoreBundle/Helper/ContentProxy.php @@ -120,12 +120,12 @@ class ContentProxy $this->validateAndSetLanguage( $entry, - isset($content['language']) ? $content['language'] : '' + isset($content['language']) ? $content['language'] : null ); $this->validateAndSetPreviewPicture( $entry, - isset($content['open_graph']['og_image']) ? $content['open_graph']['og_image'] : '' + isset($content['open_graph']['og_image']) ? $content['open_graph']['og_image'] : null ); // if content is an image, define it as a preview too -- cgit v1.2.3 From caa0b1765b8c249ff4a868980d90e3410b26b664 Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Wed, 14 Jun 2017 17:30:12 +0200 Subject: Add client_credentials oAuth2 auth method Signed-off-by: Thomas Citharel --- src/Wallabag/ApiBundle/Controller/DeveloperController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/DeveloperController.php b/src/Wallabag/ApiBundle/Controller/DeveloperController.php index 9cb1b626..9cb73f4c 100644 --- a/src/Wallabag/ApiBundle/Controller/DeveloperController.php +++ b/src/Wallabag/ApiBundle/Controller/DeveloperController.php @@ -43,7 +43,7 @@ class DeveloperController extends Controller $clientForm->handleRequest($request); if ($clientForm->isSubmitted() && $clientForm->isValid()) { - $client->setAllowedGrantTypes(['token', 'authorization_code', 'password', 'refresh_token']); + $client->setAllowedGrantTypes(['client_credentials', 'token', 'authorization_code', 'password', 'refresh_token']); $em->persist($client); $em->flush(); -- cgit v1.2.3 From f92fcb53ca78cc8822962e676b0db117e1a08aa5 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Sun, 4 Dec 2016 13:51:58 +0100 Subject: Add CRUD for site credentials --- .../Controller/SiteCredentialController.php | 138 +++++++++++++++ src/Wallabag/CoreBundle/Entity/SiteCredential.php | 197 +++++++++++++++++++++ .../CoreBundle/Form/Type/SiteCredentialType.php | 43 +++++ .../Repository/SiteCredentialRepository.php | 13 ++ .../Resources/translations/messages.da.yml | 25 +++ .../Resources/translations/messages.de.yml | 25 +++ .../Resources/translations/messages.en.yml | 25 +++ .../Resources/translations/messages.es.yml | 25 +++ .../Resources/translations/messages.fa.yml | 25 +++ .../Resources/translations/messages.fr.yml | 31 +++- .../Resources/translations/messages.it.yml | 25 +++ .../Resources/translations/messages.oc.yml | 25 +++ .../Resources/translations/messages.pl.yml | 25 +++ .../Resources/translations/messages.pt.yml | 25 +++ .../Resources/translations/messages.ro.yml | 25 +++ .../Resources/translations/messages.tr.yml | 5 + .../themes/baggy/SiteCredential/edit.html.twig | 60 +++++++ .../themes/baggy/SiteCredential/index.html.twig | 44 +++++ .../themes/baggy/SiteCredential/new.html.twig | 53 ++++++ .../views/themes/material/Config/index.html.twig | 20 +-- .../themes/material/SiteCredential/edit.html.twig | 60 +++++++ .../themes/material/SiteCredential/index.html.twig | 44 +++++ .../themes/material/SiteCredential/new.html.twig | 53 ++++++ 23 files changed, 998 insertions(+), 13 deletions(-) create mode 100644 src/Wallabag/CoreBundle/Controller/SiteCredentialController.php create mode 100644 src/Wallabag/CoreBundle/Entity/SiteCredential.php create mode 100644 src/Wallabag/CoreBundle/Form/Type/SiteCredentialType.php create mode 100644 src/Wallabag/CoreBundle/Repository/SiteCredentialRepository.php create mode 100644 src/Wallabag/CoreBundle/Resources/views/themes/baggy/SiteCredential/edit.html.twig create mode 100644 src/Wallabag/CoreBundle/Resources/views/themes/baggy/SiteCredential/index.html.twig create mode 100644 src/Wallabag/CoreBundle/Resources/views/themes/baggy/SiteCredential/new.html.twig create mode 100644 src/Wallabag/CoreBundle/Resources/views/themes/material/SiteCredential/edit.html.twig create mode 100644 src/Wallabag/CoreBundle/Resources/views/themes/material/SiteCredential/index.html.twig create mode 100644 src/Wallabag/CoreBundle/Resources/views/themes/material/SiteCredential/new.html.twig (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Controller/SiteCredentialController.php b/src/Wallabag/CoreBundle/Controller/SiteCredentialController.php new file mode 100644 index 00000000..e7e43800 --- /dev/null +++ b/src/Wallabag/CoreBundle/Controller/SiteCredentialController.php @@ -0,0 +1,138 @@ +getDoctrine()->getManager(); + + $credentials = $em->getRepository('WallabagCoreBundle:SiteCredential')->findAll(); + + return $this->render('WallabagCoreBundle:SiteCredential:index.html.twig', array( + 'credentials' => $credentials, + )); + } + + /** + * Creates a new site credential entity. + * + * @Route("/site-credential/new", name="site_credential_new") + * @Method({"GET", "POST"}) + */ + public function newAction(Request $request) + { + $credential = new SiteCredential($this->getUser()); + + $form = $this->createForm('Wallabag\CoreBundle\Form\Type\SiteCredentialType', $credential); + $form->handleRequest($request); + + if ($form->isSubmitted() && $form->isValid()) { + $em = $this->getDoctrine()->getManager(); + $em->persist($credential); + $em->flush($credential); + + $this->get('session')->getFlashBag()->add( + 'notice', + $this->get('translator')->trans('flashes.site_credential.notice.added', ['%host%' => $credential->getHost()]) + ); + + return $this->redirectToRoute('site_credential_edit', array('id' => $credential->getId())); + } + + return $this->render('WallabagCoreBundle:SiteCredential:new.html.twig', array( + 'credential' => $credential, + 'form' => $form->createView(), + )); + } + + /** + * Displays a form to edit an existing site credential entity. + * + * @Route("/site-credential/{id}/edit", name="site_credential_edit") + * @Method({"GET", "POST"}) + */ + public function editAction(Request $request, SiteCredential $siteCredential) + { + $deleteForm = $this->createDeleteForm($siteCredential); + $editForm = $this->createForm('Wallabag\CoreBundle\Form\Type\SiteCredentialType', $siteCredential); + $editForm->handleRequest($request); + + if ($editForm->isSubmitted() && $editForm->isValid()) { + $em = $this->getDoctrine()->getManager(); + $em->persist($siteCredential); + $em->flush(); + + $this->get('session')->getFlashBag()->add( + 'notice', + $this->get('translator')->trans('flashes.site_credential.notice.updated', ['%host%' => $siteCredential->getHost()]) + ); + + return $this->redirectToRoute('site_credential_edit', array('id' => $siteCredential->getId())); + } + + return $this->render('WallabagCoreBundle:SiteCredential:edit.html.twig', array( + 'credential' => $siteCredential, + 'edit_form' => $editForm->createView(), + 'delete_form' => $deleteForm->createView(), + )); + } + + /** + * Deletes a site credential entity. + * + * @Route("/site-credential/{id}", name="site_credential_delete") + * @Method("DELETE") + */ + public function deleteAction(Request $request, SiteCredential $siteCredential) + { + $form = $this->createDeleteForm($siteCredential); + $form->handleRequest($request); + + if ($form->isSubmitted() && $form->isValid()) { + $this->get('session')->getFlashBag()->add( + 'notice', + $this->get('translator')->trans('flashes.site_credential.notice.deleted', ['%host%' => $siteCredential->getHost()]) + ); + + $em = $this->getDoctrine()->getManager(); + $em->remove($siteCredential); + $em->flush(); + } + + return $this->redirectToRoute('site_credential_index'); + } + + /** + * Creates a form to delete a site credential entity. + * + * @param SiteCredential $siteCredential The site credential entity + * + * @return \Symfony\Component\Form\Form The form + */ + private function createDeleteForm(SiteCredential $siteCredential) + { + return $this->createFormBuilder() + ->setAction($this->generateUrl('site_credential_delete', array('id' => $siteCredential->getId()))) + ->setMethod('DELETE') + ->getForm() + ; + } +} diff --git a/src/Wallabag/CoreBundle/Entity/SiteCredential.php b/src/Wallabag/CoreBundle/Entity/SiteCredential.php new file mode 100644 index 00000000..85ee07d4 --- /dev/null +++ b/src/Wallabag/CoreBundle/Entity/SiteCredential.php @@ -0,0 +1,197 @@ +user = $user; + } + + /** + * Get id. + * + * @return int + */ + public function getId() + { + return $this->id; + } + + /** + * Set host. + * + * @param string $host + * + * @return SiteCredential + */ + public function setHost($host) + { + $this->host = $host; + + return $this; + } + + /** + * Get host. + * + * @return string + */ + public function getHost() + { + return $this->host; + } + + /** + * Set username. + * + * @param string $username + * + * @return SiteCredential + */ + public function setUsername($username) + { + $this->username = $username; + + return $this; + } + + /** + * Get username. + * + * @return string + */ + public function getUsername() + { + return $this->username; + } + + /** + * Set password. + * + * @param string $password + * + * @return SiteCredential + */ + public function setPassword($password) + { + $this->password = $password; + + return $this; + } + + /** + * Get password. + * + * @return string + */ + public function getPassword() + { + return $this->password; + } + + /** + * Set createdAt. + * + * @param \DateTime $createdAt + * + * @return SiteCredential + */ + public function setCreatedAt($createdAt) + { + $this->createdAt = $createdAt; + + return $this; + } + + /** + * Get createdAt. + * + * @return \DateTime + */ + public function getCreatedAt() + { + return $this->createdAt; + } + + /** + * @return User + */ + public function getUser() + { + return $this->user; + } + + /** + * @ORM\PrePersist + */ + public function timestamps() + { + if (is_null($this->createdAt)) { + $this->createdAt = new \DateTime(); + } + } +} diff --git a/src/Wallabag/CoreBundle/Form/Type/SiteCredentialType.php b/src/Wallabag/CoreBundle/Form/Type/SiteCredentialType.php new file mode 100644 index 00000000..9db7c155 --- /dev/null +++ b/src/Wallabag/CoreBundle/Form/Type/SiteCredentialType.php @@ -0,0 +1,43 @@ +add('host', TextType::class, [ + 'label' => 'site_credential.form.host_label', + ]) + ->add('username', TextType::class, [ + 'label' => 'site_credential.form.username_label', + ]) + ->add('password', PasswordType::class, [ + 'label' => 'site_credential.form.password_label', + ]) + ->add('save', SubmitType::class, [ + 'label' => 'config.form.save', + ]) + ; + } + + public function configureOptions(OptionsResolver $resolver) + { + $resolver->setDefaults([ + 'data_class' => 'Wallabag\CoreBundle\Entity\SiteCredential', + ]); + } + + public function getBlockPrefix() + { + return 'site_credential'; + } +} diff --git a/src/Wallabag/CoreBundle/Repository/SiteCredentialRepository.php b/src/Wallabag/CoreBundle/Repository/SiteCredentialRepository.php new file mode 100644 index 00000000..501b4439 --- /dev/null +++ b/src/Wallabag/CoreBundle/Repository/SiteCredentialRepository.php @@ -0,0 +1,13 @@ + +
        +
        +
        +
        +

        {{ 'site_credential.edit_site_credential'|trans }}

        + +
        + {{ form_start(edit_form) }} + {{ form_errors(edit_form) }} + +
        +
        + {{ form_label(edit_form.host) }} + {{ form_errors(edit_form.host) }} + {{ form_widget(edit_form.host) }} +
        +
        + +
        +
        + {{ form_label(edit_form.username) }} + {{ form_errors(edit_form.username) }} + {{ form_widget(edit_form.username) }} +
        +
        + +
        +
        + {{ form_label(edit_form.password) }} + {{ form_errors(edit_form.password) }} + {{ form_widget(edit_form.password) }} +
        +
        + +
        + + {{ form_widget(edit_form.save, {'attr': {'class': 'btn waves-effect waves-light'}}) }} + {{ form_widget(edit_form._token) }} + +

        + {{ form_start(delete_form) }} + + {{ form_end(delete_form) }} +

        +

        {{ 'site_credential.form.back_to_list'|trans }}

        +
        +
        +
        +
        +
        +
        + +{% endblock %} diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/baggy/SiteCredential/index.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/baggy/SiteCredential/index.html.twig new file mode 100644 index 00000000..fda60b31 --- /dev/null +++ b/src/Wallabag/CoreBundle/Resources/views/themes/baggy/SiteCredential/index.html.twig @@ -0,0 +1,44 @@ +{% extends "WallabagCoreBundle::layout.html.twig" %} + +{% block title %}{{ 'site_credential.page_title'|trans }}{% endblock %} + +{% block content %} + +
        +
        +
        +
        +
        +

        {{ 'site_credential.description'|trans|raw }}

        + +
        {{ 'developer.existing_clients.field_id'|trans }}{{ client.id }}_{{ client.randomId }}{{ client.clientId }}
        {{ 'developer.existing_clients.field_secret'|trans }}
        + + + + + + + + + {% for credential in credentials %} + + + + + + {% endfor %} + +
        {{ 'site_credential.form.host_label'|trans }}{{ 'site_credential.form.username_label'|trans }}{{ 'site_credential.list.actions'|trans }}
        {{ credential.host }}{{ credential.username }} + {{ 'site_credential.list.edit_action'|trans }} +
        +
        +

        + {{ 'site_credential.list.create_new_one'|trans }} +

        +
        +
    +
    + + + +{% endblock %} diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/baggy/SiteCredential/new.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/baggy/SiteCredential/new.html.twig new file mode 100644 index 00000000..bf713902 --- /dev/null +++ b/src/Wallabag/CoreBundle/Resources/views/themes/baggy/SiteCredential/new.html.twig @@ -0,0 +1,53 @@ +{% extends "WallabagCoreBundle::layout.html.twig" %} + +{% block title %}{{ 'site_credential.page_title'|trans }}{% endblock %} + +{% block content %} + +
    +
    +
    +
    +
    +

    {{ 'site_credential.new_site_credential'|trans }}

    + +
    + {{ form_start(form) }} + {{ form_errors(form) }} + +
    +
    + {{ form_label(form.host) }} + {{ form_errors(form.host) }} + {{ form_widget(form.host) }} +
    +
    + +
    +
    + {{ form_label(form.username) }} + {{ form_errors(form.username) }} + {{ form_widget(form.username) }} +
    +
    + +
    +
    + {{ form_label(form.password) }} + {{ form_errors(form.password) }} + {{ form_widget(form.password) }} +
    +
    + + {{ form_widget(form.save, {'attr': {'class': 'btn waves-effect waves-light'}}) }} + {{ form_rest(form) }} + +

    {{ 'site_credential.form.back_to_list'|trans }}

    +
    +
    +
    +
    +
    +
    + +{% endblock %} diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/material/Config/index.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/material/Config/index.html.twig index 9b0816eb..1e10bf38 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/material/Config/index.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/material/Config/index.html.twig @@ -66,13 +66,13 @@ -
    -
    - {{ form_errors(form.config.action_mark_as_read) }} - {{ form_widget(form.config.action_mark_as_read) }} - {{ form_label(form.config.action_mark_as_read) }} +
    +
    + {{ form_label(form.config.action_mark_as_read) }} + {{ form_errors(form.config.action_mark_as_read) }} + {{ form_widget(form.config.action_mark_as_read) }} +
    -
    @@ -254,11 +254,11 @@ {{ form_start(form.pwd) }} {{ form_errors(form.pwd) }} -
    -
    - {{ 'config.form_password.description'|trans }} +
    +
    + {{ 'config.form_password.description'|trans }} +
    -
    diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/material/SiteCredential/edit.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/material/SiteCredential/edit.html.twig new file mode 100644 index 00000000..8448f17e --- /dev/null +++ b/src/Wallabag/CoreBundle/Resources/views/themes/material/SiteCredential/edit.html.twig @@ -0,0 +1,60 @@ +{% extends "WallabagCoreBundle::layout.html.twig" %} + +{% block title %}{{ 'site_credential.page_title'|trans }}{% endblock %} + +{% block content %} + +
    +
    +
    +
    +
    +

    {{ 'site_credential.edit_site_credential'|trans }}

    + +
    + {{ form_start(edit_form) }} + {{ form_errors(edit_form) }} + +
    +
    + {{ form_label(edit_form.host) }} + {{ form_errors(edit_form.host) }} + {{ form_widget(edit_form.host) }} +
    +
    + +
    +
    + {{ form_label(edit_form.username) }} + {{ form_errors(edit_form.username) }} + {{ form_widget(edit_form.username) }} +
    +
    + +
    +
    + {{ form_label(edit_form.password) }} + {{ form_errors(edit_form.password) }} + {{ form_widget(edit_form.password) }} +
    +
    + +
    + + {{ form_widget(edit_form.save, {'attr': {'class': 'btn waves-effect waves-light'}}) }} + {{ form_widget(edit_form._token) }} + +

    + {{ form_start(delete_form) }} + + {{ form_end(delete_form) }} +

    +

    {{ 'site_credential.form.back_to_list'|trans }}

    +
    +
    +
    +
    +
    +
    + +{% endblock %} diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/material/SiteCredential/index.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/material/SiteCredential/index.html.twig new file mode 100644 index 00000000..fda60b31 --- /dev/null +++ b/src/Wallabag/CoreBundle/Resources/views/themes/material/SiteCredential/index.html.twig @@ -0,0 +1,44 @@ +{% extends "WallabagCoreBundle::layout.html.twig" %} + +{% block title %}{{ 'site_credential.page_title'|trans }}{% endblock %} + +{% block content %} + +
    +
    +
    +
    +
    +

    {{ 'site_credential.description'|trans|raw }}

    + + + + + + + + + + + {% for credential in credentials %} + + + + + + {% endfor %} + +
    {{ 'site_credential.form.host_label'|trans }}{{ 'site_credential.form.username_label'|trans }}{{ 'site_credential.list.actions'|trans }}
    {{ credential.host }}{{ credential.username }} + {{ 'site_credential.list.edit_action'|trans }} +
    +
    +

    + {{ 'site_credential.list.create_new_one'|trans }} +

    +
    +
    +
    +
    +
    + +{% endblock %} diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/material/SiteCredential/new.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/material/SiteCredential/new.html.twig new file mode 100644 index 00000000..bf713902 --- /dev/null +++ b/src/Wallabag/CoreBundle/Resources/views/themes/material/SiteCredential/new.html.twig @@ -0,0 +1,53 @@ +{% extends "WallabagCoreBundle::layout.html.twig" %} + +{% block title %}{{ 'site_credential.page_title'|trans }}{% endblock %} + +{% block content %} + +
    +
    +
    +
    +
    +

    {{ 'site_credential.new_site_credential'|trans }}

    + +
    + {{ form_start(form) }} + {{ form_errors(form) }} + +
    +
    + {{ form_label(form.host) }} + {{ form_errors(form.host) }} + {{ form_widget(form.host) }} +
    +
    + +
    +
    + {{ form_label(form.username) }} + {{ form_errors(form.username) }} + {{ form_widget(form.username) }} +
    +
    + +
    +
    + {{ form_label(form.password) }} + {{ form_errors(form.password) }} + {{ form_widget(form.password) }} +
    +
    + + {{ form_widget(form.save, {'attr': {'class': 'btn waves-effect waves-light'}}) }} + {{ form_rest(form) }} + +

    {{ 'site_credential.form.back_to_list'|trans }}

    +
    +
    +
    +
    +
    +
    + +{% endblock %} -- cgit v1.2.3 From fc6d92c63dc5629a9e005628e416e0ecf4daa6ed Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Fri, 9 Dec 2016 16:47:50 +0100 Subject: Update route & user verification --- .../Controller/SiteCredentialController.php | 36 ++++++++++++++++------ .../Repository/SiteCredentialRepository.php | 3 -- .../Resources/translations/messages.fr.yml | 6 ++-- .../themes/material/SiteCredential/edit.html.twig | 2 +- .../themes/material/SiteCredential/index.html.twig | 4 +-- .../themes/material/SiteCredential/new.html.twig | 2 +- 6 files changed, 34 insertions(+), 19 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Controller/SiteCredentialController.php b/src/Wallabag/CoreBundle/Controller/SiteCredentialController.php index e7e43800..429f529a 100644 --- a/src/Wallabag/CoreBundle/Controller/SiteCredentialController.php +++ b/src/Wallabag/CoreBundle/Controller/SiteCredentialController.php @@ -11,20 +11,22 @@ use Wallabag\CoreBundle\Entity\SiteCredential; /** * SiteCredential controller. + * + * @Route("/site-credentials") */ class SiteCredentialController extends Controller { /** * Lists all User entities. * - * @Route("/site-credential", name="site_credential_index") + * @Route("/", name="site_credentials_index") * @Method("GET") */ public function indexAction() { $em = $this->getDoctrine()->getManager(); - $credentials = $em->getRepository('WallabagCoreBundle:SiteCredential')->findAll(); + $credentials = $em->getRepository('WallabagCoreBundle:SiteCredential')->findByUser($this->getUser()); return $this->render('WallabagCoreBundle:SiteCredential:index.html.twig', array( 'credentials' => $credentials, @@ -34,7 +36,7 @@ class SiteCredentialController extends Controller /** * Creates a new site credential entity. * - * @Route("/site-credential/new", name="site_credential_new") + * @Route("/new", name="site_credentials_new") * @Method({"GET", "POST"}) */ public function newAction(Request $request) @@ -54,7 +56,7 @@ class SiteCredentialController extends Controller $this->get('translator')->trans('flashes.site_credential.notice.added', ['%host%' => $credential->getHost()]) ); - return $this->redirectToRoute('site_credential_edit', array('id' => $credential->getId())); + return $this->redirectToRoute('site_credentials_edit', array('id' => $credential->getId())); } return $this->render('WallabagCoreBundle:SiteCredential:new.html.twig', array( @@ -66,11 +68,13 @@ class SiteCredentialController extends Controller /** * Displays a form to edit an existing site credential entity. * - * @Route("/site-credential/{id}/edit", name="site_credential_edit") + * @Route("/{id}/edit", name="site_credentials_edit") * @Method({"GET", "POST"}) */ public function editAction(Request $request, SiteCredential $siteCredential) { + $this->checkUserAction($siteCredential); + $deleteForm = $this->createDeleteForm($siteCredential); $editForm = $this->createForm('Wallabag\CoreBundle\Form\Type\SiteCredentialType', $siteCredential); $editForm->handleRequest($request); @@ -85,7 +89,7 @@ class SiteCredentialController extends Controller $this->get('translator')->trans('flashes.site_credential.notice.updated', ['%host%' => $siteCredential->getHost()]) ); - return $this->redirectToRoute('site_credential_edit', array('id' => $siteCredential->getId())); + return $this->redirectToRoute('site_credentials_edit', array('id' => $siteCredential->getId())); } return $this->render('WallabagCoreBundle:SiteCredential:edit.html.twig', array( @@ -98,11 +102,13 @@ class SiteCredentialController extends Controller /** * Deletes a site credential entity. * - * @Route("/site-credential/{id}", name="site_credential_delete") + * @Route("/{id}", name="site_credentials_delete") * @Method("DELETE") */ public function deleteAction(Request $request, SiteCredential $siteCredential) { + $this->checkUserAction($siteCredential); + $form = $this->createDeleteForm($siteCredential); $form->handleRequest($request); @@ -117,7 +123,7 @@ class SiteCredentialController extends Controller $em->flush(); } - return $this->redirectToRoute('site_credential_index'); + return $this->redirectToRoute('site_credentials_index'); } /** @@ -130,9 +136,21 @@ class SiteCredentialController extends Controller private function createDeleteForm(SiteCredential $siteCredential) { return $this->createFormBuilder() - ->setAction($this->generateUrl('site_credential_delete', array('id' => $siteCredential->getId()))) + ->setAction($this->generateUrl('site_credentials_delete', array('id' => $siteCredential->getId()))) ->setMethod('DELETE') ->getForm() ; } + + /** + * Check if the logged user can manage the given site credential. + * + * @param SiteCredential $siteCredential The site credential entity + */ + private function checkUserAction(SiteCredential $siteCredential) + { + if (null === $this->getUser() || $this->getUser()->getId() != $siteCredential->getUser()->getId()) { + throw $this->createAccessDeniedException('You can not access this site credential.'); + } + } } diff --git a/src/Wallabag/CoreBundle/Repository/SiteCredentialRepository.php b/src/Wallabag/CoreBundle/Repository/SiteCredentialRepository.php index 501b4439..88aee6d5 100644 --- a/src/Wallabag/CoreBundle/Repository/SiteCredentialRepository.php +++ b/src/Wallabag/CoreBundle/Repository/SiteCredentialRepository.php @@ -4,9 +4,6 @@ namespace Wallabag\CoreBundle\Repository; /** * SiteCredentialRepository. - * - * This class was generated by the Doctrine ORM. Add your own custom - * repository methods below. */ class SiteCredentialRepository extends \Doctrine\ORM\EntityRepository { diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml index e37abfd3..17eaf015 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml @@ -514,7 +514,7 @@ user: twofactor_label: "Double authentification" save: "Sauvegarder" delete: "Supprimer" - delete_confirm: "Voulez-vous vraiment ?" + delete_confirm: "Êtes-vous sur ?" back_to_list: "Revenir à la liste" search: placeholder: "Filtrer par nom d’utilisateur ou email" @@ -523,7 +523,7 @@ site_credential: page_title: Gestion des accès aux sites new_site_credential: Créer un accès à un site edit_site_credential: Éditer l'accès d'un site - description: "Ici vous pouvez gérer les accès aux différents sites. Ces accès permettent de récupérer des contenus sur des sites qui requiert une authentification ou un paywall" + description: "Ici vous pouvez gérer les accès aux différents sites. Ces accès permettent de récupérer des contenus sur des sites qui requièrent une authentification ou un paywall" list: actions: Actions edit_action: Éditer @@ -536,7 +536,7 @@ site_credential: password_label: 'Mot de passe' save: "Sauvegarder" delete: "Supprimer" - delete_confirm: "Voulez-vous vraiment ?" + delete_confirm: "Êtes-vous sur ?" back_to_list: "Revenir à la liste" error: diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/material/SiteCredential/edit.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/material/SiteCredential/edit.html.twig index 8448f17e..882be430 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/material/SiteCredential/edit.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/material/SiteCredential/edit.html.twig @@ -49,7 +49,7 @@ {{ form_end(delete_form) }}

    -

    {{ 'site_credential.form.back_to_list'|trans }}

    +

    {{ 'site_credential.form.back_to_list'|trans }}

    diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/material/SiteCredential/index.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/material/SiteCredential/index.html.twig index fda60b31..c128bceb 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/material/SiteCredential/index.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/material/SiteCredential/index.html.twig @@ -25,7 +25,7 @@ {{ credential.host }} {{ credential.username }} - {{ 'site_credential.list.edit_action'|trans }} + {{ 'site_credential.list.edit_action'|trans }} {% endfor %} @@ -33,7 +33,7 @@

    - {{ 'site_credential.list.create_new_one'|trans }} + {{ 'site_credential.list.create_new_one'|trans }}

    diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/material/SiteCredential/new.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/material/SiteCredential/new.html.twig index bf713902..3c008cde 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/material/SiteCredential/new.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/material/SiteCredential/new.html.twig @@ -42,7 +42,7 @@ {{ form_widget(form.save, {'attr': {'class': 'btn waves-effect waves-light'}}) }} {{ form_rest(form) }} -

    {{ 'site_credential.form.back_to_list'|trans }}

    +

    {{ 'site_credential.form.back_to_list'|trans }}

    -- cgit v1.2.3 From 5a9bc00726ddaf7c8798d4932d0a8b7a38422670 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Mon, 1 May 2017 22:13:17 +0200 Subject: Retrieve username/password from database Inject the current user & the repo to retrieve username/password from the database --- .../GrabySiteConfigBuilder.php | 32 ++++++++++++++++------ .../Repository/SiteCredentialRepository.php | 18 ++++++++++++ .../CoreBundle/Resources/config/services.yml | 9 +++++- 3 files changed, 49 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php b/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php index 1c56fa9f..94615687 100644 --- a/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php +++ b/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php @@ -6,6 +6,8 @@ use BD\GuzzleSiteAuthenticator\SiteConfig\SiteConfig; use BD\GuzzleSiteAuthenticator\SiteConfig\SiteConfigBuilder; use Graby\SiteConfig\ConfigBuilder; use Psr\Log\LoggerInterface; +use Wallabag\CoreBundle\Repository\SiteCredentialRepository; +use Wallabag\UserBundle\Entity\User; class GrabySiteConfigBuilder implements SiteConfigBuilder { @@ -13,26 +15,36 @@ class GrabySiteConfigBuilder implements SiteConfigBuilder * @var ConfigBuilder */ private $grabyConfigBuilder; + /** - * @var array + * @var SiteCredentialRepository */ - private $credentials; + private $credentialRepository; + /** * @var LoggerInterface */ private $logger; + /** + * @var User + */ + private $currentUser; + + /** * GrabySiteConfigBuilder constructor. * - * @param ConfigBuilder $grabyConfigBuilder - * @param array $credentials + * @param ConfigBuilder $grabyConfigBuilder + * @param User $currentUser + * @param SiteCredentialRepository $credentialRepository * @param LoggerInterface $logger */ - public function __construct(ConfigBuilder $grabyConfigBuilder, array $credentials, LoggerInterface $logger) + public function __construct(ConfigBuilder $grabyConfigBuilder, User $currentUser, SiteCredentialRepository $credentialRepository, LoggerInterface $logger) { $this->grabyConfigBuilder = $grabyConfigBuilder; - $this->credentials = $credentials; + $this->credentialRepository = $credentialRepository; + $this->currentUser = $currentUser; $this->logger = $logger; } @@ -47,7 +59,9 @@ class GrabySiteConfigBuilder implements SiteConfigBuilder $host = substr($host, 4); } - if (empty($this->credentials[$host])) { + $credentials = $this->credentialRepository->findOneByHostAndUser($host, $this->currentUser->getId()); + + if (null === $credentials) { $this->logger->debug('Auth: no credentials available for host.', ['host' => $host]); return false; @@ -62,8 +76,8 @@ class GrabySiteConfigBuilder implements SiteConfigBuilder 'passwordField' => $config->login_password_field ?: null, 'extraFields' => $this->processExtraFields($config->login_extra_fields), 'notLoggedInXpath' => $config->not_logged_in_xpath ?: null, - 'username' => $this->credentials[$host]['username'], - 'password' => $this->credentials[$host]['password'], + 'username' => $credentials['username'], + 'password' => $credentials['password'], ]; $config = new SiteConfig($parameters); diff --git a/src/Wallabag/CoreBundle/Repository/SiteCredentialRepository.php b/src/Wallabag/CoreBundle/Repository/SiteCredentialRepository.php index 88aee6d5..316ecc75 100644 --- a/src/Wallabag/CoreBundle/Repository/SiteCredentialRepository.php +++ b/src/Wallabag/CoreBundle/Repository/SiteCredentialRepository.php @@ -7,4 +7,22 @@ namespace Wallabag\CoreBundle\Repository; */ class SiteCredentialRepository extends \Doctrine\ORM\EntityRepository { + /** + * Retrieve one username/password for the given host and userId. + * + * @param string $host + * @param int $userId + * + * @return null|array + */ + public function findOneByHostAndUser($host, $userId) + { + return $this->createQueryBuilder('s') + ->select('s.username', 's.password') + ->where('s.host = :hostname')->setParameter('hostname', $host) + ->andWhere('s.user = :userId')->setParameter('userId', $userId) + ->setMaxResults(1) + ->getQuery() + ->getOneOrNullResult(); + } } diff --git a/src/Wallabag/CoreBundle/Resources/config/services.yml b/src/Wallabag/CoreBundle/Resources/config/services.yml index 4be79547..a59152d3 100644 --- a/src/Wallabag/CoreBundle/Resources/config/services.yml +++ b/src/Wallabag/CoreBundle/Resources/config/services.yml @@ -63,7 +63,8 @@ services: class: Wallabag\CoreBundle\GuzzleSiteAuthenticator\GrabySiteConfigBuilder arguments: - "@wallabag_core.graby.config_builder" - - "%sites_credentials%" + - "@=service('security.token_storage').getToken().getUser()" + - "@wallabag_core.site_credential_repository" - '@logger' tags: - { name: monolog.logger, channel: graby } @@ -120,6 +121,12 @@ services: arguments: - WallabagCoreBundle:Tag + wallabag_core.site_credential_repository: + class: Wallabag\CoreBundle\Repository\SiteCredentialRepository + factory: [ "@doctrine.orm.default_entity_manager", getRepository ] + arguments: + - WallabagCoreBundle:SiteCredential + wallabag_core.helper.entries_export: class: Wallabag\CoreBundle\Helper\EntriesExport arguments: -- cgit v1.2.3 From b8427f22f06cab58383ec3080f09715c712c65ef Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Mon, 1 May 2017 22:13:35 +0200 Subject: Add menu access to site credentials CRUD --- .../DataFixtures/ORM/LoadSiteCredentialData.php | 34 ++++++++++++++++++++++ .../GrabySiteConfigBuilder.php | 18 ++++++++---- .../CoreBundle/Resources/config/services.yml | 2 +- .../Resources/translations/messages.da.yml | 1 + .../Resources/translations/messages.de.yml | 1 + .../Resources/translations/messages.en.yml | 1 + .../Resources/translations/messages.es.yml | 1 + .../Resources/translations/messages.fa.yml | 1 + .../Resources/translations/messages.fr.yml | 1 + .../Resources/translations/messages.it.yml | 1 + .../Resources/translations/messages.oc.yml | 1 + .../Resources/translations/messages.pl.yml | 1 + .../Resources/translations/messages.pt.yml | 1 + .../Resources/translations/messages.ro.yml | 1 + .../Resources/translations/messages.tr.yml | 1 + .../themes/baggy/SiteCredential/edit.html.twig | 2 +- .../themes/baggy/SiteCredential/index.html.twig | 4 +-- .../themes/baggy/SiteCredential/new.html.twig | 2 +- .../Resources/views/themes/baggy/layout.html.twig | 3 ++ .../views/themes/material/layout.html.twig | 5 ++++ 20 files changed, 71 insertions(+), 11 deletions(-) create mode 100644 src/Wallabag/CoreBundle/DataFixtures/ORM/LoadSiteCredentialData.php (limited to 'src') diff --git a/src/Wallabag/CoreBundle/DataFixtures/ORM/LoadSiteCredentialData.php b/src/Wallabag/CoreBundle/DataFixtures/ORM/LoadSiteCredentialData.php new file mode 100644 index 00000000..866f55a4 --- /dev/null +++ b/src/Wallabag/CoreBundle/DataFixtures/ORM/LoadSiteCredentialData.php @@ -0,0 +1,34 @@ +getReference('admin-user')); + $credential->setHost('example.com'); + $credential->setUsername('foo'); + $credential->setPassword('bar'); + + $manager->persist($credential); + + $manager->flush(); + } + + /** + * {@inheritdoc} + */ + public function getOrder() + { + return 50; + } +} diff --git a/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php b/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php index 94615687..ae69492d 100644 --- a/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php +++ b/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php @@ -7,7 +7,7 @@ use BD\GuzzleSiteAuthenticator\SiteConfig\SiteConfigBuilder; use Graby\SiteConfig\ConfigBuilder; use Psr\Log\LoggerInterface; use Wallabag\CoreBundle\Repository\SiteCredentialRepository; -use Wallabag\UserBundle\Entity\User; +use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage; class GrabySiteConfigBuilder implements SiteConfigBuilder { @@ -27,7 +27,7 @@ class GrabySiteConfigBuilder implements SiteConfigBuilder private $logger; /** - * @var User + * @var Wallabag\UserBundle\Entity\User|null */ private $currentUser; @@ -36,16 +36,19 @@ class GrabySiteConfigBuilder implements SiteConfigBuilder * GrabySiteConfigBuilder constructor. * * @param ConfigBuilder $grabyConfigBuilder - * @param User $currentUser + * @param TokenStorage $token * @param SiteCredentialRepository $credentialRepository * @param LoggerInterface $logger */ - public function __construct(ConfigBuilder $grabyConfigBuilder, User $currentUser, SiteCredentialRepository $credentialRepository, LoggerInterface $logger) + public function __construct(ConfigBuilder $grabyConfigBuilder, TokenStorage $token, SiteCredentialRepository $credentialRepository, LoggerInterface $logger) { $this->grabyConfigBuilder = $grabyConfigBuilder; $this->credentialRepository = $credentialRepository; - $this->currentUser = $currentUser; $this->logger = $logger; + + if ($token->getToken()) { + $this->currentUser = $token->getToken()->getUser(); + } } /** @@ -59,7 +62,10 @@ class GrabySiteConfigBuilder implements SiteConfigBuilder $host = substr($host, 4); } - $credentials = $this->credentialRepository->findOneByHostAndUser($host, $this->currentUser->getId()); + $credentials = null; + if ($this->currentUser) { + $credentials = $this->credentialRepository->findOneByHostAndUser($host, $this->currentUser->getId()); + } if (null === $credentials) { $this->logger->debug('Auth: no credentials available for host.', ['host' => $host]); diff --git a/src/Wallabag/CoreBundle/Resources/config/services.yml b/src/Wallabag/CoreBundle/Resources/config/services.yml index a59152d3..09bc77fe 100644 --- a/src/Wallabag/CoreBundle/Resources/config/services.yml +++ b/src/Wallabag/CoreBundle/Resources/config/services.yml @@ -63,7 +63,7 @@ services: class: Wallabag\CoreBundle\GuzzleSiteAuthenticator\GrabySiteConfigBuilder arguments: - "@wallabag_core.graby.config_builder" - - "@=service('security.token_storage').getToken().getUser()" + - "@security.token_storage" - "@wallabag_core.site_credential_repository" - '@logger' tags: diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml index ef58a16b..3a3fb91d 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml @@ -32,6 +32,7 @@ menu: # save_link: 'Save a link' back_to_unread: 'Tilbage til de ulæste artikler' # users_management: 'Users management' + # site_credentials: 'Site credentials' top: add_new_entry: 'Tilføj ny artikel' search: 'Søg' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml index d026a030..85f0e1a3 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml @@ -32,6 +32,7 @@ menu: save_link: 'Link speichern' back_to_unread: 'Zurück zu ungelesenen Artikeln' users_management: 'Benutzerverwaltung' + # site_credentials: 'Site credentials' top: add_new_entry: 'Neuen Artikel hinzufügen' search: 'Suche' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml index 12feb7dd..284fa2fb 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml @@ -32,6 +32,7 @@ menu: save_link: 'Save a link' back_to_unread: 'Back to unread articles' users_management: 'Users management' + site_credentials: 'Site credentials' top: add_new_entry: 'Add a new entry' search: 'Search' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml index 2351d467..33bb879c 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml @@ -32,6 +32,7 @@ menu: save_link: 'Guardar un enlace' back_to_unread: 'Volver a los artículos sin leer' users_management: 'Configuración de usuarios' + # site_credentials: 'Site credentials' top: add_new_entry: 'Añadir un nuevo artículo' search: 'Buscar' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml index 32e1ff42..90eb119c 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml @@ -32,6 +32,7 @@ menu: save_link: 'ذخیرهٔ یک پیوند' back_to_unread: 'بازگشت به خوانده‌نشده‌ها' # users_management: 'Users management' + # site_credentials: 'Site credentials' top: add_new_entry: 'افزودن مقالهٔ تازه' search: 'جستجو' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml index 17eaf015..542ddf48 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml @@ -32,6 +32,7 @@ menu: save_link: "Sauvegarder un nouvel article" back_to_unread: "Retour aux articles non lus" users_management: "Gestion des utilisateurs" + site_credentials: 'Accès aux sites' top: add_new_entry: "Sauvegarder un nouvel article" search: "Rechercher" diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml index 752085c8..5cb2a68f 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml @@ -32,6 +32,7 @@ menu: save_link: 'Salva collegamento' back_to_unread: 'Torna ai contenuti non letti' # users_management: 'Users management' + # site_credentials: 'Site credentials' top: add_new_entry: 'Aggiungi un nuovo contenuto' search: 'Cerca' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml index 9e941de0..bc11b2a4 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml @@ -32,6 +32,7 @@ menu: save_link: 'Enregistrar un novèl article' back_to_unread: 'Tornar als articles pas legits' users_management: 'Gestion dels utilizaires' + # site_credentials: 'Site credentials' top: add_new_entry: 'Enregistrar un novèl article' search: 'Cercar' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml index 38e051f5..033d6ac5 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml @@ -32,6 +32,7 @@ menu: save_link: 'Zapisz link' back_to_unread: 'Powrót do nieprzeczytanych artykułów' users_management: 'Zarządzanie użytkownikami' + # site_credentials: 'Site credentials' top: add_new_entry: 'Dodaj nowy wpis' search: 'Szukaj' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml index d3b245b8..c70c2496 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml @@ -32,6 +32,7 @@ menu: save_link: 'Salvar um link' back_to_unread: 'Voltar para os artigos não lidos' users_management: 'Gestão de Usuários' + # site_credentials: 'Site credentials' top: add_new_entry: 'Adicionar uma nova entrada' search: 'Pesquisa' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml index 66c72429..a5dc44f0 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml @@ -32,6 +32,7 @@ menu: # save_link: 'Save a link' back_to_unread: 'Înapoi la articolele necitite' # users_management: 'Users management' + # site_credentials: 'Site credentials' top: add_new_entry: 'Introdu un nou articol' search: 'Căutare' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml index 34ae5b87..4d01e7f7 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml @@ -32,6 +32,7 @@ menu: # save_link: 'Save a link' back_to_unread: 'Okunmayan makalelere geri dön' # users_management: 'Users management' + # site_credentials: 'Site credentials' top: add_new_entry: 'Yeni bir makale ekle' search: 'Ara' diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/baggy/SiteCredential/edit.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/baggy/SiteCredential/edit.html.twig index 8448f17e..882be430 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/baggy/SiteCredential/edit.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/baggy/SiteCredential/edit.html.twig @@ -49,7 +49,7 @@ {{ form_end(delete_form) }}

    -

    {{ 'site_credential.form.back_to_list'|trans }}

    +

    {{ 'site_credential.form.back_to_list'|trans }}

    diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/baggy/SiteCredential/index.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/baggy/SiteCredential/index.html.twig index fda60b31..c128bceb 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/baggy/SiteCredential/index.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/baggy/SiteCredential/index.html.twig @@ -25,7 +25,7 @@ {{ credential.host }} {{ credential.username }} - {{ 'site_credential.list.edit_action'|trans }} + {{ 'site_credential.list.edit_action'|trans }} {% endfor %} @@ -33,7 +33,7 @@

    - {{ 'site_credential.list.create_new_one'|trans }} + {{ 'site_credential.list.create_new_one'|trans }}

    diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/baggy/SiteCredential/new.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/baggy/SiteCredential/new.html.twig index bf713902..3c008cde 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/baggy/SiteCredential/new.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/baggy/SiteCredential/new.html.twig @@ -42,7 +42,7 @@ {{ form_widget(form.save, {'attr': {'class': 'btn waves-effect waves-light'}}) }} {{ form_rest(form) }} -

    {{ 'site_credential.form.back_to_list'|trans }}

    +

    {{ 'site_credential.form.back_to_list'|trans }}

    diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/baggy/layout.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/baggy/layout.html.twig index 42aeace9..17fa13bb 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/baggy/layout.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/baggy/layout.html.twig @@ -38,6 +38,9 @@ {{ render(controller("WallabagCoreBundle:Entry:searchForm", {'currentRoute': app.request.attributes.get('_route')})) }} + {% if craue_setting('restricted_access') %} + + {% endif %} {% if is_granted('ROLE_SUPER_ADMIN') %} diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/material/layout.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/material/layout.html.twig index 2dab1c18..60907e11 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/material/layout.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/material/layout.html.twig @@ -66,6 +66,11 @@
  • {{ 'menu.left.config'|trans }}
  • + {% if craue_setting('restricted_access') %} +
  • + {{ 'menu.left.site_credentials'|trans }} +
  • + {% endif %} {% if is_granted('ROLE_SUPER_ADMIN') %}
  • {{ 'menu.left.users_management'|trans }} -- cgit v1.2.3 From 9de9f1e5ceed4ac7ecd27e1cb808e630a831f94b Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Wed, 3 May 2017 10:23:49 +0200 Subject: Add a live test for restricted article MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit It is not aimed to test if we can get the full article (since we aren't using real login/password) but mostly to test the full work (with authentication, etc.) Do not clean fixtured to avoid SQLite to re-use id for entry tag relation 😓 --- src/Wallabag/CoreBundle/Controller/SiteCredentialController.php | 4 +--- .../CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php | 5 ++--- 2 files changed, 3 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Controller/SiteCredentialController.php b/src/Wallabag/CoreBundle/Controller/SiteCredentialController.php index 429f529a..dc8e723d 100644 --- a/src/Wallabag/CoreBundle/Controller/SiteCredentialController.php +++ b/src/Wallabag/CoreBundle/Controller/SiteCredentialController.php @@ -24,9 +24,7 @@ class SiteCredentialController extends Controller */ public function indexAction() { - $em = $this->getDoctrine()->getManager(); - - $credentials = $em->getRepository('WallabagCoreBundle:SiteCredential')->findByUser($this->getUser()); + $credentials = $this->get('wallabag_core.site_credential_repository')->findByUser($this->getUser()); return $this->render('WallabagCoreBundle:SiteCredential:index.html.twig', array( 'credentials' => $credentials, diff --git a/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php b/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php index ae69492d..62a3bc13 100644 --- a/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php +++ b/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php @@ -31,14 +31,13 @@ class GrabySiteConfigBuilder implements SiteConfigBuilder */ private $currentUser; - /** * GrabySiteConfigBuilder constructor. * * @param ConfigBuilder $grabyConfigBuilder - * @param TokenStorage $token + * @param TokenStorage $token * @param SiteCredentialRepository $credentialRepository - * @param LoggerInterface $logger + * @param LoggerInterface $logger */ public function __construct(ConfigBuilder $grabyConfigBuilder, TokenStorage $token, SiteCredentialRepository $credentialRepository, LoggerInterface $logger) { -- cgit v1.2.3 From 906424c1b6fd884bf2081bfe6dd0b1f9651c2801 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Sun, 11 Jun 2017 23:05:19 +0200 Subject: Crypt site credential password --- src/Wallabag/CoreBundle/Command/InstallCommand.php | 2 + .../Controller/SiteCredentialController.php | 2 + .../DependencyInjection/Configuration.php | 2 + .../DependencyInjection/WallabagCoreExtension.php | 1 + src/Wallabag/CoreBundle/Entity/SiteCredential.php | 3 +- src/Wallabag/CoreBundle/Helper/CryptoProxy.php | 86 ++++++++++++++++++++++ .../Repository/SiteCredentialRepository.php | 20 ++++- .../CoreBundle/Resources/config/services.yml | 8 ++ 8 files changed, 121 insertions(+), 3 deletions(-) create mode 100644 src/Wallabag/CoreBundle/Helper/CryptoProxy.php (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Command/InstallCommand.php b/src/Wallabag/CoreBundle/Command/InstallCommand.php index 0f119377..eb725a59 100644 --- a/src/Wallabag/CoreBundle/Command/InstallCommand.php +++ b/src/Wallabag/CoreBundle/Command/InstallCommand.php @@ -313,6 +313,8 @@ class InstallCommand extends ContainerAwareCommand $this ->runCommand('doctrine:migrations:migrate', ['--no-interaction' => true]); + + return $this; } /** diff --git a/src/Wallabag/CoreBundle/Controller/SiteCredentialController.php b/src/Wallabag/CoreBundle/Controller/SiteCredentialController.php index dc8e723d..0bacafb7 100644 --- a/src/Wallabag/CoreBundle/Controller/SiteCredentialController.php +++ b/src/Wallabag/CoreBundle/Controller/SiteCredentialController.php @@ -45,6 +45,8 @@ class SiteCredentialController extends Controller $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { + $credential->setPassword($this->get('wallabag_core.helper.crypto_proxy')->crypt($credential->getPassword())); + $em = $this->getDoctrine()->getManager(); $em->persist($credential); $em->flush($credential); diff --git a/src/Wallabag/CoreBundle/DependencyInjection/Configuration.php b/src/Wallabag/CoreBundle/DependencyInjection/Configuration.php index 33df92d3..a9791f6b 100644 --- a/src/Wallabag/CoreBundle/DependencyInjection/Configuration.php +++ b/src/Wallabag/CoreBundle/DependencyInjection/Configuration.php @@ -63,6 +63,8 @@ class Configuration implements ConfigurationInterface ->end() ->end() ->end() + ->scalarNode('encryption_key_path') + ->end() ->end() ; diff --git a/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php b/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php index b4d8a386..532ce238 100644 --- a/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php +++ b/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php @@ -29,6 +29,7 @@ class WallabagCoreExtension extends Extension $container->setParameter('wallabag_core.fetching_error_message_title', $config['fetching_error_message_title']); $container->setParameter('wallabag_core.api_limit_mass_actions', $config['api_limit_mass_actions']); $container->setParameter('wallabag_core.default_internal_settings', $config['default_internal_settings']); + $container->setParameter('wallabag_core.site_credentials.encryption_key_path', $config['encryption_key_path']); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.yml'); diff --git a/src/Wallabag/CoreBundle/Entity/SiteCredential.php b/src/Wallabag/CoreBundle/Entity/SiteCredential.php index 85ee07d4..732d9506 100644 --- a/src/Wallabag/CoreBundle/Entity/SiteCredential.php +++ b/src/Wallabag/CoreBundle/Entity/SiteCredential.php @@ -46,8 +46,7 @@ class SiteCredential * @var string * * @Assert\NotBlank() - * @Assert\Length(max=255) - * @ORM\Column(name="password", type="string", length=255) + * @ORM\Column(name="password", type="text") */ private $password; diff --git a/src/Wallabag/CoreBundle/Helper/CryptoProxy.php b/src/Wallabag/CoreBundle/Helper/CryptoProxy.php new file mode 100644 index 00000000..d0a9b85c --- /dev/null +++ b/src/Wallabag/CoreBundle/Helper/CryptoProxy.php @@ -0,0 +1,86 @@ +logger = $logger; + + if (!file_exists($encryptionKeyPath)) { + $key = Key::createNewRandomKey(); + + file_put_contents($encryptionKeyPath, $key->saveToAsciiSafeString()); + chmod($encryptionKeyPath, 0600); + } + + $this->encryptionKey = file_get_contents($encryptionKeyPath); + } + + /** + * Ensure the given value will be crypted. + * + * @param string $secretValue Secret valye to crypt + * + * @return string + */ + public function crypt($secretValue) + { + $this->logger->debug('Crypto: crypting value: '.$this->mask($secretValue)); + + return Crypto::encrypt($secretValue, $this->loadKey()); + } + + /** + * Ensure the given crypted value will be decrypted. + * + * @param string $cryptedValue The value to be decrypted + * + * @return string + */ + public function decrypt($cryptedValue) + { + $this->logger->debug('Crypto: decrypting value: '.$this->mask($cryptedValue)); + + try { + return Crypto::decrypt($cryptedValue, $this->loadKey()); + } catch (WrongKeyOrModifiedCiphertextException $e) { + throw new \RuntimeException('Decrypt fail: '.$e->getMessage()); + } + } + + /** + * Load the private key. + * + * @return string + */ + private function loadKey() + { + return Key::loadFromAsciiSafeString($this->encryptionKey); + } + + /** + * Keep first and last character and put some stars in between. + * + * @param string $value Value to mask + * + * @return string + */ + private function mask($value) + { + return $value[0].'*****'.$value[strlen($value) - 1]; + } +} diff --git a/src/Wallabag/CoreBundle/Repository/SiteCredentialRepository.php b/src/Wallabag/CoreBundle/Repository/SiteCredentialRepository.php index 316ecc75..6f904f0a 100644 --- a/src/Wallabag/CoreBundle/Repository/SiteCredentialRepository.php +++ b/src/Wallabag/CoreBundle/Repository/SiteCredentialRepository.php @@ -2,11 +2,20 @@ namespace Wallabag\CoreBundle\Repository; +use Wallabag\CoreBundle\Helper\CryptoProxy; + /** * SiteCredentialRepository. */ class SiteCredentialRepository extends \Doctrine\ORM\EntityRepository { + private $cryptoProxy; + + public function setCrypto(CryptoProxy $cryptoProxy) + { + $this->cryptoProxy = $cryptoProxy; + } + /** * Retrieve one username/password for the given host and userId. * @@ -17,12 +26,21 @@ class SiteCredentialRepository extends \Doctrine\ORM\EntityRepository */ public function findOneByHostAndUser($host, $userId) { - return $this->createQueryBuilder('s') + $res = $this->createQueryBuilder('s') ->select('s.username', 's.password') ->where('s.host = :hostname')->setParameter('hostname', $host) ->andWhere('s.user = :userId')->setParameter('userId', $userId) ->setMaxResults(1) ->getQuery() ->getOneOrNullResult(); + + if (null === $res) { + return; + } + + // decrypt password before returning it + $res['password'] = $this->cryptoProxy->decrypt($res['password']); + + return $res; } } diff --git a/src/Wallabag/CoreBundle/Resources/config/services.yml b/src/Wallabag/CoreBundle/Resources/config/services.yml index 09bc77fe..e09b0f18 100644 --- a/src/Wallabag/CoreBundle/Resources/config/services.yml +++ b/src/Wallabag/CoreBundle/Resources/config/services.yml @@ -126,6 +126,8 @@ services: factory: [ "@doctrine.orm.default_entity_manager", getRepository ] arguments: - WallabagCoreBundle:SiteCredential + calls: + - [ setCrypto, [ "@wallabag_core.helper.crypto_proxy" ] ] wallabag_core.helper.entries_export: class: Wallabag\CoreBundle\Helper\EntriesExport @@ -208,3 +210,9 @@ services: wallabag_core.entry.download_images.client: class: GuzzleHttp\Client + + wallabag_core.helper.crypto_proxy: + class: Wallabag\CoreBundle\Helper\CryptoProxy + arguments: + - "%wallabag_core.site_credentials.encryption_key_path%" + - "@logger" -- cgit v1.2.3 From bead8b42da4f17238dc0d5e0f90184b224ec5df7 Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Wed, 14 Jun 2017 15:02:34 +0200 Subject: Fix reviews Encrypt username too Redirect to list after saving credentials Fix typos Signed-off-by: Thomas Citharel --- .../Controller/SiteCredentialController.php | 38 ++++++++++++++++------ src/Wallabag/CoreBundle/Entity/SiteCredential.php | 3 +- .../CoreBundle/Form/Type/SiteCredentialType.php | 1 + .../GrabySiteConfigBuilder.php | 3 +- src/Wallabag/CoreBundle/Helper/CryptoProxy.php | 4 +-- .../Repository/SiteCredentialRepository.php | 3 +- .../Resources/translations/messages.fr.yml | 4 +-- .../themes/material/SiteCredential/index.html.twig | 4 ++- 8 files changed, 41 insertions(+), 19 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Controller/SiteCredentialController.php b/src/Wallabag/CoreBundle/Controller/SiteCredentialController.php index 0bacafb7..98781dab 100644 --- a/src/Wallabag/CoreBundle/Controller/SiteCredentialController.php +++ b/src/Wallabag/CoreBundle/Controller/SiteCredentialController.php @@ -26,9 +26,9 @@ class SiteCredentialController extends Controller { $credentials = $this->get('wallabag_core.site_credential_repository')->findByUser($this->getUser()); - return $this->render('WallabagCoreBundle:SiteCredential:index.html.twig', array( + return $this->render('WallabagCoreBundle:SiteCredential:index.html.twig', [ 'credentials' => $credentials, - )); + ]); } /** @@ -36,6 +36,10 @@ class SiteCredentialController extends Controller * * @Route("/new", name="site_credentials_new") * @Method({"GET", "POST"}) + * + * @param Request $request + * + * @return \Symfony\Component\HttpFoundation\Response */ public function newAction(Request $request) { @@ -45,24 +49,25 @@ class SiteCredentialController extends Controller $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { + $credential->setUsername($this->get('wallabag_core.helper.crypto_proxy')->crypt($credential->getUsername())); $credential->setPassword($this->get('wallabag_core.helper.crypto_proxy')->crypt($credential->getPassword())); $em = $this->getDoctrine()->getManager(); $em->persist($credential); - $em->flush($credential); + $em->flush(); $this->get('session')->getFlashBag()->add( 'notice', $this->get('translator')->trans('flashes.site_credential.notice.added', ['%host%' => $credential->getHost()]) ); - return $this->redirectToRoute('site_credentials_edit', array('id' => $credential->getId())); + return $this->redirectToRoute('site_credentials_index'); } - return $this->render('WallabagCoreBundle:SiteCredential:new.html.twig', array( + return $this->render('WallabagCoreBundle:SiteCredential:new.html.twig', [ 'credential' => $credential, 'form' => $form->createView(), - )); + ]); } /** @@ -70,6 +75,11 @@ class SiteCredentialController extends Controller * * @Route("/{id}/edit", name="site_credentials_edit") * @Method({"GET", "POST"}) + * + * @param Request $request + * @param SiteCredential $siteCredential + * + * @return \Symfony\Component\HttpFoundation\Response */ public function editAction(Request $request, SiteCredential $siteCredential) { @@ -80,6 +90,9 @@ class SiteCredentialController extends Controller $editForm->handleRequest($request); if ($editForm->isSubmitted() && $editForm->isValid()) { + $siteCredential->setUsername($this->get('wallabag_core.helper.crypto_proxy')->crypt($siteCredential->getUsername())); + $siteCredential->setPassword($this->get('wallabag_core.helper.crypto_proxy')->crypt($siteCredential->getPassword())); + $em = $this->getDoctrine()->getManager(); $em->persist($siteCredential); $em->flush(); @@ -89,14 +102,14 @@ class SiteCredentialController extends Controller $this->get('translator')->trans('flashes.site_credential.notice.updated', ['%host%' => $siteCredential->getHost()]) ); - return $this->redirectToRoute('site_credentials_edit', array('id' => $siteCredential->getId())); + return $this->redirectToRoute('site_credentials_index'); } - return $this->render('WallabagCoreBundle:SiteCredential:edit.html.twig', array( + return $this->render('WallabagCoreBundle:SiteCredential:edit.html.twig', [ 'credential' => $siteCredential, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView(), - )); + ]); } /** @@ -104,6 +117,11 @@ class SiteCredentialController extends Controller * * @Route("/{id}", name="site_credentials_delete") * @Method("DELETE") + * + * @param Request $request + * @param SiteCredential $siteCredential + * + * @return \Symfony\Component\HttpFoundation\RedirectResponse */ public function deleteAction(Request $request, SiteCredential $siteCredential) { @@ -136,7 +154,7 @@ class SiteCredentialController extends Controller private function createDeleteForm(SiteCredential $siteCredential) { return $this->createFormBuilder() - ->setAction($this->generateUrl('site_credentials_delete', array('id' => $siteCredential->getId()))) + ->setAction($this->generateUrl('site_credentials_delete', ['id' => $siteCredential->getId()])) ->setMethod('DELETE') ->getForm() ; diff --git a/src/Wallabag/CoreBundle/Entity/SiteCredential.php b/src/Wallabag/CoreBundle/Entity/SiteCredential.php index 732d9506..58075e92 100644 --- a/src/Wallabag/CoreBundle/Entity/SiteCredential.php +++ b/src/Wallabag/CoreBundle/Entity/SiteCredential.php @@ -37,8 +37,7 @@ class SiteCredential * @var string * * @Assert\NotBlank() - * @Assert\Length(max=255) - * @ORM\Column(name="username", type="string", length=255) + * @ORM\Column(name="username", type="text") */ private $username; diff --git a/src/Wallabag/CoreBundle/Form/Type/SiteCredentialType.php b/src/Wallabag/CoreBundle/Form/Type/SiteCredentialType.php index 9db7c155..fd409ad2 100644 --- a/src/Wallabag/CoreBundle/Form/Type/SiteCredentialType.php +++ b/src/Wallabag/CoreBundle/Form/Type/SiteCredentialType.php @@ -19,6 +19,7 @@ class SiteCredentialType extends AbstractType ]) ->add('username', TextType::class, [ 'label' => 'site_credential.form.username_label', + 'data' => '', ]) ->add('password', PasswordType::class, [ 'label' => 'site_credential.form.password_label', diff --git a/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php b/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php index 62a3bc13..a79e6ebe 100644 --- a/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php +++ b/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php @@ -87,7 +87,8 @@ class GrabySiteConfigBuilder implements SiteConfigBuilder $config = new SiteConfig($parameters); - // do not leak password in log + // do not leak usernames and passwords in log + $parameters['username'] = '**masked**'; $parameters['password'] = '**masked**'; $this->logger->debug('Auth: add parameters.', ['host' => $host, 'parameters' => $parameters]); diff --git a/src/Wallabag/CoreBundle/Helper/CryptoProxy.php b/src/Wallabag/CoreBundle/Helper/CryptoProxy.php index d0a9b85c..e8b19cb9 100644 --- a/src/Wallabag/CoreBundle/Helper/CryptoProxy.php +++ b/src/Wallabag/CoreBundle/Helper/CryptoProxy.php @@ -65,7 +65,7 @@ class CryptoProxy /** * Load the private key. * - * @return string + * @return Key */ private function loadKey() { @@ -81,6 +81,6 @@ class CryptoProxy */ private function mask($value) { - return $value[0].'*****'.$value[strlen($value) - 1]; + return strlen($value) > 0 ? $value[0].'*****'.$value[strlen($value) - 1] : 'Empty value'; } } diff --git a/src/Wallabag/CoreBundle/Repository/SiteCredentialRepository.php b/src/Wallabag/CoreBundle/Repository/SiteCredentialRepository.php index 6f904f0a..36906761 100644 --- a/src/Wallabag/CoreBundle/Repository/SiteCredentialRepository.php +++ b/src/Wallabag/CoreBundle/Repository/SiteCredentialRepository.php @@ -38,7 +38,8 @@ class SiteCredentialRepository extends \Doctrine\ORM\EntityRepository return; } - // decrypt password before returning it + // decrypt user & password before returning them + $res['username'] = $this->cryptoProxy->decrypt($res['username']); $res['password'] = $this->cryptoProxy->decrypt($res['password']); return $res; diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml index 542ddf48..cd239b5c 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml @@ -515,7 +515,7 @@ user: twofactor_label: "Double authentification" save: "Sauvegarder" delete: "Supprimer" - delete_confirm: "Êtes-vous sur ?" + delete_confirm: "Êtes-vous sûr ?" back_to_list: "Revenir à la liste" search: placeholder: "Filtrer par nom d’utilisateur ou email" @@ -537,7 +537,7 @@ site_credential: password_label: 'Mot de passe' save: "Sauvegarder" delete: "Supprimer" - delete_confirm: "Êtes-vous sur ?" + delete_confirm: "Êtes-vous sûr ?" back_to_list: "Revenir à la liste" error: diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/material/SiteCredential/index.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/material/SiteCredential/index.html.twig index c128bceb..4d30a692 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/material/SiteCredential/index.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/material/SiteCredential/index.html.twig @@ -16,6 +16,7 @@ {{ 'site_credential.form.host_label'|trans }} {{ 'site_credential.form.username_label'|trans }} + {{ 'site_credential.form.password_label'|trans }} {{ 'site_credential.list.actions'|trans }} @@ -23,7 +24,8 @@ {% for credential in credentials %} {{ credential.host }} - {{ credential.username }} + ***** + ***** {{ 'site_credential.list.edit_action'|trans }} -- cgit v1.2.3 From f44dba22fc1a566cb156d9e6eda5afc353163eda Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Sun, 18 Jun 2017 15:34:59 +0200 Subject: Get rid of masked value in listing --- .../Resources/views/themes/baggy/SiteCredential/index.html.twig | 2 -- .../Resources/views/themes/material/SiteCredential/index.html.twig | 4 ---- 2 files changed, 6 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/baggy/SiteCredential/index.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/baggy/SiteCredential/index.html.twig index c128bceb..324854ad 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/baggy/SiteCredential/index.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/baggy/SiteCredential/index.html.twig @@ -15,7 +15,6 @@ {{ 'site_credential.form.host_label'|trans }} - {{ 'site_credential.form.username_label'|trans }} {{ 'site_credential.list.actions'|trans }} @@ -23,7 +22,6 @@ {% for credential in credentials %} {{ credential.host }} - {{ credential.username }} {{ 'site_credential.list.edit_action'|trans }} diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/material/SiteCredential/index.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/material/SiteCredential/index.html.twig index 4d30a692..324854ad 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/material/SiteCredential/index.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/material/SiteCredential/index.html.twig @@ -15,8 +15,6 @@ {{ 'site_credential.form.host_label'|trans }} - {{ 'site_credential.form.username_label'|trans }} - {{ 'site_credential.form.password_label'|trans }} {{ 'site_credential.list.actions'|trans }} @@ -24,8 +22,6 @@ {% for credential in credentials %} {{ credential.host }} - ***** - ***** {{ 'site_credential.list.edit_action'|trans }} -- cgit v1.2.3 From 25203e5081c8da21869db1d16610f83f888249b5 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Sat, 10 Jun 2017 12:33:58 +0200 Subject: User existing service instead of getDoctrine --- .../CoreBundle/Command/CleanDuplicatesCommand.php | 6 +++--- src/Wallabag/CoreBundle/Command/ExportCommand.php | 5 ++--- src/Wallabag/CoreBundle/Command/ShowUserCommand.php | 2 +- src/Wallabag/CoreBundle/Command/TagAllCommand.php | 2 +- .../CoreBundle/Controller/ConfigController.php | 21 +++++++-------------- .../CoreBundle/Controller/ExportController.php | 13 +++++++------ .../CoreBundle/Controller/RssController.php | 2 +- .../CoreBundle/Controller/TagController.php | 18 ++++++++++-------- 8 files changed, 32 insertions(+), 37 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Command/CleanDuplicatesCommand.php b/src/Wallabag/CoreBundle/Command/CleanDuplicatesCommand.php index 65f35d8e..89ae7998 100644 --- a/src/Wallabag/CoreBundle/Command/CleanDuplicatesCommand.php +++ b/src/Wallabag/CoreBundle/Command/CleanDuplicatesCommand.php @@ -46,7 +46,7 @@ class CleanDuplicatesCommand extends ContainerAwareCommand return 1; } } else { - $users = $this->getDoctrine()->getRepository('WallabagUserBundle:User')->findAll(); + $users = $this->get('wallabag_user.user_repository')->findAll(); $output->writeln(sprintf('Cleaning through %d user accounts', count($users))); @@ -66,7 +66,7 @@ class CleanDuplicatesCommand extends ContainerAwareCommand private function cleanDuplicates(User $user) { $em = $this->getContainer()->get('doctrine.orm.entity_manager'); - $repo = $this->getDoctrine()->getRepository('WallabagCoreBundle:Entry'); + $repo = $this->get('wallabag_core.entry_repository'); $entries = $repo->getAllEntriesIdAndUrl($user->getId()); @@ -109,7 +109,7 @@ class CleanDuplicatesCommand extends ContainerAwareCommand */ private function getUser($username) { - return $this->getDoctrine()->getRepository('WallabagUserBundle:User')->findOneByUserName($username); + return $this->get('wallabag_user.user_repository')->findOneByUserName($username); } private function getDoctrine() diff --git a/src/Wallabag/CoreBundle/Command/ExportCommand.php b/src/Wallabag/CoreBundle/Command/ExportCommand.php index e3d3b399..e4977e11 100644 --- a/src/Wallabag/CoreBundle/Command/ExportCommand.php +++ b/src/Wallabag/CoreBundle/Command/ExportCommand.php @@ -32,15 +32,14 @@ class ExportCommand extends ContainerAwareCommand protected function execute(InputInterface $input, OutputInterface $output) { try { - $user = $this->getDoctrine()->getRepository('WallabagUserBundle:User')->findOneByUserName($input->getArgument('username')); + $user = $this->get('wallabag_user.user_repository')->findOneByUserName($input->getArgument('username')); } catch (NoResultException $e) { $output->writeln(sprintf('User "%s" not found.', $input->getArgument('username'))); return 1; } - $entries = $this->getDoctrine() - ->getRepository('WallabagCoreBundle:Entry') + $entries = $this->get('wallabag_core.entry_repository') ->getBuilderForAllByUser($user->getId()) ->getQuery() ->getResult(); diff --git a/src/Wallabag/CoreBundle/Command/ShowUserCommand.php b/src/Wallabag/CoreBundle/Command/ShowUserCommand.php index 0eeaabc4..90a7e03f 100644 --- a/src/Wallabag/CoreBundle/Command/ShowUserCommand.php +++ b/src/Wallabag/CoreBundle/Command/ShowUserCommand.php @@ -67,7 +67,7 @@ class ShowUserCommand extends ContainerAwareCommand */ private function getUser($username) { - return $this->getDoctrine()->getRepository('WallabagUserBundle:User')->findOneByUserName($username); + return $this->get('wallabag_user.user_repository')->findOneByUserName($username); } private function getDoctrine() diff --git a/src/Wallabag/CoreBundle/Command/TagAllCommand.php b/src/Wallabag/CoreBundle/Command/TagAllCommand.php index 3f9bb04d..5a6dc04e 100644 --- a/src/Wallabag/CoreBundle/Command/TagAllCommand.php +++ b/src/Wallabag/CoreBundle/Command/TagAllCommand.php @@ -59,7 +59,7 @@ class TagAllCommand extends ContainerAwareCommand */ private function getUser($username) { - return $this->getDoctrine()->getRepository('WallabagUserBundle:User')->findOneByUserName($username); + return $this->get('wallabag_user.user_repository')->findOneByUserName($username); } private function getDoctrine() diff --git a/src/Wallabag/CoreBundle/Controller/ConfigController.php b/src/Wallabag/CoreBundle/Controller/ConfigController.php index 89d27425..d4170d39 100644 --- a/src/Wallabag/CoreBundle/Controller/ConfigController.php +++ b/src/Wallabag/CoreBundle/Controller/ConfigController.php @@ -152,8 +152,7 @@ class ConfigController extends Controller ], 'twofactor_auth' => $this->getParameter('twofactor_auth'), 'wallabag_url' => $this->getParameter('domain_name'), - 'enabled_users' => $this->getDoctrine() - ->getRepository('WallabagUserBundle:User') + 'enabled_users' => $this->get('wallabag_user.user_repository') ->getSumEnabledUsers(), ]); } @@ -257,9 +256,7 @@ class ConfigController extends Controller // manually remove tags to avoid orphan tag $this->removeAllTagsByUserId($this->getUser()->getId()); - $this->getDoctrine() - ->getRepository('WallabagCoreBundle:Entry') - ->removeAllByUserId($this->getUser()->getId()); + $this->get('wallabag_core.entry_repository')->removeAllByUserId($this->getUser()->getId()); break; case 'archived': if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) { @@ -269,9 +266,7 @@ class ConfigController extends Controller // manually remove tags to avoid orphan tag $this->removeTagsForArchivedByUserId($this->getUser()->getId()); - $this->getDoctrine() - ->getRepository('WallabagCoreBundle:Entry') - ->removeArchivedByUserId($this->getUser()->getId()); + $this->get('wallabag_core.entry_repository')->removeArchivedByUserId($this->getUser()->getId()); break; } @@ -295,8 +290,7 @@ class ConfigController extends Controller return; } - $this->getDoctrine() - ->getRepository('WallabagCoreBundle:Entry') + $this->get('wallabag_core.entry_repository') ->removeTags($userId, $tags); // cleanup orphan tags @@ -318,7 +312,7 @@ class ConfigController extends Controller */ private function removeAllTagsByUserId($userId) { - $tags = $this->getDoctrine()->getRepository('WallabagCoreBundle:Tag')->findAllTags($userId); + $tags = $this->get('wallabag_core.tag_repository')->findAllTags($userId); $this->removeAllTagsByStatusAndUserId($tags, $userId); } @@ -329,7 +323,7 @@ class ConfigController extends Controller */ private function removeTagsForArchivedByUserId($userId) { - $tags = $this->getDoctrine()->getRepository('WallabagCoreBundle:Tag')->findForArchivedArticlesByUser($userId); + $tags = $this->get('wallabag_core.tag_repository')->findForArchivedArticlesByUser($userId); $this->removeAllTagsByStatusAndUserId($tags, $userId); } @@ -393,8 +387,7 @@ class ConfigController extends Controller */ public function deleteAccountAction(Request $request) { - $enabledUsers = $this->getDoctrine() - ->getRepository('WallabagUserBundle:User') + $enabledUsers = $this->get('wallabag_user.user_repository') ->getSumEnabledUsers(); if ($enabledUsers <= 1) { diff --git a/src/Wallabag/CoreBundle/Controller/ExportController.php b/src/Wallabag/CoreBundle/Controller/ExportController.php index abc3336a..b9e5a974 100644 --- a/src/Wallabag/CoreBundle/Controller/ExportController.php +++ b/src/Wallabag/CoreBundle/Controller/ExportController.php @@ -57,16 +57,17 @@ class ExportController extends Controller { $method = ucfirst($category); $methodBuilder = 'getBuilderFor'.$method.'ByUser'; + $epository = $this->get('wallabag_core.entry_repository'); if ($category == 'tag_entries') { - $tag = $this->getDoctrine()->getRepository('WallabagCoreBundle:Tag')->findOneBySlug($request->query->get('tag')); + $tag = $this->get('wallabag_core.tag_repository')->findOneBySlug($request->query->get('tag')); - $entries = $this->getDoctrine() - ->getRepository('WallabagCoreBundle:Entry') - ->findAllByTagId($this->getUser()->getId(), $tag->getId()); + $entries = $epository->findAllByTagId( + $this->getUser()->getId(), + $tag->getId() + ); } else { - $entries = $this->getDoctrine() - ->getRepository('WallabagCoreBundle:Entry') + $entries = $epository ->$methodBuilder($this->getUser()->getId()) ->getQuery() ->getResult(); diff --git a/src/Wallabag/CoreBundle/Controller/RssController.php b/src/Wallabag/CoreBundle/Controller/RssController.php index 92f18707..5f7502fc 100644 --- a/src/Wallabag/CoreBundle/Controller/RssController.php +++ b/src/Wallabag/CoreBundle/Controller/RssController.php @@ -66,7 +66,7 @@ class RssController extends Controller */ private function showEntries($type, User $user, $page = 1) { - $repository = $this->getDoctrine()->getRepository('WallabagCoreBundle:Entry'); + $repository = $this->get('wallabag_core.entry_repository'); switch ($type) { case 'starred': diff --git a/src/Wallabag/CoreBundle/Controller/TagController.php b/src/Wallabag/CoreBundle/Controller/TagController.php index 9422bae4..72822479 100644 --- a/src/Wallabag/CoreBundle/Controller/TagController.php +++ b/src/Wallabag/CoreBundle/Controller/TagController.php @@ -84,16 +84,17 @@ class TagController extends Controller */ public function showTagAction() { - $tags = $this->getDoctrine() - ->getRepository('WallabagCoreBundle:Tag') + $repository = $this->get('wallabag_core.entry_repository'); + $tags = $this->get('wallabag_core.tag_repository') ->findAllTags($this->getUser()->getId()); $flatTags = []; foreach ($tags as $tag) { - $nbEntries = $this->getDoctrine() - ->getRepository('WallabagCoreBundle:Entry') - ->countAllEntriesByUserIdAndTagId($this->getUser()->getId(), $tag->getId()); + $nbEntries = $repository->countAllEntriesByUserIdAndTagId( + $this->getUser()->getId(), + $tag->getId() + ); $flatTags[] = [ 'id' => $tag->getId(), @@ -119,9 +120,10 @@ class TagController extends Controller */ public function showEntriesForTagAction(Tag $tag, $page, Request $request) { - $entriesByTag = $this->getDoctrine() - ->getRepository('WallabagCoreBundle:Entry') - ->findAllByTagId($this->getUser()->getId(), $tag->getId()); + $entriesByTag = $this->get('wallabag_core.entry_repository')->findAllByTagId( + $this->getUser()->getId(), + $tag->getId() + ); $pagerAdapter = new ArrayAdapter($entriesByTag); -- cgit v1.2.3 From 18c38dffc67d04e59a9cc26b6910d9b9a4a49cd6 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Sat, 10 Jun 2017 13:11:08 +0200 Subject: Add RSS tags feeds --- .../CoreBundle/Controller/RssController.php | 81 ++++++++++++++++++++-- .../CoreBundle/Helper/PreparePagerForEntries.php | 8 ++- .../views/themes/common/Entry/entries.xml.twig | 6 +- 3 files changed, 83 insertions(+), 12 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Controller/RssController.php b/src/Wallabag/CoreBundle/Controller/RssController.php index 5f7502fc..090eccab 100644 --- a/src/Wallabag/CoreBundle/Controller/RssController.php +++ b/src/Wallabag/CoreBundle/Controller/RssController.php @@ -3,13 +3,16 @@ namespace Wallabag\CoreBundle\Controller; use Pagerfanta\Adapter\DoctrineORMAdapter; +use Pagerfanta\Adapter\ArrayAdapter; use Pagerfanta\Exception\OutOfRangeCurrentPageException; use Pagerfanta\Pagerfanta; use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Wallabag\CoreBundle\Entity\Entry; +use Wallabag\CoreBundle\Entity\Tag; use Wallabag\UserBundle\Entity\User; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; @@ -31,7 +34,7 @@ class RssController extends Controller /** * Shows read entries for current user. * - * @Route("/{username}/{token}/archive.xml", name="archive_rss") + * @Route("/{username}/{token}/archive.xml", name="archive_rss", defaults={"_format"="xml"}) * @ParamConverter("user", class="WallabagUserBundle:User", converter="username_rsstoken_converter") * * @return \Symfony\Component\HttpFoundation\Response @@ -44,7 +47,7 @@ class RssController extends Controller /** * Shows starred entries for current user. * - * @Route("/{username}/{token}/starred.xml", name="starred_rss") + * @Route("/{username}/{token}/starred.xml", name="starred_rss", defaults={"_format"="xml"}) * @ParamConverter("user", class="WallabagUserBundle:User", converter="username_rsstoken_converter") * * @return \Symfony\Component\HttpFoundation\Response @@ -54,6 +57,65 @@ class RssController extends Controller return $this->showEntries('starred', $user, $request->query->get('page', 1)); } + /** + * Shows entries associated to a tag for current user. + * + * @Route("/{username}/{token}/tags/{slug}.xml", name="tag_rss", defaults={"_format"="xml"}) + * @ParamConverter("user", class="WallabagUserBundle:User", converter="username_rsstoken_converter") + * @ParamConverter("tag", options={"mapping": {"slug": "slug"}}) + * + * @return \Symfony\Component\HttpFoundation\Response + */ + public function showTagsAction(Request $request, User $user, Tag $tag) + { + $page = $request->query->get('page', 1); + + $url = $this->generateUrl( + 'tag_rss', + [ + 'username' => $user->getUsername(), + 'token' => $user->getConfig()->getRssToken(), + 'slug' => $tag->getSlug(), + ], + UrlGeneratorInterface::ABSOLUTE_URL + ); + + $entriesByTag = $this->get('wallabag_core.entry_repository')->findAllByTagId( + $user->getId(), + $tag->getId() + ); + + $pagerAdapter = new ArrayAdapter($entriesByTag); + + $entries = $this->get('wallabag_core.helper.prepare_pager_for_entries')->prepare( + $pagerAdapter, + $user + ); + + if (null === $entries) { + throw $this->createNotFoundException('No entries found?'); + } + + try { + $entries->setCurrentPage($page); + } catch (OutOfRangeCurrentPageException $e) { + if ($page > 1) { + return $this->redirect($url.'?page='.$entries->getNbPages(), 302); + } + } + + return $this->render( + '@WallabagCore/themes/common/Entry/entries.xml.twig', + [ + 'url_html' => $this->generateUrl('tag_entries', ['slug' => $tag->getSlug()], UrlGeneratorInterface::ABSOLUTE_URL), + 'type' => 'tag ('.$tag->getLabel().')', + 'url' => $url, + 'entries' => $entries, + ], + new Response('', 200, ['Content-Type' => 'application/rss+xml']) + ); + } + /** * Global method to retrieve entries depending on the given type * It returns the response to be send. @@ -108,10 +170,15 @@ class RssController extends Controller } } - return $this->render('@WallabagCore/themes/common/Entry/entries.xml.twig', [ - 'type' => $type, - 'url' => $url, - 'entries' => $entries, - ]); + return $this->render( + '@WallabagCore/themes/common/Entry/entries.xml.twig', + [ + 'url_html' => $this->generateUrl($type, [], UrlGeneratorInterface::ABSOLUTE_URL), + 'type' => $type, + 'url' => $url, + 'entries' => $entries, + ], + new Response('', 200, ['Content-Type' => 'application/rss+xml']) + ); } } diff --git a/src/Wallabag/CoreBundle/Helper/PreparePagerForEntries.php b/src/Wallabag/CoreBundle/Helper/PreparePagerForEntries.php index df579ebd..231a0b52 100644 --- a/src/Wallabag/CoreBundle/Helper/PreparePagerForEntries.php +++ b/src/Wallabag/CoreBundle/Helper/PreparePagerForEntries.php @@ -4,6 +4,7 @@ namespace Wallabag\CoreBundle\Helper; use Pagerfanta\Adapter\AdapterInterface; use Pagerfanta\Pagerfanta; +use Wallabag\UserBundle\Entity\User; use Symfony\Component\Routing\Router; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; @@ -20,12 +21,15 @@ class PreparePagerForEntries /** * @param AdapterInterface $adapter + * @param User $user If user isn't logged in, we can force it (like for rss) * * @return null|Pagerfanta */ - public function prepare(AdapterInterface $adapter) + public function prepare(AdapterInterface $adapter, User $user = null) { - $user = $this->tokenStorage->getToken() ? $this->tokenStorage->getToken()->getUser() : null; + if (null === $user) { + $user = $this->tokenStorage->getToken() ? $this->tokenStorage->getToken()->getUser() : null; + } if (null === $user || !is_object($user)) { return; diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/common/Entry/entries.xml.twig b/src/Wallabag/CoreBundle/Resources/views/themes/common/Entry/entries.xml.twig index 12e8c79f..d70aa5dc 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/common/Entry/entries.xml.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/common/Entry/entries.xml.twig @@ -1,8 +1,8 @@ - wallabag — {{type}} feed - {{ url(type) }} + wallabag - {{ type }} feed + {{ url_html }} {% if entries.hasPreviousPage -%} @@ -13,7 +13,7 @@ {{ "now"|date('D, d M Y H:i:s') }} wallabag - wallabag {{type}} elements + wallabag {{ type }} elements {% for entry in entries %} -- cgit v1.2.3 From 03ce43d466daf9d085f5b521b223cb8b351a1c0e Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Sat, 10 Jun 2017 13:19:43 +0200 Subject: Fix getContainer in command --- src/Wallabag/CoreBundle/Command/CleanDuplicatesCommand.php | 6 +++--- src/Wallabag/CoreBundle/Command/ExportCommand.php | 4 ++-- src/Wallabag/CoreBundle/Command/ShowUserCommand.php | 2 +- src/Wallabag/CoreBundle/Command/TagAllCommand.php | 2 +- src/Wallabag/CoreBundle/Controller/ExportController.php | 1 - 5 files changed, 7 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Command/CleanDuplicatesCommand.php b/src/Wallabag/CoreBundle/Command/CleanDuplicatesCommand.php index 89ae7998..74da1e5f 100644 --- a/src/Wallabag/CoreBundle/Command/CleanDuplicatesCommand.php +++ b/src/Wallabag/CoreBundle/Command/CleanDuplicatesCommand.php @@ -46,7 +46,7 @@ class CleanDuplicatesCommand extends ContainerAwareCommand return 1; } } else { - $users = $this->get('wallabag_user.user_repository')->findAll(); + $users = $this->getContainer()->get('wallabag_user.user_repository')->findAll(); $output->writeln(sprintf('Cleaning through %d user accounts', count($users))); @@ -66,7 +66,7 @@ class CleanDuplicatesCommand extends ContainerAwareCommand private function cleanDuplicates(User $user) { $em = $this->getContainer()->get('doctrine.orm.entity_manager'); - $repo = $this->get('wallabag_core.entry_repository'); + $repo = $this->getContainer()->get('wallabag_core.entry_repository'); $entries = $repo->getAllEntriesIdAndUrl($user->getId()); @@ -109,7 +109,7 @@ class CleanDuplicatesCommand extends ContainerAwareCommand */ private function getUser($username) { - return $this->get('wallabag_user.user_repository')->findOneByUserName($username); + return $this->getContainer()->get('wallabag_user.user_repository')->findOneByUserName($username); } private function getDoctrine() diff --git a/src/Wallabag/CoreBundle/Command/ExportCommand.php b/src/Wallabag/CoreBundle/Command/ExportCommand.php index e4977e11..ebb2b4cf 100644 --- a/src/Wallabag/CoreBundle/Command/ExportCommand.php +++ b/src/Wallabag/CoreBundle/Command/ExportCommand.php @@ -32,14 +32,14 @@ class ExportCommand extends ContainerAwareCommand protected function execute(InputInterface $input, OutputInterface $output) { try { - $user = $this->get('wallabag_user.user_repository')->findOneByUserName($input->getArgument('username')); + $user = $this->getContainer()->get('wallabag_user.user_repository')->findOneByUserName($input->getArgument('username')); } catch (NoResultException $e) { $output->writeln(sprintf('User "%s" not found.', $input->getArgument('username'))); return 1; } - $entries = $this->get('wallabag_core.entry_repository') + $entries = $this->getContainer()->get('wallabag_core.entry_repository') ->getBuilderForAllByUser($user->getId()) ->getQuery() ->getResult(); diff --git a/src/Wallabag/CoreBundle/Command/ShowUserCommand.php b/src/Wallabag/CoreBundle/Command/ShowUserCommand.php index 90a7e03f..eef04988 100644 --- a/src/Wallabag/CoreBundle/Command/ShowUserCommand.php +++ b/src/Wallabag/CoreBundle/Command/ShowUserCommand.php @@ -67,7 +67,7 @@ class ShowUserCommand extends ContainerAwareCommand */ private function getUser($username) { - return $this->get('wallabag_user.user_repository')->findOneByUserName($username); + return $this->getContainer()->get('wallabag_user.user_repository')->findOneByUserName($username); } private function getDoctrine() diff --git a/src/Wallabag/CoreBundle/Command/TagAllCommand.php b/src/Wallabag/CoreBundle/Command/TagAllCommand.php index 5a6dc04e..9843674e 100644 --- a/src/Wallabag/CoreBundle/Command/TagAllCommand.php +++ b/src/Wallabag/CoreBundle/Command/TagAllCommand.php @@ -59,7 +59,7 @@ class TagAllCommand extends ContainerAwareCommand */ private function getUser($username) { - return $this->get('wallabag_user.user_repository')->findOneByUserName($username); + return $this->getContainer()->get('wallabag_user.user_repository')->findOneByUserName($username); } private function getDoctrine() diff --git a/src/Wallabag/CoreBundle/Controller/ExportController.php b/src/Wallabag/CoreBundle/Controller/ExportController.php index b9e5a974..e61b6d32 100644 --- a/src/Wallabag/CoreBundle/Controller/ExportController.php +++ b/src/Wallabag/CoreBundle/Controller/ExportController.php @@ -7,7 +7,6 @@ use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Wallabag\CoreBundle\Entity\Entry; -use Wallabag\CoreBundle\Entity\Tag; /** * The try/catch can be removed once all formats will be implemented. -- cgit v1.2.3 From 8c59809432928781b8ba3d43bc300cca6860771f Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Tue, 13 Jun 2017 14:17:04 +0200 Subject: add rss icon Signed-off-by: Thomas Citharel --- .../CoreBundle/Resources/views/themes/material/Tag/tags.html.twig | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/material/Tag/tags.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/material/Tag/tags.html.twig index c83543ac..98d7b037 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/material/Tag/tags.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/material/Tag/tags.html.twig @@ -14,6 +14,9 @@ {% for tag in tags %}
  • {{tag.label}} ({{ tag.nbEntries }}) + {% if app.user.config.rssToken %} + rss_feed + {% endif %}
  • {% endfor %} -- cgit v1.2.3 From ebf2d9232798111ea4762f1d8b1cc05533238eb2 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Sun, 18 Jun 2017 14:58:50 +0200 Subject: Fix typo --- src/Wallabag/CoreBundle/Controller/ExportController.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Controller/ExportController.php b/src/Wallabag/CoreBundle/Controller/ExportController.php index e61b6d32..fda04cfb 100644 --- a/src/Wallabag/CoreBundle/Controller/ExportController.php +++ b/src/Wallabag/CoreBundle/Controller/ExportController.php @@ -56,17 +56,17 @@ class ExportController extends Controller { $method = ucfirst($category); $methodBuilder = 'getBuilderFor'.$method.'ByUser'; - $epository = $this->get('wallabag_core.entry_repository'); + $repository = $this->get('wallabag_core.entry_repository'); if ($category == 'tag_entries') { $tag = $this->get('wallabag_core.tag_repository')->findOneBySlug($request->query->get('tag')); - $entries = $epository->findAllByTagId( + $entries = $repository->findAllByTagId( $this->getUser()->getId(), $tag->getId() ); } else { - $entries = $epository + $entries = $repository ->$methodBuilder($this->getUser()->getId()) ->getQuery() ->getResult(); -- cgit v1.2.3 From bd40f1af88979cb5257206d178d26819e350a24c Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Tue, 20 Jun 2017 18:29:46 +0200 Subject: Add all entries RSS feed and put links on tag page itself and baggy too Signed-off-by: Thomas Citharel --- .../CoreBundle/Controller/RssController.php | 23 +++++++++++++++++++--- .../CoreBundle/Controller/TagController.php | 2 +- .../Resources/translations/messages.da.yml | 7 ++++--- .../Resources/translations/messages.de.yml | 1 + .../Resources/translations/messages.en.yml | 7 ++++--- .../Resources/translations/messages.es.yml | 1 + .../Resources/translations/messages.fa.yml | 1 + .../Resources/translations/messages.fr.yml | 9 +++++---- .../Resources/translations/messages.it.yml | 7 ++++--- .../Resources/translations/messages.oc.yml | 9 +++++---- .../Resources/translations/messages.pl.yml | 7 ++++--- .../Resources/translations/messages.pt.yml | 7 ++++--- .../Resources/translations/messages.ro.yml | 7 ++++--- .../Resources/translations/messages.tr.yml | 7 ++++--- .../views/themes/baggy/Config/index.html.twig | 11 ++++++----- .../views/themes/baggy/Entry/entries.html.twig | 13 ++++++++++-- .../views/themes/baggy/Tag/tags.html.twig | 7 ++++++- .../views/themes/common/Entry/_rss_link.html.twig | 6 ++++++ .../views/themes/material/Config/index.html.twig | 1 + .../views/themes/material/Entry/entries.html.twig | 16 ++++++++++++--- .../views/themes/material/Tag/tags.html.twig | 2 +- 21 files changed, 106 insertions(+), 45 deletions(-) create mode 100644 src/Wallabag/CoreBundle/Resources/views/themes/common/Entry/_rss_link.html.twig (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Controller/RssController.php b/src/Wallabag/CoreBundle/Controller/RssController.php index 090eccab..e87dd9a1 100644 --- a/src/Wallabag/CoreBundle/Controller/RssController.php +++ b/src/Wallabag/CoreBundle/Controller/RssController.php @@ -26,7 +26,7 @@ class RssController extends Controller * * @return \Symfony\Component\HttpFoundation\Response */ - public function showUnreadAction(Request $request, User $user) + public function showUnreadRSSAction(Request $request, User $user) { return $this->showEntries('unread', $user, $request->query->get('page', 1)); } @@ -39,7 +39,7 @@ class RssController extends Controller * * @return \Symfony\Component\HttpFoundation\Response */ - public function showArchiveAction(Request $request, User $user) + public function showArchiveRSSAction(Request $request, User $user) { return $this->showEntries('archive', $user, $request->query->get('page', 1)); } @@ -52,11 +52,24 @@ class RssController extends Controller * * @return \Symfony\Component\HttpFoundation\Response */ - public function showStarredAction(Request $request, User $user) + public function showStarredRSSAction(Request $request, User $user) { return $this->showEntries('starred', $user, $request->query->get('page', 1)); } + /** + * Shows all entries for current user. + * + * @Route("/{username}/{token}/all.xml", name="all_rss", defaults={"_format"="xml"}) + * @ParamConverter("user", class="WallabagUserBundle:User", converter="username_rsstoken_converter") + * + * @return \Symfony\Component\HttpFoundation\Response + */ + public function showAllRSSAction(Request $request, User $user) + { + return $this->showEntries('all', $user, $request->query->get('page', 1)); + } + /** * Shows entries associated to a tag for current user. * @@ -143,6 +156,10 @@ class RssController extends Controller $qb = $repository->getBuilderForUnreadByUser($user->getId()); break; + case 'all': + $qb = $repository->getBuilderForAllByUser($user->getId()); + break; + default: throw new \InvalidArgumentException(sprintf('Type "%s" is not implemented.', $type)); } diff --git a/src/Wallabag/CoreBundle/Controller/TagController.php b/src/Wallabag/CoreBundle/Controller/TagController.php index 72822479..a8b1eadd 100644 --- a/src/Wallabag/CoreBundle/Controller/TagController.php +++ b/src/Wallabag/CoreBundle/Controller/TagController.php @@ -144,7 +144,7 @@ class TagController extends Controller 'form' => null, 'entries' => $entries, 'currentPage' => $page, - 'tag' => $tag->getSlug(), + 'tag' => $tag, ]); } } diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml index a91a0ce4..52904d25 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml @@ -90,9 +90,10 @@ config: token_reset: 'Nulstil token' rss_links: 'RSS-Links' rss_link: - unread: 'ulæst' - starred: 'favoritter' - archive: 'arkiv' + unread: 'Ulæst' + starred: 'Favoritter' + archive: 'Arkiv' + # all: 'All' # rss_limit: 'Number of items in the feed' form_user: # two_factor_description: "Enabling two factor authentication means you'll receive an email with a code on every new untrusted connexion" diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml index e77cdca3..481b5d05 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml @@ -93,6 +93,7 @@ config: unread: 'Ungelesene' starred: 'Favoriten' archive: 'Archivierte' + # all: 'All' rss_limit: 'Anzahl der Einträge pro Feed' form_user: two_factor_description: "Wenn du die Zwei-Faktor-Authentifizierung aktivierst, erhältst du eine E-Mail mit einem Code bei jeder nicht vertrauenswürdigen Verbindung" diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml index 50edab3a..98888d05 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml @@ -90,9 +90,10 @@ config: token_reset: 'Regenerate your token' rss_links: 'RSS links' rss_link: - unread: 'unread' - starred: 'starred' - archive: 'archived' + unread: 'Unread' + starred: 'Starred' + archive: 'Archived' + all: 'All' rss_limit: 'Number of items in the feed' form_user: two_factor_description: "Enabling two factor authentication means you'll receive an email with a code on every new untrusted connection." diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml index 6fbf00eb..310a00de 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml @@ -93,6 +93,7 @@ config: unread: 'sin leer' starred: 'favoritos' archive: 'archivados' + # all: 'All' rss_limit: 'Límite de artículos en feed RSS' form_user: two_factor_description: "Con la autenticación en dos pasos recibirá código por e-mail en cada nueva conexión que no sea de confianza." diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml index ad7d6cd9..d5247fc3 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml @@ -93,6 +93,7 @@ config: unread: 'خوانده‌نشده' starred: 'برگزیده' archive: 'بایگانی' + # all: 'All' rss_limit: 'محدودیت آر-اس-اس' form_user: two_factor_description: "با فعال‌کردن تأیید ۲مرحله‌ای هر بار که اتصال تأییدنشده‌ای برقرار شد، به شما یک کد از راه ایمیل فرستاده می‌شود" diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml index c4b029c3..b338eba4 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml @@ -88,11 +88,12 @@ config: no_token: "Aucun jeton généré" token_create: "Créez votre jeton" token_reset: "Réinitialisez votre jeton" - rss_links: "Adresse de vos flux RSS" + rss_links: "Adresses de vos flux RSS" rss_link: - unread: "non lus" - starred: "favoris" - archive: "lus" + unread: "Non lus" + starred: "Favoris" + archive: "Lus" + all: "Tous" rss_limit: "Nombre d’articles dans le flux" form_user: two_factor_description: "Activer l’authentification double-facteur veut dire que vous allez recevoir un code par courriel à chaque nouvelle connexion non approuvée." diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml index 4bd04aad..a3ff5495 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml @@ -90,9 +90,10 @@ config: token_reset: 'Rigenera il tuo token' rss_links: 'Collegamenti RSS' rss_link: - unread: 'non letti' - starred: 'preferiti' - archive: 'archiviati' + unread: 'Non letti' + starred: 'Preferiti' + archive: 'Archiviati' + # all: 'All' rss_limit: 'Numero di elementi nel feed' form_user: two_factor_description: "Abilitando l'\autenticazione a due fattori riceverai una e-mail con un codice per ogni nuova connesione non verificata" diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml index a6dd4dcd..a6566a12 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml @@ -88,11 +88,12 @@ config: no_token: 'Pas cap de geton generat' token_create: 'Creatz vòstre geton' token_reset: 'Reïnicializatz vòstre geton' - rss_links: 'URL de vòstres fluxes RSS' + rss_links: 'URLs de vòstres fluxes RSS' rss_link: - unread: 'pas legits' - starred: 'favorits' - archive: 'legits' + unread: 'Pas legits' + starred: 'Favorits' + archive: 'Legits' + # all: 'All' rss_limit: "Nombre d'articles dins un flux RSS" form_user: two_factor_description: "Activar l'autentificacion doble-factor vòl dire que recebretz un còdi per corrièl per cada novèla connexion pas aprovada." diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml index 7312abd7..8e1276d9 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml @@ -90,9 +90,10 @@ config: token_reset: 'Zresetuj swojego tokena' rss_links: 'RSS links' rss_link: - unread: 'nieprzeczytane' - starred: 'oznaczone gwiazdką' - archive: 'archiwum' + unread: 'Nieprzeczytane' + starred: 'Oznaczone gwiazdką' + archive: 'Archiwum' + # all: 'All' rss_limit: 'Link do RSS' form_user: two_factor_description: "Włączenie autoryzacji dwuetapowej oznacza, że będziesz otrzymywał maile z kodem przy każdym nowym, niezaufanym połączeniu" diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml index 18090352..953c86bb 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml @@ -90,9 +90,10 @@ config: token_reset: 'Gerar novamente seu token' rss_links: 'Links RSS' rss_link: - unread: 'não lido' - starred: 'destacado' - archive: 'arquivado' + unread: 'Não lido' + starred: 'Destacado' + archive: 'Arquivado' + # all: 'All' rss_limit: 'Número de itens no feed' form_user: two_factor_description: 'Habilitar autenticação de dois passos significa que você receberá um e-mail com um código a cada nova conexão desconhecida.' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml index f8866fdc..51dbbcaf 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml @@ -90,9 +90,10 @@ config: token_reset: 'Resetează-ți token-ul' rss_links: 'Link-uri RSS' rss_link: - unread: 'unread' - starred: 'starred' - archive: 'archived' + unread: 'Unread' + starred: 'Starred' + archive: 'Archived' + # all: 'All' rss_limit: 'Limită RSS' form_user: # two_factor_description: "Enabling two factor authentication means you'll receive an email with a code on every new untrusted connexion" diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml index 4d01e7f7..ff19e9d9 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml @@ -90,9 +90,10 @@ config: token_reset: 'Belirteci (token) sıfırla' rss_links: 'RSS akış bağlantıları' rss_link: - unread: 'okunmayan' - starred: 'favoriler' - archive: 'arşiv' + unread: 'Okunmayan' + starred: 'Favoriler' + archive: 'Arşiv' + # all: 'All' rss_limit: 'RSS içeriğinden talep edilecek makale limiti' form_user: two_factor_description: "İki adımlı doğrulamayı aktifleştirdiğinizde, her yeni güvenilmeyen bağlantılarda size e-posta ile bir kod alacaksınız." diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Config/index.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Config/index.html.twig index 01f63a7b..2bf64cd6 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Config/index.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Config/index.html.twig @@ -82,7 +82,7 @@

    {{ 'config.form_settings.android_configuration'|trans }}

    - Touch here to prefill your Android application + Touch here to prefill your Android application
    -- cgit v1.2.3 From 151f45db0ef6d0a4737eb220b0803b3ccfd0b6f5 Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Thu, 22 Jun 2017 14:55:49 +0200 Subject: Don't load js for nothing in prod --- .../CoreBundle/Resources/views/themes/common/Entry/share.html.twig | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/common/Entry/share.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/common/Entry/share.html.twig index 2e8fe65c..a67807f9 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/common/Entry/share.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/common/Entry/share.html.twig @@ -14,11 +14,12 @@ - {% if not app.debug %} + {% if app.debug %} + + {% else %} {% endif %} -
    -- cgit v1.2.3 From 18696f77fdc76f7055d84460d459051a6bb7253a Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Fri, 23 Jun 2017 08:30:23 +0200 Subject: Avoid BC on exists endpoint --- src/Wallabag/ApiBundle/Controller/EntryRestController.php | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/EntryRestController.php b/src/Wallabag/ApiBundle/Controller/EntryRestController.php index 768c4fdc..793b91ba 100644 --- a/src/Wallabag/ApiBundle/Controller/EntryRestController.php +++ b/src/Wallabag/ApiBundle/Controller/EntryRestController.php @@ -18,9 +18,12 @@ class EntryRestController extends WallabagRestController { /** * Check if an entry exist by url. + * Return ID if entry(ies) exist (and if you give the return_id parameter). + * Otherwise it returns false. * * @ApiDoc( * parameters={ + * {"name"="return_id", "dataType"="string", "required"=false, "format"="1 or 0", "description"="Set 1 if you want to retrieve ID in case entry(ies) exists, 0 by default"}, * {"name"="url", "dataType"="string", "required"=true, "format"="An url", "description"="Url to check if it exists"}, * {"name"="urls", "dataType"="string", "required"=false, "format"="An array of urls (?urls[]=http...&urls[]=http...)", "description"="Urls (as an array) to check if it exists"} * } @@ -32,6 +35,7 @@ class EntryRestController extends WallabagRestController { $this->validateAuthentication(); + $returnId = (null === $request->query->get('return_id')) ? 0 : (bool) $request->query->get('return_id'); $urls = $request->query->get('urls', []); // handle multiple urls first @@ -42,7 +46,7 @@ class EntryRestController extends WallabagRestController ->getRepository('WallabagCoreBundle:Entry') ->findByUrlAndUserId($url, $this->getUser()->getId()); - $results[$url] = $res instanceof Entry ? $res->getId() : false; + $results[$url] = $res instanceof Entry ? ($returnId ? $res->getId() : true) : false; } return $this->sendResponse($results); @@ -59,7 +63,7 @@ class EntryRestController extends WallabagRestController ->getRepository('WallabagCoreBundle:Entry') ->findByUrlAndUserId($url, $this->getUser()->getId()); - $exists = $res instanceof Entry ? $res->getId() : false; + $exists = $res instanceof Entry ? ($returnId ? $res->getId() : true) : false; return $this->sendResponse(['exists' => $exists]); } -- cgit v1.2.3 From 39ffaba3232b6378f47883615c58a9ffba668af3 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Wed, 28 Jun 2017 08:15:06 +0200 Subject: Return null instead of false --- .../ApiBundle/Controller/EntryRestController.php | 30 +++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/EntryRestController.php b/src/Wallabag/ApiBundle/Controller/EntryRestController.php index 793b91ba..9786c4d3 100644 --- a/src/Wallabag/ApiBundle/Controller/EntryRestController.php +++ b/src/Wallabag/ApiBundle/Controller/EntryRestController.php @@ -4,6 +4,7 @@ namespace Wallabag\ApiBundle\Controller; use Hateoas\Configuration\Route; use Hateoas\Representation\Factory\PagerfantaFactory; +use JMS\Serializer\SerializationContext; use Nelmio\ApiDocBundle\Annotation\ApiDoc; use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpFoundation\Request; @@ -21,6 +22,8 @@ class EntryRestController extends WallabagRestController * Return ID if entry(ies) exist (and if you give the return_id parameter). * Otherwise it returns false. * + * @todo Remove that `return_id` in the next major release + * * @ApiDoc( * parameters={ * {"name"="return_id", "dataType"="string", "required"=false, "format"="1 or 0", "description"="Set 1 if you want to retrieve ID in case entry(ies) exists, 0 by default"}, @@ -46,7 +49,7 @@ class EntryRestController extends WallabagRestController ->getRepository('WallabagCoreBundle:Entry') ->findByUrlAndUserId($url, $this->getUser()->getId()); - $results[$url] = $res instanceof Entry ? ($returnId ? $res->getId() : true) : false; + $results[$url] = $this->returnExistInformation($res, $returnId); } return $this->sendResponse($results); @@ -63,7 +66,7 @@ class EntryRestController extends WallabagRestController ->getRepository('WallabagCoreBundle:Entry') ->findByUrlAndUserId($url, $this->getUser()->getId()); - $exists = $res instanceof Entry ? ($returnId ? $res->getId() : true) : false; + $exists = $this->returnExistInformation($res, $returnId); return $this->sendResponse(['exists' => $exists]); } @@ -621,7 +624,11 @@ class EntryRestController extends WallabagRestController */ private function sendResponse($data) { - $json = $this->get('serializer')->serialize($data, 'json'); + // https://github.com/schmittjoh/JMSSerializerBundle/issues/293 + $context = new SerializationContext(); + $context->setSerializeNull(true); + + $json = $this->get('serializer')->serialize($data, 'json', $context); return (new JsonResponse())->setJson($json); } @@ -698,4 +705,21 @@ class EntryRestController extends WallabagRestController // entry saved, dispatch event about it! $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry)); } + + /** + * Return information about the entry if it exist and depending on the id or not. + * + * @param Entry|null $entry + * @param bool $returnId + * + * @return bool|int + */ + private function returnExistInformation($entry, $returnId) + { + if ($returnId) { + return $entry instanceof Entry ? $entry->getId() : null; + } + + return $entry instanceof Entry ? true : false; + } } -- cgit v1.2.3 From 331e5b026189ff6433014659f32304b1706015e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Benoist?= Date: Wed, 28 Jun 2017 09:18:22 +0200 Subject: CS --- src/Wallabag/ApiBundle/Controller/EntryRestController.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/EntryRestController.php b/src/Wallabag/ApiBundle/Controller/EntryRestController.php index 9786c4d3..c7938633 100644 --- a/src/Wallabag/ApiBundle/Controller/EntryRestController.php +++ b/src/Wallabag/ApiBundle/Controller/EntryRestController.php @@ -38,7 +38,7 @@ class EntryRestController extends WallabagRestController { $this->validateAuthentication(); - $returnId = (null === $request->query->get('return_id')) ? 0 : (bool) $request->query->get('return_id'); + $returnId = (null === $request->query->get('return_id')) ? false : (bool) $request->query->get('return_id'); $urls = $request->query->get('urls', []); // handle multiple urls first @@ -720,6 +720,6 @@ class EntryRestController extends WallabagRestController return $entry instanceof Entry ? $entry->getId() : null; } - return $entry instanceof Entry ? true : false; + return $entry instanceof Entry; } } -- cgit v1.2.3 From f808b01692a835673f328d7221ba8c212caa9b61 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Sat, 1 Jul 2017 09:52:38 +0200 Subject: Add a real configuration for CS-Fixer --- .../Controller/WallabagAnnotationController.php | 2 +- .../AnnotationBundle/Entity/Annotation.php | 10 +- .../Repository/AnnotationRepository.php | 32 +-- .../Controller/AnnotationRestController.php | 4 +- .../ApiBundle/Controller/DeveloperController.php | 4 +- .../ApiBundle/Controller/EntryRestController.php | 18 +- .../ApiBundle/Controller/TagRestController.php | 2 +- .../ApiBundle/Controller/UserRestController.php | 4 +- .../Controller/WallabagRestController.php | 4 +- src/Wallabag/ApiBundle/Entity/Client.php | 4 +- src/Wallabag/ApiBundle/Form/Type/ClientType.php | 2 +- .../CoreBundle/Command/CleanDuplicatesCommand.php | 4 +- src/Wallabag/CoreBundle/Command/ExportCommand.php | 2 +- src/Wallabag/CoreBundle/Command/InstallCommand.php | 22 +- .../CoreBundle/Controller/ConfigController.php | 140 ++++++----- .../CoreBundle/Controller/EntryController.php | 260 ++++++++++----------- .../CoreBundle/Controller/ExceptionController.php | 2 +- .../CoreBundle/Controller/ExportController.php | 4 +- .../CoreBundle/Controller/RssController.php | 18 +- .../Controller/SiteCredentialController.php | 8 +- .../CoreBundle/Controller/StaticController.php | 7 +- .../CoreBundle/Controller/TagController.php | 2 +- .../DataFixtures/ORM/LoadSettingData.php | 2 +- .../DependencyInjection/WallabagCoreExtension.php | 2 +- src/Wallabag/CoreBundle/Entity/Entry.php | 10 +- src/Wallabag/CoreBundle/Entity/SiteCredential.php | 2 +- src/Wallabag/CoreBundle/Entity/Tag.php | 2 +- .../Event/Subscriber/DownloadImagesSubscriber.php | 8 +- .../Subscriber/SQLiteCascadeDeleteSubscriber.php | 2 +- .../Event/Subscriber/TablePrefixSubscriber.php | 4 +- .../CoreBundle/Form/Type/EntryFilterType.php | 16 +- .../GrabySiteConfigBuilder.php | 4 +- src/Wallabag/CoreBundle/Helper/ContentProxy.php | 10 +- src/Wallabag/CoreBundle/Helper/CryptoProxy.php | 12 +- .../CoreBundle/Helper/DetectActiveTheme.php | 2 +- src/Wallabag/CoreBundle/Helper/DownloadImages.php | 44 ++-- src/Wallabag/CoreBundle/Helper/EntriesExport.php | 46 ++-- .../CoreBundle/Helper/HttpClientFactory.php | 2 +- .../CoreBundle/Helper/PreparePagerForEntries.php | 2 +- src/Wallabag/CoreBundle/Helper/RuleBasedTagger.php | 2 +- .../CoreBundle/Repository/EntryRepository.php | 34 +-- src/Wallabag/CoreBundle/Twig/WallabagExtension.php | 12 +- .../ImportBundle/Command/ImportCommand.php | 10 +- .../ImportBundle/Command/RedisWorkerCommand.php | 12 +- .../ImportBundle/Consumer/AbstractConsumer.php | 10 +- .../ImportBundle/Controller/BrowserController.php | 43 ++-- .../ImportBundle/Controller/ChromeController.php | 16 +- .../ImportBundle/Controller/FirefoxController.php | 16 +- .../ImportBundle/Controller/ImportController.php | 6 +- .../Controller/InstapaperController.php | 20 +- .../ImportBundle/Controller/PinboardController.php | 20 +- .../ImportBundle/Controller/PocketController.php | 46 ++-- .../Controller/ReadabilityController.php | 20 +- .../ImportBundle/Controller/WallabagController.php | 46 ++-- .../Controller/WallabagV1Controller.php | 16 +- .../Controller/WallabagV2Controller.php | 16 +- .../WallabagImportExtension.php | 6 +- .../ImportBundle/Form/Type/UploadImportType.php | 6 +- .../ImportBundle/Import/AbstractImport.php | 52 ++--- src/Wallabag/ImportBundle/Import/BrowserImport.php | 150 ++++++------ src/Wallabag/ImportBundle/Import/ChromeImport.php | 2 +- src/Wallabag/ImportBundle/Import/FirefoxImport.php | 2 +- .../ImportBundle/Import/ImportCompilerPass.php | 2 +- .../ImportBundle/Import/InstapaperImport.php | 2 +- src/Wallabag/ImportBundle/Import/PocketImport.php | 13 +- .../ImportBundle/Import/WallabagV1Import.php | 4 +- src/Wallabag/ImportBundle/Redis/Producer.php | 2 +- src/Wallabag/ImportBundle/WallabagImportBundle.php | 2 +- .../UserBundle/Controller/ManageController.php | 48 ++-- .../DependencyInjection/WallabagUserExtension.php | 6 +- src/Wallabag/UserBundle/Entity/User.php | 36 +-- .../AuthenticationFailureListener.php | 2 +- .../EventListener/PasswordResettingListener.php | 2 +- src/Wallabag/UserBundle/Form/UserType.php | 10 +- src/Wallabag/UserBundle/Mailer/AuthCodeMailer.php | 2 +- .../UserBundle/Repository/UserRepository.php | 2 +- 76 files changed, 703 insertions(+), 718 deletions(-) (limited to 'src') diff --git a/src/Wallabag/AnnotationBundle/Controller/WallabagAnnotationController.php b/src/Wallabag/AnnotationBundle/Controller/WallabagAnnotationController.php index 2b4b0e8d..8d7b6ee9 100644 --- a/src/Wallabag/AnnotationBundle/Controller/WallabagAnnotationController.php +++ b/src/Wallabag/AnnotationBundle/Controller/WallabagAnnotationController.php @@ -3,9 +3,9 @@ namespace Wallabag\AnnotationBundle\Controller; use FOS\RestBundle\Controller\FOSRestController; +use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; -use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; use Wallabag\AnnotationBundle\Entity\Annotation; use Wallabag\AnnotationBundle\Form\EditAnnotationType; use Wallabag\AnnotationBundle\Form\NewAnnotationType; diff --git a/src/Wallabag/AnnotationBundle/Entity/Annotation.php b/src/Wallabag/AnnotationBundle/Entity/Annotation.php index c8e41649..04d83001 100644 --- a/src/Wallabag/AnnotationBundle/Entity/Annotation.php +++ b/src/Wallabag/AnnotationBundle/Entity/Annotation.php @@ -3,14 +3,14 @@ namespace Wallabag\AnnotationBundle\Entity; use Doctrine\ORM\Mapping as ORM; -use JMS\Serializer\Annotation\ExclusionPolicy; use JMS\Serializer\Annotation\Exclude; -use JMS\Serializer\Annotation\VirtualProperty; -use JMS\Serializer\Annotation\SerializedName; +use JMS\Serializer\Annotation\ExclusionPolicy; use JMS\Serializer\Annotation\Groups; +use JMS\Serializer\Annotation\SerializedName; +use JMS\Serializer\Annotation\VirtualProperty; use Symfony\Component\Validator\Constraints as Assert; -use Wallabag\UserBundle\Entity\User; use Wallabag\CoreBundle\Entity\Entry; +use Wallabag\UserBundle\Entity\User; /** * Annotation. @@ -139,7 +139,7 @@ class Annotation */ public function timestamps() { - if (is_null($this->createdAt)) { + if (null === $this->createdAt) { $this->createdAt = new \DateTime(); } $this->updatedAt = new \DateTime(); diff --git a/src/Wallabag/AnnotationBundle/Repository/AnnotationRepository.php b/src/Wallabag/AnnotationBundle/Repository/AnnotationRepository.php index da361308..014c29b6 100644 --- a/src/Wallabag/AnnotationBundle/Repository/AnnotationRepository.php +++ b/src/Wallabag/AnnotationBundle/Repository/AnnotationRepository.php @@ -9,22 +9,6 @@ use Doctrine\ORM\EntityRepository; */ class AnnotationRepository extends EntityRepository { - /** - * Return a query builder to used by other getBuilderFor* method. - * - * @param int $userId - * - * @return QueryBuilder - */ - private function getBuilderByUser($userId) - { - return $this->createQueryBuilder('a') - ->leftJoin('a.user', 'u') - ->andWhere('u.id = :userId')->setParameter('userId', $userId) - ->orderBy('a.id', 'desc') - ; - } - /** * Retrieves all annotations for a user. * @@ -139,4 +123,20 @@ class AnnotationRepository extends EntityRepository ->getQuery() ->getResult(); } + + /** + * Return a query builder to used by other getBuilderFor* method. + * + * @param int $userId + * + * @return QueryBuilder + */ + private function getBuilderByUser($userId) + { + return $this->createQueryBuilder('a') + ->leftJoin('a.user', 'u') + ->andWhere('u.id = :userId')->setParameter('userId', $userId) + ->orderBy('a.id', 'desc') + ; + } } diff --git a/src/Wallabag/ApiBundle/Controller/AnnotationRestController.php b/src/Wallabag/ApiBundle/Controller/AnnotationRestController.php index 2dd26c07..28d55ba9 100644 --- a/src/Wallabag/ApiBundle/Controller/AnnotationRestController.php +++ b/src/Wallabag/ApiBundle/Controller/AnnotationRestController.php @@ -4,10 +4,10 @@ namespace Wallabag\ApiBundle\Controller; use Nelmio\ApiDocBundle\Annotation\ApiDoc; use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; -use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\JsonResponse; -use Wallabag\CoreBundle\Entity\Entry; +use Symfony\Component\HttpFoundation\Request; use Wallabag\AnnotationBundle\Entity\Annotation; +use Wallabag\CoreBundle\Entity\Entry; class AnnotationRestController extends WallabagRestController { diff --git a/src/Wallabag/ApiBundle/Controller/DeveloperController.php b/src/Wallabag/ApiBundle/Controller/DeveloperController.php index 9cb73f4c..c8a1c635 100644 --- a/src/Wallabag/ApiBundle/Controller/DeveloperController.php +++ b/src/Wallabag/ApiBundle/Controller/DeveloperController.php @@ -3,8 +3,8 @@ namespace Wallabag\ApiBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; -use Symfony\Component\HttpFoundation\Request; use Symfony\Bundle\FrameworkBundle\Controller\Controller; +use Symfony\Component\HttpFoundation\Request; use Wallabag\ApiBundle\Entity\Client; use Wallabag\ApiBundle\Form\Type\ClientType; @@ -75,7 +75,7 @@ class DeveloperController extends Controller */ public function deleteClientAction(Client $client) { - if (null === $this->getUser() || $client->getUser()->getId() != $this->getUser()->getId()) { + if (null === $this->getUser() || $client->getUser()->getId() !== $this->getUser()->getId()) { throw $this->createAccessDeniedException('You can not access this client.'); } diff --git a/src/Wallabag/ApiBundle/Controller/EntryRestController.php b/src/Wallabag/ApiBundle/Controller/EntryRestController.php index c7938633..ca460c84 100644 --- a/src/Wallabag/ApiBundle/Controller/EntryRestController.php +++ b/src/Wallabag/ApiBundle/Controller/EntryRestController.php @@ -6,14 +6,14 @@ use Hateoas\Configuration\Route; use Hateoas\Representation\Factory\PagerfantaFactory; use JMS\Serializer\SerializationContext; use Nelmio\ApiDocBundle\Annotation\ApiDoc; -use Symfony\Component\HttpKernel\Exception\HttpException; -use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\JsonResponse; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Wallabag\CoreBundle\Entity\Entry; use Wallabag\CoreBundle\Entity\Tag; -use Wallabag\CoreBundle\Event\EntrySavedEvent; use Wallabag\CoreBundle\Event\EntryDeletedEvent; +use Wallabag\CoreBundle\Event\EntrySavedEvent; class EntryRestController extends WallabagRestController { @@ -59,7 +59,7 @@ class EntryRestController extends WallabagRestController $url = $request->query->get('url', ''); if (empty($url)) { - throw $this->createAccessDeniedException('URL is empty?, logged user id: '.$this->getUser()->getId()); + throw $this->createAccessDeniedException('URL is empty?, logged user id: ' . $this->getUser()->getId()); } $res = $this->getDoctrine() @@ -239,9 +239,9 @@ class EntryRestController extends WallabagRestController * } * ) * - * @return JsonResponse - * * @throws HttpException When limit is reached + * + * @return JsonResponse */ public function postEntriesListAction(Request $request) { @@ -678,11 +678,11 @@ class EntryRestController extends WallabagRestController ]); } - if (!is_null($isArchived)) { + if (null !== $isArchived) { $entry->setArchived((bool) $isArchived); } - if (!is_null($isStarred)) { + if (null !== $isStarred) { $entry->setStarred((bool) $isStarred); } @@ -690,7 +690,7 @@ class EntryRestController extends WallabagRestController $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags); } - if (!is_null($isPublic)) { + if (null !== $isPublic) { if (true === (bool) $isPublic && null === $entry->getUid()) { $entry->generateUid(); } elseif (false === (bool) $isPublic) { diff --git a/src/Wallabag/ApiBundle/Controller/TagRestController.php b/src/Wallabag/ApiBundle/Controller/TagRestController.php index 354187a0..efa4e8cf 100644 --- a/src/Wallabag/ApiBundle/Controller/TagRestController.php +++ b/src/Wallabag/ApiBundle/Controller/TagRestController.php @@ -3,8 +3,8 @@ namespace Wallabag\ApiBundle\Controller; use Nelmio\ApiDocBundle\Annotation\ApiDoc; -use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\JsonResponse; +use Symfony\Component\HttpFoundation\Request; use Wallabag\CoreBundle\Entity\Entry; use Wallabag\CoreBundle\Entity\Tag; diff --git a/src/Wallabag/ApiBundle/Controller/UserRestController.php b/src/Wallabag/ApiBundle/Controller/UserRestController.php index 7471f5f6..6f47cff0 100644 --- a/src/Wallabag/ApiBundle/Controller/UserRestController.php +++ b/src/Wallabag/ApiBundle/Controller/UserRestController.php @@ -6,10 +6,10 @@ use FOS\UserBundle\Event\UserEvent; use FOS\UserBundle\FOSUserEvents; use JMS\Serializer\SerializationContext; use Nelmio\ApiDocBundle\Annotation\ApiDoc; -use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\JsonResponse; -use Wallabag\UserBundle\Entity\User; +use Symfony\Component\HttpFoundation\Request; use Wallabag\ApiBundle\Entity\Client; +use Wallabag\UserBundle\Entity\User; class UserRestController extends WallabagRestController { diff --git a/src/Wallabag/ApiBundle/Controller/WallabagRestController.php b/src/Wallabag/ApiBundle/Controller/WallabagRestController.php index b1e08ca4..71da2a64 100644 --- a/src/Wallabag/ApiBundle/Controller/WallabagRestController.php +++ b/src/Wallabag/ApiBundle/Controller/WallabagRestController.php @@ -40,8 +40,8 @@ class WallabagRestController extends FOSRestController protected function validateUserAccess($requestUserId) { $user = $this->get('security.token_storage')->getToken()->getUser(); - if ($requestUserId != $user->getId()) { - throw $this->createAccessDeniedException('Access forbidden. Entry user id: '.$requestUserId.', logged user id: '.$user->getId()); + if ($requestUserId !== $user->getId()) { + throw $this->createAccessDeniedException('Access forbidden. Entry user id: ' . $requestUserId . ', logged user id: ' . $user->getId()); } } } diff --git a/src/Wallabag/ApiBundle/Entity/Client.php b/src/Wallabag/ApiBundle/Entity/Client.php index c15fd3fa..e6f98f98 100644 --- a/src/Wallabag/ApiBundle/Entity/Client.php +++ b/src/Wallabag/ApiBundle/Entity/Client.php @@ -4,10 +4,10 @@ namespace Wallabag\ApiBundle\Entity; use Doctrine\ORM\Mapping as ORM; use FOS\OAuthServerBundle\Entity\Client as BaseClient; -use Wallabag\UserBundle\Entity\User; use JMS\Serializer\Annotation\Groups; use JMS\Serializer\Annotation\SerializedName; use JMS\Serializer\Annotation\VirtualProperty; +use Wallabag\UserBundle\Entity\User; /** * @ORM\Table("oauth2_clients") @@ -99,6 +99,6 @@ class Client extends BaseClient */ public function getClientId() { - return $this->getId().'_'.$this->getRandomId(); + return $this->getId() . '_' . $this->getRandomId(); } } diff --git a/src/Wallabag/ApiBundle/Form/Type/ClientType.php b/src/Wallabag/ApiBundle/Form/Type/ClientType.php index eaea4feb..fc22538f 100644 --- a/src/Wallabag/ApiBundle/Form/Type/ClientType.php +++ b/src/Wallabag/ApiBundle/Form/Type/ClientType.php @@ -5,8 +5,8 @@ namespace Wallabag\ApiBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\CallbackTransformer; use Symfony\Component\Form\Extension\Core\Type\SubmitType; -use Symfony\Component\Form\Extension\Core\Type\UrlType; use Symfony\Component\Form\Extension\Core\Type\TextType; +use Symfony\Component\Form\Extension\Core\Type\UrlType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; diff --git a/src/Wallabag/CoreBundle/Command/CleanDuplicatesCommand.php b/src/Wallabag/CoreBundle/Command/CleanDuplicatesCommand.php index 74da1e5f..d964439d 100644 --- a/src/Wallabag/CoreBundle/Command/CleanDuplicatesCommand.php +++ b/src/Wallabag/CoreBundle/Command/CleanDuplicatesCommand.php @@ -76,7 +76,7 @@ class CleanDuplicatesCommand extends ContainerAwareCommand $url = $this->similarUrl($entry['url']); /* @var $entry Entry */ - if (in_array($url, $urls)) { + if (in_array($url, $urls, true)) { ++$duplicatesCount; $em->remove($repo->find($entry['id'])); @@ -93,7 +93,7 @@ class CleanDuplicatesCommand extends ContainerAwareCommand private function similarUrl($url) { - if (in_array(substr($url, -1), ['/', '#'])) { // get rid of "/" and "#" and the end of urls + if (in_array(substr($url, -1), ['/', '#'], true)) { // get rid of "/" and "#" and the end of urls return substr($url, 0, strlen($url)); } diff --git a/src/Wallabag/CoreBundle/Command/ExportCommand.php b/src/Wallabag/CoreBundle/Command/ExportCommand.php index ebb2b4cf..0dacb734 100644 --- a/src/Wallabag/CoreBundle/Command/ExportCommand.php +++ b/src/Wallabag/CoreBundle/Command/ExportCommand.php @@ -49,7 +49,7 @@ class ExportCommand extends ContainerAwareCommand $filePath = $input->getArgument('filepath'); if (!$filePath) { - $filePath = $this->getContainer()->getParameter('kernel.root_dir').'/../'.sprintf('%s-export.json', $user->getUsername()); + $filePath = $this->getContainer()->getParameter('kernel.root_dir') . '/../' . sprintf('%s-export.json', $user->getUsername()); } try { diff --git a/src/Wallabag/CoreBundle/Command/InstallCommand.php b/src/Wallabag/CoreBundle/Command/InstallCommand.php index eb725a59..50551480 100644 --- a/src/Wallabag/CoreBundle/Command/InstallCommand.php +++ b/src/Wallabag/CoreBundle/Command/InstallCommand.php @@ -2,6 +2,7 @@ namespace Wallabag\CoreBundle\Command; +use Craue\ConfigBundle\Entity\Setting; use FOS\UserBundle\Event\UserEvent; use FOS\UserBundle\FOSUserEvents; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; @@ -14,7 +15,6 @@ use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Question\ConfirmationQuestion; use Symfony\Component\Console\Question\Question; use Wallabag\CoreBundle\Entity\Config; -use Craue\ConfigBundle\Entity\Setting; class InstallCommand extends ContainerAwareCommand { @@ -86,7 +86,7 @@ class InstallCommand extends ContainerAwareCommand if (!extension_loaded($this->getContainer()->getParameter('database_driver'))) { $fulfilled = false; $status = 'ERROR!'; - $help = 'Database driver "'.$this->getContainer()->getParameter('database_driver').'" is not installed.'; + $help = 'Database driver "' . $this->getContainer()->getParameter('database_driver') . '" is not installed.'; } $rows[] = [sprintf($label, $this->getContainer()->getParameter('database_driver')), $status, $help]; @@ -101,10 +101,10 @@ class InstallCommand extends ContainerAwareCommand $conn->connect(); } catch (\Exception $e) { if (false === strpos($e->getMessage(), 'Unknown database') - && false === strpos($e->getMessage(), 'database "'.$this->getContainer()->getParameter('database_name').'" does not exist')) { + && false === strpos($e->getMessage(), 'database "' . $this->getContainer()->getParameter('database_name') . '" does not exist')) { $fulfilled = false; $status = 'ERROR!'; - $help = 'Can\'t connect to the database: '.$e->getMessage(); + $help = 'Can\'t connect to the database: ' . $e->getMessage(); } } @@ -123,7 +123,7 @@ class InstallCommand extends ContainerAwareCommand if (false === version_compare($version, $minimalVersion, '>')) { $fulfilled = false; $status = 'ERROR!'; - $help = 'Your MySQL version ('.$version.') is too old, consider upgrading ('.$minimalVersion.'+).'; + $help = 'Your MySQL version (' . $version . ') is too old, consider upgrading (' . $minimalVersion . '+).'; } } @@ -137,21 +137,21 @@ class InstallCommand extends ContainerAwareCommand if (isset($matches[1]) & version_compare($matches[1], '9.2.0', '<')) { $fulfilled = false; $status = 'ERROR!'; - $help = 'PostgreSQL should be greater than 9.1 (actual version: '.$matches[1].')'; + $help = 'PostgreSQL should be greater than 9.1 (actual version: ' . $matches[1] . ')'; } } $rows[] = [$label, $status, $help]; foreach ($this->functionExists as $functionRequired) { - $label = ''.$functionRequired.''; + $label = '' . $functionRequired . ''; $status = 'OK!'; $help = ''; if (!function_exists($functionRequired)) { $fulfilled = false; $status = 'ERROR!'; - $help = 'You need the '.$functionRequired.' function activated'; + $help = 'You need the ' . $functionRequired . ' function activated'; } $rows[] = [$label, $status, $help]; @@ -351,8 +351,8 @@ class InstallCommand extends ContainerAwareCommand $this->getApplication()->setAutoExit(true); throw new \RuntimeException( - 'The command "'.$command."\" generates some errors: \n\n" - .$output->fetch()); + 'The command "' . $command . "\" generates some errors: \n\n" + . $output->fetch()); } return $this; @@ -396,7 +396,7 @@ class InstallCommand extends ContainerAwareCommand } try { - return in_array($databaseName, $schemaManager->listDatabases()); + return in_array($databaseName, $schemaManager->listDatabases(), true); } catch (\Doctrine\DBAL\Exception\DriverException $e) { // it means we weren't able to get database list, assume the database doesn't exist diff --git a/src/Wallabag/CoreBundle/Controller/ConfigController.php b/src/Wallabag/CoreBundle/Controller/ConfigController.php index d4170d39..7e39992d 100644 --- a/src/Wallabag/CoreBundle/Controller/ConfigController.php +++ b/src/Wallabag/CoreBundle/Controller/ConfigController.php @@ -10,8 +10,8 @@ use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; use Wallabag\CoreBundle\Entity\Config; use Wallabag\CoreBundle\Entity\TaggingRule; -use Wallabag\CoreBundle\Form\Type\ConfigType; use Wallabag\CoreBundle\Form\Type\ChangePasswordType; +use Wallabag\CoreBundle\Form\Type\ConfigType; use Wallabag\CoreBundle\Form\Type\RssType; use Wallabag\CoreBundle\Form\Type\TaggingRuleType; use Wallabag\CoreBundle\Form\Type\UserInformationType; @@ -54,7 +54,7 @@ class ConfigController extends Controller } // handle changing password - $pwdForm = $this->createForm(ChangePasswordType::class, null, ['action' => $this->generateUrl('config').'#set4']); + $pwdForm = $this->createForm(ChangePasswordType::class, null, ['action' => $this->generateUrl('config') . '#set4']); $pwdForm->handleRequest($request); if ($pwdForm->isSubmitted() && $pwdForm->isValid()) { @@ -69,13 +69,13 @@ class ConfigController extends Controller $this->get('session')->getFlashBag()->add('notice', $message); - return $this->redirect($this->generateUrl('config').'#set4'); + return $this->redirect($this->generateUrl('config') . '#set4'); } // handle changing user information $userForm = $this->createForm(UserInformationType::class, $user, [ 'validation_groups' => ['Profile'], - 'action' => $this->generateUrl('config').'#set3', + 'action' => $this->generateUrl('config') . '#set3', ]); $userForm->handleRequest($request); @@ -87,11 +87,11 @@ class ConfigController extends Controller 'flashes.config.notice.user_updated' ); - return $this->redirect($this->generateUrl('config').'#set3'); + return $this->redirect($this->generateUrl('config') . '#set3'); } // handle rss information - $rssForm = $this->createForm(RssType::class, $config, ['action' => $this->generateUrl('config').'#set2']); + $rssForm = $this->createForm(RssType::class, $config, ['action' => $this->generateUrl('config') . '#set2']); $rssForm->handleRequest($request); if ($rssForm->isSubmitted() && $rssForm->isValid()) { @@ -103,12 +103,12 @@ class ConfigController extends Controller 'flashes.config.notice.rss_updated' ); - return $this->redirect($this->generateUrl('config').'#set2'); + return $this->redirect($this->generateUrl('config') . '#set2'); } // handle tagging rule $taggingRule = new TaggingRule(); - $action = $this->generateUrl('config').'#set5'; + $action = $this->generateUrl('config') . '#set5'; if ($request->query->has('tagging-rule')) { $taggingRule = $this->getDoctrine() @@ -119,7 +119,7 @@ class ConfigController extends Controller return $this->redirect($action); } - $action = $this->generateUrl('config').'?tagging-rule='.$taggingRule->getId().'#set5'; + $action = $this->generateUrl('config') . '?tagging-rule=' . $taggingRule->getId() . '#set5'; } $newTaggingRule = $this->createForm(TaggingRuleType::class, $taggingRule, ['action' => $action]); @@ -135,7 +135,7 @@ class ConfigController extends Controller 'flashes.config.notice.tagging_rules_updated' ); - return $this->redirect($this->generateUrl('config').'#set5'); + return $this->redirect($this->generateUrl('config') . '#set5'); } return $this->render('WallabagCoreBundle:Config:index.html.twig', [ @@ -182,7 +182,7 @@ class ConfigController extends Controller 'flashes.config.notice.rss_token_updated' ); - return $this->redirect($this->generateUrl('config').'#set2'); + return $this->redirect($this->generateUrl('config') . '#set2'); } /** @@ -207,7 +207,7 @@ class ConfigController extends Controller 'flashes.config.notice.tagging_rules_deleted' ); - return $this->redirect($this->generateUrl('config').'#set5'); + return $this->redirect($this->generateUrl('config') . '#set5'); } /** @@ -223,7 +223,7 @@ class ConfigController extends Controller { $this->validateRuleAction($rule); - return $this->redirect($this->generateUrl('config').'?tagging-rule='.$rule->getId().'#set5'); + return $this->redirect($this->generateUrl('config') . '?tagging-rule=' . $rule->getId() . '#set5'); } /** @@ -241,11 +241,9 @@ class ConfigController extends Controller ->getRepository('WallabagAnnotationBundle:Annotation') ->removeAllByUserId($this->getUser()->getId()); break; - case 'tags': $this->removeAllTagsByUserId($this->getUser()->getId()); break; - case 'entries': // SQLite doesn't care about cascading remove, so we need to manually remove associated stuff // otherwise they won't be removed ... @@ -272,10 +270,63 @@ class ConfigController extends Controller $this->get('session')->getFlashBag()->add( 'notice', - 'flashes.config.notice.'.$type.'_reset' + 'flashes.config.notice.' . $type . '_reset' ); - return $this->redirect($this->generateUrl('config').'#set3'); + return $this->redirect($this->generateUrl('config') . '#set3'); + } + + /** + * Delete account for current user. + * + * @Route("/account/delete", name="delete_account") + * + * @param Request $request + * + * @throws AccessDeniedHttpException + * + * @return \Symfony\Component\HttpFoundation\RedirectResponse + */ + public function deleteAccountAction(Request $request) + { + $enabledUsers = $this->get('wallabag_user.user_repository') + ->getSumEnabledUsers(); + + if ($enabledUsers <= 1) { + throw new AccessDeniedHttpException(); + } + + $user = $this->getUser(); + + // logout current user + $this->get('security.token_storage')->setToken(null); + $request->getSession()->invalidate(); + + $em = $this->get('fos_user.user_manager'); + $em->deleteUser($user); + + return $this->redirect($this->generateUrl('fos_user_security_login')); + } + + /** + * Switch view mode for current user. + * + * @Route("/config/view-mode", name="switch_view_mode") + * + * @param Request $request + * + * @return \Symfony\Component\HttpFoundation\RedirectResponse + */ + public function changeViewModeAction(Request $request) + { + $user = $this->getUser(); + $user->getConfig()->setListMode(!$user->getConfig()->getListMode()); + + $em = $this->getDoctrine()->getManager(); + $em->persist($user); + $em->flush(); + + return $this->redirect($request->headers->get('referer')); } /** @@ -349,7 +400,7 @@ class ConfigController extends Controller */ private function validateRuleAction(TaggingRule $rule) { - if ($this->getUser()->getId() != $rule->getConfig()->getUser()->getId()) { + if ($this->getUser()->getId() !== $rule->getConfig()->getUser()->getId()) { throw $this->createAccessDeniedException('You can not access this tagging rule.'); } } @@ -373,57 +424,4 @@ class ConfigController extends Controller return $config; } - - /** - * Delete account for current user. - * - * @Route("/account/delete", name="delete_account") - * - * @param Request $request - * - * @throws AccessDeniedHttpException - * - * @return \Symfony\Component\HttpFoundation\RedirectResponse - */ - public function deleteAccountAction(Request $request) - { - $enabledUsers = $this->get('wallabag_user.user_repository') - ->getSumEnabledUsers(); - - if ($enabledUsers <= 1) { - throw new AccessDeniedHttpException(); - } - - $user = $this->getUser(); - - // logout current user - $this->get('security.token_storage')->setToken(null); - $request->getSession()->invalidate(); - - $em = $this->get('fos_user.user_manager'); - $em->deleteUser($user); - - return $this->redirect($this->generateUrl('fos_user_security_login')); - } - - /** - * Switch view mode for current user. - * - * @Route("/config/view-mode", name="switch_view_mode") - * - * @param Request $request - * - * @return \Symfony\Component\HttpFoundation\RedirectResponse - */ - public function changeViewModeAction(Request $request) - { - $user = $this->getUser(); - $user->getConfig()->setListMode(!$user->getConfig()->getListMode()); - - $em = $this->getDoctrine()->getManager(); - $em->persist($user); - $em->flush(); - - return $this->redirect($request->headers->get('referer')); - } } diff --git a/src/Wallabag/CoreBundle/Controller/EntryController.php b/src/Wallabag/CoreBundle/Controller/EntryController.php index fafa49f1..445cfeeb 100644 --- a/src/Wallabag/CoreBundle/Controller/EntryController.php +++ b/src/Wallabag/CoreBundle/Controller/EntryController.php @@ -4,17 +4,17 @@ namespace Wallabag\CoreBundle\Controller; use Pagerfanta\Adapter\DoctrineORMAdapter; use Pagerfanta\Exception\OutOfRangeCurrentPageException; +use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Wallabag\CoreBundle\Entity\Entry; -use Wallabag\CoreBundle\Form\Type\EntryFilterType; +use Wallabag\CoreBundle\Event\EntryDeletedEvent; +use Wallabag\CoreBundle\Event\EntrySavedEvent; use Wallabag\CoreBundle\Form\Type\EditEntryType; +use Wallabag\CoreBundle\Form\Type\EntryFilterType; use Wallabag\CoreBundle\Form\Type\NewEntryType; -use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache; -use Wallabag\CoreBundle\Event\EntrySavedEvent; -use Wallabag\CoreBundle\Event\EntryDeletedEvent; use Wallabag\CoreBundle\Form\Type\SearchEntryType; class EntryController extends Controller @@ -51,31 +51,6 @@ class EntryController extends Controller ]); } - /** - * Fetch content and update entry. - * In case it fails, $entry->getContent will return an error message. - * - * @param Entry $entry - * @param string $prefixMessage Should be the translation key: entry_saved or entry_reloaded - */ - private function updateEntry(Entry $entry, $prefixMessage = 'entry_saved') - { - $message = 'flashes.entry.notice.'.$prefixMessage; - - try { - $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl()); - } catch (\Exception $e) { - $this->get('logger')->error('Error while saving an entry', [ - 'exception' => $e, - 'entry' => $entry, - ]); - - $message = 'flashes.entry.notice.'.$prefixMessage.'_failed'; - } - - $this->get('session')->getFlashBag()->add('notice', $message); - } - /** * @param Request $request * @@ -220,7 +195,7 @@ class EntryController extends Controller public function showUnreadAction(Request $request, $page) { // load the quickstart if no entry in database - if ($page == 1 && $this->get('wallabag_core.entry_repository')->countAllEntriesByUser($this->getUser()->getId()) == 0) { + if ($page === 1 && $this->get('wallabag_core.entry_repository')->countAllEntriesByUser($this->getUser()->getId()) === 0) { return $this->redirect($this->generateUrl('quickstart')); } @@ -257,83 +232,6 @@ class EntryController extends Controller return $this->showEntries('starred', $request, $page); } - /** - * Global method to retrieve entries depending on the given type - * It returns the response to be send. - * - * @param string $type Entries type: unread, starred or archive - * @param Request $request - * @param int $page - * - * @return \Symfony\Component\HttpFoundation\Response - */ - private function showEntries($type, Request $request, $page) - { - $repository = $this->get('wallabag_core.entry_repository'); - $searchTerm = (isset($request->get('search_entry')['term']) ? $request->get('search_entry')['term'] : ''); - $currentRoute = (!is_null($request->query->get('currentRoute')) ? $request->query->get('currentRoute') : ''); - - switch ($type) { - case 'search': - $qb = $repository->getBuilderForSearchByUser($this->getUser()->getId(), $searchTerm, $currentRoute); - - break; - case 'untagged': - $qb = $repository->getBuilderForUntaggedByUser($this->getUser()->getId()); - - break; - case 'starred': - $qb = $repository->getBuilderForStarredByUser($this->getUser()->getId()); - break; - - case 'archive': - $qb = $repository->getBuilderForArchiveByUser($this->getUser()->getId()); - break; - - case 'unread': - $qb = $repository->getBuilderForUnreadByUser($this->getUser()->getId()); - break; - - case 'all': - $qb = $repository->getBuilderForAllByUser($this->getUser()->getId()); - break; - - default: - throw new \InvalidArgumentException(sprintf('Type "%s" is not implemented.', $type)); - } - - $form = $this->createForm(EntryFilterType::class); - - if ($request->query->has($form->getName())) { - // manually bind values from the request - $form->submit($request->query->get($form->getName())); - - // build the query from the given form object - $this->get('lexik_form_filter.query_builder_updater')->addFilterConditions($form, $qb); - } - - $pagerAdapter = new DoctrineORMAdapter($qb->getQuery(), true, false); - - $entries = $this->get('wallabag_core.helper.prepare_pager_for_entries')->prepare($pagerAdapter); - - try { - $entries->setCurrentPage($page); - } catch (OutOfRangeCurrentPageException $e) { - if ($page > 1) { - return $this->redirect($this->generateUrl($type, ['page' => $entries->getNbPages()]), 302); - } - } - - return $this->render( - 'WallabagCoreBundle:Entry:entries.html.twig', [ - 'form' => $form->createView(), - 'entries' => $entries, - 'currentPage' => $page, - 'searchTerm' => $searchTerm, - ] - ); - } - /** * Shows entry content. * @@ -487,37 +385,13 @@ class EntryController extends Controller // don't redirect user to the deleted entry (check that the referer doesn't end with the same url) $referer = $request->headers->get('referer'); - $to = (1 !== preg_match('#'.$url.'$#i', $referer) ? $referer : null); + $to = (1 !== preg_match('#' . $url . '$#i', $referer) ? $referer : null); $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($to); return $this->redirect($redirectUrl); } - /** - * Check if the logged user can manage the given entry. - * - * @param Entry $entry - */ - private function checkUserAction(Entry $entry) - { - if (null === $this->getUser() || $this->getUser()->getId() != $entry->getUser()->getId()) { - throw $this->createAccessDeniedException('You can not access this entry.'); - } - } - - /** - * Check for existing entry, if it exists, redirect to it with a message. - * - * @param Entry $entry - * - * @return Entry|bool - */ - private function checkIfEntryAlreadyExists(Entry $entry) - { - return $this->get('wallabag_core.entry_repository')->findByUrlAndUserId($entry->getUrl(), $this->getUser()->getId()); - } - /** * Get public URL for entry (and generate it if necessary). * @@ -604,4 +478,126 @@ class EntryController extends Controller { return $this->showEntries('untagged', $request, $page); } + + /** + * Fetch content and update entry. + * In case it fails, $entry->getContent will return an error message. + * + * @param Entry $entry + * @param string $prefixMessage Should be the translation key: entry_saved or entry_reloaded + */ + private function updateEntry(Entry $entry, $prefixMessage = 'entry_saved') + { + $message = 'flashes.entry.notice.' . $prefixMessage; + + try { + $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl()); + } catch (\Exception $e) { + $this->get('logger')->error('Error while saving an entry', [ + 'exception' => $e, + 'entry' => $entry, + ]); + + $message = 'flashes.entry.notice.' . $prefixMessage . '_failed'; + } + + $this->get('session')->getFlashBag()->add('notice', $message); + } + + /** + * Global method to retrieve entries depending on the given type + * It returns the response to be send. + * + * @param string $type Entries type: unread, starred or archive + * @param Request $request + * @param int $page + * + * @return \Symfony\Component\HttpFoundation\Response + */ + private function showEntries($type, Request $request, $page) + { + $repository = $this->get('wallabag_core.entry_repository'); + $searchTerm = (isset($request->get('search_entry')['term']) ? $request->get('search_entry')['term'] : ''); + $currentRoute = (null !== $request->query->get('currentRoute') ? $request->query->get('currentRoute') : ''); + + switch ($type) { + case 'search': + $qb = $repository->getBuilderForSearchByUser($this->getUser()->getId(), $searchTerm, $currentRoute); + + break; + case 'untagged': + $qb = $repository->getBuilderForUntaggedByUser($this->getUser()->getId()); + + break; + case 'starred': + $qb = $repository->getBuilderForStarredByUser($this->getUser()->getId()); + break; + case 'archive': + $qb = $repository->getBuilderForArchiveByUser($this->getUser()->getId()); + break; + case 'unread': + $qb = $repository->getBuilderForUnreadByUser($this->getUser()->getId()); + break; + case 'all': + $qb = $repository->getBuilderForAllByUser($this->getUser()->getId()); + break; + default: + throw new \InvalidArgumentException(sprintf('Type "%s" is not implemented.', $type)); + } + + $form = $this->createForm(EntryFilterType::class); + + if ($request->query->has($form->getName())) { + // manually bind values from the request + $form->submit($request->query->get($form->getName())); + + // build the query from the given form object + $this->get('lexik_form_filter.query_builder_updater')->addFilterConditions($form, $qb); + } + + $pagerAdapter = new DoctrineORMAdapter($qb->getQuery(), true, false); + + $entries = $this->get('wallabag_core.helper.prepare_pager_for_entries')->prepare($pagerAdapter); + + try { + $entries->setCurrentPage($page); + } catch (OutOfRangeCurrentPageException $e) { + if ($page > 1) { + return $this->redirect($this->generateUrl($type, ['page' => $entries->getNbPages()]), 302); + } + } + + return $this->render( + 'WallabagCoreBundle:Entry:entries.html.twig', [ + 'form' => $form->createView(), + 'entries' => $entries, + 'currentPage' => $page, + 'searchTerm' => $searchTerm, + ] + ); + } + + /** + * Check if the logged user can manage the given entry. + * + * @param Entry $entry + */ + private function checkUserAction(Entry $entry) + { + if (null === $this->getUser() || $this->getUser()->getId() !== $entry->getUser()->getId()) { + throw $this->createAccessDeniedException('You can not access this entry.'); + } + } + + /** + * Check for existing entry, if it exists, redirect to it with a message. + * + * @param Entry $entry + * + * @return Entry|bool + */ + private function checkIfEntryAlreadyExists(Entry $entry) + { + return $this->get('wallabag_core.entry_repository')->findByUrlAndUserId($entry->getUrl(), $this->getUser()->getId()); + } } diff --git a/src/Wallabag/CoreBundle/Controller/ExceptionController.php b/src/Wallabag/CoreBundle/Controller/ExceptionController.php index abfa9c2f..461309ea 100644 --- a/src/Wallabag/CoreBundle/Controller/ExceptionController.php +++ b/src/Wallabag/CoreBundle/Controller/ExceptionController.php @@ -14,7 +14,7 @@ class ExceptionController extends BaseExceptionController protected function findTemplate(Request $request, $format, $code, $showException) { $name = $showException ? 'exception' : 'error'; - if ($showException && 'html' == $format) { + if ($showException && 'html' === $format) { $name = 'exception_full'; } diff --git a/src/Wallabag/CoreBundle/Controller/ExportController.php b/src/Wallabag/CoreBundle/Controller/ExportController.php index fda04cfb..6fad122e 100644 --- a/src/Wallabag/CoreBundle/Controller/ExportController.php +++ b/src/Wallabag/CoreBundle/Controller/ExportController.php @@ -55,10 +55,10 @@ class ExportController extends Controller public function downloadEntriesAction(Request $request, $format, $category) { $method = ucfirst($category); - $methodBuilder = 'getBuilderFor'.$method.'ByUser'; + $methodBuilder = 'getBuilderFor' . $method . 'ByUser'; $repository = $this->get('wallabag_core.entry_repository'); - if ($category == 'tag_entries') { + if ($category === 'tag_entries') { $tag = $this->get('wallabag_core.tag_repository')->findOneBySlug($request->query->get('tag')); $entries = $repository->findAllByTagId( diff --git a/src/Wallabag/CoreBundle/Controller/RssController.php b/src/Wallabag/CoreBundle/Controller/RssController.php index e87dd9a1..e84044b1 100644 --- a/src/Wallabag/CoreBundle/Controller/RssController.php +++ b/src/Wallabag/CoreBundle/Controller/RssController.php @@ -2,19 +2,19 @@ namespace Wallabag\CoreBundle\Controller; -use Pagerfanta\Adapter\DoctrineORMAdapter; use Pagerfanta\Adapter\ArrayAdapter; +use Pagerfanta\Adapter\DoctrineORMAdapter; use Pagerfanta\Exception\OutOfRangeCurrentPageException; use Pagerfanta\Pagerfanta; use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; +use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; -use Symfony\Bundle\FrameworkBundle\Controller\Controller; +use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Wallabag\CoreBundle\Entity\Entry; use Wallabag\CoreBundle\Entity\Tag; use Wallabag\UserBundle\Entity\User; -use Symfony\Component\Routing\Generator\UrlGeneratorInterface; class RssController extends Controller { @@ -113,7 +113,7 @@ class RssController extends Controller $entries->setCurrentPage($page); } catch (OutOfRangeCurrentPageException $e) { if ($page > 1) { - return $this->redirect($url.'?page='.$entries->getNbPages(), 302); + return $this->redirect($url . '?page=' . $entries->getNbPages(), 302); } } @@ -121,7 +121,7 @@ class RssController extends Controller '@WallabagCore/themes/common/Entry/entries.xml.twig', [ 'url_html' => $this->generateUrl('tag_entries', ['slug' => $tag->getSlug()], UrlGeneratorInterface::ABSOLUTE_URL), - 'type' => 'tag ('.$tag->getLabel().')', + 'type' => 'tag (' . $tag->getLabel() . ')', 'url' => $url, 'entries' => $entries, ], @@ -147,19 +147,15 @@ class RssController extends Controller case 'starred': $qb = $repository->getBuilderForStarredByUser($user->getId()); break; - case 'archive': $qb = $repository->getBuilderForArchiveByUser($user->getId()); break; - case 'unread': $qb = $repository->getBuilderForUnreadByUser($user->getId()); break; - case 'all': $qb = $repository->getBuilderForAllByUser($user->getId()); break; - default: throw new \InvalidArgumentException(sprintf('Type "%s" is not implemented.', $type)); } @@ -171,7 +167,7 @@ class RssController extends Controller $entries->setMaxPerPage($perPage); $url = $this->generateUrl( - $type.'_rss', + $type . '_rss', [ 'username' => $user->getUsername(), 'token' => $user->getConfig()->getRssToken(), @@ -183,7 +179,7 @@ class RssController extends Controller $entries->setCurrentPage((int) $page); } catch (OutOfRangeCurrentPageException $e) { if ($page > 1) { - return $this->redirect($url.'?page='.$entries->getNbPages(), 302); + return $this->redirect($url . '?page=' . $entries->getNbPages(), 302); } } diff --git a/src/Wallabag/CoreBundle/Controller/SiteCredentialController.php b/src/Wallabag/CoreBundle/Controller/SiteCredentialController.php index 98781dab..fa2066dc 100644 --- a/src/Wallabag/CoreBundle/Controller/SiteCredentialController.php +++ b/src/Wallabag/CoreBundle/Controller/SiteCredentialController.php @@ -2,12 +2,12 @@ namespace Wallabag\CoreBundle\Controller; -use Symfony\Component\HttpFoundation\Request; -use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; -use Wallabag\UserBundle\Entity\User; +use Symfony\Bundle\FrameworkBundle\Controller\Controller; +use Symfony\Component\HttpFoundation\Request; use Wallabag\CoreBundle\Entity\SiteCredential; +use Wallabag\UserBundle\Entity\User; /** * SiteCredential controller. @@ -167,7 +167,7 @@ class SiteCredentialController extends Controller */ private function checkUserAction(SiteCredential $siteCredential) { - if (null === $this->getUser() || $this->getUser()->getId() != $siteCredential->getUser()->getId()) { + if (null === $this->getUser() || $this->getUser()->getId() !== $siteCredential->getUser()->getId()) { throw $this->createAccessDeniedException('You can not access this site credential.'); } } diff --git a/src/Wallabag/CoreBundle/Controller/StaticController.php b/src/Wallabag/CoreBundle/Controller/StaticController.php index 82714217..318af303 100644 --- a/src/Wallabag/CoreBundle/Controller/StaticController.php +++ b/src/Wallabag/CoreBundle/Controller/StaticController.php @@ -16,7 +16,9 @@ class StaticController extends Controller return $this->render( '@WallabagCore/themes/common/Static/howto.html.twig', - ['addonsUrl' => $addonsUrl] + [ + 'addonsUrl' => $addonsUrl, + ] ); } @@ -40,8 +42,7 @@ class StaticController extends Controller public function quickstartAction() { return $this->render( - '@WallabagCore/themes/common/Static/quickstart.html.twig', - [] + '@WallabagCore/themes/common/Static/quickstart.html.twig' ); } } diff --git a/src/Wallabag/CoreBundle/Controller/TagController.php b/src/Wallabag/CoreBundle/Controller/TagController.php index a8b1eadd..f2ca58c6 100644 --- a/src/Wallabag/CoreBundle/Controller/TagController.php +++ b/src/Wallabag/CoreBundle/Controller/TagController.php @@ -4,13 +4,13 @@ namespace Wallabag\CoreBundle\Controller; use Pagerfanta\Adapter\ArrayAdapter; use Pagerfanta\Exception\OutOfRangeCurrentPageException; +use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Wallabag\CoreBundle\Entity\Entry; use Wallabag\CoreBundle\Entity\Tag; use Wallabag\CoreBundle\Form\Type\NewTagType; -use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; class TagController extends Controller { diff --git a/src/Wallabag/CoreBundle/DataFixtures/ORM/LoadSettingData.php b/src/Wallabag/CoreBundle/DataFixtures/ORM/LoadSettingData.php index a52288e6..3fe88e7f 100644 --- a/src/Wallabag/CoreBundle/DataFixtures/ORM/LoadSettingData.php +++ b/src/Wallabag/CoreBundle/DataFixtures/ORM/LoadSettingData.php @@ -2,10 +2,10 @@ namespace Wallabag\CoreBundle\DataFixtures\ORM; +use Craue\ConfigBundle\Entity\Setting; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\OrderedFixtureInterface; use Doctrine\Common\Persistence\ObjectManager; -use Craue\ConfigBundle\Entity\Setting; use Symfony\Component\DependencyInjection\ContainerAwareInterface; use Symfony\Component\DependencyInjection\ContainerInterface; diff --git a/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php b/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php index 532ce238..a3ef2b53 100644 --- a/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php +++ b/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php @@ -31,7 +31,7 @@ class WallabagCoreExtension extends Extension $container->setParameter('wallabag_core.default_internal_settings', $config['default_internal_settings']); $container->setParameter('wallabag_core.site_credentials.encryption_key_path', $config['encryption_key_path']); - $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); + $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); $loader->load('services.yml'); $loader->load('parameters.yml'); } diff --git a/src/Wallabag/CoreBundle/Entity/Entry.php b/src/Wallabag/CoreBundle/Entity/Entry.php index a0503c39..581e8906 100644 --- a/src/Wallabag/CoreBundle/Entity/Entry.php +++ b/src/Wallabag/CoreBundle/Entity/Entry.php @@ -5,14 +5,14 @@ namespace Wallabag\CoreBundle\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; use Hateoas\Configuration\Annotation as Hateoas; -use JMS\Serializer\Annotation\Groups; -use JMS\Serializer\Annotation\XmlRoot; use JMS\Serializer\Annotation\Exclude; -use JMS\Serializer\Annotation\VirtualProperty; +use JMS\Serializer\Annotation\Groups; use JMS\Serializer\Annotation\SerializedName; +use JMS\Serializer\Annotation\VirtualProperty; +use JMS\Serializer\Annotation\XmlRoot; use Symfony\Component\Validator\Constraints as Assert; -use Wallabag\UserBundle\Entity\User; use Wallabag\AnnotationBundle\Entity\Annotation; +use Wallabag\UserBundle\Entity\User; /** * Entry. @@ -478,7 +478,7 @@ class Entry */ public function timestamps() { - if (is_null($this->createdAt)) { + if (null === $this->createdAt) { $this->createdAt = new \DateTime(); } diff --git a/src/Wallabag/CoreBundle/Entity/SiteCredential.php b/src/Wallabag/CoreBundle/Entity/SiteCredential.php index 58075e92..380f820d 100644 --- a/src/Wallabag/CoreBundle/Entity/SiteCredential.php +++ b/src/Wallabag/CoreBundle/Entity/SiteCredential.php @@ -188,7 +188,7 @@ class SiteCredential */ public function timestamps() { - if (is_null($this->createdAt)) { + if (null === $this->createdAt) { $this->createdAt = new \DateTime(); } } diff --git a/src/Wallabag/CoreBundle/Entity/Tag.php b/src/Wallabag/CoreBundle/Entity/Tag.php index 4b480ff1..c19023af 100644 --- a/src/Wallabag/CoreBundle/Entity/Tag.php +++ b/src/Wallabag/CoreBundle/Entity/Tag.php @@ -4,9 +4,9 @@ namespace Wallabag\CoreBundle\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; +use Gedmo\Mapping\Annotation as Gedmo; use JMS\Serializer\Annotation\ExclusionPolicy; use JMS\Serializer\Annotation\Expose; -use Gedmo\Mapping\Annotation as Gedmo; use JMS\Serializer\Annotation\XmlRoot; /** diff --git a/src/Wallabag/CoreBundle/Event/Subscriber/DownloadImagesSubscriber.php b/src/Wallabag/CoreBundle/Event/Subscriber/DownloadImagesSubscriber.php index 4ebe837b..1dd0a1a4 100644 --- a/src/Wallabag/CoreBundle/Event/Subscriber/DownloadImagesSubscriber.php +++ b/src/Wallabag/CoreBundle/Event/Subscriber/DownloadImagesSubscriber.php @@ -2,13 +2,13 @@ namespace Wallabag\CoreBundle\Event\Subscriber; -use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Doctrine\ORM\EntityManager; use Psr\Log\LoggerInterface; -use Wallabag\CoreBundle\Helper\DownloadImages; +use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Wallabag\CoreBundle\Entity\Entry; -use Wallabag\CoreBundle\Event\EntrySavedEvent; use Wallabag\CoreBundle\Event\EntryDeletedEvent; -use Doctrine\ORM\EntityManager; +use Wallabag\CoreBundle\Event\EntrySavedEvent; +use Wallabag\CoreBundle\Helper\DownloadImages; class DownloadImagesSubscriber implements EventSubscriberInterface { diff --git a/src/Wallabag/CoreBundle/Event/Subscriber/SQLiteCascadeDeleteSubscriber.php b/src/Wallabag/CoreBundle/Event/Subscriber/SQLiteCascadeDeleteSubscriber.php index 5e6af8cc..9c1d8a1d 100644 --- a/src/Wallabag/CoreBundle/Event/Subscriber/SQLiteCascadeDeleteSubscriber.php +++ b/src/Wallabag/CoreBundle/Event/Subscriber/SQLiteCascadeDeleteSubscriber.php @@ -2,10 +2,10 @@ namespace Wallabag\CoreBundle\Event\Subscriber; +use Doctrine\Bundle\DoctrineBundle\Registry; use Doctrine\Common\EventSubscriber; use Doctrine\ORM\Event\LifecycleEventArgs; use Wallabag\CoreBundle\Entity\Entry; -use Doctrine\Bundle\DoctrineBundle\Registry; /** * SQLite doesn't care about cascading remove, so we need to manually remove associated stuf for an Entry. diff --git a/src/Wallabag/CoreBundle/Event/Subscriber/TablePrefixSubscriber.php b/src/Wallabag/CoreBundle/Event/Subscriber/TablePrefixSubscriber.php index 711c3bf8..35902654 100644 --- a/src/Wallabag/CoreBundle/Event/Subscriber/TablePrefixSubscriber.php +++ b/src/Wallabag/CoreBundle/Event/Subscriber/TablePrefixSubscriber.php @@ -39,12 +39,12 @@ class TablePrefixSubscriber implements EventSubscriber return; } - $classMetadata->setPrimaryTable(['name' => $this->prefix.$classMetadata->getTableName()]); + $classMetadata->setPrimaryTable(['name' => $this->prefix . $classMetadata->getTableName()]); foreach ($classMetadata->getAssociationMappings() as $fieldName => $mapping) { if ($mapping['type'] === ClassMetadataInfo::MANY_TO_MANY && isset($classMetadata->associationMappings[$fieldName]['joinTable']['name'])) { $mappedTableName = $classMetadata->associationMappings[$fieldName]['joinTable']['name']; - $classMetadata->associationMappings[$fieldName]['joinTable']['name'] = $this->prefix.$mappedTableName; + $classMetadata->associationMappings[$fieldName]['joinTable']['name'] = $this->prefix . $mappedTableName; } } } diff --git a/src/Wallabag/CoreBundle/Form/Type/EntryFilterType.php b/src/Wallabag/CoreBundle/Form/Type/EntryFilterType.php index 6a4c485f..6f8c9e27 100644 --- a/src/Wallabag/CoreBundle/Form/Type/EntryFilterType.php +++ b/src/Wallabag/CoreBundle/Form/Type/EntryFilterType.php @@ -4,12 +4,12 @@ namespace Wallabag\CoreBundle\Form\Type; use Doctrine\ORM\EntityRepository; use Lexik\Bundle\FormFilterBundle\Filter\FilterOperands; -use Lexik\Bundle\FormFilterBundle\Filter\Query\QueryInterface; -use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\NumberRangeFilterType; -use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\DateRangeFilterType; -use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\TextFilterType; use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\CheckboxFilterType; use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\ChoiceFilterType; +use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\DateRangeFilterType; +use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\NumberRangeFilterType; +use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\TextFilterType; +use Lexik\Bundle\FormFilterBundle\Filter\Query\QueryInterface; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\HttpFoundation\Response; @@ -99,7 +99,7 @@ class EntryFilterType extends AbstractType if (strlen($value) <= 2 || empty($value)) { return; } - $expression = $filterQuery->getExpr()->like($field, $filterQuery->getExpr()->lower($filterQuery->getExpr()->literal('%'.$value.'%'))); + $expression = $filterQuery->getExpr()->like($field, $filterQuery->getExpr()->lower($filterQuery->getExpr()->literal('%' . $value . '%'))); return $filterQuery->createCondition($expression); }, @@ -113,8 +113,8 @@ class EntryFilterType extends AbstractType } $paramName = sprintf('%s', str_replace('.', '_', $field)); - $expression = $filterQuery->getExpr()->eq($field, ':'.$paramName); - $parameters = array($paramName => $value); + $expression = $filterQuery->getExpr()->eq($field, ':' . $paramName); + $parameters = [$paramName => $value]; return $filterQuery->createCondition($expression, $parameters); }, @@ -158,7 +158,7 @@ class EntryFilterType extends AbstractType // is_public isn't a real field // we should use the "uid" field to determine if the entry has been made public - $expression = $filterQuery->getExpr()->isNotNull($values['alias'].'.uid'); + $expression = $filterQuery->getExpr()->isNotNull($values['alias'] . '.uid'); return $filterQuery->createCondition($expression); }, diff --git a/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php b/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php index a79e6ebe..10689c62 100644 --- a/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php +++ b/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php @@ -6,8 +6,8 @@ use BD\GuzzleSiteAuthenticator\SiteConfig\SiteConfig; use BD\GuzzleSiteAuthenticator\SiteConfig\SiteConfigBuilder; use Graby\SiteConfig\ConfigBuilder; use Psr\Log\LoggerInterface; -use Wallabag\CoreBundle\Repository\SiteCredentialRepository; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage; +use Wallabag\CoreBundle\Repository\SiteCredentialRepository; class GrabySiteConfigBuilder implements SiteConfigBuilder { @@ -57,7 +57,7 @@ class GrabySiteConfigBuilder implements SiteConfigBuilder { // required by credentials below $host = strtolower($host); - if (substr($host, 0, 4) == 'www.') { + if (substr($host, 0, 4) === 'www.') { $host = substr($host, 4); } diff --git a/src/Wallabag/CoreBundle/Helper/ContentProxy.php b/src/Wallabag/CoreBundle/Helper/ContentProxy.php index 51bb2ca2..ddecd6f4 100644 --- a/src/Wallabag/CoreBundle/Helper/ContentProxy.php +++ b/src/Wallabag/CoreBundle/Helper/ContentProxy.php @@ -4,12 +4,12 @@ namespace Wallabag\CoreBundle\Helper; use Graby\Graby; use Psr\Log\LoggerInterface; -use Wallabag\CoreBundle\Entity\Entry; -use Wallabag\CoreBundle\Tools\Utils; use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeExtensionGuesser; use Symfony\Component\Validator\Constraints\Locale as LocaleConstraint; use Symfony\Component\Validator\Constraints\Url as UrlConstraint; use Symfony\Component\Validator\Validator\ValidatorInterface; +use Wallabag\CoreBundle\Entity\Entry; +use Wallabag\CoreBundle\Tools\Utils; /** * This kind of proxy class take care of getting the content from an url @@ -100,7 +100,7 @@ class ContentProxy // is it a timestamp? if (filter_var($date, FILTER_VALIDATE_INT) !== false) { - $date = '@'.$content['date']; + $date = '@' . $content['date']; } try { @@ -189,7 +189,7 @@ class ContentProxy return; } - $this->logger->warning('Language validation failed. '.(string) $errors); + $this->logger->warning('Language validation failed. ' . (string) $errors); } /** @@ -211,6 +211,6 @@ class ContentProxy return; } - $this->logger->warning('PreviewPicture validation failed. '.(string) $errors); + $this->logger->warning('PreviewPicture validation failed. ' . (string) $errors); } } diff --git a/src/Wallabag/CoreBundle/Helper/CryptoProxy.php b/src/Wallabag/CoreBundle/Helper/CryptoProxy.php index e8b19cb9..7d8c9888 100644 --- a/src/Wallabag/CoreBundle/Helper/CryptoProxy.php +++ b/src/Wallabag/CoreBundle/Helper/CryptoProxy.php @@ -2,10 +2,10 @@ namespace Wallabag\CoreBundle\Helper; -use Psr\Log\LoggerInterface; -use Defuse\Crypto\Key; use Defuse\Crypto\Crypto; use Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException; +use Defuse\Crypto\Key; +use Psr\Log\LoggerInterface; /** * This is a proxy to crypt and decrypt password used by SiteCredential entity. @@ -39,7 +39,7 @@ class CryptoProxy */ public function crypt($secretValue) { - $this->logger->debug('Crypto: crypting value: '.$this->mask($secretValue)); + $this->logger->debug('Crypto: crypting value: ' . $this->mask($secretValue)); return Crypto::encrypt($secretValue, $this->loadKey()); } @@ -53,12 +53,12 @@ class CryptoProxy */ public function decrypt($cryptedValue) { - $this->logger->debug('Crypto: decrypting value: '.$this->mask($cryptedValue)); + $this->logger->debug('Crypto: decrypting value: ' . $this->mask($cryptedValue)); try { return Crypto::decrypt($cryptedValue, $this->loadKey()); } catch (WrongKeyOrModifiedCiphertextException $e) { - throw new \RuntimeException('Decrypt fail: '.$e->getMessage()); + throw new \RuntimeException('Decrypt fail: ' . $e->getMessage()); } } @@ -81,6 +81,6 @@ class CryptoProxy */ private function mask($value) { - return strlen($value) > 0 ? $value[0].'*****'.$value[strlen($value) - 1] : 'Empty value'; + return strlen($value) > 0 ? $value[0] . '*****' . $value[strlen($value) - 1] : 'Empty value'; } } diff --git a/src/Wallabag/CoreBundle/Helper/DetectActiveTheme.php b/src/Wallabag/CoreBundle/Helper/DetectActiveTheme.php index 23e98042..9f90ee3e 100644 --- a/src/Wallabag/CoreBundle/Helper/DetectActiveTheme.php +++ b/src/Wallabag/CoreBundle/Helper/DetectActiveTheme.php @@ -44,7 +44,7 @@ class DetectActiveTheme implements DeviceDetectionInterface { $token = $this->tokenStorage->getToken(); - if (is_null($token)) { + if (null === $token) { return $this->defaultTheme; } diff --git a/src/Wallabag/CoreBundle/Helper/DownloadImages.php b/src/Wallabag/CoreBundle/Helper/DownloadImages.php index ed888cdb..252ba57c 100644 --- a/src/Wallabag/CoreBundle/Helper/DownloadImages.php +++ b/src/Wallabag/CoreBundle/Helper/DownloadImages.php @@ -2,12 +2,12 @@ namespace Wallabag\CoreBundle\Helper; -use Psr\Log\LoggerInterface; -use Symfony\Component\DomCrawler\Crawler; use GuzzleHttp\Client; use GuzzleHttp\Message\Response; -use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeExtensionGuesser; +use Psr\Log\LoggerInterface; +use Symfony\Component\DomCrawler\Crawler; use Symfony\Component\Finder\Finder; +use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeExtensionGuesser; class DownloadImages { @@ -30,17 +30,6 @@ class DownloadImages $this->setFolder(); } - /** - * Setup base folder where all images are going to be saved. - */ - private function setFolder() - { - // if folder doesn't exist, attempt to create one and store the folder name in property $folder - if (!file_exists($this->baseFolder)) { - mkdir($this->baseFolder, 0755, true); - } - } - /** * Process the html and extract image from it, save them to local and return the updated html. * @@ -97,9 +86,9 @@ class DownloadImages $relativePath = $this->getRelativePath($entryId); } - $this->logger->debug('DownloadImages: working on image: '.$imagePath); + $this->logger->debug('DownloadImages: working on image: ' . $imagePath); - $folderPath = $this->baseFolder.'/'.$relativePath; + $folderPath = $this->baseFolder . '/' . $relativePath; // build image path $absolutePath = $this->getAbsoluteLink($url, $imagePath); @@ -123,7 +112,7 @@ class DownloadImages } $hashImage = hash('crc32', $absolutePath); - $localPath = $folderPath.'/'.$hashImage.'.'.$ext; + $localPath = $folderPath . '/' . $hashImage . '.' . $ext; try { $im = imagecreatefromstring($res->getBody()); @@ -156,7 +145,7 @@ class DownloadImages imagedestroy($im); - return $this->wallabagUrl.'/assets/images/'.$relativePath.'/'.$hashImage.'.'.$ext; + return $this->wallabagUrl . '/assets/images/' . $relativePath . '/' . $hashImage . '.' . $ext; } /** @@ -167,7 +156,7 @@ class DownloadImages public function removeImages($entryId) { $relativePath = $this->getRelativePath($entryId); - $folderPath = $this->baseFolder.'/'.$relativePath; + $folderPath = $this->baseFolder . '/' . $relativePath; $finder = new Finder(); $finder @@ -182,6 +171,17 @@ class DownloadImages @rmdir($folderPath); } + /** + * Setup base folder where all images are going to be saved. + */ + private function setFolder() + { + // if folder doesn't exist, attempt to create one and store the folder name in property $folder + if (!file_exists($this->baseFolder)) { + mkdir($this->baseFolder, 0755, true); + } + } + /** * Generate the folder where we are going to save images based on the entry url. * @@ -192,8 +192,8 @@ class DownloadImages private function getRelativePath($entryId) { $hashId = hash('crc32', $entryId); - $relativePath = $hashId[0].'/'.$hashId[1].'/'.$hashId; - $folderPath = $this->baseFolder.'/'.$relativePath; + $relativePath = $hashId[0] . '/' . $hashId[1] . '/' . $hashId; + $folderPath = $this->baseFolder . '/' . $relativePath; if (!file_exists($folderPath)) { mkdir($folderPath, 0777, true); @@ -270,7 +270,7 @@ class DownloadImages } if (!in_array($ext, ['jpeg', 'jpg', 'gif', 'png'], true)) { - $this->logger->error('DownloadImages: Processed image with not allowed extension. Skipping: '.$imagePath); + $this->logger->error('DownloadImages: Processed image with not allowed extension. Skipping: ' . $imagePath); return false; } diff --git a/src/Wallabag/CoreBundle/Helper/EntriesExport.php b/src/Wallabag/CoreBundle/Helper/EntriesExport.php index 3d36a4c8..cd74cc4f 100644 --- a/src/Wallabag/CoreBundle/Helper/EntriesExport.php +++ b/src/Wallabag/CoreBundle/Helper/EntriesExport.php @@ -63,7 +63,7 @@ class EntriesExport */ public function updateTitle($method) { - $this->title = $method.' articles'; + $this->title = $method . ' articles'; if ('entry' === $method) { $this->title = $this->entries[0]->getTitle(); @@ -81,7 +81,7 @@ class EntriesExport */ public function exportAs($format) { - $functionName = 'produce'.ucfirst($format); + $functionName = 'produce' . ucfirst($format); if (method_exists($this, $functionName)) { return $this->$functionName(); } @@ -106,12 +106,12 @@ class EntriesExport */ $content_start = "\n" - ."\n" - .'' - ."\n" - ."wallabag articles book\n" - ."\n" - ."\n"; + . "\n" + . '' + . "\n" + . "wallabag articles book\n" + . "\n" + . "\n"; $bookEnd = "\n\n"; @@ -164,11 +164,11 @@ class EntriesExport // in filenames, we limit to A-z/0-9 $filename = preg_replace('/[^A-Za-z0-9\-]/', '', $entry->getTitle()); - $chapter = $content_start.$entry->getContent().$bookEnd; - $book->addChapter($entry->getTitle(), htmlspecialchars($filename).'.html', $chapter, true, EPub::EXTERNAL_REF_ADD); + $chapter = $content_start . $entry->getContent() . $bookEnd; + $book->addChapter($entry->getTitle(), htmlspecialchars($filename) . '.html', $chapter, true, EPub::EXTERNAL_REF_ADD); } - $book->addChapter('Notices', 'Cover2.html', $content_start.$this->getExportInformation('PHPePub').$bookEnd); + $book->addChapter('Notices', 'Cover2.html', $content_start . $this->getExportInformation('PHPePub') . $bookEnd); return Response::create( $book->getBook(), @@ -176,7 +176,7 @@ class EntriesExport [ 'Content-Description' => 'File Transfer', 'Content-type' => 'application/epub+zip', - 'Content-Disposition' => 'attachment; filename="'.$this->title.'.epub"', + 'Content-Disposition' => 'attachment; filename="' . $this->title . '.epub"', 'Content-Transfer-Encoding' => 'binary', ] ); @@ -228,7 +228,7 @@ class EntriesExport 'Accept-Ranges' => 'bytes', 'Content-Description' => 'File Transfer', 'Content-type' => 'application/x-mobipocket-ebook', - 'Content-Disposition' => 'attachment; filename="'.$this->title.'.mobi"', + 'Content-Disposition' => 'attachment; filename="' . $this->title . '.mobi"', 'Content-Transfer-Encoding' => 'binary', ] ); @@ -256,7 +256,7 @@ class EntriesExport * Front page */ $pdf->AddPage(); - $intro = '

    '.$this->title.'

    '.$this->getExportInformation('tcpdf'); + $intro = '

    ' . $this->title . '

    ' . $this->getExportInformation('tcpdf'); $pdf->writeHTMLCell(0, 0, '', '', $intro, 0, 1, 0, true, '', true); @@ -269,7 +269,7 @@ class EntriesExport } $pdf->AddPage(); - $html = '

    '.$entry->getTitle().'

    '; + $html = '

    ' . $entry->getTitle() . '

    '; $html .= $entry->getContent(); $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true); @@ -284,7 +284,7 @@ class EntriesExport [ 'Content-Description' => 'File Transfer', 'Content-type' => 'application/pdf', - 'Content-Disposition' => 'attachment; filename="'.$this->title.'.pdf"', + 'Content-Disposition' => 'attachment; filename="' . $this->title . '.pdf"', 'Content-Transfer-Encoding' => 'binary', ] ); @@ -330,7 +330,7 @@ class EntriesExport 200, [ 'Content-type' => 'application/csv', - 'Content-Disposition' => 'attachment; filename="'.$this->title.'.csv"', + 'Content-Disposition' => 'attachment; filename="' . $this->title . '.csv"', 'Content-Transfer-Encoding' => 'UTF-8', ] ); @@ -348,7 +348,7 @@ class EntriesExport 200, [ 'Content-type' => 'application/json', - 'Content-Disposition' => 'attachment; filename="'.$this->title.'.json"', + 'Content-Disposition' => 'attachment; filename="' . $this->title . '.json"', 'Content-Transfer-Encoding' => 'UTF-8', ] ); @@ -366,7 +366,7 @@ class EntriesExport 200, [ 'Content-type' => 'application/xml', - 'Content-Disposition' => 'attachment; filename="'.$this->title.'.xml"', + 'Content-Disposition' => 'attachment; filename="' . $this->title . '.xml"', 'Content-Transfer-Encoding' => 'UTF-8', ] ); @@ -382,8 +382,8 @@ class EntriesExport $content = ''; $bar = str_repeat('=', 100); foreach ($this->entries as $entry) { - $content .= "\n\n".$bar."\n\n".$entry->getTitle()."\n\n".$bar."\n\n"; - $content .= trim(preg_replace('/\s+/S', ' ', strip_tags($entry->getContent())))."\n\n"; + $content .= "\n\n" . $bar . "\n\n" . $entry->getTitle() . "\n\n" . $bar . "\n\n"; + $content .= trim(preg_replace('/\s+/S', ' ', strip_tags($entry->getContent()))) . "\n\n"; } return Response::create( @@ -391,7 +391,7 @@ class EntriesExport 200, [ 'Content-type' => 'text/plain', - 'Content-Disposition' => 'attachment; filename="'.$this->title.'.txt"', + 'Content-Disposition' => 'attachment; filename="' . $this->title . '.txt"', 'Content-Transfer-Encoding' => 'UTF-8', ] ); @@ -427,7 +427,7 @@ class EntriesExport $info = str_replace('%EXPORT_METHOD%', $type, $this->footerTemplate); if ('tcpdf' === $type) { - return str_replace('%IMAGE%', '', $info); + return str_replace('%IMAGE%', '', $info); } return str_replace('%IMAGE%', '', $info); diff --git a/src/Wallabag/CoreBundle/Helper/HttpClientFactory.php b/src/Wallabag/CoreBundle/Helper/HttpClientFactory.php index 43f5b119..4602a684 100644 --- a/src/Wallabag/CoreBundle/Helper/HttpClientFactory.php +++ b/src/Wallabag/CoreBundle/Helper/HttpClientFactory.php @@ -41,7 +41,7 @@ class HttpClientFactory */ public function buildHttpClient() { - $this->logger->log('debug', 'Restricted access config enabled?', array('enabled' => (int) $this->restrictedAccess)); + $this->logger->log('debug', 'Restricted access config enabled?', ['enabled' => (int) $this->restrictedAccess]); if (0 === (int) $this->restrictedAccess) { return; diff --git a/src/Wallabag/CoreBundle/Helper/PreparePagerForEntries.php b/src/Wallabag/CoreBundle/Helper/PreparePagerForEntries.php index 231a0b52..49c1ea41 100644 --- a/src/Wallabag/CoreBundle/Helper/PreparePagerForEntries.php +++ b/src/Wallabag/CoreBundle/Helper/PreparePagerForEntries.php @@ -4,9 +4,9 @@ namespace Wallabag\CoreBundle\Helper; use Pagerfanta\Adapter\AdapterInterface; use Pagerfanta\Pagerfanta; -use Wallabag\UserBundle\Entity\User; use Symfony\Component\Routing\Router; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; +use Wallabag\UserBundle\Entity\User; class PreparePagerForEntries { diff --git a/src/Wallabag/CoreBundle/Helper/RuleBasedTagger.php b/src/Wallabag/CoreBundle/Helper/RuleBasedTagger.php index 509d0dec..63f65067 100644 --- a/src/Wallabag/CoreBundle/Helper/RuleBasedTagger.php +++ b/src/Wallabag/CoreBundle/Helper/RuleBasedTagger.php @@ -2,13 +2,13 @@ namespace Wallabag\CoreBundle\Helper; +use Psr\Log\LoggerInterface; use RulerZ\RulerZ; use Wallabag\CoreBundle\Entity\Entry; use Wallabag\CoreBundle\Entity\Tag; use Wallabag\CoreBundle\Repository\EntryRepository; use Wallabag\CoreBundle\Repository\TagRepository; use Wallabag\UserBundle\Entity\User; -use Psr\Log\LoggerInterface; class RuleBasedTagger { diff --git a/src/Wallabag/CoreBundle/Repository/EntryRepository.php b/src/Wallabag/CoreBundle/Repository/EntryRepository.php index 9bda4e15..a65bfe3b 100644 --- a/src/Wallabag/CoreBundle/Repository/EntryRepository.php +++ b/src/Wallabag/CoreBundle/Repository/EntryRepository.php @@ -10,21 +10,6 @@ use Wallabag\CoreBundle\Entity\Tag; class EntryRepository extends EntityRepository { - /** - * Return a query builder to used by other getBuilderFor* method. - * - * @param int $userId - * - * @return QueryBuilder - */ - private function getBuilderByUser($userId) - { - return $this->createQueryBuilder('e') - ->andWhere('e.user = :userId')->setParameter('userId', $userId) - ->orderBy('e.createdAt', 'desc') - ; - } - /** * Retrieves all entries for a user. * @@ -108,7 +93,7 @@ class EntryRepository extends EntityRepository // We lower() all parts here because PostgreSQL 'LIKE' verb is case-sensitive $qb - ->andWhere('lower(e.content) LIKE lower(:term) OR lower(e.title) LIKE lower(:term) OR lower(e.url) LIKE lower(:term)')->setParameter('term', '%'.$term.'%') + ->andWhere('lower(e.content) LIKE lower(:term) OR lower(e.title) LIKE lower(:term) OR lower(e.url) LIKE lower(:term)')->setParameter('term', '%' . $term . '%') ->leftJoin('e.tags', 't') ->groupBy('e.id'); @@ -158,7 +143,7 @@ class EntryRepository extends EntityRepository } if (null !== $isPublic) { - $qb->andWhere('e.uid IS '.(true === $isPublic ? 'NOT' : '').' NULL'); + $qb->andWhere('e.uid IS ' . (true === $isPublic ? 'NOT' : '') . ' NULL'); } if ($since > 0) { @@ -414,4 +399,19 @@ class EntryRepository extends EntityRepository ->getQuery() ->getResult(); } + + /** + * Return a query builder to used by other getBuilderFor* method. + * + * @param int $userId + * + * @return QueryBuilder + */ + private function getBuilderByUser($userId) + { + return $this->createQueryBuilder('e') + ->andWhere('e.user = :userId')->setParameter('userId', $userId) + ->orderBy('e.createdAt', 'desc') + ; + } } diff --git a/src/Wallabag/CoreBundle/Twig/WallabagExtension.php b/src/Wallabag/CoreBundle/Twig/WallabagExtension.php index a305c53f..351172c4 100644 --- a/src/Wallabag/CoreBundle/Twig/WallabagExtension.php +++ b/src/Wallabag/CoreBundle/Twig/WallabagExtension.php @@ -3,9 +3,9 @@ namespace Wallabag\CoreBundle\Twig; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; +use Symfony\Component\Translation\TranslatorInterface; use Wallabag\CoreBundle\Repository\EntryRepository; use Wallabag\CoreBundle\Repository\TagRepository; -use Symfony\Component\Translation\TranslatorInterface; class WallabagExtension extends \Twig_Extension implements \Twig_Extension_GlobalsInterface { @@ -33,11 +33,11 @@ class WallabagExtension extends \Twig_Extension implements \Twig_Extension_Globa public function getFunctions() { - return array( + return [ new \Twig_SimpleFunction('count_entries', [$this, 'countEntries']), new \Twig_SimpleFunction('count_tags', [$this, 'countTags']), new \Twig_SimpleFunction('display_stats', [$this, 'displayStats']), - ); + ]; } public function removeWww($url) @@ -64,19 +64,15 @@ class WallabagExtension extends \Twig_Extension implements \Twig_Extension_Globa case 'starred': $qb = $this->entryRepository->getBuilderForStarredByUser($user->getId()); break; - case 'archive': $qb = $this->entryRepository->getBuilderForArchiveByUser($user->getId()); break; - case 'unread': $qb = $this->entryRepository->getBuilderForUnreadByUser($user->getId()); break; - case 'all': $qb = $this->entryRepository->getBuilderForAllByUser($user->getId()); break; - default: throw new \InvalidArgumentException(sprintf('Type "%s" is not implemented.', $type)); } @@ -139,7 +135,7 @@ class WallabagExtension extends \Twig_Extension implements \Twig_Extension_Globa $nbDays = (int) $interval->format('%a') ?: 1; // force setlocale for date translation - setlocale(LC_TIME, strtolower($user->getConfig()->getLanguage()).'_'.strtoupper(strtolower($user->getConfig()->getLanguage()))); + setlocale(LC_TIME, strtolower($user->getConfig()->getLanguage()) . '_' . strtoupper(strtolower($user->getConfig()->getLanguage()))); return $this->translator->trans('footer.stats', [ '%user_creation%' => strftime('%e %B %Y', $user->getCreatedAt()->getTimestamp()), diff --git a/src/Wallabag/ImportBundle/Command/ImportCommand.php b/src/Wallabag/ImportBundle/Command/ImportCommand.php index 5f1ab0af..99056c2c 100644 --- a/src/Wallabag/ImportBundle/Command/ImportCommand.php +++ b/src/Wallabag/ImportBundle/Command/ImportCommand.php @@ -5,8 +5,8 @@ namespace Wallabag\ImportBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Config\Definition\Exception\Exception; use Symfony\Component\Console\Input\InputArgument; -use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class ImportCommand extends ContainerAwareCommand @@ -27,7 +27,7 @@ class ImportCommand extends ContainerAwareCommand protected function execute(InputInterface $input, OutputInterface $output) { - $output->writeln('Start : '.(new \DateTime())->format('d-m-Y G:i:s').' ---'); + $output->writeln('Start : ' . (new \DateTime())->format('d-m-Y G:i:s') . ' ---'); if (!file_exists($input->getArgument('filepath'))) { throw new Exception(sprintf('File "%s" not found', $input->getArgument('filepath'))); @@ -80,12 +80,12 @@ class ImportCommand extends ContainerAwareCommand if (true === $res) { $summary = $import->getSummary(); - $output->writeln(''.$summary['imported'].' imported'); - $output->writeln(''.$summary['skipped'].' already saved'); + $output->writeln('' . $summary['imported'] . ' imported'); + $output->writeln('' . $summary['skipped'] . ' already saved'); } $em->clear(); - $output->writeln('End : '.(new \DateTime())->format('d-m-Y G:i:s').' ---'); + $output->writeln('End : ' . (new \DateTime())->format('d-m-Y G:i:s') . ' ---'); } } diff --git a/src/Wallabag/ImportBundle/Command/RedisWorkerCommand.php b/src/Wallabag/ImportBundle/Command/RedisWorkerCommand.php index 2d06af44..d94900ad 100644 --- a/src/Wallabag/ImportBundle/Command/RedisWorkerCommand.php +++ b/src/Wallabag/ImportBundle/Command/RedisWorkerCommand.php @@ -2,13 +2,13 @@ namespace Wallabag\ImportBundle\Command; +use Simpleue\Worker\QueueWorker; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Config\Definition\Exception\Exception; use Symfony\Component\Console\Input\InputArgument; -use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -use Simpleue\Worker\QueueWorker; class RedisWorkerCommand extends ContainerAwareCommand { @@ -24,18 +24,18 @@ class RedisWorkerCommand extends ContainerAwareCommand protected function execute(InputInterface $input, OutputInterface $output) { - $output->writeln('Worker started at: '.(new \DateTime())->format('d-m-Y G:i:s')); + $output->writeln('Worker started at: ' . (new \DateTime())->format('d-m-Y G:i:s')); $output->writeln('Waiting for message ...'); $serviceName = $input->getArgument('serviceName'); - if (!$this->getContainer()->has('wallabag_import.queue.redis.'.$serviceName) || !$this->getContainer()->has('wallabag_import.consumer.redis.'.$serviceName)) { + if (!$this->getContainer()->has('wallabag_import.queue.redis.' . $serviceName) || !$this->getContainer()->has('wallabag_import.consumer.redis.' . $serviceName)) { throw new Exception(sprintf('No queue or consumer found for service name: "%s"', $input->getArgument('serviceName'))); } $worker = new QueueWorker( - $this->getContainer()->get('wallabag_import.queue.redis.'.$serviceName), - $this->getContainer()->get('wallabag_import.consumer.redis.'.$serviceName), + $this->getContainer()->get('wallabag_import.queue.redis.' . $serviceName), + $this->getContainer()->get('wallabag_import.consumer.redis.' . $serviceName), (int) $input->getOption('maxIterations') ); diff --git a/src/Wallabag/ImportBundle/Consumer/AbstractConsumer.php b/src/Wallabag/ImportBundle/Consumer/AbstractConsumer.php index 992ce1ad..b035f5cc 100644 --- a/src/Wallabag/ImportBundle/Consumer/AbstractConsumer.php +++ b/src/Wallabag/ImportBundle/Consumer/AbstractConsumer.php @@ -3,14 +3,14 @@ namespace Wallabag\ImportBundle\Consumer; use Doctrine\ORM\EntityManager; -use Wallabag\ImportBundle\Import\AbstractImport; -use Wallabag\UserBundle\Repository\UserRepository; -use Wallabag\CoreBundle\Entity\Entry; -use Wallabag\CoreBundle\Entity\Tag; use Psr\Log\LoggerInterface; use Psr\Log\NullLogger; use Symfony\Component\EventDispatcher\EventDispatcherInterface; +use Wallabag\CoreBundle\Entity\Entry; +use Wallabag\CoreBundle\Entity\Tag; use Wallabag\CoreBundle\Event\EntrySavedEvent; +use Wallabag\ImportBundle\Import\AbstractImport; +use Wallabag\UserBundle\Repository\UserRepository; abstract class AbstractConsumer { @@ -76,7 +76,7 @@ abstract class AbstractConsumer return false; } - $this->logger->info('Content with url imported! ('.$entry->getUrl().')'); + $this->logger->info('Content with url imported! (' . $entry->getUrl() . ')'); return true; } diff --git a/src/Wallabag/ImportBundle/Controller/BrowserController.php b/src/Wallabag/ImportBundle/Controller/BrowserController.php index e119098f..0753e318 100644 --- a/src/Wallabag/ImportBundle/Controller/BrowserController.php +++ b/src/Wallabag/ImportBundle/Controller/BrowserController.php @@ -2,28 +2,14 @@ namespace Wallabag\ImportBundle\Controller; -use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; +use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Wallabag\ImportBundle\Form\Type\UploadImportType; abstract class BrowserController extends Controller { - /** - * Return the service to handle the import. - * - * @return \Wallabag\ImportBundle\Import\ImportInterface - */ - abstract protected function getImportService(); - - /** - * Return the template used for the form. - * - * @return string - */ - abstract protected function getImportTemplate(); - /** * @Route("/browser", name="import_browser") * @@ -42,11 +28,11 @@ abstract class BrowserController extends Controller if ($form->isSubmitted() && $form->isValid()) { $file = $form->get('file')->getData(); $markAsRead = $form->get('mark_as_read')->getData(); - $name = $this->getUser()->getId().'.json'; + $name = $this->getUser()->getId() . '.json'; - if (null !== $file && in_array($file->getClientMimeType(), $this->getParameter('wallabag_import.allow_mimetypes')) && $file->move($this->getParameter('wallabag_import.resource_dir'), $name)) { + if (null !== $file && in_array($file->getClientMimeType(), $this->getParameter('wallabag_import.allow_mimetypes'), true) && $file->move($this->getParameter('wallabag_import.resource_dir'), $name)) { $res = $wallabag - ->setFilepath($this->getParameter('wallabag_import.resource_dir').'/'.$name) + ->setFilepath($this->getParameter('wallabag_import.resource_dir') . '/' . $name) ->setMarkAsRead($markAsRead) ->import(); @@ -65,7 +51,7 @@ abstract class BrowserController extends Controller ]); } - unlink($this->getParameter('wallabag_import.resource_dir').'/'.$name); + unlink($this->getParameter('wallabag_import.resource_dir') . '/' . $name); } $this->get('session')->getFlashBag()->add( @@ -74,12 +60,11 @@ abstract class BrowserController extends Controller ); return $this->redirect($this->generateUrl('homepage')); - } else { - $this->get('session')->getFlashBag()->add( + } + $this->get('session')->getFlashBag()->add( 'notice', 'flashes.import.notice.failed_on_file' ); - } } return $this->render($this->getImportTemplate(), [ @@ -87,4 +72,18 @@ abstract class BrowserController extends Controller 'import' => $wallabag, ]); } + + /** + * Return the service to handle the import. + * + * @return \Wallabag\ImportBundle\Import\ImportInterface + */ + abstract protected function getImportService(); + + /** + * Return the template used for the form. + * + * @return string + */ + abstract protected function getImportTemplate(); } diff --git a/src/Wallabag/ImportBundle/Controller/ChromeController.php b/src/Wallabag/ImportBundle/Controller/ChromeController.php index 454f3347..0cb418a1 100644 --- a/src/Wallabag/ImportBundle/Controller/ChromeController.php +++ b/src/Wallabag/ImportBundle/Controller/ChromeController.php @@ -7,6 +7,14 @@ use Symfony\Component\HttpFoundation\Request; class ChromeController extends BrowserController { + /** + * @Route("/chrome", name="import_chrome") + */ + public function indexAction(Request $request) + { + return parent::indexAction($request); + } + /** * {@inheritdoc} */ @@ -30,12 +38,4 @@ class ChromeController extends BrowserController { return 'WallabagImportBundle:Chrome:index.html.twig'; } - - /** - * @Route("/chrome", name="import_chrome") - */ - public function indexAction(Request $request) - { - return parent::indexAction($request); - } } diff --git a/src/Wallabag/ImportBundle/Controller/FirefoxController.php b/src/Wallabag/ImportBundle/Controller/FirefoxController.php index c329b9c4..88697f9d 100644 --- a/src/Wallabag/ImportBundle/Controller/FirefoxController.php +++ b/src/Wallabag/ImportBundle/Controller/FirefoxController.php @@ -7,6 +7,14 @@ use Symfony\Component\HttpFoundation\Request; class FirefoxController extends BrowserController { + /** + * @Route("/firefox", name="import_firefox") + */ + public function indexAction(Request $request) + { + return parent::indexAction($request); + } + /** * {@inheritdoc} */ @@ -30,12 +38,4 @@ class FirefoxController extends BrowserController { return 'WallabagImportBundle:Firefox:index.html.twig'; } - - /** - * @Route("/firefox", name="import_firefox") - */ - public function indexAction(Request $request) - { - return parent::indexAction($request); - } } diff --git a/src/Wallabag/ImportBundle/Controller/ImportController.php b/src/Wallabag/ImportBundle/Controller/ImportController.php index 237c748e..7e4fd174 100644 --- a/src/Wallabag/ImportBundle/Controller/ImportController.php +++ b/src/Wallabag/ImportBundle/Controller/ImportController.php @@ -2,8 +2,8 @@ namespace Wallabag\ImportBundle\Controller; -use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; +use Symfony\Bundle\FrameworkBundle\Controller\Controller; class ImportController extends Controller { @@ -86,9 +86,9 @@ class ImportController extends Controller private function getTotalMessageInRabbitQueue($importService) { $message = $this - ->get('old_sound_rabbit_mq.import_'.$importService.'_consumer') + ->get('old_sound_rabbit_mq.import_' . $importService . '_consumer') ->getChannel() - ->basic_get('wallabag.import.'.$importService); + ->basic_get('wallabag.import.' . $importService); if (null === $message) { return 0; diff --git a/src/Wallabag/ImportBundle/Controller/InstapaperController.php b/src/Wallabag/ImportBundle/Controller/InstapaperController.php index 0251acb9..550679c3 100644 --- a/src/Wallabag/ImportBundle/Controller/InstapaperController.php +++ b/src/Wallabag/ImportBundle/Controller/InstapaperController.php @@ -2,8 +2,8 @@ namespace Wallabag\ImportBundle\Controller; -use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; +use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Wallabag\ImportBundle\Form\Type\UploadImportType; @@ -29,11 +29,11 @@ class InstapaperController extends Controller if ($form->isSubmitted() && $form->isValid()) { $file = $form->get('file')->getData(); $markAsRead = $form->get('mark_as_read')->getData(); - $name = 'instapaper_'.$this->getUser()->getId().'.csv'; + $name = 'instapaper_' . $this->getUser()->getId() . '.csv'; - if (null !== $file && in_array($file->getClientMimeType(), $this->getParameter('wallabag_import.allow_mimetypes')) && $file->move($this->getParameter('wallabag_import.resource_dir'), $name)) { + if (null !== $file && in_array($file->getClientMimeType(), $this->getParameter('wallabag_import.allow_mimetypes'), true) && $file->move($this->getParameter('wallabag_import.resource_dir'), $name)) { $res = $instapaper - ->setFilepath($this->getParameter('wallabag_import.resource_dir').'/'.$name) + ->setFilepath($this->getParameter('wallabag_import.resource_dir') . '/' . $name) ->setMarkAsRead($markAsRead) ->import(); @@ -52,7 +52,7 @@ class InstapaperController extends Controller ]); } - unlink($this->getParameter('wallabag_import.resource_dir').'/'.$name); + unlink($this->getParameter('wallabag_import.resource_dir') . '/' . $name); } $this->get('session')->getFlashBag()->add( @@ -61,12 +61,12 @@ class InstapaperController extends Controller ); return $this->redirect($this->generateUrl('homepage')); - } else { - $this->get('session')->getFlashBag()->add( - 'notice', - 'flashes.import.notice.failed_on_file' - ); } + + $this->get('session')->getFlashBag()->add( + 'notice', + 'flashes.import.notice.failed_on_file' + ); } return $this->render('WallabagImportBundle:Instapaper:index.html.twig', [ diff --git a/src/Wallabag/ImportBundle/Controller/PinboardController.php b/src/Wallabag/ImportBundle/Controller/PinboardController.php index d0ad8aa8..0e57fd41 100644 --- a/src/Wallabag/ImportBundle/Controller/PinboardController.php +++ b/src/Wallabag/ImportBundle/Controller/PinboardController.php @@ -2,8 +2,8 @@ namespace Wallabag\ImportBundle\Controller; -use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; +use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Wallabag\ImportBundle\Form\Type\UploadImportType; @@ -29,11 +29,11 @@ class PinboardController extends Controller if ($form->isSubmitted() && $form->isValid()) { $file = $form->get('file')->getData(); $markAsRead = $form->get('mark_as_read')->getData(); - $name = 'pinboard_'.$this->getUser()->getId().'.json'; + $name = 'pinboard_' . $this->getUser()->getId() . '.json'; - if (null !== $file && in_array($file->getClientMimeType(), $this->getParameter('wallabag_import.allow_mimetypes')) && $file->move($this->getParameter('wallabag_import.resource_dir'), $name)) { + if (null !== $file && in_array($file->getClientMimeType(), $this->getParameter('wallabag_import.allow_mimetypes'), true) && $file->move($this->getParameter('wallabag_import.resource_dir'), $name)) { $res = $pinboard - ->setFilepath($this->getParameter('wallabag_import.resource_dir').'/'.$name) + ->setFilepath($this->getParameter('wallabag_import.resource_dir') . '/' . $name) ->setMarkAsRead($markAsRead) ->import(); @@ -52,7 +52,7 @@ class PinboardController extends Controller ]); } - unlink($this->getParameter('wallabag_import.resource_dir').'/'.$name); + unlink($this->getParameter('wallabag_import.resource_dir') . '/' . $name); } $this->get('session')->getFlashBag()->add( @@ -61,12 +61,12 @@ class PinboardController extends Controller ); return $this->redirect($this->generateUrl('homepage')); - } else { - $this->get('session')->getFlashBag()->add( - 'notice', - 'flashes.import.notice.failed_on_file' - ); } + + $this->get('session')->getFlashBag()->add( + 'notice', + 'flashes.import.notice.failed_on_file' + ); } return $this->render('WallabagImportBundle:Pinboard:index.html.twig', [ diff --git a/src/Wallabag/ImportBundle/Controller/PocketController.php b/src/Wallabag/ImportBundle/Controller/PocketController.php index 56be5cbf..9f28819a 100644 --- a/src/Wallabag/ImportBundle/Controller/PocketController.php +++ b/src/Wallabag/ImportBundle/Controller/PocketController.php @@ -2,33 +2,14 @@ namespace Wallabag\ImportBundle\Controller; -use Symfony\Bundle\FrameworkBundle\Controller\Controller; -use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; -use Symfony\Component\HttpFoundation\Request; +use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\Form\Extension\Core\Type\CheckboxType; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\Routing\Generator\UrlGeneratorInterface; class PocketController extends Controller { - /** - * Return Pocket Import Service with or without RabbitMQ enabled. - * - * @return \Wallabag\ImportBundle\Import\PocketImport - */ - private function getPocketImportService() - { - $pocket = $this->get('wallabag_import.pocket.import'); - $pocket->setUser($this->getUser()); - - if ($this->get('craue_config')->get('import_with_rabbitmq')) { - $pocket->setProducer($this->get('old_sound_rabbit_mq.import_pocket_producer')); - } elseif ($this->get('craue_config')->get('import_with_redis')) { - $pocket->setProducer($this->get('wallabag_import.producer.redis.pocket')); - } - - return $pocket; - } - /** * @Route("/pocket", name="import_pocket") */ @@ -70,7 +51,7 @@ class PocketController extends Controller $this->get('session')->set('mark_as_read', $request->request->get('form')['mark_as_read']); return $this->redirect( - 'https://getpocket.com/auth/authorize?request_token='.$requestToken.'&redirect_uri='.$this->generateUrl('import_pocket_callback', [], UrlGeneratorInterface::ABSOLUTE_URL), + 'https://getpocket.com/auth/authorize?request_token=' . $requestToken . '&redirect_uri=' . $this->generateUrl('import_pocket_callback', [], UrlGeneratorInterface::ABSOLUTE_URL), 301 ); } @@ -117,4 +98,23 @@ class PocketController extends Controller return $this->redirect($this->generateUrl('homepage')); } + + /** + * Return Pocket Import Service with or without RabbitMQ enabled. + * + * @return \Wallabag\ImportBundle\Import\PocketImport + */ + private function getPocketImportService() + { + $pocket = $this->get('wallabag_import.pocket.import'); + $pocket->setUser($this->getUser()); + + if ($this->get('craue_config')->get('import_with_rabbitmq')) { + $pocket->setProducer($this->get('old_sound_rabbit_mq.import_pocket_producer')); + } elseif ($this->get('craue_config')->get('import_with_redis')) { + $pocket->setProducer($this->get('wallabag_import.producer.redis.pocket')); + } + + return $pocket; + } } diff --git a/src/Wallabag/ImportBundle/Controller/ReadabilityController.php b/src/Wallabag/ImportBundle/Controller/ReadabilityController.php index aa732ddd..59de24cb 100644 --- a/src/Wallabag/ImportBundle/Controller/ReadabilityController.php +++ b/src/Wallabag/ImportBundle/Controller/ReadabilityController.php @@ -2,8 +2,8 @@ namespace Wallabag\ImportBundle\Controller; -use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; +use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Wallabag\ImportBundle\Form\Type\UploadImportType; @@ -29,11 +29,11 @@ class ReadabilityController extends Controller if ($form->isSubmitted() && $form->isValid()) { $file = $form->get('file')->getData(); $markAsRead = $form->get('mark_as_read')->getData(); - $name = 'readability_'.$this->getUser()->getId().'.json'; + $name = 'readability_' . $this->getUser()->getId() . '.json'; - if (null !== $file && in_array($file->getClientMimeType(), $this->getParameter('wallabag_import.allow_mimetypes')) && $file->move($this->getParameter('wallabag_import.resource_dir'), $name)) { + if (null !== $file && in_array($file->getClientMimeType(), $this->getParameter('wallabag_import.allow_mimetypes'), true) && $file->move($this->getParameter('wallabag_import.resource_dir'), $name)) { $res = $readability - ->setFilepath($this->getParameter('wallabag_import.resource_dir').'/'.$name) + ->setFilepath($this->getParameter('wallabag_import.resource_dir') . '/' . $name) ->setMarkAsRead($markAsRead) ->import(); @@ -52,7 +52,7 @@ class ReadabilityController extends Controller ]); } - unlink($this->getParameter('wallabag_import.resource_dir').'/'.$name); + unlink($this->getParameter('wallabag_import.resource_dir') . '/' . $name); } $this->get('session')->getFlashBag()->add( @@ -61,12 +61,12 @@ class ReadabilityController extends Controller ); return $this->redirect($this->generateUrl('homepage')); - } else { - $this->get('session')->getFlashBag()->add( - 'notice', - 'flashes.import.notice.failed_on_file' - ); } + + $this->get('session')->getFlashBag()->add( + 'notice', + 'flashes.import.notice.failed_on_file' + ); } return $this->render('WallabagImportBundle:Readability:index.html.twig', [ diff --git a/src/Wallabag/ImportBundle/Controller/WallabagController.php b/src/Wallabag/ImportBundle/Controller/WallabagController.php index e81c1ca9..7b61805b 100644 --- a/src/Wallabag/ImportBundle/Controller/WallabagController.php +++ b/src/Wallabag/ImportBundle/Controller/WallabagController.php @@ -11,20 +11,6 @@ use Wallabag\ImportBundle\Form\Type\UploadImportType; */ abstract class WallabagController extends Controller { - /** - * Return the service to handle the import. - * - * @return \Wallabag\ImportBundle\Import\ImportInterface - */ - abstract protected function getImportService(); - - /** - * Return the template used for the form. - * - * @return string - */ - abstract protected function getImportTemplate(); - /** * Handle import request. * @@ -43,11 +29,11 @@ abstract class WallabagController extends Controller if ($form->isSubmitted() && $form->isValid()) { $file = $form->get('file')->getData(); $markAsRead = $form->get('mark_as_read')->getData(); - $name = $this->getUser()->getId().'.json'; + $name = $this->getUser()->getId() . '.json'; - if (null !== $file && in_array($file->getClientMimeType(), $this->getParameter('wallabag_import.allow_mimetypes')) && $file->move($this->getParameter('wallabag_import.resource_dir'), $name)) { + if (null !== $file && in_array($file->getClientMimeType(), $this->getParameter('wallabag_import.allow_mimetypes'), true) && $file->move($this->getParameter('wallabag_import.resource_dir'), $name)) { $res = $wallabag - ->setFilepath($this->getParameter('wallabag_import.resource_dir').'/'.$name) + ->setFilepath($this->getParameter('wallabag_import.resource_dir') . '/' . $name) ->setMarkAsRead($markAsRead) ->import(); @@ -66,7 +52,7 @@ abstract class WallabagController extends Controller ]); } - unlink($this->getParameter('wallabag_import.resource_dir').'/'.$name); + unlink($this->getParameter('wallabag_import.resource_dir') . '/' . $name); } $this->get('session')->getFlashBag()->add( @@ -75,12 +61,12 @@ abstract class WallabagController extends Controller ); return $this->redirect($this->generateUrl('homepage')); - } else { - $this->get('session')->getFlashBag()->add( - 'notice', - 'flashes.import.notice.failed_on_file' - ); } + + $this->get('session')->getFlashBag()->add( + 'notice', + 'flashes.import.notice.failed_on_file' + ); } return $this->render($this->getImportTemplate(), [ @@ -88,4 +74,18 @@ abstract class WallabagController extends Controller 'import' => $wallabag, ]); } + + /** + * Return the service to handle the import. + * + * @return \Wallabag\ImportBundle\Import\ImportInterface + */ + abstract protected function getImportService(); + + /** + * Return the template used for the form. + * + * @return string + */ + abstract protected function getImportTemplate(); } diff --git a/src/Wallabag/ImportBundle/Controller/WallabagV1Controller.php b/src/Wallabag/ImportBundle/Controller/WallabagV1Controller.php index 312c7a35..d700d8a8 100644 --- a/src/Wallabag/ImportBundle/Controller/WallabagV1Controller.php +++ b/src/Wallabag/ImportBundle/Controller/WallabagV1Controller.php @@ -7,6 +7,14 @@ use Symfony\Component\HttpFoundation\Request; class WallabagV1Controller extends WallabagController { + /** + * @Route("/wallabag-v1", name="import_wallabag_v1") + */ + public function indexAction(Request $request) + { + return parent::indexAction($request); + } + /** * {@inheritdoc} */ @@ -30,12 +38,4 @@ class WallabagV1Controller extends WallabagController { return 'WallabagImportBundle:WallabagV1:index.html.twig'; } - - /** - * @Route("/wallabag-v1", name="import_wallabag_v1") - */ - public function indexAction(Request $request) - { - return parent::indexAction($request); - } } diff --git a/src/Wallabag/ImportBundle/Controller/WallabagV2Controller.php b/src/Wallabag/ImportBundle/Controller/WallabagV2Controller.php index 45211fe6..ab26400c 100644 --- a/src/Wallabag/ImportBundle/Controller/WallabagV2Controller.php +++ b/src/Wallabag/ImportBundle/Controller/WallabagV2Controller.php @@ -7,6 +7,14 @@ use Symfony\Component\HttpFoundation\Request; class WallabagV2Controller extends WallabagController { + /** + * @Route("/wallabag-v2", name="import_wallabag_v2") + */ + public function indexAction(Request $request) + { + return parent::indexAction($request); + } + /** * {@inheritdoc} */ @@ -30,12 +38,4 @@ class WallabagV2Controller extends WallabagController { return 'WallabagImportBundle:WallabagV2:index.html.twig'; } - - /** - * @Route("/wallabag-v2", name="import_wallabag_v2") - */ - public function indexAction(Request $request) - { - return parent::indexAction($request); - } } diff --git a/src/Wallabag/ImportBundle/DependencyInjection/WallabagImportExtension.php b/src/Wallabag/ImportBundle/DependencyInjection/WallabagImportExtension.php index 3f23c36b..cab70297 100644 --- a/src/Wallabag/ImportBundle/DependencyInjection/WallabagImportExtension.php +++ b/src/Wallabag/ImportBundle/DependencyInjection/WallabagImportExtension.php @@ -2,10 +2,10 @@ namespace Wallabag\ImportBundle\DependencyInjection; -use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; -use Symfony\Component\HttpKernel\DependencyInjection\Extension; +use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader; +use Symfony\Component\HttpKernel\DependencyInjection\Extension; class WallabagImportExtension extends Extension { @@ -16,7 +16,7 @@ class WallabagImportExtension extends Extension $container->setParameter('wallabag_import.allow_mimetypes', $config['allow_mimetypes']); $container->setParameter('wallabag_import.resource_dir', $config['resource_dir']); - $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); + $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); $loader->load('services.yml'); } diff --git a/src/Wallabag/ImportBundle/Form/Type/UploadImportType.php b/src/Wallabag/ImportBundle/Form/Type/UploadImportType.php index f50424c1..c50ef8c9 100644 --- a/src/Wallabag/ImportBundle/Form/Type/UploadImportType.php +++ b/src/Wallabag/ImportBundle/Form/Type/UploadImportType.php @@ -3,10 +3,10 @@ namespace Wallabag\ImportBundle\Form\Type; use Symfony\Component\Form\AbstractType; -use Symfony\Component\Form\FormBuilderInterface; -use Symfony\Component\Form\Extension\Core\Type\SubmitType; -use Symfony\Component\Form\Extension\Core\Type\FileType; use Symfony\Component\Form\Extension\Core\Type\CheckboxType; +use Symfony\Component\Form\Extension\Core\Type\FileType; +use Symfony\Component\Form\Extension\Core\Type\SubmitType; +use Symfony\Component\Form\FormBuilderInterface; class UploadImportType extends AbstractType { diff --git a/src/Wallabag/ImportBundle/Import/AbstractImport.php b/src/Wallabag/ImportBundle/Import/AbstractImport.php index 9b624296..cb46db09 100644 --- a/src/Wallabag/ImportBundle/Import/AbstractImport.php +++ b/src/Wallabag/ImportBundle/Import/AbstractImport.php @@ -2,17 +2,17 @@ namespace Wallabag\ImportBundle\Import; +use Doctrine\ORM\EntityManager; +use OldSound\RabbitMqBundle\RabbitMq\ProducerInterface; use Psr\Log\LoggerInterface; use Psr\Log\NullLogger; -use Doctrine\ORM\EntityManager; -use Wallabag\CoreBundle\Helper\ContentProxy; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Wallabag\CoreBundle\Entity\Entry; use Wallabag\CoreBundle\Entity\Tag; +use Wallabag\CoreBundle\Event\EntrySavedEvent; +use Wallabag\CoreBundle\Helper\ContentProxy; use Wallabag\CoreBundle\Helper\TagsAssigner; use Wallabag\UserBundle\Entity\User; -use OldSound\RabbitMqBundle\RabbitMq\ProducerInterface; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; -use Wallabag\CoreBundle\Event\EntrySavedEvent; abstract class AbstractImport implements ImportInterface { @@ -97,6 +97,27 @@ abstract class AbstractImport implements ImportInterface return $this; } + /** + * {@inheritdoc} + */ + public function getSummary() + { + return [ + 'skipped' => $this->skippedEntries, + 'imported' => $this->importedEntries, + 'queued' => $this->queuedEntries, + ]; + } + + /** + * Parse one entry. + * + * @param array $importedEntry + * + * @return Entry + */ + abstract public function parseEntry(array $importedEntry); + /** * Fetch content from the ContentProxy (using graby). * If it fails return the given entry to be saved in all case (to avoid user to loose the content). @@ -195,27 +216,6 @@ abstract class AbstractImport implements ImportInterface } } - /** - * {@inheritdoc} - */ - public function getSummary() - { - return [ - 'skipped' => $this->skippedEntries, - 'imported' => $this->importedEntries, - 'queued' => $this->queuedEntries, - ]; - } - - /** - * Parse one entry. - * - * @param array $importedEntry - * - * @return Entry - */ - abstract public function parseEntry(array $importedEntry); - /** * Set current imported entry to archived / read. * Implementation is different accross all imports. diff --git a/src/Wallabag/ImportBundle/Import/BrowserImport.php b/src/Wallabag/ImportBundle/Import/BrowserImport.php index 71e65e59..f1195824 100644 --- a/src/Wallabag/ImportBundle/Import/BrowserImport.php +++ b/src/Wallabag/ImportBundle/Import/BrowserImport.php @@ -3,8 +3,8 @@ namespace Wallabag\ImportBundle\Import; use Wallabag\CoreBundle\Entity\Entry; -use Wallabag\UserBundle\Entity\User; use Wallabag\CoreBundle\Event\EntrySavedEvent; +use Wallabag\UserBundle\Entity\User; abstract class BrowserImport extends AbstractImport { @@ -73,6 +73,80 @@ abstract class BrowserImport extends AbstractImport return $this; } + /** + * {@inheritdoc} + */ + public function parseEntry(array $importedEntry) + { + if ((!array_key_exists('guid', $importedEntry) || (!array_key_exists('id', $importedEntry))) && is_array(reset($importedEntry))) { + if ($this->producer) { + $this->parseEntriesForProducer($importedEntry); + + return; + } + + $this->parseEntries($importedEntry); + + return; + } + + if (array_key_exists('children', $importedEntry)) { + if ($this->producer) { + $this->parseEntriesForProducer($importedEntry['children']); + + return; + } + + $this->parseEntries($importedEntry['children']); + + return; + } + + if (!array_key_exists('uri', $importedEntry) && !array_key_exists('url', $importedEntry)) { + return; + } + + $url = array_key_exists('uri', $importedEntry) ? $importedEntry['uri'] : $importedEntry['url']; + + $existingEntry = $this->em + ->getRepository('WallabagCoreBundle:Entry') + ->findByUrlAndUserId($url, $this->user->getId()); + + if (false !== $existingEntry) { + ++$this->skippedEntries; + + return; + } + + $data = $this->prepareEntry($importedEntry); + + $entry = new Entry($this->user); + $entry->setUrl($data['url']); + $entry->setTitle($data['title']); + + // update entry with content (in case fetching failed, the given entry will be return) + $this->fetchContent($entry, $data['url'], $data); + + if (array_key_exists('tags', $data)) { + $this->tagsAssigner->assignTagsToEntry( + $entry, + $data['tags'] + ); + } + + $entry->setArchived($data['is_archived']); + + if (!empty($data['created_at'])) { + $dt = new \DateTime(); + $entry->setCreatedAt($dt->setTimestamp($data['created_at'])); + } + + $this->em->persist($entry); + ++$this->importedEntries; + + return $entry; + } + /** * Parse and insert all given entries. * @@ -149,80 +223,6 @@ abstract class BrowserImport extends AbstractImport } } - /** - * {@inheritdoc} - */ - public function parseEntry(array $importedEntry) - { - if ((!array_key_exists('guid', $importedEntry) || (!array_key_exists('id', $importedEntry))) && is_array(reset($importedEntry))) { - if ($this->producer) { - $this->parseEntriesForProducer($importedEntry); - - return; - } - - $this->parseEntries($importedEntry); - - return; - } - - if (array_key_exists('children', $importedEntry)) { - if ($this->producer) { - $this->parseEntriesForProducer($importedEntry['children']); - - return; - } - - $this->parseEntries($importedEntry['children']); - - return; - } - - if (!array_key_exists('uri', $importedEntry) && !array_key_exists('url', $importedEntry)) { - return; - } - - $url = array_key_exists('uri', $importedEntry) ? $importedEntry['uri'] : $importedEntry['url']; - - $existingEntry = $this->em - ->getRepository('WallabagCoreBundle:Entry') - ->findByUrlAndUserId($url, $this->user->getId()); - - if (false !== $existingEntry) { - ++$this->skippedEntries; - - return; - } - - $data = $this->prepareEntry($importedEntry); - - $entry = new Entry($this->user); - $entry->setUrl($data['url']); - $entry->setTitle($data['title']); - - // update entry with content (in case fetching failed, the given entry will be return) - $this->fetchContent($entry, $data['url'], $data); - - if (array_key_exists('tags', $data)) { - $this->tagsAssigner->assignTagsToEntry( - $entry, - $data['tags'] - ); - } - - $entry->setArchived($data['is_archived']); - - if (!empty($data['created_at'])) { - $dt = new \DateTime(); - $entry->setCreatedAt($dt->setTimestamp($data['created_at'])); - } - - $this->em->persist($entry); - ++$this->importedEntries; - - return $entry; - } - /** * {@inheritdoc} */ diff --git a/src/Wallabag/ImportBundle/Import/ChromeImport.php b/src/Wallabag/ImportBundle/Import/ChromeImport.php index 2667890f..e3ba636a 100644 --- a/src/Wallabag/ImportBundle/Import/ChromeImport.php +++ b/src/Wallabag/ImportBundle/Import/ChromeImport.php @@ -45,7 +45,7 @@ class ChromeImport extends BrowserImport 'created_at' => substr($entry['date_added'], 0, 10), ]; - if (array_key_exists('tags', $entry) && $entry['tags'] != '') { + if (array_key_exists('tags', $entry) && $entry['tags'] !== '') { $data['tags'] = $entry['tags']; } diff --git a/src/Wallabag/ImportBundle/Import/FirefoxImport.php b/src/Wallabag/ImportBundle/Import/FirefoxImport.php index c50c69b3..c18e7e93 100644 --- a/src/Wallabag/ImportBundle/Import/FirefoxImport.php +++ b/src/Wallabag/ImportBundle/Import/FirefoxImport.php @@ -45,7 +45,7 @@ class FirefoxImport extends BrowserImport 'created_at' => substr($entry['dateAdded'], 0, 10), ]; - if (array_key_exists('tags', $entry) && $entry['tags'] != '') { + if (array_key_exists('tags', $entry) && $entry['tags'] !== '') { $data['tags'] = $entry['tags']; } diff --git a/src/Wallabag/ImportBundle/Import/ImportCompilerPass.php b/src/Wallabag/ImportBundle/Import/ImportCompilerPass.php index a363a566..d7df0a83 100644 --- a/src/Wallabag/ImportBundle/Import/ImportCompilerPass.php +++ b/src/Wallabag/ImportBundle/Import/ImportCompilerPass.php @@ -2,8 +2,8 @@ namespace Wallabag\ImportBundle\Import; -use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; +use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; class ImportCompilerPass implements CompilerPassInterface diff --git a/src/Wallabag/ImportBundle/Import/InstapaperImport.php b/src/Wallabag/ImportBundle/Import/InstapaperImport.php index 3aa12f6f..7d70154a 100644 --- a/src/Wallabag/ImportBundle/Import/InstapaperImport.php +++ b/src/Wallabag/ImportBundle/Import/InstapaperImport.php @@ -72,7 +72,7 @@ class InstapaperImport extends AbstractImport // BUT it can also be the status (since status = folder in Instapaper) // and we don't want archive, unread & starred to become a tag $tags = null; - if (false === in_array($data[3], ['Archive', 'Unread', 'Starred'])) { + if (false === in_array($data[3], ['Archive', 'Unread', 'Starred'], true)) { $tags = [$data[3]]; } diff --git a/src/Wallabag/ImportBundle/Import/PocketImport.php b/src/Wallabag/ImportBundle/Import/PocketImport.php index c1d5b6da..7d38826b 100644 --- a/src/Wallabag/ImportBundle/Import/PocketImport.php +++ b/src/Wallabag/ImportBundle/Import/PocketImport.php @@ -8,11 +8,10 @@ use Wallabag\CoreBundle\Entity\Entry; class PocketImport extends AbstractImport { + const NB_ELEMENTS = 5000; private $client; private $accessToken; - const NB_ELEMENTS = 5000; - /** * Only used for test purpose. * @@ -176,7 +175,7 @@ class PocketImport extends AbstractImport */ public function parseEntry(array $importedEntry) { - $url = isset($importedEntry['resolved_url']) && $importedEntry['resolved_url'] != '' ? $importedEntry['resolved_url'] : $importedEntry['given_url']; + $url = isset($importedEntry['resolved_url']) && $importedEntry['resolved_url'] !== '' ? $importedEntry['resolved_url'] : $importedEntry['given_url']; $existingEntry = $this->em ->getRepository('WallabagCoreBundle:Entry') @@ -195,15 +194,15 @@ class PocketImport extends AbstractImport $this->fetchContent($entry, $url); // 0, 1, 2 - 1 if the item is archived - 2 if the item should be deleted - $entry->setArchived($importedEntry['status'] == 1 || $this->markAsRead); + $entry->setArchived($importedEntry['status'] === 1 || $this->markAsRead); // 0 or 1 - 1 If the item is starred - $entry->setStarred($importedEntry['favorite'] == 1); + $entry->setStarred($importedEntry['favorite'] === 1); $title = 'Untitled'; - if (isset($importedEntry['resolved_title']) && $importedEntry['resolved_title'] != '') { + if (isset($importedEntry['resolved_title']) && $importedEntry['resolved_title'] !== '') { $title = $importedEntry['resolved_title']; - } elseif (isset($importedEntry['given_title']) && $importedEntry['given_title'] != '') { + } elseif (isset($importedEntry['given_title']) && $importedEntry['given_title'] !== '') { $title = $importedEntry['given_title']; } diff --git a/src/Wallabag/ImportBundle/Import/WallabagV1Import.php b/src/Wallabag/ImportBundle/Import/WallabagV1Import.php index 1f0df646..d585d44d 100644 --- a/src/Wallabag/ImportBundle/Import/WallabagV1Import.php +++ b/src/Wallabag/ImportBundle/Import/WallabagV1Import.php @@ -56,12 +56,12 @@ class WallabagV1Import extends WallabagImport // In case of a bad fetch in v1, replace title and content with v2 error strings // If fetching fails again, they will get this instead of the v1 strings - if (in_array($entry['title'], $this->untitled)) { + if (in_array($entry['title'], $this->untitled, true)) { $data['title'] = $this->fetchingErrorMessageTitle; $data['html'] = $this->fetchingErrorMessage; } - if (array_key_exists('tags', $entry) && $entry['tags'] != '') { + if (array_key_exists('tags', $entry) && $entry['tags'] !== '') { $data['tags'] = $entry['tags']; } diff --git a/src/Wallabag/ImportBundle/Redis/Producer.php b/src/Wallabag/ImportBundle/Redis/Producer.php index fedc3e57..c77b5174 100644 --- a/src/Wallabag/ImportBundle/Redis/Producer.php +++ b/src/Wallabag/ImportBundle/Redis/Producer.php @@ -29,7 +29,7 @@ class Producer implements ProducerInterface * @param string $routingKey NOT USED * @param array $additionalProperties NOT USED */ - public function publish($msgBody, $routingKey = '', $additionalProperties = array()) + public function publish($msgBody, $routingKey = '', $additionalProperties = []) { $this->queue->sendJob($msgBody); } diff --git a/src/Wallabag/ImportBundle/WallabagImportBundle.php b/src/Wallabag/ImportBundle/WallabagImportBundle.php index a5ddc1b4..98c2f97b 100644 --- a/src/Wallabag/ImportBundle/WallabagImportBundle.php +++ b/src/Wallabag/ImportBundle/WallabagImportBundle.php @@ -2,8 +2,8 @@ namespace Wallabag\ImportBundle; -use Symfony\Component\HttpKernel\Bundle\Bundle; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\HttpKernel\Bundle\Bundle; use Wallabag\ImportBundle\Import\ImportCompilerPass; class WallabagImportBundle extends Bundle diff --git a/src/Wallabag/UserBundle/Controller/ManageController.php b/src/Wallabag/UserBundle/Controller/ManageController.php index 084f2c67..f3de656f 100644 --- a/src/Wallabag/UserBundle/Controller/ManageController.php +++ b/src/Wallabag/UserBundle/Controller/ManageController.php @@ -7,10 +7,10 @@ use FOS\UserBundle\FOSUserEvents; use Pagerfanta\Adapter\DoctrineORMAdapter; use Pagerfanta\Exception\OutOfRangeCurrentPageException; use Pagerfanta\Pagerfanta; -use Symfony\Component\HttpFoundation\Request; -use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; +use Symfony\Bundle\FrameworkBundle\Controller\Controller; +use Symfony\Component\HttpFoundation\Request; use Wallabag\UserBundle\Entity\User; use Wallabag\UserBundle\Form\SearchUserType; @@ -48,13 +48,13 @@ class ManageController extends Controller $this->get('translator')->trans('flashes.user.notice.added', ['%username%' => $user->getUsername()]) ); - return $this->redirectToRoute('user_edit', array('id' => $user->getId())); + return $this->redirectToRoute('user_edit', ['id' => $user->getId()]); } - return $this->render('WallabagUserBundle:Manage:new.html.twig', array( + return $this->render('WallabagUserBundle:Manage:new.html.twig', [ 'user' => $user, 'form' => $form->createView(), - )); + ]); } /** @@ -79,15 +79,15 @@ class ManageController extends Controller $this->get('translator')->trans('flashes.user.notice.updated', ['%username%' => $user->getUsername()]) ); - return $this->redirectToRoute('user_edit', array('id' => $user->getId())); + return $this->redirectToRoute('user_edit', ['id' => $user->getId()]); } - return $this->render('WallabagUserBundle:Manage:edit.html.twig', array( + return $this->render('WallabagUserBundle:Manage:edit.html.twig', [ 'user' => $user, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView(), 'twofactor_auth' => $this->getParameter('twofactor_auth'), - )); + ]); } /** @@ -115,22 +115,6 @@ class ManageController extends Controller return $this->redirectToRoute('user_index'); } - /** - * Creates a form to delete a User entity. - * - * @param User $user The User entity - * - * @return \Symfony\Component\Form\Form The form - */ - private function createDeleteForm(User $user) - { - return $this->createFormBuilder() - ->setAction($this->generateUrl('user_delete', array('id' => $user->getId()))) - ->setMethod('DELETE') - ->getForm() - ; - } - /** * @param Request $request * @param int $page @@ -175,4 +159,20 @@ class ManageController extends Controller 'users' => $pagerFanta, ]); } + + /** + * Creates a form to delete a User entity. + * + * @param User $user The User entity + * + * @return \Symfony\Component\Form\Form The form + */ + private function createDeleteForm(User $user) + { + return $this->createFormBuilder() + ->setAction($this->generateUrl('user_delete', ['id' => $user->getId()])) + ->setMethod('DELETE') + ->getForm() + ; + } } diff --git a/src/Wallabag/UserBundle/DependencyInjection/WallabagUserExtension.php b/src/Wallabag/UserBundle/DependencyInjection/WallabagUserExtension.php index 99040f69..5ca3482e 100644 --- a/src/Wallabag/UserBundle/DependencyInjection/WallabagUserExtension.php +++ b/src/Wallabag/UserBundle/DependencyInjection/WallabagUserExtension.php @@ -2,10 +2,10 @@ namespace Wallabag\UserBundle\DependencyInjection; -use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; -use Symfony\Component\HttpKernel\DependencyInjection\Extension; +use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader; +use Symfony\Component\HttpKernel\DependencyInjection\Extension; class WallabagUserExtension extends Extension { @@ -14,7 +14,7 @@ class WallabagUserExtension extends Extension $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); - $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); + $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); $loader->load('services.yml'); $container->setParameter('wallabag_user.registration_enabled', $config['registration_enabled']); } diff --git a/src/Wallabag/UserBundle/Entity/User.php b/src/Wallabag/UserBundle/Entity/User.php index aba76ca7..20aca298 100644 --- a/src/Wallabag/UserBundle/Entity/User.php +++ b/src/Wallabag/UserBundle/Entity/User.php @@ -4,12 +4,12 @@ namespace Wallabag\UserBundle\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; +use FOS\UserBundle\Model\User as BaseUser; +use JMS\Serializer\Annotation\Accessor; use JMS\Serializer\Annotation\Groups; use JMS\Serializer\Annotation\XmlRoot; -use JMS\Serializer\Annotation\Accessor; use Scheb\TwoFactorBundle\Model\Email\TwoFactorInterface; use Scheb\TwoFactorBundle\Model\TrustedComputerInterface; -use FOS\UserBundle\Model\User as BaseUser; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; use Symfony\Component\Security\Core\User\UserInterface; use Wallabag\ApiBundle\Entity\Client; @@ -93,36 +93,36 @@ class User extends BaseUser implements TwoFactorInterface, TrustedComputerInterf protected $config; /** - * @ORM\Column(type="integer", nullable=true) + * @var ArrayCollection + * + * @ORM\OneToMany(targetEntity="Wallabag\ApiBundle\Entity\Client", mappedBy="user", cascade={"remove"}) */ - private $authCode; + protected $clients; /** - * @var bool + * @see getFirstClient() below * - * @ORM\Column(type="boolean") + * @Groups({"user_api_with_client"}) + * @Accessor(getter="getFirstClient") */ - private $twoFactorAuthentication = false; + protected $default_client; /** - * @ORM\Column(type="json_array", nullable=true) + * @ORM\Column(type="integer", nullable=true) */ - private $trusted; + private $authCode; /** - * @var ArrayCollection + * @var bool * - * @ORM\OneToMany(targetEntity="Wallabag\ApiBundle\Entity\Client", mappedBy="user", cascade={"remove"}) + * @ORM\Column(type="boolean") */ - protected $clients; + private $twoFactorAuthentication = false; /** - * @see getFirstClient() below - * - * @Groups({"user_api_with_client"}) - * @Accessor(getter="getFirstClient") + * @ORM\Column(type="json_array", nullable=true) */ - protected $default_client; + private $trusted; public function __construct() { @@ -137,7 +137,7 @@ class User extends BaseUser implements TwoFactorInterface, TrustedComputerInterf */ public function timestamps() { - if (is_null($this->createdAt)) { + if (null === $this->createdAt) { $this->createdAt = new \DateTime(); } diff --git a/src/Wallabag/UserBundle/EventListener/AuthenticationFailureListener.php b/src/Wallabag/UserBundle/EventListener/AuthenticationFailureListener.php index 10f13233..18f14a3a 100644 --- a/src/Wallabag/UserBundle/EventListener/AuthenticationFailureListener.php +++ b/src/Wallabag/UserBundle/EventListener/AuthenticationFailureListener.php @@ -35,6 +35,6 @@ class AuthenticationFailureListener implements EventSubscriberInterface { $request = $this->requestStack->getMasterRequest(); - $this->logger->error('Authentication failure for user "'.$request->request->get('_username').'", from IP "'.$request->getClientIp().'", with UA: "'.$request->server->get('HTTP_USER_AGENT').'".'); + $this->logger->error('Authentication failure for user "' . $request->request->get('_username') . '", from IP "' . $request->getClientIp() . '", with UA: "' . $request->server->get('HTTP_USER_AGENT') . '".'); } } diff --git a/src/Wallabag/UserBundle/EventListener/PasswordResettingListener.php b/src/Wallabag/UserBundle/EventListener/PasswordResettingListener.php index 3a7f2637..7df093f1 100644 --- a/src/Wallabag/UserBundle/EventListener/PasswordResettingListener.php +++ b/src/Wallabag/UserBundle/EventListener/PasswordResettingListener.php @@ -2,8 +2,8 @@ namespace Wallabag\UserBundle\EventListener; -use FOS\UserBundle\FOSUserEvents; use FOS\UserBundle\Event\FormEvent; +use FOS\UserBundle\FOSUserEvents; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; diff --git a/src/Wallabag/UserBundle/Form/UserType.php b/src/Wallabag/UserBundle/Form/UserType.php index d8cdbaf9..56fea640 100644 --- a/src/Wallabag/UserBundle/Form/UserType.php +++ b/src/Wallabag/UserBundle/Form/UserType.php @@ -3,12 +3,12 @@ namespace Wallabag\UserBundle\Form; use Symfony\Component\Form\AbstractType; -use Symfony\Component\Form\FormBuilderInterface; -use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Form\Extension\Core\Type\CheckboxType; +use Symfony\Component\Form\Extension\Core\Type\EmailType; use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\Extension\Core\Type\TextType; -use Symfony\Component\Form\Extension\Core\Type\EmailType; +use Symfony\Component\Form\FormBuilderInterface; +use Symfony\Component\OptionsResolver\OptionsResolver; class UserType extends AbstractType { @@ -50,8 +50,8 @@ class UserType extends AbstractType */ public function configureOptions(OptionsResolver $resolver) { - $resolver->setDefaults(array( + $resolver->setDefaults([ 'data_class' => 'Wallabag\UserBundle\Entity\User', - )); + ]); } } diff --git a/src/Wallabag/UserBundle/Mailer/AuthCodeMailer.php b/src/Wallabag/UserBundle/Mailer/AuthCodeMailer.php index 961208f2..aed805c9 100644 --- a/src/Wallabag/UserBundle/Mailer/AuthCodeMailer.php +++ b/src/Wallabag/UserBundle/Mailer/AuthCodeMailer.php @@ -2,8 +2,8 @@ namespace Wallabag\UserBundle\Mailer; -use Scheb\TwoFactorBundle\Model\Email\TwoFactorInterface; use Scheb\TwoFactorBundle\Mailer\AuthCodeMailerInterface; +use Scheb\TwoFactorBundle\Model\Email\TwoFactorInterface; /** * Custom mailer for TwoFactorBundle email. diff --git a/src/Wallabag/UserBundle/Repository/UserRepository.php b/src/Wallabag/UserBundle/Repository/UserRepository.php index 6adbe329..b1d753d2 100644 --- a/src/Wallabag/UserBundle/Repository/UserRepository.php +++ b/src/Wallabag/UserBundle/Repository/UserRepository.php @@ -63,6 +63,6 @@ class UserRepository extends EntityRepository public function getQueryBuilderForSearch($term) { return $this->createQueryBuilder('u') - ->andWhere('lower(u.username) LIKE lower(:term) OR lower(u.email) LIKE lower(:term) OR lower(u.name) LIKE lower(:term)')->setParameter('term', '%'.$term.'%'); + ->andWhere('lower(u.username) LIKE lower(:term) OR lower(u.email) LIKE lower(:term) OR lower(u.name) LIKE lower(:term)')->setParameter('term', '%' . $term . '%'); } } -- cgit v1.2.3 From 38520658addc217f127b0627ea28dcf8d6e6178c Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Mon, 3 Jul 2017 07:30:54 +0200 Subject: Fix tests --- src/Wallabag/CoreBundle/Controller/EntryController.php | 2 +- src/Wallabag/CoreBundle/Repository/EntryRepository.php | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Controller/EntryController.php b/src/Wallabag/CoreBundle/Controller/EntryController.php index 445cfeeb..845ebef6 100644 --- a/src/Wallabag/CoreBundle/Controller/EntryController.php +++ b/src/Wallabag/CoreBundle/Controller/EntryController.php @@ -195,7 +195,7 @@ class EntryController extends Controller public function showUnreadAction(Request $request, $page) { // load the quickstart if no entry in database - if ($page === 1 && $this->get('wallabag_core.entry_repository')->countAllEntriesByUser($this->getUser()->getId()) === 0) { + if ((int) $page === 1 && $this->get('wallabag_core.entry_repository')->countAllEntriesByUser($this->getUser()->getId()) === 0) { return $this->redirect($this->generateUrl('quickstart')); } diff --git a/src/Wallabag/CoreBundle/Repository/EntryRepository.php b/src/Wallabag/CoreBundle/Repository/EntryRepository.php index a65bfe3b..c27ee90c 100644 --- a/src/Wallabag/CoreBundle/Repository/EntryRepository.php +++ b/src/Wallabag/CoreBundle/Repository/EntryRepository.php @@ -325,7 +325,7 @@ class EntryRepository extends EntityRepository ->where('e.user=:userId')->setParameter('userId', $userId) ; - return $qb->getQuery()->getSingleScalarResult(); + return (int) $qb->getQuery()->getSingleScalarResult(); } /** @@ -345,7 +345,7 @@ class EntryRepository extends EntityRepository ->andWhere('t.id=:tagId')->setParameter('tagId', $tagId) ; - return $qb->getQuery()->getSingleScalarResult(); + return (int) $qb->getQuery()->getSingleScalarResult(); } /** -- cgit v1.2.3 From 9114615adcee0255273c7e91d6d8e55f57fc3d6f Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Sat, 1 Jul 2017 09:32:13 +0200 Subject: Fixed mapping entities There were this error in the console: > The association Wallabag\CoreBundle\Entity\SiteCredential#user refers to the inverse side field Wallabag\UserBundle\Entity\User#site_credentials which does not exist. --- src/Wallabag/UserBundle/Entity/User.php | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'src') diff --git a/src/Wallabag/UserBundle/Entity/User.php b/src/Wallabag/UserBundle/Entity/User.php index 20aca298..a3320bbc 100644 --- a/src/Wallabag/UserBundle/Entity/User.php +++ b/src/Wallabag/UserBundle/Entity/User.php @@ -92,6 +92,13 @@ class User extends BaseUser implements TwoFactorInterface, TrustedComputerInterf */ protected $config; + /** + * @var ArrayCollection + * + * @ORM\OneToMany(targetEntity="Wallabag\CoreBundle\Entity\SiteCredential", mappedBy="user", cascade={"remove"}) + */ + protected $site_credentials; + /** * @var ArrayCollection * -- cgit v1.2.3 From e50d7d31c0746ffbfe69065258981e1b4dcd203b Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Mon, 3 Jul 2017 11:49:46 +0200 Subject: CS --- src/Wallabag/CoreBundle/Entity/SiteCredential.php | 2 +- src/Wallabag/UserBundle/Entity/User.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Entity/SiteCredential.php b/src/Wallabag/CoreBundle/Entity/SiteCredential.php index 380f820d..4d6557c5 100644 --- a/src/Wallabag/CoreBundle/Entity/SiteCredential.php +++ b/src/Wallabag/CoreBundle/Entity/SiteCredential.php @@ -57,7 +57,7 @@ class SiteCredential private $createdAt; /** - * @ORM\ManyToOne(targetEntity="Wallabag\UserBundle\Entity\User", inversedBy="site_credentials") + * @ORM\ManyToOne(targetEntity="Wallabag\UserBundle\Entity\User", inversedBy="siteCredentials") */ private $user; diff --git a/src/Wallabag/UserBundle/Entity/User.php b/src/Wallabag/UserBundle/Entity/User.php index a3320bbc..53c327f9 100644 --- a/src/Wallabag/UserBundle/Entity/User.php +++ b/src/Wallabag/UserBundle/Entity/User.php @@ -97,7 +97,7 @@ class User extends BaseUser implements TwoFactorInterface, TrustedComputerInterf * * @ORM\OneToMany(targetEntity="Wallabag\CoreBundle\Entity\SiteCredential", mappedBy="user", cascade={"remove"}) */ - protected $site_credentials; + protected $siteCredentials; /** * @var ArrayCollection -- cgit v1.2.3 From a05b61159e147776f63baee731b5026796e5f7ae Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Fri, 30 Jun 2017 16:54:26 +0200 Subject: Fix PATCH method The PATCH method for the entry should only update what user sent to us and not the whole entry as it was before. Also, sending tags when patching an entry will now remove all current tags & assocatied new ones. --- .../ApiBundle/Controller/EntryRestController.php | 211 ++++++++++++++------- src/Wallabag/CoreBundle/Entity/Entry.php | 16 ++ src/Wallabag/CoreBundle/Helper/ContentProxy.php | 89 +++++---- 3 files changed, 210 insertions(+), 106 deletions(-) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/EntryRestController.php b/src/Wallabag/ApiBundle/Controller/EntryRestController.php index ca460c84..a2e913af 100644 --- a/src/Wallabag/ApiBundle/Controller/EntryRestController.php +++ b/src/Wallabag/ApiBundle/Controller/EntryRestController.php @@ -299,8 +299,8 @@ class EntryRestController extends WallabagRestController * {"name"="url", "dataType"="string", "required"=true, "format"="http://www.test.com/article.html", "description"="Url for the entry."}, * {"name"="title", "dataType"="string", "required"=false, "description"="Optional, we'll get the title from the page."}, * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."}, - * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="entry already starred"}, * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="entry already archived"}, + * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="entry already starred"}, * {"name"="content", "dataType"="string", "required"=false, "description"="Content of the entry"}, * {"name"="language", "dataType"="string", "required"=false, "description"="Language of the entry"}, * {"name"="preview_picture", "dataType"="string", "required"=false, "description"="Preview picture of the entry"}, @@ -328,7 +328,58 @@ class EntryRestController extends WallabagRestController $entry->setUrl($url); } - $this->upsertEntry($entry, $request); + $data = $this->retrieveValueFromRequest($request); + + try { + $this->get('wallabag_core.content_proxy')->updateEntry( + $entry, + $entry->getUrl(), + [ + 'title' => !empty($data['title']) ? $data['title'] : $entry->getTitle(), + 'html' => !empty($data['content']) ? $data['content'] : $entry->getContent(), + 'url' => $entry->getUrl(), + 'language' => !empty($data['language']) ? $data['language'] : $entry->getLanguage(), + 'date' => !empty($data['publishedAt']) ? $data['publishedAt'] : $entry->getPublishedAt(), + // faking the open graph preview picture + 'open_graph' => [ + 'og_image' => !empty($data['picture']) ? $data['picture'] : $entry->getPreviewPicture(), + ], + 'authors' => is_string($data['authors']) ? explode(',', $data['authors']) : $entry->getPublishedBy(), + ] + ); + } catch (\Exception $e) { + $this->get('logger')->error('Error while saving an entry', [ + 'exception' => $e, + 'entry' => $entry, + ]); + } + + if (!is_null($data['isArchived'])) { + $entry->setArchived((bool) $data['isArchived']); + } + + if (!is_null($data['isStarred'])) { + $entry->setStarred((bool) $data['isStarred']); + } + + if (!empty($data['tags'])) { + $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $data['tags']); + } + + if (!is_null($data['isPublic'])) { + if (true === (bool) $data['isPublic'] && null === $entry->getUid()) { + $entry->generateUid(); + } elseif (false === (bool) $data['isPublic']) { + $entry->cleanUid(); + } + } + + $em = $this->getDoctrine()->getManager(); + $em->persist($entry); + $em->flush(); + + // entry saved, dispatch event about it! + $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry)); return $this->sendResponse($entry); } @@ -361,7 +412,78 @@ class EntryRestController extends WallabagRestController $this->validateAuthentication(); $this->validateUserAccess($entry->getUser()->getId()); - $this->upsertEntry($entry, $request, true); + $contentProxy = $this->get('wallabag_core.content_proxy'); + + $data = $this->retrieveValueFromRequest($request); + + // this is a special case where user want to manually update the entry content + // the ContentProxy will only cleanup the html + // and also we force to not re-fetch the content in case of error + if (!empty($data['content'])) { + try { + $contentProxy->updateEntry( + $entry, + $entry->getUrl(), + [ + 'html' => $data['content'], + ], + true + ); + } catch (\Exception $e) { + $this->get('logger')->error('Error while saving an entry', [ + 'exception' => $e, + 'entry' => $entry, + ]); + } + } + + if (!empty($data['title'])) { + $entry->setTitle($data['title']); + } + + if (!empty($data['language'])) { + $contentProxy->updateLanguage($entry, $data['language']); + } + + if (!empty($data['authors']) && is_string($data['authors'])) { + $entry->setPublishedBy(explode(',', $data['authors'])); + } + + if (!empty($data['picture'])) { + $contentProxy->updatePreviewPicture($entry, $data['picture']); + } + + if (!empty($data['publishedAt'])) { + $contentProxy->updatePublishedAt($entry, $data['publishedAt']); + } + + if (!is_null($data['isArchived'])) { + $entry->setArchived((bool) $data['isArchived']); + } + + if (!is_null($data['isStarred'])) { + $entry->setStarred((bool) $data['isStarred']); + } + + if (!empty($data['tags'])) { + $entry->removeAllTags(); + $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $data['tags']); + } + + if (!is_null($data['isPublic'])) { + if (true === (bool) $data['isPublic'] && null === $entry->getUid()) { + $entry->generateUid(); + } elseif (false === (bool) $data['isPublic']) { + $entry->cleanUid(); + } + } + + $em = $this->getDoctrine()->getManager(); + $em->persist($entry); + $em->flush(); + + // entry saved, dispatch event about it! + $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry)); return $this->sendResponse($entry); } @@ -634,76 +756,27 @@ class EntryRestController extends WallabagRestController } /** - * Update or Insert a new entry. + * Retrieve value from the request. + * Used for POST & PATCH on a an entry. * - * @param Entry $entry * @param Request $request - * @param bool $disableContentUpdate If we don't want the content to be update by fetching the url (used when patching instead of posting) + * + * @return array */ - private function upsertEntry(Entry $entry, Request $request, $disableContentUpdate = false) + private function retrieveValueFromRequest(Request $request) { - $title = $request->request->get('title'); - $tags = $request->request->get('tags', []); - $isArchived = $request->request->get('archive'); - $isStarred = $request->request->get('starred'); - $isPublic = $request->request->get('public'); - $content = $request->request->get('content'); - $language = $request->request->get('language'); - $picture = $request->request->get('preview_picture'); - $publishedAt = $request->request->get('published_at'); - $authors = $request->request->get('authors', ''); - - try { - $this->get('wallabag_core.content_proxy')->updateEntry( - $entry, - $entry->getUrl(), - [ - 'title' => !empty($title) ? $title : $entry->getTitle(), - 'html' => !empty($content) ? $content : $entry->getContent(), - 'url' => $entry->getUrl(), - 'language' => !empty($language) ? $language : $entry->getLanguage(), - 'date' => !empty($publishedAt) ? $publishedAt : $entry->getPublishedAt(), - // faking the open graph preview picture - 'open_graph' => [ - 'og_image' => !empty($picture) ? $picture : $entry->getPreviewPicture(), - ], - 'authors' => is_string($authors) ? explode(',', $authors) : $entry->getPublishedBy(), - ], - $disableContentUpdate - ); - } catch (\Exception $e) { - $this->get('logger')->error('Error while saving an entry', [ - 'exception' => $e, - 'entry' => $entry, - ]); - } - - if (null !== $isArchived) { - $entry->setArchived((bool) $isArchived); - } - - if (null !== $isStarred) { - $entry->setStarred((bool) $isStarred); - } - - if (!empty($tags)) { - $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags); - } - - if (null !== $isPublic) { - if (true === (bool) $isPublic && null === $entry->getUid()) { - $entry->generateUid(); - } elseif (false === (bool) $isPublic) { - $entry->cleanUid(); - } - } - - $em = $this->getDoctrine()->getManager(); - $em->persist($entry); - $em->flush(); - - // entry saved, dispatch event about it! - $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry)); + return [ + 'title' => $request->request->get('title'), + 'tags' => $request->request->get('tags', []), + 'isArchived' => $request->request->get('archive'), + 'isStarred' => $request->request->get('starred'), + 'isPublic' => $request->request->get('public'), + 'content' => $request->request->get('content'), + 'language' => $request->request->get('language'), + 'picture' => $request->request->get('preview_picture'), + 'publishedAt' => $request->request->get('published_at'), + 'authors' => $request->request->get('authors', ''), + ]; } /** diff --git a/src/Wallabag/CoreBundle/Entity/Entry.php b/src/Wallabag/CoreBundle/Entity/Entry.php index 581e8906..cba72d31 100644 --- a/src/Wallabag/CoreBundle/Entity/Entry.php +++ b/src/Wallabag/CoreBundle/Entity/Entry.php @@ -593,6 +593,11 @@ class Entry $tag->addEntry($this); } + /** + * Remove the given tag from the entry (if the tag is associated). + * + * @param Tag $tag + */ public function removeTag(Tag $tag) { if (!$this->tags->contains($tag)) { @@ -603,6 +608,17 @@ class Entry $tag->removeEntry($this); } + /** + * Remove all assigned tags from the entry. + */ + public function removeAllTags() + { + foreach ($this->tags as $tag) { + $this->tags->removeElement($tag); + $tag->removeEntry($this); + } + } + /** * Set previewPicture. * diff --git a/src/Wallabag/CoreBundle/Helper/ContentProxy.php b/src/Wallabag/CoreBundle/Helper/ContentProxy.php index ddecd6f4..2a650e97 100644 --- a/src/Wallabag/CoreBundle/Helper/ContentProxy.php +++ b/src/Wallabag/CoreBundle/Helper/ContentProxy.php @@ -75,9 +75,17 @@ class ContentProxy */ private function stockEntry(Entry $entry, array $content) { - $title = $content['title']; - if (!$title && !empty($content['open_graph']['og_title'])) { - $title = $content['open_graph']['og_title']; + $entry->setUrl($content['url']); + + $domainName = parse_url($entry->getUrl(), PHP_URL_HOST); + if (false !== $domainName) { + $entry->setDomainName($domainName); + } + + if (!empty($content['title'])) { + $entry->setTitle($content['title']); + } elseif (!empty($content['open_graph']['og_title'])) { + $entry->setTitle($content['open_graph']['og_title']); } $html = $content['html']; @@ -90,24 +98,11 @@ class ContentProxy } } - $entry->setUrl($content['url']); - $entry->setTitle($title); $entry->setContent($html); - $entry->setHttpStatus(isset($content['status']) ? $content['status'] : ''); - - if (!empty($content['date'])) { - $date = $content['date']; - - // is it a timestamp? - if (filter_var($date, FILTER_VALIDATE_INT) !== false) { - $date = '@' . $content['date']; - } + $entry->setReadingTime(Utils::getReadingTime($html)); - try { - $entry->setPublishedAt(new \DateTime($date)); - } catch (\Exception $e) { - $this->logger->warning('Error while defining date', ['e' => $e, 'url' => $content['url'], 'date' => $content['date']]); - } + if (!empty($content['status'])) { + $entry->setHttpStatus($content['status']); } if (!empty($content['authors']) && is_array($content['authors'])) { @@ -118,15 +113,17 @@ class ContentProxy $entry->setHeaders($content['all_headers']); } - $this->validateAndSetLanguage( - $entry, - isset($content['language']) ? $content['language'] : null - ); + if (!empty($content['date'])) { + $this->updatePublishedAt($entry, $content['date']); + } - $this->validateAndSetPreviewPicture( - $entry, - isset($content['open_graph']['og_image']) ? $content['open_graph']['og_image'] : null - ); + if (!empty($content['language'])) { + $this->updateLanguage($entry, $content['language']); + } + + if (!empty($content['open_graph']['og_image'])) { + $this->updatePreviewPicture($entry, $content['open_graph']['og_image']); + } // if content is an image, define it as a preview too if (!empty($content['content_type']) && in_array($this->mimeGuesser->guess($content['content_type']), ['jpeg', 'jpg', 'gif', 'png'], true)) { @@ -136,12 +133,8 @@ class ContentProxy ); } - $entry->setMimetype(isset($content['content_type']) ? $content['content_type'] : ''); - $entry->setReadingTime(Utils::getReadingTime($html)); - - $domainName = parse_url($entry->getUrl(), PHP_URL_HOST); - if (false !== $domainName) { - $entry->setDomainName($domainName); + if (!empty($content['content_type'])) { + $entry->setMimetype($content['content_type']); } try { @@ -170,9 +163,9 @@ class ContentProxy * Use a Symfony validator to ensure the language is well formatted. * * @param Entry $entry - * @param string $value Language to validate + * @param string $value Language to validate and save */ - private function validateAndSetLanguage($entry, $value) + public function updateLanguage(Entry $entry, $value) { // some lang are defined as fr-FR, es-ES. // replacing - by _ might increase language support @@ -196,9 +189,9 @@ class ContentProxy * Use a Symfony validator to ensure the preview picture is a real url. * * @param Entry $entry - * @param string $value URL to validate + * @param string $value URL to validate and save */ - private function validateAndSetPreviewPicture($entry, $value) + public function updatePreviewPicture(Entry $entry, $value) { $errors = $this->validator->validate( $value, @@ -213,4 +206,26 @@ class ContentProxy $this->logger->warning('PreviewPicture validation failed. ' . (string) $errors); } + + /** + * Update date. + * + * @param Entry $entry + * @param string $value Date to validate and save + */ + public function updatePublishedAt(Entry $entry, $value) + { + $date = $value; + + // is it a timestamp? + if (filter_var($date, FILTER_VALIDATE_INT) !== false) { + $date = '@'.$value; + } + + try { + $entry->setPublishedAt(new \DateTime($date)); + } catch (\Exception $e) { + $this->logger->warning('Error while defining date', ['e' => $e, 'url' => $entry->getUrl(), 'date' => $value]); + } + } } -- cgit v1.2.3 From d0ec2ddd2354e39badd947c2214f47193784b1c7 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Fri, 30 Jun 2017 17:04:40 +0200 Subject: Fix validateAndSetPreviewPicture Which wasn't covered by a test! --- src/Wallabag/CoreBundle/Helper/ContentProxy.php | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Helper/ContentProxy.php b/src/Wallabag/CoreBundle/Helper/ContentProxy.php index 2a650e97..5622cc83 100644 --- a/src/Wallabag/CoreBundle/Helper/ContentProxy.php +++ b/src/Wallabag/CoreBundle/Helper/ContentProxy.php @@ -127,10 +127,7 @@ class ContentProxy // if content is an image, define it as a preview too if (!empty($content['content_type']) && in_array($this->mimeGuesser->guess($content['content_type']), ['jpeg', 'jpg', 'gif', 'png'], true)) { - $this->validateAndSetPreviewPicture( - $entry, - $content['url'] - ); + $this->updatePreviewPicture($entry, $content['url']); } if (!empty($content['content_type'])) { -- cgit v1.2.3 From c18a2476b601bc6b9893462d9be680c2e13c89e8 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Mon, 3 Jul 2017 13:56:39 +0200 Subject: CS --- .../ApiBundle/Controller/EntryRestController.php | 12 +- src/Wallabag/CoreBundle/Helper/ContentProxy.php | 140 ++++++++++----------- 2 files changed, 76 insertions(+), 76 deletions(-) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/EntryRestController.php b/src/Wallabag/ApiBundle/Controller/EntryRestController.php index a2e913af..8a206124 100644 --- a/src/Wallabag/ApiBundle/Controller/EntryRestController.php +++ b/src/Wallabag/ApiBundle/Controller/EntryRestController.php @@ -354,11 +354,11 @@ class EntryRestController extends WallabagRestController ]); } - if (!is_null($data['isArchived'])) { + if (null !== $data['isArchived']) { $entry->setArchived((bool) $data['isArchived']); } - if (!is_null($data['isStarred'])) { + if (null !== $data['isStarred']) { $entry->setStarred((bool) $data['isStarred']); } @@ -366,7 +366,7 @@ class EntryRestController extends WallabagRestController $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $data['tags']); } - if (!is_null($data['isPublic'])) { + if (null !== $data['isPublic']) { if (true === (bool) $data['isPublic'] && null === $entry->getUid()) { $entry->generateUid(); } elseif (false === (bool) $data['isPublic']) { @@ -457,11 +457,11 @@ class EntryRestController extends WallabagRestController $contentProxy->updatePublishedAt($entry, $data['publishedAt']); } - if (!is_null($data['isArchived'])) { + if (null !== $data['isArchived']) { $entry->setArchived((bool) $data['isArchived']); } - if (!is_null($data['isStarred'])) { + if (null !== $data['isStarred']) { $entry->setStarred((bool) $data['isStarred']); } @@ -470,7 +470,7 @@ class EntryRestController extends WallabagRestController $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $data['tags']); } - if (!is_null($data['isPublic'])) { + if (null !== $data['isPublic']) { if (true === (bool) $data['isPublic'] && null === $entry->getUid()) { $entry->generateUid(); } elseif (false === (bool) $data['isPublic']) { diff --git a/src/Wallabag/CoreBundle/Helper/ContentProxy.php b/src/Wallabag/CoreBundle/Helper/ContentProxy.php index 5622cc83..656ac6ee 100644 --- a/src/Wallabag/CoreBundle/Helper/ContentProxy.php +++ b/src/Wallabag/CoreBundle/Helper/ContentProxy.php @@ -66,6 +66,76 @@ class ContentProxy $this->stockEntry($entry, $content); } + /** + * Use a Symfony validator to ensure the language is well formatted. + * + * @param Entry $entry + * @param string $value Language to validate and save + */ + public function updateLanguage(Entry $entry, $value) + { + // some lang are defined as fr-FR, es-ES. + // replacing - by _ might increase language support + $value = str_replace('-', '_', $value); + + $errors = $this->validator->validate( + $value, + (new LocaleConstraint()) + ); + + if (0 === count($errors)) { + $entry->setLanguage($value); + + return; + } + + $this->logger->warning('Language validation failed. ' . (string) $errors); + } + + /** + * Use a Symfony validator to ensure the preview picture is a real url. + * + * @param Entry $entry + * @param string $value URL to validate and save + */ + public function updatePreviewPicture(Entry $entry, $value) + { + $errors = $this->validator->validate( + $value, + (new UrlConstraint()) + ); + + if (0 === count($errors)) { + $entry->setPreviewPicture($value); + + return; + } + + $this->logger->warning('PreviewPicture validation failed. ' . (string) $errors); + } + + /** + * Update date. + * + * @param Entry $entry + * @param string $value Date to validate and save + */ + public function updatePublishedAt(Entry $entry, $value) + { + $date = $value; + + // is it a timestamp? + if (filter_var($date, FILTER_VALIDATE_INT) !== false) { + $date = '@' . $value; + } + + try { + $entry->setPublishedAt(new \DateTime($date)); + } catch (\Exception $e) { + $this->logger->warning('Error while defining date', ['e' => $e, 'url' => $entry->getUrl(), 'date' => $value]); + } + } + /** * Stock entry with fetched or imported content. * Will fall back to OpenGraph data if available. @@ -155,74 +225,4 @@ class ContentProxy { return !empty($content['title']) && !empty($content['html']) && !empty($content['url']); } - - /** - * Use a Symfony validator to ensure the language is well formatted. - * - * @param Entry $entry - * @param string $value Language to validate and save - */ - public function updateLanguage(Entry $entry, $value) - { - // some lang are defined as fr-FR, es-ES. - // replacing - by _ might increase language support - $value = str_replace('-', '_', $value); - - $errors = $this->validator->validate( - $value, - (new LocaleConstraint()) - ); - - if (0 === count($errors)) { - $entry->setLanguage($value); - - return; - } - - $this->logger->warning('Language validation failed. ' . (string) $errors); - } - - /** - * Use a Symfony validator to ensure the preview picture is a real url. - * - * @param Entry $entry - * @param string $value URL to validate and save - */ - public function updatePreviewPicture(Entry $entry, $value) - { - $errors = $this->validator->validate( - $value, - (new UrlConstraint()) - ); - - if (0 === count($errors)) { - $entry->setPreviewPicture($value); - - return; - } - - $this->logger->warning('PreviewPicture validation failed. ' . (string) $errors); - } - - /** - * Update date. - * - * @param Entry $entry - * @param string $value Date to validate and save - */ - public function updatePublishedAt(Entry $entry, $value) - { - $date = $value; - - // is it a timestamp? - if (filter_var($date, FILTER_VALIDATE_INT) !== false) { - $date = '@'.$value; - } - - try { - $entry->setPublishedAt(new \DateTime($date)); - } catch (\Exception $e) { - $this->logger->warning('Error while defining date', ['e' => $e, 'url' => $entry->getUrl(), 'date' => $value]); - } - } } -- cgit v1.2.3 From 927c9e796ff6fad2bf82a965234f52932cdee657 Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Thu, 6 Jul 2017 09:00:37 +0200 Subject: Add EntityTimestampsTrait to handle dates Refactorize timestamps() method to avoid re-writing it on each entity --- .../AnnotationBundle/Entity/Annotation.php | 15 +++----------- src/Wallabag/CoreBundle/Entity/Entry.php | 16 +++------------ src/Wallabag/CoreBundle/Entity/SiteCredential.php | 13 +++--------- .../CoreBundle/Helper/EntityTimestampsTrait.php | 24 ++++++++++++++++++++++ src/Wallabag/UserBundle/Entity/User.php | 16 +++------------ 5 files changed, 36 insertions(+), 48 deletions(-) create mode 100644 src/Wallabag/CoreBundle/Helper/EntityTimestampsTrait.php (limited to 'src') diff --git a/src/Wallabag/AnnotationBundle/Entity/Annotation.php b/src/Wallabag/AnnotationBundle/Entity/Annotation.php index 04d83001..a180d504 100644 --- a/src/Wallabag/AnnotationBundle/Entity/Annotation.php +++ b/src/Wallabag/AnnotationBundle/Entity/Annotation.php @@ -10,6 +10,7 @@ use JMS\Serializer\Annotation\SerializedName; use JMS\Serializer\Annotation\VirtualProperty; use Symfony\Component\Validator\Constraints as Assert; use Wallabag\CoreBundle\Entity\Entry; +use Wallabag\CoreBundle\Helper\EntityTimestampsTrait; use Wallabag\UserBundle\Entity\User; /** @@ -22,6 +23,8 @@ use Wallabag\UserBundle\Entity\User; */ class Annotation { + use EntityTimestampsTrait; + /** * @var int * @@ -133,18 +136,6 @@ class Annotation return $this->text; } - /** - * @ORM\PrePersist - * @ORM\PreUpdate - */ - public function timestamps() - { - if (null === $this->createdAt) { - $this->createdAt = new \DateTime(); - } - $this->updatedAt = new \DateTime(); - } - /** * Get created. * diff --git a/src/Wallabag/CoreBundle/Entity/Entry.php b/src/Wallabag/CoreBundle/Entity/Entry.php index cba72d31..61d01bdc 100644 --- a/src/Wallabag/CoreBundle/Entity/Entry.php +++ b/src/Wallabag/CoreBundle/Entity/Entry.php @@ -12,6 +12,7 @@ use JMS\Serializer\Annotation\VirtualProperty; use JMS\Serializer\Annotation\XmlRoot; use Symfony\Component\Validator\Constraints as Assert; use Wallabag\AnnotationBundle\Entity\Annotation; +use Wallabag\CoreBundle\Helper\EntityTimestampsTrait; use Wallabag\UserBundle\Entity\User; /** @@ -32,6 +33,8 @@ use Wallabag\UserBundle\Entity\User; */ class Entry { + use EntityTimestampsTrait; + /** @Serializer\XmlAttribute */ /** * @var int @@ -472,19 +475,6 @@ class Entry return $this->updatedAt; } - /** - * @ORM\PrePersist - * @ORM\PreUpdate - */ - public function timestamps() - { - if (null === $this->createdAt) { - $this->createdAt = new \DateTime(); - } - - $this->updatedAt = new \DateTime(); - } - /** * @return ArrayCollection */ diff --git a/src/Wallabag/CoreBundle/Entity/SiteCredential.php b/src/Wallabag/CoreBundle/Entity/SiteCredential.php index 4d6557c5..ac714359 100644 --- a/src/Wallabag/CoreBundle/Entity/SiteCredential.php +++ b/src/Wallabag/CoreBundle/Entity/SiteCredential.php @@ -4,6 +4,7 @@ namespace Wallabag\CoreBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; +use Wallabag\CoreBundle\Helper\EntityTimestampsTrait; use Wallabag\UserBundle\Entity\User; /** @@ -15,6 +16,8 @@ use Wallabag\UserBundle\Entity\User; */ class SiteCredential { + use EntityTimestampsTrait; + /** * @var int * @@ -182,14 +185,4 @@ class SiteCredential { return $this->user; } - - /** - * @ORM\PrePersist - */ - public function timestamps() - { - if (null === $this->createdAt) { - $this->createdAt = new \DateTime(); - } - } } diff --git a/src/Wallabag/CoreBundle/Helper/EntityTimestampsTrait.php b/src/Wallabag/CoreBundle/Helper/EntityTimestampsTrait.php new file mode 100644 index 00000000..1b1ff54a --- /dev/null +++ b/src/Wallabag/CoreBundle/Helper/EntityTimestampsTrait.php @@ -0,0 +1,24 @@ +createdAt) { + $this->createdAt = new \DateTime(); + } + + $this->updatedAt = new \DateTime(); + } +} diff --git a/src/Wallabag/UserBundle/Entity/User.php b/src/Wallabag/UserBundle/Entity/User.php index 53c327f9..48446e3c 100644 --- a/src/Wallabag/UserBundle/Entity/User.php +++ b/src/Wallabag/UserBundle/Entity/User.php @@ -15,6 +15,7 @@ use Symfony\Component\Security\Core\User\UserInterface; use Wallabag\ApiBundle\Entity\Client; use Wallabag\CoreBundle\Entity\Config; use Wallabag\CoreBundle\Entity\Entry; +use Wallabag\CoreBundle\Helper\EntityTimestampsTrait; /** * User. @@ -29,6 +30,8 @@ use Wallabag\CoreBundle\Entity\Entry; */ class User extends BaseUser implements TwoFactorInterface, TrustedComputerInterface { + use EntityTimestampsTrait; + /** @Serializer\XmlAttribute */ /** * @var int @@ -138,19 +141,6 @@ class User extends BaseUser implements TwoFactorInterface, TrustedComputerInterf $this->roles = ['ROLE_USER']; } - /** - * @ORM\PrePersist - * @ORM\PreUpdate - */ - public function timestamps() - { - if (null === $this->createdAt) { - $this->createdAt = new \DateTime(); - } - - $this->updatedAt = new \DateTime(); - } - /** * Set name. * -- cgit v1.2.3 From 2e5b2fa808ca2793705069e56a3cc7e6631f9d9d Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Sat, 8 Jul 2017 19:28:12 +0200 Subject: Revert client_credentials grant types --- src/Wallabag/ApiBundle/Controller/DeveloperController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/DeveloperController.php b/src/Wallabag/ApiBundle/Controller/DeveloperController.php index c8a1c635..c7178017 100644 --- a/src/Wallabag/ApiBundle/Controller/DeveloperController.php +++ b/src/Wallabag/ApiBundle/Controller/DeveloperController.php @@ -43,7 +43,7 @@ class DeveloperController extends Controller $clientForm->handleRequest($request); if ($clientForm->isSubmitted() && $clientForm->isValid()) { - $client->setAllowedGrantTypes(['client_credentials', 'token', 'authorization_code', 'password', 'refresh_token']); + $client->setAllowedGrantTypes(['token', 'authorization_code', 'password', 'refresh_token']); $em->persist($client); $em->flush(); -- cgit v1.2.3 From 07320a2bd25c6ace1f9b1aa06b1b08e8dbf4f4fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89tienne=20Gilli?= Date: Sat, 8 Jul 2017 17:55:58 +0200 Subject: Use the article domain as author for export files When exporting an entry, use the domain name as author name for epub, mobi and pdf formats, instead of 'wallabag'. Change the author from array to string, because for now, there is always only one author. --- .../ApiBundle/Controller/EntryRestController.php | 1 + src/Wallabag/CoreBundle/Command/ExportCommand.php | 1 + .../CoreBundle/Controller/ExportController.php | 2 ++ src/Wallabag/CoreBundle/Helper/EntriesExport.php | 28 +++++++++++++++++----- 4 files changed, 26 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/Wallabag/ApiBundle/Controller/EntryRestController.php b/src/Wallabag/ApiBundle/Controller/EntryRestController.php index 8a206124..9277e1a1 100644 --- a/src/Wallabag/ApiBundle/Controller/EntryRestController.php +++ b/src/Wallabag/ApiBundle/Controller/EntryRestController.php @@ -180,6 +180,7 @@ class EntryRestController extends WallabagRestController return $this->get('wallabag_core.helper.entries_export') ->setEntries($entry) ->updateTitle('entry') + ->updateAuthor('entry') ->exportAs($request->attributes->get('_format')); } diff --git a/src/Wallabag/CoreBundle/Command/ExportCommand.php b/src/Wallabag/CoreBundle/Command/ExportCommand.php index 0dacb734..c2e4be05 100644 --- a/src/Wallabag/CoreBundle/Command/ExportCommand.php +++ b/src/Wallabag/CoreBundle/Command/ExportCommand.php @@ -56,6 +56,7 @@ class ExportCommand extends ContainerAwareCommand $data = $this->getContainer()->get('wallabag_core.helper.entries_export') ->setEntries($entries) ->updateTitle('All') + ->updateAuthor('All') ->exportJsonData(); file_put_contents($filePath, $data); } catch (\InvalidArgumentException $e) { diff --git a/src/Wallabag/CoreBundle/Controller/ExportController.php b/src/Wallabag/CoreBundle/Controller/ExportController.php index 6fad122e..35a22046 100644 --- a/src/Wallabag/CoreBundle/Controller/ExportController.php +++ b/src/Wallabag/CoreBundle/Controller/ExportController.php @@ -33,6 +33,7 @@ class ExportController extends Controller return $this->get('wallabag_core.helper.entries_export') ->setEntries($entry) ->updateTitle('entry') + ->updateAuthor('entry') ->exportAs($format); } catch (\InvalidArgumentException $e) { throw new NotFoundHttpException($e->getMessage()); @@ -76,6 +77,7 @@ class ExportController extends Controller return $this->get('wallabag_core.helper.entries_export') ->setEntries($entries) ->updateTitle($method) + ->updateAuthor($method) ->exportAs($format); } catch (\InvalidArgumentException $e) { throw new NotFoundHttpException($e->getMessage()); diff --git a/src/Wallabag/CoreBundle/Helper/EntriesExport.php b/src/Wallabag/CoreBundle/Helper/EntriesExport.php index cd74cc4f..d749dcf9 100644 --- a/src/Wallabag/CoreBundle/Helper/EntriesExport.php +++ b/src/Wallabag/CoreBundle/Helper/EntriesExport.php @@ -18,7 +18,7 @@ class EntriesExport private $logoPath; private $title = ''; private $entries = []; - private $authors = ['wallabag']; + private $author = 'wallabag'; private $language = ''; private $footerTemplate = '

    Produced by wallabag with %EXPORT_METHOD%

    @@ -72,6 +72,24 @@ class EntriesExport return $this; } + /** + * Sets the author for just one entry. + * + * @param string $method Method to get articles + * + * @return EntriesExport + */ + public function updateAuthor($method) + { + $this->author = $method.' authors'; + + if ('entry' === $method) { + $this->author = $this->entries[0]->getDomainName(); + } + + return $this; + } + /** * Sets the output format. * @@ -128,9 +146,7 @@ class EntriesExport $book->setLanguage($this->language); $book->setDescription('Some articles saved on my wallabag'); - foreach ($this->authors as $author) { - $book->setAuthor($author, $author); - } + $book->setAuthor($this->author, $this->author); // I hope this is a non existant address :) $book->setPublisher('wallabag', 'wallabag'); @@ -196,7 +212,7 @@ class EntriesExport * Book metadata */ $content->set('title', $this->title); - $content->set('author', implode($this->authors)); + $content->set('author', $this->author); $content->set('subject', $this->title); /* @@ -247,7 +263,7 @@ class EntriesExport * Book metadata */ $pdf->SetCreator(PDF_CREATOR); - $pdf->SetAuthor('wallabag'); + $pdf->SetAuthor($this->author); $pdf->SetTitle($this->title); $pdf->SetSubject('Articles via wallabag'); $pdf->SetKeywords('wallabag'); -- cgit v1.2.3 From c57f69d967dea05e507e997193a783fed991de8e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89tienne=20Gilli?= Date: Sun, 9 Jul 2017 18:33:14 +0200 Subject: Use the article publisher as author for export When exporting an entry, use the publishedBy field as author name for epub, mobi and pdf formats. Fallback to domain name if empty. --- src/Wallabag/CoreBundle/Helper/EntriesExport.php | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Helper/EntriesExport.php b/src/Wallabag/CoreBundle/Helper/EntriesExport.php index d749dcf9..e16168b1 100644 --- a/src/Wallabag/CoreBundle/Helper/EntriesExport.php +++ b/src/Wallabag/CoreBundle/Helper/EntriesExport.php @@ -73,7 +73,9 @@ class EntriesExport } /** - * Sets the author for just one entry. + * Sets the author for one entry or category. + * + * The publishers are used, or the domain name if empty. * * @param string $method Method to get articles * @@ -84,7 +86,12 @@ class EntriesExport $this->author = $method.' authors'; if ('entry' === $method) { - $this->author = $this->entries[0]->getDomainName(); + $publishedBy = $this->entries[0]->getPublishedBy(); + if (!empty($publishedBy)) { + $this->author = implode(', ', $this->entries[0]->getPublishedBy()); + } else { + $this->author = $this->entries[0]->getDomainName(); + } } return $this; -- cgit v1.2.3 From eeabca8090ebf9a084b6b823ddf7c6493b956d4c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89tienne=20Gilli?= Date: Mon, 10 Jul 2017 09:58:18 +0200 Subject: Make updateAuthor code simpler to read --- src/Wallabag/CoreBundle/Helper/EntriesExport.php | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Helper/EntriesExport.php b/src/Wallabag/CoreBundle/Helper/EntriesExport.php index e16168b1..64d82193 100644 --- a/src/Wallabag/CoreBundle/Helper/EntriesExport.php +++ b/src/Wallabag/CoreBundle/Helper/EntriesExport.php @@ -83,15 +83,17 @@ class EntriesExport */ public function updateAuthor($method) { - $this->author = $method.' authors'; + if ('entry' !== $method) { + $this->author = $method . ' authors'; - if ('entry' === $method) { - $publishedBy = $this->entries[0]->getPublishedBy(); - if (!empty($publishedBy)) { - $this->author = implode(', ', $this->entries[0]->getPublishedBy()); - } else { - $this->author = $this->entries[0]->getDomainName(); - } + return $this; + } + + $this->author = $this->entries[0]->getDomainName(); + + $publishedBy = $this->entries[0]->getPublishedBy(); + if (!empty($publishedBy)) { + $this->author = implode(', ', $publishedBy); } return $this; -- cgit v1.2.3 From 459374022f39977656cc393e6313b85e3e60cfbb Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Mon, 24 Jul 2017 11:52:43 +0200 Subject: CS --- src/Wallabag/ImportBundle/Controller/BrowserController.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/Wallabag/ImportBundle/Controller/BrowserController.php b/src/Wallabag/ImportBundle/Controller/BrowserController.php index 0753e318..77a7a904 100644 --- a/src/Wallabag/ImportBundle/Controller/BrowserController.php +++ b/src/Wallabag/ImportBundle/Controller/BrowserController.php @@ -80,10 +80,10 @@ abstract class BrowserController extends Controller */ abstract protected function getImportService(); - /** - * Return the template used for the form. - * - * @return string - */ - abstract protected function getImportTemplate(); + /** + * Return the template used for the form. + * + * @return string + */ + abstract protected function getImportTemplate(); } -- cgit v1.2.3 From b236d3f627a21bc9b02e7726bbb72d632937a45e Mon Sep 17 00:00:00 2001 From: Simounet Date: Wed, 19 Jul 2017 20:16:23 +0200 Subject: Fix updatePublishedAt on already parsed article's date --- src/Wallabag/CoreBundle/Helper/ContentProxy.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Helper/ContentProxy.php b/src/Wallabag/CoreBundle/Helper/ContentProxy.php index 656ac6ee..fd97e0ff 100644 --- a/src/Wallabag/CoreBundle/Helper/ContentProxy.php +++ b/src/Wallabag/CoreBundle/Helper/ContentProxy.php @@ -122,7 +122,7 @@ class ContentProxy */ public function updatePublishedAt(Entry $entry, $value) { - $date = $value; + $date = $value instanceof \DateTime ? $value->date : $value; // is it a timestamp? if (filter_var($date, FILTER_VALIDATE_INT) !== false) { -- cgit v1.2.3 From ff9f89fd2318cfb29a18d941077b5afc859bf0fe Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Mon, 24 Jul 2017 16:39:29 +0200 Subject: Add a test for updatePublishedAt To avoid error when a content is re-submitted and it previously add a published date. Also, fix the `testPostSameEntry` --- src/Wallabag/CoreBundle/Helper/ContentProxy.php | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Helper/ContentProxy.php b/src/Wallabag/CoreBundle/Helper/ContentProxy.php index fd97e0ff..1ac7ad83 100644 --- a/src/Wallabag/CoreBundle/Helper/ContentProxy.php +++ b/src/Wallabag/CoreBundle/Helper/ContentProxy.php @@ -122,15 +122,21 @@ class ContentProxy */ public function updatePublishedAt(Entry $entry, $value) { - $date = $value instanceof \DateTime ? $value->date : $value; + $date = $value; // is it a timestamp? if (filter_var($date, FILTER_VALIDATE_INT) !== false) { - $date = '@' . $value; + $date = '@' . $date; } try { - $entry->setPublishedAt(new \DateTime($date)); + // is it already a DateTime? + // (it's inside the try/catch in case of fail to be parse time string) + if (!$date instanceof \DateTime) { + $date = new \DateTime($date); + } + + $entry->setPublishedAt($date); } catch (\Exception $e) { $this->logger->warning('Error while defining date', ['e' => $e, 'url' => $entry->getUrl(), 'date' => $value]); } -- cgit v1.2.3 From 383215866f81139e50baff59073f8f0706564b9d Mon Sep 17 00:00:00 2001 From: Nicolas Hart Date: Thu, 27 Jul 2017 22:35:59 +0200 Subject: add a dedicated title for all entries page --- src/Wallabag/CoreBundle/Controller/EntryController.php | 1 + src/Wallabag/CoreBundle/Resources/translations/messages.da.yml | 1 + src/Wallabag/CoreBundle/Resources/translations/messages.de.yml | 1 + src/Wallabag/CoreBundle/Resources/translations/messages.en.yml | 1 + src/Wallabag/CoreBundle/Resources/translations/messages.es.yml | 1 + src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml | 1 + src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml | 1 + src/Wallabag/CoreBundle/Resources/translations/messages.it.yml | 1 + src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml | 1 + src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml | 1 + src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml | 1 + src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml | 1 + src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml | 1 + .../CoreBundle/Resources/views/themes/common/Entry/_title.html.twig | 2 +- 14 files changed, 14 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Controller/EntryController.php b/src/Wallabag/CoreBundle/Controller/EntryController.php index 845ebef6..3dcfbebe 100644 --- a/src/Wallabag/CoreBundle/Controller/EntryController.php +++ b/src/Wallabag/CoreBundle/Controller/EntryController.php @@ -573,6 +573,7 @@ class EntryController extends Controller 'entries' => $entries, 'currentPage' => $page, 'searchTerm' => $searchTerm, + 'isFiltered' => $form->isSubmitted(), ] ); } diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml index 5229ac73..5e5bbde2 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.da.yml @@ -169,6 +169,7 @@ entry: # filtered_tags: 'Filtered by tags:' # filtered_search: 'Filtered by search:' # untagged: 'Untagged entries' + # all: 'All entries' list: # number_on_the_page: '{0} There is no entry.|{1} There is one entry.|]1,Inf[ There are %count% entries.' reading_time: 'estimeret læsetid' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml index 996f173a..48f8a535 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.de.yml @@ -169,6 +169,7 @@ entry: filtered_tags: 'Gefiltert nach Tags:' filtered_search: 'Gefiltert nach Suche:' untagged: 'Nicht getaggte Einträge' + all: 'Alle Einträge' list: number_on_the_page: '{0} Es gibt keine Einträge.|{1} Es gibt einen Eintrag.|]1,Inf[ Es gibt %count% Einträge.' reading_time: 'geschätzte Lesezeit' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml index aa1cd1a9..f41a7c85 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.en.yml @@ -169,6 +169,7 @@ entry: filtered_tags: 'Filtered by tags:' filtered_search: 'Filtered by search:' untagged: 'Untagged entries' + all: 'All entries' list: number_on_the_page: '{0} There are no entries.|{1} There is one entry.|]1,Inf[ There are %count% entries.' reading_time: 'estimated reading time' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml index 96998f53..ea4d84ba 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.es.yml @@ -169,6 +169,7 @@ entry: filtered_tags: 'Filtrado por etiquetas:' filtered_search: 'Filtrado por búsqueda:' untagged: 'Artículos sin etiquetas' + all: "Todos los artículos" list: number_on_the_page: '{0} No hay artículos.|{1} Hay un artículo.|]1,Inf[ Hay %count% artículos.' reading_time: 'tiempo estimado de lectura' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml index 57e6c029..11047e83 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.fa.yml @@ -169,6 +169,7 @@ entry: # filtered_tags: 'Filtered by tags:' # filtered_search: 'Filtered by search:' # untagged: 'Untagged entries' + # all: 'All entries' list: number_on_the_page: '{0} هیج مقاله‌ای نیست.|{1} یک مقاله هست.|]1,Inf[ %count% مقاله هست.' reading_time: 'زمان تخمینی برای خواندن' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml index 6eac4c36..246add86 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.fr.yml @@ -169,6 +169,7 @@ entry: filtered_tags: "Articles filtrés par tags :" filtered_search: "Articles filtrés par recherche :" untagged: "Article sans tag" + all: "Tous les articles" list: number_on_the_page: "{0} Il n’y a pas d’article.|{1} Il y a un article.|]1,Inf[ Il y a %count% articles." reading_time: "durée de lecture" diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml index fa7ae0b2..0de8bed7 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.it.yml @@ -169,6 +169,7 @@ entry: filtered_tags: 'Filtrati per etichetta:' filtered_search: 'Filtrati per ricerca:' untagged: 'Articoli non etichettati' + all: 'Tutti gli articoli' list: number_on_the_page: "{0} Non ci sono contenuti.|{1} C'è un contenuto.|]1,Inf[ Ci sono %count% contenuti." reading_time: 'tempo di lettura stimato' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml index be57e903..b2842ed2 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.oc.yml @@ -169,6 +169,7 @@ entry: filtered_tags: 'Articles filtrats per etiquetas :' filtered_search: 'Articles filtrats per recèrca :' untagged: 'Articles sens etiqueta' + all: 'Totes los articles' list: number_on_the_page: "{0} I a pas cap d'article.|{1} I a un article.|]1,Inf[ I a %count% articles." reading_time: 'durada de lectura' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml index 00c559ed..ab1b3d63 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.pl.yml @@ -169,6 +169,7 @@ entry: filtered_tags: 'Filtrowane po tagach:' filtered_search: 'Filtrowanie po wyszukiwaniu:' untagged: 'Odtaguj wpisy' + all: 'Wszystkie przedmioty' list: number_on_the_page: '{0} Nie ma wpisów.|{1} Jest jeden wpis.|]1,Inf[ Są %count% wpisy.' reading_time: 'szacunkowy czas czytania' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml index 4ab5f144..5c1ae058 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.pt.yml @@ -169,6 +169,7 @@ entry: filtered_tags: 'Filtrar por tags:' # filtered_search: 'Filtered by search:' untagged: 'Entradas sem tags' + # all: 'All entries' list: number_on_the_page: '{0} Não existem entradas.|{1} Existe uma entrada.|]1,Inf[ Existem %count% entradas.' reading_time: 'tempo estimado de leitura' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml index f16504ed..0d6f5f8e 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.ro.yml @@ -169,6 +169,7 @@ entry: # filtered_tags: 'Filtered by tags:' # filtered_search: 'Filtered by search:' # untagged: 'Untagged entries' + # all: 'All entries' list: # number_on_the_page: '{0} There is no entry.|{1} There is one entry.|]1,Inf[ There are %count% entries.' reading_time: 'timp estimat de citire' diff --git a/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml b/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml index 90a140cd..87b5e200 100644 --- a/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml +++ b/src/Wallabag/CoreBundle/Resources/translations/messages.tr.yml @@ -169,6 +169,7 @@ entry: # filtered_tags: 'Filtered by tags:' # filtered_search: 'Filtered by search:' # untagged: 'Untagged entries' + # all: 'All entries' list: number_on_the_page: '{0} Herhangi bir makale yok.|{1} Burada bir adet makale var.|]1,Inf[ Burada %count% adet makale var.' reading_time: 'tahmini okuma süresi' diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/common/Entry/_title.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/common/Entry/_title.html.twig index 654c1d2d..5c17e9f7 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/common/Entry/_title.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/common/Entry/_title.html.twig @@ -5,7 +5,7 @@ {% elseif currentRoute == 'archive' %} {{ 'entry.page_titles.archived'|trans }} {% elseif currentRoute == 'all' %} - {{ 'entry.page_titles.filtered'|trans }} + {{ isFiltered ? 'entry.page_titles.filtered'|trans : 'entry.page_titles.all'|trans }} {% elseif currentRoute == 'search' %} {{ 'entry.page_titles.filtered_search'|trans }} {{ filter }} {% elseif currentRoute == 'tag_entries' %} -- cgit v1.2.3 From d58199f3624c1cca1f851b4af5b8c88dea613a3b Mon Sep 17 00:00:00 2001 From: Nicolas Hart Date: Thu, 27 Jul 2017 23:25:27 +0200 Subject: Better rendering for show user command using symfony style --- .../CoreBundle/Command/ShowUserCommand.php | 23 ++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Command/ShowUserCommand.php b/src/Wallabag/CoreBundle/Command/ShowUserCommand.php index eef04988..33888fa3 100644 --- a/src/Wallabag/CoreBundle/Command/ShowUserCommand.php +++ b/src/Wallabag/CoreBundle/Command/ShowUserCommand.php @@ -7,12 +7,13 @@ use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Style\SymfonyStyle; use Wallabag\UserBundle\Entity\User; class ShowUserCommand extends ContainerAwareCommand { - /** @var OutputInterface */ - protected $output; + /** @var SymfonyStyle */ + protected $io; protected function configure() { @@ -29,7 +30,7 @@ class ShowUserCommand extends ContainerAwareCommand protected function execute(InputInterface $input, OutputInterface $output) { - $this->output = $output; + $this->io = new SymfonyStyle($input, $output); $username = $input->getArgument('username'); @@ -37,7 +38,7 @@ class ShowUserCommand extends ContainerAwareCommand $user = $this->getUser($username); $this->showUser($user); } catch (NoResultException $e) { - $output->writeln(sprintf('User "%s" not found.', $username)); + $this->io->error(sprintf('User "%s" not found.', $username)); return 1; } @@ -50,12 +51,14 @@ class ShowUserCommand extends ContainerAwareCommand */ private function showUser(User $user) { - $this->output->writeln(sprintf('Username : %s', $user->getUsername())); - $this->output->writeln(sprintf('Email : %s', $user->getEmail())); - $this->output->writeln(sprintf('Display name : %s', $user->getName())); - $this->output->writeln(sprintf('Creation date : %s', $user->getCreatedAt()->format('Y-m-d H:i:s'))); - $this->output->writeln(sprintf('Last login : %s', $user->getLastLogin() !== null ? $user->getLastLogin()->format('Y-m-d H:i:s') : 'never')); - $this->output->writeln(sprintf('2FA activated: %s', $user->isTwoFactorAuthentication() ? 'yes' : 'no')); + $this->io->listing([ + sprintf('Username : %s', $user->getUsername()), + sprintf('Email : %s', $user->getEmail()), + sprintf('Display name : %s', $user->getName()), + sprintf('Creation date : %s', $user->getCreatedAt()->format('Y-m-d H:i:s')), + sprintf('Last login : %s', $user->getLastLogin() !== null ? $user->getLastLogin()->format('Y-m-d H:i:s') : 'never'), + sprintf('2FA activated: %s', $user->isTwoFactorAuthentication() ? 'yes' : 'no'), + ]); } /** -- cgit v1.2.3 From a19e212f433be7d989f27c6271cba9a84fcefac9 Mon Sep 17 00:00:00 2001 From: Nicolas Hart Date: Thu, 27 Jul 2017 23:44:12 +0200 Subject: Remove unused method getDoctrine in several commands --- src/Wallabag/CoreBundle/Command/CleanDuplicatesCommand.php | 5 ----- src/Wallabag/CoreBundle/Command/ExportCommand.php | 5 ----- src/Wallabag/CoreBundle/Command/ShowUserCommand.php | 5 ----- 3 files changed, 15 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Command/CleanDuplicatesCommand.php b/src/Wallabag/CoreBundle/Command/CleanDuplicatesCommand.php index d964439d..b4aa4e47 100644 --- a/src/Wallabag/CoreBundle/Command/CleanDuplicatesCommand.php +++ b/src/Wallabag/CoreBundle/Command/CleanDuplicatesCommand.php @@ -111,9 +111,4 @@ class CleanDuplicatesCommand extends ContainerAwareCommand { return $this->getContainer()->get('wallabag_user.user_repository')->findOneByUserName($username); } - - private function getDoctrine() - { - return $this->getContainer()->get('doctrine'); - } } diff --git a/src/Wallabag/CoreBundle/Command/ExportCommand.php b/src/Wallabag/CoreBundle/Command/ExportCommand.php index c2e4be05..291926e4 100644 --- a/src/Wallabag/CoreBundle/Command/ExportCommand.php +++ b/src/Wallabag/CoreBundle/Command/ExportCommand.php @@ -69,9 +69,4 @@ class ExportCommand extends ContainerAwareCommand return 0; } - - private function getDoctrine() - { - return $this->getContainer()->get('doctrine'); - } } diff --git a/src/Wallabag/CoreBundle/Command/ShowUserCommand.php b/src/Wallabag/CoreBundle/Command/ShowUserCommand.php index eef04988..4511c235 100644 --- a/src/Wallabag/CoreBundle/Command/ShowUserCommand.php +++ b/src/Wallabag/CoreBundle/Command/ShowUserCommand.php @@ -69,9 +69,4 @@ class ShowUserCommand extends ContainerAwareCommand { return $this->getContainer()->get('wallabag_user.user_repository')->findOneByUserName($username); } - - private function getDoctrine() - { - return $this->getContainer()->get('doctrine'); - } } -- cgit v1.2.3 From 04f19537e71630887fa3fa57bde9ae634d2f267e Mon Sep 17 00:00:00 2001 From: Nicolas Hart Date: Thu, 27 Jul 2017 23:51:01 +0200 Subject: Remove unused use statement in install command --- src/Wallabag/CoreBundle/Command/InstallCommand.php | 1 - 1 file changed, 1 deletion(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Command/InstallCommand.php b/src/Wallabag/CoreBundle/Command/InstallCommand.php index 50551480..c7809053 100644 --- a/src/Wallabag/CoreBundle/Command/InstallCommand.php +++ b/src/Wallabag/CoreBundle/Command/InstallCommand.php @@ -14,7 +14,6 @@ use Symfony\Component\Console\Output\BufferedOutput; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Question\ConfirmationQuestion; use Symfony\Component\Console\Question\Question; -use Wallabag\CoreBundle\Entity\Config; class InstallCommand extends ContainerAwareCommand { -- cgit v1.2.3 From bde23a44f8585c0c668719d9e34f06e30e5571aa Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Fri, 28 Jul 2017 08:07:09 +0200 Subject: Empty currentTag should be null And when a parameter is null, it won't appear in the url like `?tag=`. --- .../CoreBundle/Resources/views/themes/baggy/Entry/entries.html.twig | 2 +- .../CoreBundle/Resources/views/themes/material/Entry/entries.html.twig | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Entry/entries.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Entry/entries.html.twig index 6424df8d..12cead48 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Entry/entries.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/baggy/Entry/entries.html.twig @@ -86,7 +86,7 @@