date-poll-api/src/Controller/api/v1/PollController.php

631 lines
16 KiB
PHP
Raw Normal View History

2020-10-26 11:39:04 +01:00
<?php
2021-05-03 12:38:30 +02:00
namespace App\Controller\api\v1;
2020-10-26 11:39:04 +01:00
use App\Controller\EmailsController;
2020-10-26 11:39:04 +01:00
use App\Entity\Choice;
use App\Entity\Owner;
use App\Entity\Poll;
use App\Repository\PollRepository;
2021-04-30 12:28:05 +02:00
use DateTime;
2021-04-27 10:22:16 +02:00
use FOS\RestBundle\Controller\Annotations\Delete;
use FOS\RestBundle\Controller\Annotations\Get;
use FOS\RestBundle\Controller\Annotations\Post;
use FOS\RestBundle\Controller\Annotations\Put;
use FOS\RestBundle\Controller\Annotations\Route;
2020-10-26 11:39:04 +01:00
use JMS\Serializer\SerializerInterface;
use Swift_Mailer;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Class DefaultController
* @package App\Controller
* @Route("/api/v1/poll",name="api_")
*/
class PollController extends EmailsController {
2020-10-26 11:39:04 +01:00
/**
* @Get(
* path = "/",
* name = "get_all_polls"
* )
*/
public function getAllPollsAction( PollRepository $pollRepository ): Response {
$data = $pollRepository->findAll();
2020-10-26 11:39:04 +01:00
2021-04-26 13:47:44 +02:00
$polls = $data;
$titles = [];
$pollData = [
2020-10-26 11:39:04 +01:00
'message' => 'here are your polls',
2021-04-26 13:47:44 +02:00
'count' => count( $polls ),
];
2021-04-26 13:47:44 +02:00
$debug = 1;
2021-04-26 13:47:44 +02:00
if ( $debug ) {
foreach ( $polls as $poll ) {
2021-04-26 13:47:44 +02:00
$titles[] = [
'title' => $poll->getTitle(),
'slug' => $poll->getCustomUrl(),
];
}
2021-04-26 13:47:44 +02:00
$pollData[ 'polls' ] = $titles;
}
2021-04-26 13:47:44 +02:00
return $this->json( $pollData );
2020-10-26 11:39:04 +01:00
}
/**
* get a poll config by its custom URL, we do not want polls to be reachable by their numeric id
2020-10-26 11:39:04 +01:00
* @Get(
* path = "/{customUrl}",
2021-04-21 11:22:01 +02:00
* name = "get_poll"
2020-10-26 11:39:04 +01:00
* )
*
2020-10-26 11:39:04 +01:00
* @param SerializerInterface $serializer
* @param Request $request
*
* @return JsonResponse|Response
*/
public function getPollConfig(
SerializerInterface $serializer,
$customUrl,
2020-10-26 11:39:04 +01:00
Request $request
2021-04-26 13:47:44 +02:00
) {
$repository = $this->getDoctrine()->getRepository( Poll::class );
$poll = $repository->findOneByCustomUrl( $customUrl );
if ( ! $poll ) {
return $this->notFoundPoll( $customUrl );
}
2020-10-26 11:39:04 +01:00
$comments = $poll->getComments();
2021-04-26 15:21:19 +02:00
$stacks = $poll->getStacksOfVotes();
2021-04-26 15:14:25 +02:00
2020-10-26 11:39:04 +01:00
2021-04-26 15:43:33 +02:00
$pass = $poll->getPassword();
2020-10-26 11:39:04 +01:00
/**
* password protected content
*/
if ( $pass ) {
2021-02-24 10:57:56 +01:00
// no password possibly given by this route
return $this->json( [
2021-04-26 13:47:44 +02:00
'message' => 'this is protected by a password,but you did not provide the encoded password parameter, and you should feel bad. ',
2021-02-24 10:57:56 +01:00
],
403 );
2020-10-26 11:39:04 +01:00
} else {
// free access to poll
2021-04-26 15:43:33 +02:00
return $this->json( $poll->display() );
}
2020-10-26 11:39:04 +01:00
}
2020-10-26 11:39:04 +01:00
2021-04-27 10:22:16 +02:00
/**
* @param $id
* message when the poll is not found
*
* @return JsonResponse
*/
public function notFoundPoll( $id ): Response {
return $this->json( [
'message' => $id . ' : poll not found',
],
404 );
}
2021-02-24 10:57:56 +01:00
/**
* get a poll config by its custom URL, we do not want polls to be reachable by their numeric id
* @Get(
* path = "/{customUrl}/pass/{md5}",
2021-02-24 10:57:56 +01:00
* name = "get_protected_poll",
* )
*
* @param SerializerInterface $serializer
* @param Request $request
*
* @return JsonResponse|Response
*/
2021-04-26 13:47:44 +02:00
function getProtectedPoll( $customUrl, $md5, SerializerInterface $serializer ) {
2021-02-24 10:57:56 +01:00
$repository = $this->getDoctrine()->getRepository( Poll::class );
2021-04-21 11:44:06 +02:00
$poll = $repository->findOneByCustomUrl( $customUrl );
2021-02-24 10:57:56 +01:00
if ( ! $poll ) {
2021-04-26 13:47:44 +02:00
return $this->notFoundPoll( $customUrl );
2021-02-24 10:57:56 +01:00
}
2021-04-27 12:51:21 +02:00
if ( md5( $poll->getPassword() ) === $md5 ) {
2021-02-24 10:57:56 +01:00
// good matching pass
2021-04-26 15:43:33 +02:00
return $this->json( $poll->display() );
2021-02-24 10:57:56 +01:00
} else {
// wrong pass
return $this->json( [
2021-04-26 13:47:44 +02:00
'message' => 'this is protected by a password, your password hash "' . $md5 . '" is wrong, and you should feel bad',
2021-05-03 14:03:21 +02:00
// 'md5' => md5( $md5 ),
2021-02-24 10:57:56 +01:00
'data' => null,
],
403 );
}
}
2021-05-03 14:03:21 +02:00
/**
* as an administrator of a poll, get a poll config by its custom URL, we do not want polls to be reachable by their numeric id
* @Get(
* path = "admin/{admin_key}",
* name = "get_admin_poll",
* )
*
* @param SerializerInterface $serializer
* @param Request $request
*
* @return JsonResponse|Response
*/
function getAdminPoll( $admin_key, $md5, SerializerInterface $serializer ) {
$repository = $this->getDoctrine()->getRepository( Poll::class );
$poll = $repository->findOneByAdminKey( $admin_key );
if ( ! $poll ) {
return $this->notFoundPoll( $admin_key );
}
// good matching pass
return $this->json( $poll->displayForAdmin() );
2021-05-03 14:03:21 +02:00
}
function returnPollData( $poll, $serializer ) {
$jsonResponse = $serializer->serialize( $poll, 'json' );
$response = new Response( $jsonResponse );
$response->headers->set( 'Content-Type', 'application/json' );
$response->setStatusCode( 200 );
2020-10-26 11:39:04 +01:00
return $response;
2020-10-26 11:39:04 +01:00
}
/**
* @Put(
2021-05-20 14:28:25 +02:00
* path = "/{customUrl}/update/{token}",
2020-10-26 11:39:04 +01:00
* name = "update_poll",
* requirements = {"content"="\w+", "poll_id"="\d+"}
* )
*/
public function updatePollConfig(
Poll $poll,
string $token,
Request $request
) {
if ( $poll->getAdminKey() !== $token ) {
return $this->json( [
'message' => 'you are NOT allowed to update the poll ' . $poll->getTitle(),
],
403 );
}
// TODO check validity of request
// update only if we have the admin key
$em = $this->getDoctrine()->getManager();
$em->persist( $poll );
$em->flush();
2021-04-27 10:22:16 +02:00
return $this->json( $poll->displayForAdmin()
,
2020-10-26 11:39:04 +01:00
200 );
}
/**
* @Post(
* path = "/",
* name = "new_poll",
* requirements = {"creator"="\w+"}
* )
* @param Request $request
*
* @return JsonResponse
*/
public function newPollAction( Request $request ) {
$data = $request->getContent();
2021-04-30 12:28:05 +02:00
$data = json_decode( $data, true );
2021-05-18 22:35:32 +02:00
// search for existing custom url, which must be unique
$custom_url = $data[ 'custom_url' ];
$repository = $this->getDoctrine()->getRepository( Poll::class );
$poll = $repository->findOneByCustomUrl( $custom_url );
if ( $poll ) {
2021-05-18 23:38:13 +02:00
throw new \JsonException( 'NOPE, ce sondage existe déjà: ' . $custom_url );
2021-05-18 22:35:32 +02:00
}
2021-04-30 12:28:05 +02:00
$newpoll = new Poll();
2020-10-26 11:39:04 +01:00
$newpoll
2021-05-18 22:35:32 +02:00
->setModificationPolicy( isset( $data[ 'modification_policy' ] ) ? $data[ 'modification_policy' ] : 'everybody' )
2021-04-30 12:28:05 +02:00
->setTitle( $data[ 'title' ] )
2021-05-03 13:42:19 +02:00
->setKind( $data[ 'kind' ] )
2021-04-30 12:28:05 +02:00
->setCustomUrl( $data[ 'custom_url' ] );
if ( count( $data[ 'allowed_answers' ] ) ) {
2021-05-20 12:53:39 +02:00
// TODO check this one
2021-04-30 12:28:05 +02:00
$newpoll->setAllowedAnswers( $data[ 'allowed_answers' ] );
}
$expiracyCalculated = $newpoll->addDaysToDate( new DateTime(),
$data[ 'default_expiracy_days_from_now' ] );
2021-04-30 12:28:05 +02:00
$newpoll->setExpiracyDate( $expiracyCalculated );
$emOwner = $this->getDoctrine()->getRepository( Owner::class );
$foundOwner = $emOwner->findOneByEmail( $data[ 'owner' ][ 'email' ] );
2020-10-26 11:39:04 +01:00
$userWasFound = false;
if ( ! $foundOwner ) {
//create a new owner
$owner = new Owner();
$owner->setPseudo( $data[ 'owner' ][ 'pseudo' ] );
$owner->setEmail( $data[ 'owner' ][ 'email' ] );
$foundOwner = $owner;
} else {
$userWasFound = true;
}
// link the owner and the poll
$newpoll->setOwner( $foundOwner );
$foundOwner->addPoll( $newpoll );
$em = $this->getDoctrine()->getManager();
$em->persist( $newpoll );
$em->persist( $foundOwner );
// emails
$newpoll->setMailOnComment( true );
2021-05-20 12:53:39 +02:00
$newpoll->setMailOnVote( $data[ 'isOwnerNotifiedByEmailOnNewVote' ] );
$newpoll->setMailOnComment( $data[ 'isOwnerNotifiedByEmailOnNewComment' ] );
2021-04-30 23:49:02 +02:00
2021-05-20 12:53:39 +02:00
$newpoll->setIsZeroKnowledge( $data[ 'is_zero_knowledge' ] );
$newpoll->setDescription( $data[ 'description' ] );
2020-10-26 11:39:04 +01:00
$newpoll->setHideResults( false );
// possible answers
2021-05-03 13:42:19 +02:00
$newpoll->setAllowedAnswers( $data[ 'allowed_answers' ] );
2021-04-30 12:28:05 +02:00
$newpoll->setVotesMax( $data[ 'maxCountOfAnswers' ] );
$newpoll->setCommentsAllowed( $data[ 'allowComments' ] );
2020-10-26 11:39:04 +01:00
// setup the password, converting the raw with md5 hash
if ( $data[ 'password' ] ) {
$newpoll->setPassword( $data[ 'password' ] );
}
2021-05-18 22:35:32 +02:00
2020-10-26 11:39:04 +01:00
// text kind of answers, dates are below
2021-04-30 12:28:05 +02:00
if ( $data[ 'kind' ] == 'text' ) {
2021-05-18 22:35:32 +02:00
// manage choices
$choices = $data[ 'choices' ];
2020-10-26 11:39:04 +01:00
foreach ( $choices as $c ) {
$newChoice = new Choice();
$newChoice
->setPoll( $newpoll )
->setName( $c[ 'literal' ] );
$em->persist( $newChoice );
2021-05-18 22:35:32 +02:00
$newpoll->addChoice( $newChoice );
2020-10-26 11:39:04 +01:00
}
2021-04-30 12:28:05 +02:00
} // date kind of poll
elseif ( $data[ 'kind' ] == 'date' ) {
$choices = $data[ 'dateChoices' ];
if ( isset( $data[ 'hasSeveralHours' ] ) && $data[ 'hasSeveralHours' ] == true ) {
2021-04-30 12:28:05 +02:00
// different hours spans make more choices
foreach ( $choices as $c ) {
$currentDate = $c[ 'literal' ];
2021-05-18 22:35:32 +02:00
$timeSlicesOfThisChoice = $c[ 'timeSlices' ];
2021-04-30 12:28:05 +02:00
foreach ( $timeSlicesOfThisChoice as $t ) {
$newChoice = new Choice();
$newChoice
->setPoll( $newpoll )
->setName( $currentDate . ' >>> ' . $t[ 'literal' ] );
$em->persist( $newChoice );
2021-05-18 22:35:32 +02:00
$newpoll->addChoice( $newChoice );
2021-04-30 12:28:05 +02:00
}
2021-05-18 22:35:32 +02:00
2021-04-30 12:28:05 +02:00
}
2020-10-26 11:39:04 +01:00
} else {
2021-04-30 12:28:05 +02:00
// all choices will be having the same time slices from timeSlices
$timeSlicesForAllChoices = $data[ 'timeSlices' ];
foreach ( $choices as $c ) {
2021-05-18 22:35:32 +02:00
$currentDate = $c[ 'date_object' ];
2021-04-30 12:28:05 +02:00
foreach ( $timeSlicesForAllChoices as $t ) {
$newChoice = new Choice();
$newChoice
->setPoll( $newpoll )
->setName( $currentDate . ' >>> ' . $t[ 'literal' ] );
$em->persist( $newChoice );
2021-05-18 22:35:32 +02:00
$newpoll->addChoice( $newChoice );
2021-04-30 12:28:05 +02:00
}
}
2020-10-26 11:39:04 +01:00
}
}
$em->persist( $newpoll );
$em->flush();
$precision = '';
if ( $userWasFound ) {
$precision = 'from an existing user : ' . $foundOwner->getEmail();
}
$this->sendCreationMailAction( $foundOwner, $newpoll );
2021-05-18 22:35:32 +02:00
$newChoices = $newpoll->display()[ 'choices' ];
2020-10-26 11:39:04 +01:00
return $this->json( [
2021-05-18 22:35:32 +02:00
'message' => 'you created the poll ' . $newpoll->getCustomUrl() . $precision,
'id' => $newpoll->getId(),
2021-04-30 12:28:05 +02:00
'poll' => $newpoll->displayForAdmin(),
2021-04-27 10:22:16 +02:00
'password_protected' => is_string( $newpoll->getPassword() ),
2020-10-26 11:39:04 +01:00
],
201 );
}
/**
* @Get(
* path = "/mail/test-mail-poll/{emailChoice}",
* name = "test-mail-poll",
* )
*
* send the creation mail to owner
*
* @param Owner $admin_user
* @param Poll $poll
* @param Swift_Mailer $mailer
*
* @return int
* not that the email tktest_commentateur@tktest.com does not really exist
*/
// public function sendCreationMailAction( Owner $admin_user, Poll $poll, \Swift_Mailer $mailer) {
public function testSendCreationMailAction(
$emailChoice = 'tktest_commentateur@tktest.com'
) {
2021-05-18 23:38:13 +02:00
$em = $this->getDoctrine()->getRepository( Poll::class );
$foundPoll = $em->findOneByCustomUrl( 'dessin-anime' );
2020-10-26 11:39:04 +01:00
$em = $this->getDoctrine()->getRepository( Owner::class );
$foundOwner = $em->findOneByEmail( $emailChoice );
2021-05-18 23:38:13 +02:00
return $this->render( 'emails/creation-mail.html.twig',
[ 'poll' => $foundPoll, 'owner' => $foundPoll->getOwner() ] );
// if ( $foundOwner ) {
// $sent = $this->sendOwnerPollsAction( $foundOwner );
// if ( $sent ) {
// $config = [
// 'owner' => $foundOwner,
// 'title' => $this->getParameter( 'WEBSITE_NAME' ) . ' | Mes sondages',
// 'email_template' => 'emails/owner-list.html.twig',
// ];
// return $this->render( 'emails/owner-list.html.twig', $config );
// }
// }
// return $this->json( [ "message" => "test email sent to " . $foundOwner->getEmail() . "!" ], 200 );
2021-05-18 23:26:33 +02:00
// $this->sendMailWithVars( $config );
// return $this->json( [ "message" => "user with this email was not found" ], 400 );
2020-10-26 11:39:04 +01:00
}
/**
* @Delete(
* path = "/{admin_key}",
2020-10-26 11:39:04 +01:00
* name = "poll_delete",
* requirements = {"accessToken"="\w+", "poll_id"="\d+"}
* )
* @param Poll $poll
* @param $accessToken
*
* @return JsonResponse
*/
public
function deletePollAction(
$admin_key
2020-10-26 11:39:04 +01:00
) {
$emPoll = $this->getDoctrine()->getRepository( Poll::class );
$found = $emPoll->findOneByAdminKey( $admin_key );
if ( $found ) {
2020-10-26 11:39:04 +01:00
$em = $this->getDoctrine()->getManager();
$em->remove( $found );
2020-10-26 11:39:04 +01:00
$em->flush();
return $this->json( [
'message' => 'boom! le sondage et ses objets assocités a été supprimé',
] );
} else {
return $this->json( [
'message' => 'le token d\'autorisation est invalide, vous ne pouvez pas modifier ce sondage',
] );
}
}
/**
2021-02-05 15:33:38 +01:00
* Checks if a slug is already taken by a poll
2020-10-26 11:39:04 +01:00
* @Get(
* path = "/slug/{customUrl}",
2020-10-26 11:39:04 +01:00
* name = "check_slug_is_unique",
* )
*/
public function checkSlugIsUniqueAction( string $customUrl ) {
2020-10-26 11:39:04 +01:00
$emPoll = $this->getDoctrine()->getRepository( Poll::class );
$found = $emPoll->findOneByCustomUrl( $customUrl );
2020-10-26 11:39:04 +01:00
$elaborated_message_version = false;
if ( $found ) {
if ( ! $elaborated_message_version ) {
return $this->json( null,
204 );
}
// we should use an other slug
return $this->json( [
'message' => ' NO, this custom_url is already taken on this Framadate instance ',
2020-10-26 11:39:04 +01:00
'data' => [
'slug' => $customUrl,
2020-10-26 11:39:04 +01:00
],
],
204 );
}
if ( ! $elaborated_message_version ) {
return $this->json( null,
404 );
}
return $this->json( [
'message' => ' yes this slug is available on this Framadate instance ',
'data' => [
'slug' => $customUrl,
2020-10-26 11:39:04 +01:00
],
],
404 );
}
/**
* Get Admin poll config
* @Get(
* path = "/admin/{token}",
* name = "get_admin_config",
* )
*
* @param SerializerInterface $serializer
* @param $token
*
* @return JsonResponse|Response
*/
public function getAdministrationConfig( SerializerInterface $serializer, $token ) {
$emPoll = $this->getDoctrine()->getRepository( Poll::class );
$pollFound = $emPoll->findOneByAdminKey( $token );
if ( $pollFound ) {
$poll = $pollFound;
2020-10-26 11:39:04 +01:00
$returnedPoll = [
'message' => 'your poll config',
'poll' => $poll->displayForAdmin(),
2020-10-26 11:39:04 +01:00
];
2021-04-30 14:30:45 +02:00
return $this->json( $returnedPoll,
200 );;
2020-10-26 11:39:04 +01:00
}
return $this->json( [
'message' => 'You are not allowed to do anything with this token',
'data' => [
'token' => $token,
],
],
403 );
}
/**
* Find expired polls and set them as such
* @Get(
* path = "/admin/clean_expired_polls/{token}",
* name = "clean_expired_polls",
* )
*
* @param $token
*
* @return JsonResponse|Response
*/
public function getExpiredPollsCleanup( $token ) {
if ( $token !== 'superCaligistriixpirlidouciousse' ) {
return $this->json( [
'message' => 'not allowed',
'data' => [
'token' => $token,
],
],
403 );
}
$em = $this->getDoctrine()->getManager();
$emPoll = $this->getDoctrine()->getRepository( Poll::class );
$deletablePollsFound = $emPoll->findDeletableExpiredPolls(); // dead by more than 30 days
$expiredPollsFound = $emPoll->findExpiredPolls(); // just dead
$soon_expired_polls = $emPoll->findSoonExpiredPolls(); // will die in 30 days
$deletedTitle = [];
$expiredTitle = [];
$soon_expired_title = [];
$really_delete = false;
foreach ( $soon_expired_polls as $item ) {
$soon_expired_title[] = $item->getTitle();
}
foreach ( $expiredPollsFound as $item ) {
$expiredTitle[] = $item->getTitle();
$item->setVotesAllowed( false );
$em->persist( $item );
}
foreach ( $deletablePollsFound as $item ) {
$deletedTitle[] = $item->getTitle();
if ( $really_delete ) {
$item->setVotesAllowed( false );
$em->remove( $item );
}
}
$em->flush();
return $this->json( [
'message' => 'cleanup report',
'really_delete' => $really_delete,
'deleted' => count( $deletablePollsFound ),
'deleted_titles' => $deletedTitle,
'expired' => count( $expiredPollsFound ),
'expired_titles' => $expiredTitle,
'soon_to_be_expired' => count( $soon_expired_polls ),
'soon_to_be_expired_titles' => $soon_expired_title,
'data' => [
'token' => $token,
],
],
200 );
}
2020-10-26 11:39:04 +01:00
}