src/Controller/ApiBundle/UserRESTController.php line 659

Open in your IDE?
  1. <?php
  2. /**
  3.  * Created by PhpStorm.
  4.  * User: grego
  5.  * Date: 02/06/2022
  6.  * Time: 12:30
  7.  */
  8. namespace App\Controller\ApiBundle;
  9. use App\Entity\Badge;
  10. use App\Entity\FAQQuestion;
  11. use App\Entity\Feedback;
  12. use App\Entity\Recipient;
  13. use App\Entity\RequestLog;
  14. use App\Entity\Recommendation;
  15. use App\Entity\SkillsPath;
  16. use App\Entity\User;
  17. use App\Manager\CossManager;
  18. use App\Manager\GamificationManager;
  19. use App\Manager\MailerManager;
  20. use App\Manager\UserManager;
  21. use App\Repository\BadgeRepository;
  22. use App\Repository\RecommendationRepository;
  23. use App\Repository\RecipientRepository;
  24. use DateTime;
  25. use Doctrine\ORM\EntityManagerInterface;
  26. use Dompdf\Dompdf;
  27. use Dompdf\Options;
  28. use FOS\RestBundle\Controller\AbstractFOSRestController;
  29. use FOS\RestBundle\View\View;
  30. use Imagick;
  31. use ImagickException;
  32. use pChart\pCharts;
  33. use pChart\pColor;
  34. use pChart\pDraw;
  35. use Sonata\MediaBundle\Provider\Pool;
  36. use Sonata\MediaBundle\Entity\MediaManager;
  37. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  38. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  39. use Symfony\Component\HttpFoundation\JsonResponse;
  40. use Symfony\Component\HttpFoundation\Request;
  41. use Symfony\Component\HttpFoundation\Response;
  42. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  43. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  44. use Symfony\Component\Mailer\MailerInterface;
  45. use Symfony\Component\Mime\Address;
  46. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  47. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  48. use Symfony\Component\Security\Core\Security;
  49. use Symfony\Component\Security\Csrf\TokenStorage\TokenStorageInterface;
  50. use Symfony\Contracts\Translation\TranslatorInterface;
  51. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  52. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  53. use Trikoder\Bundle\OAuth2Bundle\Model\Client;
  54. use Trikoder\Bundle\OAuth2Bundle\Service\CredentialsRevoker\DoctrineCredentialsRevoker;
  55. use FOS\RestBundle\Controller\Annotations\Get;
  56. use FOS\RestBundle\Controller\Annotations\Post;
  57. use FOS\RestBundle\Controller\Annotations\Patch;
  58. use FOS\RestBundle\Controller\Annotations\Delete;
  59. class UserRESTController extends AbstractFOSRestController {
  60.     private $resetPasswordHelper;
  61.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelper)
  62.     {
  63.         $this->resetPasswordHelper $resetPasswordHelper;
  64.     }
  65.     /**
  66.      * @Get("/api/user")
  67.      */
  68.     public function getAction(Request $requestEntityManagerInterface $emUserManager $userManagerGamificationManager $gamificationManagerPool $pool)
  69.     {
  70.         $user $this->getUser();
  71.         if (!$user->getDeletedAt()) {
  72.             $request->setLocale($user->getLocale());
  73.             $featured $user->getImage();
  74.             $image "/fakepath";
  75.             if ($featured) {
  76.                 $provider $pool->getProvider($featured->getProviderName());
  77.                 $format $provider->getFormatName($featured"square");
  78.                 $image $provider->generatePublicUrl($featured$format);
  79.             }
  80.             $image $userManager->getBase64FromImage($image);
  81.             if (!$image) {
  82.                 $image $request->getSchemeAndHttpHost() . "/build/images/avatar-default.png";
  83.             }
  84.             $response = array("user" => $user);
  85.             $response["image"] = $image;
  86.             $badgesHistory $em->getRepository(Badge::class)->getBadgesHistory($user);
  87.             $badgesFormatted = array();
  88.             $today = new DateTime();
  89.             foreach ($badgesHistory as $badge) {
  90.                 $skill $badge->getSkill();
  91.                 $firstFeedback $em->getRepository(Feedback::class)->getFirstFeedbackOnSkill($user$skill$today);
  92.                 $lastFeedback $em->getRepository(Feedback::class)->getLastFeedbackOnSkill($user$skill$today);
  93.                 $start = new DateTime();
  94.                 $end = new DateTime();
  95.                 if ($firstFeedback) {
  96.                     $start $firstFeedback->getCreatedAt();
  97.                 }
  98.                 if ($lastFeedback) {
  99.                     $end $lastFeedback->getAnsweredAt();
  100.                 }
  101.                 $baseUrl $request->getSchemeAndHttpHost();
  102.                 $badgeUrl $baseUrl.'/badges/'.$user->getId().'/baked/' .$badge->getToken().'-badge-baked.png';   // Baked badge PNG
  103.                 $badgesFormatted[] = array(
  104.                     "id" => $badge->getId(),
  105.                     "user" => $badge->getUser(),
  106.                     "skill" => $badge->getSkill(),
  107.                     "createdAt" => $badge->getCreatedAt(),
  108.                     "token" => $badge->getToken(),
  109.                     "badgeUrl" => $badgeUrl,
  110.                     "start" => $start,
  111.                     "end" => $end,
  112.                     'recommendations' => $userManager->getUserSkillActiveRecommendations($user$badge)
  113.                 );
  114.             }
  115.             $response["gamification"]["badgesHistory"] = $badgesFormatted;
  116.             $response["gamification"]["myskills"]["statistics"] = $userManager->getStatistics($user$user->getLocale());
  117.             // Compute total strengths & weaknesses
  118.             $totalStrengths = array();
  119.             $totalWeaknesses = array();
  120.             foreach ($response["gamification"]["myskills"]["statistics"]['all'] as $skillStat) {
  121.                 if (isset($skillStat['strengths'])) {
  122.                     $totalStrengths array_merge($totalStrengths$skillStat['strengths']);
  123.                 }
  124.                 if (isset($skillStat['strengths'])) {
  125.                     $totalWeaknesses array_merge($totalWeaknesses$skillStat['weaknesses']);
  126.                 }
  127.             }
  128.             $totalStrengthsCumul = array();
  129.             $totalWeaknessesCumul = array();
  130.             foreach ($totalStrengths as $strength) {
  131.                 if (isset($totalStrengthsCumul[$strength['tag']])) {
  132.                     $totalStrengthsCumul[$strength['tag']]['count'] += $strength["count"];
  133.                 } else {
  134.                     $totalStrengthsCumul[$strength['tag']] = array('tag' => $strength['tag'], 'count' => $strength["count"]);
  135.                 }
  136.             }
  137.             foreach ($totalWeaknesses as $weakness) {
  138.                 if (isset($totalWeaknessesCumul[$weakness['tag']])) {
  139.                     $totalWeaknessesCumul[$weakness['tag']]['count'] += $weakness["count"];
  140.                 } else {
  141.                     $totalWeaknessesCumul[$weakness['tag']] = array('tag' => $weakness['tag'], 'count' => $weakness["count"]);
  142.                 }
  143.             }
  144.             $computedStrengthsWeaknesses $userManager->computeStrengthsWeaknesses($totalStrengthsCumul$totalWeaknessesCumul);
  145.             $totalStrengthsCumul $computedStrengthsWeaknesses['strengths'];
  146.             $totalWeaknessesCumul $computedStrengthsWeaknesses['weaknesses'];
  147.             // Desc sort
  148.             usort($totalStrengthsCumul, function ($first$second) {
  149.                 return $first['count'] < $second['count'];
  150.             });
  151.             usort($totalWeaknessesCumul, function ($first$second) {
  152.                 return $first['count'] < $second['count'];
  153.             });
  154.             $response['gamification']['strengthsWeaknessesCumul']['strengths'] = array_slice($totalStrengthsCumul05);
  155.             $response['gamification']['strengthsWeaknessesCumul']['weaknesses'] = array_slice($totalWeaknessesCumul05);;
  156.             $totalGoodBehaviors = array();
  157.             $totalMediumBehaviors = array();
  158.             $totalBadBehaviors = array();
  159.             foreach ($response['gamification']['myskills']['statistics']['all'] as &$skillStat) {
  160.                 //Total Behaviors
  161.                 $skillGoodBehavior = array("title" => $skillStat['skill']->getTitle());
  162.                 $skillMediumBehavior = array("title" => $skillStat['skill']->getTitle());
  163.                 $skillBadBehavior = array("title" => $skillStat['skill']->getTitle());
  164.                 $worstScore 5;
  165.                 $worstBehavior null;
  166.                 foreach ($skillStat['scores'] as $score) {
  167.                     if ($score['average'] < 3.9) {
  168.                         $skillBadBehavior['behaviors'][] = array('title' => $score['question']->getBehavior(), 'score' => $score['average']);
  169.                     }
  170.                     if ($score['average'] >= 3.9 && $score['average'] < 4.2) {
  171.                         $skillMediumBehavior['behaviors'][] = array('title' => $score['question']->getBehavior(), 'score' => $score['average']);
  172.                     }
  173.                     if ($score['average'] >= 4.2) {
  174.                         $skillGoodBehavior['behaviors'][] = array('title' => $score['question']->getBehavior(), 'score' => $score['average']);
  175.                     }
  176.                     //Get worst behavior
  177.                     if ($score['average'] < $worstScore) {
  178.                         $worstScore $score['average'];
  179.                         $worstBehavior = array('title' => $score['question']->getBehavior(), 'score' => $score['average']);
  180.                     }
  181.                 }
  182.                 if (!isset($skillBadBehavior['behaviors']) && isset($worstBehavior)) {
  183.                     // Add worst behavior in bad
  184.                     $skillBadBehavior['behaviors'][] = $worstBehavior;
  185.                     // Remove worst behavior from medium or good behaviors
  186.                     if (isset($skillMediumBehavior['behaviors'])) {
  187.                         for ($i 0$i count($skillMediumBehavior['behaviors']); $i++) {
  188.                             if ($skillMediumBehavior['behaviors'][$i]['title'] == $worstBehavior['title'] && $skillMediumBehavior['behaviors'][$i]['score'] == $worstBehavior['score']) {
  189.                                 // Remove the element
  190.                                 unset($skillMediumBehavior['behaviors'][$i]);
  191.                             }
  192.                         }
  193.                     }
  194.                     if (isset($skillGoodBehavior['behaviors'])) {
  195.                         for ($i 0$i count($skillGoodBehavior['behaviors']); $i++) {
  196.                             if ($skillGoodBehavior['behaviors'][$i]['title'] == $worstBehavior['title'] && $skillGoodBehavior['behaviors'][$i]['score'] == $worstBehavior['score']) {
  197.                                 // Remove the element
  198.                                 unset($skillGoodBehavior['behaviors'][$i]);
  199.                             }
  200.                         }
  201.                     }
  202.                 }
  203.                 $totalGoodBehaviors[] = $skillGoodBehavior;
  204.                 $totalMediumBehaviors[] = $skillMediumBehavior;
  205.                 $totalBadBehaviors[] = $skillBadBehavior;
  206.                 //Quality Index
  207.                 $qualityIndex $gamificationManager->getCOSSQualityIndex($user$skillStat['skill']);
  208.                 $skillStat['quality'] = $qualityIndex;
  209.                 $skillStat['missingSuperiorFeedbacks'] = $qualityIndex['missingSuperiorFeedbacks'];
  210.                 $skillStat['missingPairFeedbacks'] = $qualityIndex['missingPairFeedbacks'];
  211.                 $skillStat['missingGuestFeedbacks'] = $qualityIndex['missingGuestFeedbacks'];
  212.                 $skillStat['missingAllFeedbacks'] = $qualityIndex['missingAllFeedbacks'];
  213.             }
  214.             foreach ($totalGoodBehaviors as $i => $behavior) {
  215.                 if (!isset($behavior['behaviors'])) {
  216.                     unset($totalGoodBehaviors[$i]);
  217.                 }
  218.             }
  219.             foreach ($totalMediumBehaviors as $i => $behavior) {
  220.                 if (!isset($behavior['behaviors'])) {
  221.                     unset($totalMediumBehaviors[$i]);
  222.                 }
  223.             }
  224.             foreach ($totalBadBehaviors as $i => $behavior) {
  225.                 if (!isset($behavior['behaviors'])) {
  226.                     unset($totalBadBehaviors[$i]);
  227.                 }
  228.             }
  229.             $totalGoodBehaviors array_values($totalGoodBehaviors);
  230.             $totalMediumBehaviors array_values($totalMediumBehaviors);
  231.             $totalBadBehaviors array_values($totalBadBehaviors);
  232.             if (empty($totalBadBehaviors)) {
  233.                 $switchedArrays $gamificationManager->switchMediumToBadBehavior($totalMediumBehaviors$totalBadBehaviors);
  234.                 $totalMediumBehaviors $switchedArrays['totalMediumBehaviors'];
  235.                 $totalBadBehaviors $switchedArrays['totalBadBehaviors'];
  236.             }
  237.             $response['gamification']['behaviors']['good'] = $totalGoodBehaviors;
  238.             $response['gamification']['behaviors']['medium'] = $totalMediumBehaviors;
  239.             $response['gamification']['behaviors']['bad'] = $totalBadBehaviors;
  240.             $activeWeeksNumber 0;
  241.             $response["gamification"]["maxActiveWeeks"] = $activeWeeksNumber;
  242.             $contactsCount 0;
  243.             $response["gamification"]["contactsCount"] = $contactsCount;
  244.             $response["alreadyRequested"] = $userManager->getAlreadyRequested($user);
  245.             $response["minRecipient"] = 5;
  246.             $response["minRecipientRequestedSkill"] = 3;
  247.             $response["requestedSkill"] = array();
  248.             /** @var Feedback $fb */
  249.             foreach ($user->getSentFeedbacks() as $fb) {
  250.                 if ($fb->getSkill() && !$fb->getSelfEvaluation() && !in_array($fb->getSkill()->getId(), $response["requestedSkill"]) && !$fb->getResetted()) {
  251.                     $response["requestedSkill"][] = $fb->getSkill()->getId();
  252.                 }
  253.             }
  254.             $senders = array();
  255.             $sentFeedbacks $em->getRepository(Feedback::class)->getSentFeedbacks($user);
  256.             //Handle old app versions before optimization
  257.             foreach ($sentFeedbacks as &$feedback) {
  258.                 $feedback['skill'] = array('id' => $feedback['skill']);
  259.             }
  260.             $autoFeedbacks $em->getRepository(Feedback::class)->findBy(array("recipient" => $user"selfEvaluation" => true));
  261.             // Remove autoFeedbacks of unselected skills
  262.             $skillsIds = array();
  263.             foreach ($user->getSkills() as $skill){
  264.                 $skillsIds[] = $skill->getId();
  265.             }
  266.             foreach ($autoFeedbacks as $key => $autoFeedback) {
  267.                 if (!in_array($autoFeedback->getSkill()->getId(), $skillsIdstrue)) {
  268.                     unset($autoFeedbacks[$key]);
  269.                 }
  270.             }
  271.             $autoFeedbacks array_values($autoFeedbacks);
  272.             if ($user->getLocale() != "fr") {
  273.                 foreach ($autoFeedbacks as $autoFb) {
  274.                     $tagsFr $autoFb->getSkill()->translate('fr')->getTags();
  275.                     $tagsUserLanguage $autoFb->getSkill()->translate($user->getLocale(), 'false')->getTags();
  276.                     if ($autoFb->getStrengths() != null) {
  277.                         $strengths = array();
  278.                         $keys = array();
  279.                         foreach ($autoFb->getStrengths() as $strength) {
  280.                             $keys[] = array_search($strength$tagsFr);
  281.                         }
  282.                         $translatedStrengths = array();
  283.                         foreach ($keys as $key) {
  284.                             $translatedStrengths[] = $tagsUserLanguage[$key];
  285.                         }
  286.                         foreach ($autoFb->getStrengths() as $i => $strength) {
  287.                             $strengths[] = $translatedStrengths[$i];
  288.                         }
  289.                         $autoFb->{'strengthsTranslated'} = $strengths;
  290.                     }
  291.                     if ($autoFb->getWeaknesses() != null) {
  292.                         $weaknesses = array();
  293.                         $keys = array();
  294.                         foreach ($autoFb->getWeaknesses() as $weakness) {
  295.                             $keys[] = array_search($weakness$tagsFr);
  296.                         }
  297.                         $translatedWeaknesses = array();
  298.                         foreach ($keys as $key) {
  299.                             $translatedWeaknesses[] = $tagsUserLanguage[$key];
  300.                         }
  301.                         foreach ($autoFb->getWeaknesses() as $i => $weakness) {
  302.                             $weaknesses[] = $translatedWeaknesses[$i];
  303.                         }
  304.                         $autoFb->{'weaknessesTranslated'} = $weaknesses;
  305.                     }
  306.                 }
  307.             }
  308.             $response["feedbacks"] = array(
  309.                 'sent' => $sentFeedbacks,
  310.                 'auto' => $autoFeedbacks,
  311.                 'unread_answers' => $userManager->getFeedbackAnswersCountSinceLastDashboardUpdate($user),
  312.                 'unread_answers_by_skill' => $userManager->getFeedbackAnswersBySkillSinceLastDashboardUpdate($user)
  313.             );
  314.             /* RequestLog */
  315.             $log = new RequestLog();
  316.             $log->setUser($user);
  317.             $log->setEndpoint($request->getPathInfo());
  318.             $em->persist($log);
  319.             $em->flush();
  320.             /* RequestLog */
  321.             $user->setLastLogin(new DateTime());
  322.             $em->persist($user);
  323.             $em->flush();
  324.             return View::create($response200);
  325.         } else {
  326.             return View::create(array("deleted" => "true"), 401);
  327.         }
  328.     }
  329.     /**
  330.      * @Post("/api/forgottenpassword")
  331.      */
  332.     public function postForgottenpasswordAction(Request $requestEntityManagerInterface $entityManagerTranslatorInterface $translatorMailerInterface $mailer){
  333.         $email $request->request->get('email',false);
  334.         if(!$email){
  335.             return View::create(array("error" => "Invalid email"), 400);
  336.         }
  337.         /** @var $user UserInterface */
  338.         $user $entityManager->getRepository(User::class)->findOneBy(array('email' => $email));
  339.         if($user){
  340.             $request->setLocale($user->getLocale());
  341.             try {
  342.                 $resetToken $this->resetPasswordHelper->generateResetToken($user);
  343.             } catch (ResetPasswordExceptionInterface $e) {
  344.                 return View::create(array("success" => "OK"), 200);
  345.             }
  346.             $subject $translator->trans(
  347.                 "Réinitialisation de votre mot de passe",array(),'UserBundle'
  348.             );
  349.             $email = (new TemplatedEmail())
  350.                 ->from(new Address('noreply@globalcoss.com''COSS'))
  351.                 ->to($user->getEmail())
  352.                 ->subject($subject)
  353.                 ->htmlTemplate('CossBundle/reset_password/email.html.twig')
  354.                 ->context([
  355.                     'resetToken' => $resetToken,
  356.                     'resetType' => 'app'
  357.                 ])
  358.             ;
  359.             $mailer->send($email);
  360.             // Store the token object in session for retrieval in check-email route.
  361.             $session $request->getSession();
  362.             $session->set('ResetPasswordToken'$resetToken);
  363.             return View::create(array("success" => "OK"), 200);
  364.         } else {
  365.             return View::create(array("success" => "OK"), 200);
  366.         }
  367.     }
  368.     /**
  369.      * @Get("/api/cgu")
  370.      */
  371.     public function getCguAction(Request $requestEntityManagerInterface $em){
  372.         $user $this->getUser();
  373.         $html $this->renderView(
  374.             'CossBundle/cgu.html.twig',
  375.             array('locale' => $user->getLocale(),
  376.             )
  377.         );
  378.         return View::create(array("html" => $html), 200);
  379.     }
  380.     /**
  381.      * @Get("/api/pol_conf")
  382.      */
  383.     public function getPolConfAction(Request $requestEntityManagerInterface $em){
  384.         $user $this->getUser();
  385.         $html $this->renderView(
  386.             'CossBundle/pol_conf.html.twig',
  387.             array('locale' => $user->getLocale(),
  388.             )
  389.         );
  390.         return View::create(array("html" => $html), 200);
  391.     }
  392.     /**
  393.      * @Get("/api/user/onboarding/cgv")
  394.      */
  395.     public function getOnboardingCgvAction(Request $requestEntityManagerInterface $em){
  396.         $user $this->getUser();
  397.         $user->setOnboardingCgvDate(new DateTime());
  398.         $em->persist($user);
  399.         $em->flush();
  400.         return View::create(array("success" => "OK"), 200);
  401.     }
  402.     /**
  403.      * @Get("/api/user/onboarding/rules")
  404.      */
  405.     public function getOnboardingRulesAction(Request $requestEntityManagerInterface $em){
  406.         $user $this->getUser();
  407.         $user->setOnboardingRulesDate(new DateTime());
  408.         $em->persist($user);
  409.         $em->flush();
  410.         return View::create(array("success" => "OK"), 200);
  411.     }
  412.     /**
  413.      * @Get("/api/user/onboarding/info")
  414.      */
  415.     public function getOnboardingUserInfoAction(Request $requestEntityManagerInterface $em){
  416.         $user $this->getUser();
  417.         $user->setOnboardingUserInfoFinished(true);
  418.         $em->persist($user);
  419.         $em->flush();
  420.         return View::create(array("success" => "OK"), 200);
  421.     }
  422.     /**
  423.      * @Get("/api/user/onboarding/skills")
  424.      */
  425.     public function getOnboardingSelectSkillsAction(Request $requestEntityManagerInterface $em){
  426.         $user $this->getUser();
  427.         $user->setOnboardingSelectSkillsFinished(true);
  428.         $em->persist($user);
  429.         $em->flush();
  430.         return View::create(array("success" => "OK"), 200);
  431.     }
  432.     /**
  433.      * @Get("/api/user/onboarding/recipients")
  434.      */
  435.     public function getOnboardingSelectRecipientsAction(Request $requestEntityManagerInterface $em){
  436.         $user $this->getUser();
  437.         $user->setOnboardingSelectRecipientsFinished(true);
  438.         $em->persist($user);
  439.         $em->flush();
  440.         return View::create(array("success" => "OK"), 200);
  441.     }
  442.     /**
  443.      * @Get("/api/user/onboarding/finished")
  444.      */
  445.     public function getOnboardingFinishedAction(Request $requestEntityManagerInterface $em){
  446.         $user $this->getUser();
  447.         $user->setOnboardingFinished(true);
  448.         $em->persist($user);
  449.         $em->flush();
  450.         return $this->forward('App\Controller\ApiBundle\UserRESTController::getAction');
  451.     }
  452.     /**
  453.      * @Get("/api/user/history")
  454.      */
  455.     public function getHistoryAction(Request $requestEntityManagerInterface $em){
  456.         $user $this->getUser();
  457.         $request->setLocale($user->getLocale());
  458.         $suggestions = array();
  459.         $recipients $em->getRepository(Recipient::class)->findExistingRecipients($user);
  460.         foreach ($recipients as $recipient){
  461.             $recipient = array(
  462.                 "id" => $recipient->getId(),
  463.                 "firstname" => $recipient->getUser()->getFirstname(),
  464.                 "lastname" => $recipient->getUser()->getLastname(),
  465.                 "email" => $recipient->getUser()->getEmail(),
  466.                 "type" => $recipient->getType(),
  467.                 "title" => $recipient->getTitle(),
  468.                 "company" => $recipient->getUser()->getCompany(),
  469.                 "status" => $recipient->getStatus(),
  470.                 "sources" => $recipient->getSources(),
  471.                 "last_recall_date" => $recipient->getLastRecallDate()
  472.             );
  473.             $suggestions[] = $recipient;
  474.         }
  475.         return View::create(array("suggestions" => $suggestions), 200);
  476.     }
  477.     /**
  478.      * @Patch("/api/user")
  479.      */
  480.     public function patchAction(Request $requestEntityManagerInterface $emMediaManager $mediaManagerUserManager $userManagerUserPasswordHasherInterface $passwordHasher){
  481.         $user $this->getUser();
  482.         $request->setLocale($user->getLocale());
  483.         $firstname $request->request->get('firstname',false);
  484.         $lastname $request->request->get('lastname',false);
  485.         $company $request->request->get('company',false);
  486.         $jobTitle $request->request->get('jobTitle',false);
  487.         $password $request->request->get('password',false);
  488.         $locale $request->request->get('locale',false);
  489.         $image $request->request->get('image',false);
  490.         if($firstname){
  491.             $user->setFirstname($firstname);
  492.         }
  493.         if($lastname){
  494.             $user->setLastname($lastname);
  495.         }
  496.         if($company){
  497.             $user->setCompany($company);
  498.         }
  499.         if($jobTitle){
  500.             $user->setJobTitle($jobTitle);
  501.         }
  502.         if($password){
  503.             $token $request->request->get('currentPassword');
  504.             $hashedPassword $passwordHasher->hashPassword(
  505.                 $user,
  506.                 $password
  507.             );
  508.             $user->setPassword($hashedPassword);
  509.         }
  510.         if($image){
  511.             $data explode(",",$image);
  512.             $media $userManager->getMediaFromBase64($data[0], $data[1], "image_" $user->getId());
  513.             $mediaManager->save($media);
  514.             $em->persist($media);
  515.             $user->setImage($media);
  516.         }
  517.         if($locale)
  518.             $user->setLocale($locale);
  519.         $em->persist($user);
  520.         $em->flush();
  521.         return $this->forward('App\Controller\ApiBundle\UserRESTController::getAction');
  522.     }
  523.     /**
  524.      * @Get("/api/user/rightnesses/update")
  525.      */
  526.     function updateUsersRightnessAction(EntityManagerInterface $emUserManager $userManager)
  527.     {
  528.         $users $em->getRepository(User::class)->findAll();
  529.         foreach($users as $user){
  530.             $user->setRightness($userManager->getUserRightness($user));
  531.             $em->persist($user);
  532.         }
  533.         $em->flush();
  534.         return View::create(array(),200);
  535.     }
  536.     /**
  537.      * @Get("/api/user/dashboard/access")
  538.      */
  539.     function updateLastDashboardAccessAction(Request $requestEntityManagerInterface $entityManager){
  540.         $user $this->getUser();
  541.         $user->setLastDashboardAccess(new DateTime());
  542.         $entityManager->persist($user);
  543.         $entityManager->flush();
  544.         return View::create(array(),200);
  545.     }
  546.     /**
  547.      * @Get("/api/check-update")
  548.      */
  549.     function checkUpdateAction(Request $requestParameterBagInterface $parameterBag){
  550.         return View::create(array("androidMinVersion" => $parameterBag->get('app_min_version_android'), "iosMinVersion" => $parameterBag->get('app_min_version_ios')));
  551.     }
  552.     /**
  553.      * @Get("/api/getcredentials")
  554.      */
  555.     function getCredentialsAction(Request $requestEntityManagerInterface $entityManager){
  556.         $apiCredentials $entityManager->getRepository(Client::class)->findOneBy(array('active' => true));
  557.         return View::create(array("clientId" => $apiCredentials->getIdentifier(), "clientSecret" => $apiCredentials->getSecret()));
  558.     }
  559.     /**
  560.      * @Post("/api/check/saml")
  561.      */
  562.     public function checkSamlAction(Request $requestEntityManagerInterface $entityManagerCossManager $cossManagerSessionInterface $session)
  563.     {
  564.         $matricule $request->request->get('matricule');
  565.         $source $request->request->get('source');
  566.         if($matricule){
  567.             $user $entityManager->getRepository(User::class)->findOneBy(array('matricule' => $matricule));
  568.             if($user){
  569.                 $school $user->getSchool();
  570.                 if($school){
  571.                     if($source === "app"){
  572.                         if($school->getSamlEntityFront()){
  573.                             $entityId $school->getSamlEntityFront();
  574.                             $samlLoginUrl $request->getSchemeAndHttpHost().$this->generateUrl('lightsaml_sp.login', [
  575.                                     'idp' => $entityId,
  576.                                 ]);
  577.                             return View::create(array("link" => $samlLoginUrl"status" => "true"), 200);
  578.                         } else {
  579.                             return View::create(array("status" => "false"), 200);
  580.                         }
  581.                     } elseif ($source === "client"){
  582.                         if($school->getSamlEntityBack()){
  583.                             $entityId $school->getSamlEntityBack();
  584.                             $samlLoginUrl $request->getSchemeAndHttpHost().$this->generateUrl('lightsaml_sp.login', [
  585.                                     'idp' => $entityId,
  586.                                 ]);
  587.                             return View::create(array("link" => $samlLoginUrl"status" => "true"), 200);
  588.                         } else {
  589.                             return View::create(array("status" => "false"), 200);
  590.                         }
  591.                     } else {
  592.                         return View::create(array("status" => "false"), 200);
  593.                     }
  594.                 } else {
  595.                     return View::create(array("status" => "false"), 200);
  596.                 }
  597.             } else {
  598.                 return View::create(array("status" => "false"), 200);
  599.             }
  600.         } else {
  601.             return View::create(array("status" => "false"), 200);
  602.         }
  603.     }
  604.     /**
  605.      * @Get("/api/saml/logged")
  606.      */
  607.     public function samlLoggedAction(Request $requestEntityManagerInterface $entityManager)
  608.     {
  609.         $session $request->getSession();
  610.         $email $session->get('saml_user');
  611.         $password $session->get('saml_password');
  612.         $source $session->get('saml_source');
  613.         // TODO CHANGER URLS AVEC B2C
  614.         $user $entityManager->getRepository(User::class)->findOneBy(array('email' => $email));
  615.         if($user){
  616.             if($source == 'app'){
  617.                 return $this->redirect("https://app.globalcoss.com?saml=true&email=".$user->getEmail()."&token=".$password);
  618.             }
  619.             if($source == 'client'){
  620.                 return $this->redirect("https://manager.globalcoss.com");
  621.             }
  622.         } else {
  623.             return $this->redirect("https://app.globalcoss.com?saml=false");
  624.         }
  625.     }
  626.     /**
  627.      * @Post("/api/platform/used")
  628.      */
  629.     public function platformUsedAction(Request $requestEntityManagerInterface $entityManager)
  630.     {
  631.         $user $this->getUser();
  632.         $platform $request->request->get('platform');
  633.         if($user->getPlatform() != 'mobile'){
  634.             if($platform == "browser"){
  635.                 $user->setPlatform('browser');
  636.             } elseif($platform == "mobile") {
  637.                 $user->setPlatform('mobile');
  638.             }
  639.         }
  640.         $entityManager->persist($user);
  641.         $entityManager->flush();
  642.         return View::create(array(), 200);
  643.     }
  644.     /**
  645.      * @Get("/api/revoke-tokens")
  646.      */
  647.     public function revokeTokensAction(Request $requestDoctrineCredentialsRevoker $doctrineCredentialsRevoker)
  648.     {
  649.         $user $this->getUser();
  650.         $doctrineCredentialsRevoker->revokeCredentialsForUser($user);
  651.         return View::create(array(), 200);
  652.     }
  653.     /**
  654.      * @Post("/api/badges/linkedin/{token}")
  655.      */
  656.     public function newLinkedInBadgesAction(Request $request$token)
  657.     {
  658.         $link $this->generateUrl('badges_detail', array('token' => $token), UrlGeneratorInterface::ABSOLUTE_URL);
  659.         return View::create(array('link' => $link), 200);
  660.     }
  661.     /**
  662.      * @Get("/api/badges/email/{token}")
  663.      */
  664.     public function sendBadgesEmailAction(Request $request$tokenEntityManagerInterface $entityManagerUserManager $userManagerMailerManager $mailerManager)
  665.     {
  666.         $user $this->getUser();
  667.         $request->setLocale($user->getLocale());
  668.         $badge $entityManager->getRepository(Badge::class)->findBy(array('token' => $token));
  669.         if($badge){
  670.             $badge $badge[0];
  671.         } else {
  672.             return View::create(array("error" => "Invalid token"), 400);
  673.         }
  674.         $skill $badge->getSkill();
  675.         $average $userManager->getUserSkillAverage($user$skill$user->getLocale());
  676.         if($average){
  677.             $link $this->generateUrl('badges_detail', array('token' => $token), UrlGeneratorInterface::ABSOLUTE_URL);
  678.             $badgeImagePath __DIR__ '/../../../public/badges/'.$badge->getUser()->getId().'/'$badge->getToken().'-badge.png';
  679.             $now = new \DateTime();
  680.             $mailerManager->sendBadgesEmail($user$link,  array('link' => $badgeImagePath'skill' => $skill->getTitle(), 'name' => "badge-".$skill->getTitle().'-'.$now->format('d-m-Y').'.png'));
  681.             return View::create(array(), 200);
  682.         } else {
  683.             return View::create(array(), 400);
  684.         }
  685.     }
  686.     /**
  687.      * @Get("/api/badges/delete/{token}")
  688.      */
  689.     public function deleteBadgesAction(Request $request$tokenEntityManagerInterface $entityManager)
  690.     {
  691.         $user $this->getUser();
  692.         $request->setLocale($user->getLocale());
  693.         $badges $entityManager->getRepository(Badge::class)->findBy(array('token' => $token));
  694.         if($badges){
  695.             $badges $badges[0];
  696.         } else {
  697.             return View::create(array("error" => "Invalid token"), 400);
  698.         }
  699.         $badges->setStatus(BadgeRepository::STATUS_INACTIVE);
  700.         $entityManager->persist($badges);
  701.         $entityManager->flush();
  702.         return View::create(array(), 200);
  703.     }
  704.     /**
  705.      * @Patch("/api/recipients/{id}")
  706.      */
  707.     public function saveRecipientAction(Request $requestEntityManagerInterface $emUserPasswordHasherInterface $passwordHasher$id=null)
  708.     {
  709.         $user $this->getUser();
  710.         $request->setLocale($user->getLocale());
  711.         if(in_array('ROLE_COSS_USER'$user->getRoles())) {
  712.             $firstname $request->request->get('firstname',"");
  713.             $lastname $request->request->get('lastname',"");
  714.             $email $request->request->get('email',"");
  715.             $type $request->request->get('type',"");
  716.             $title $request->request->get('title',"");
  717.             $company $request->request->get('company',"");
  718.             $sources $request->request->get('sources',array());
  719.             if($type == "SUPERIOR" || $type == "superior"){
  720.                 $formattedType RecipientRepository::SUPERIOR_RECIPIENT;
  721.             } elseif ($type == "PAIR" || $type == "pair"){
  722.                 $formattedType RecipientRepository::PAIR_RECIPIENT;
  723.             }elseif ($type == "GUEST" || $type == "guest"){
  724.                 $formattedType RecipientRepository::GUEST_RECIPIENT;
  725.             } else {
  726.                 $formattedType RecipientRepository::GUEST_RECIPIENT;
  727.             }
  728.             if($id){
  729.                 $existingRecipients $em->getRepository(Recipient::class)->findExistingRecipients($user);
  730.                 $recipient $em->getRepository(Recipient::class)->find($id);
  731.                 foreach ($existingRecipients as $existingRecipient){
  732.                     if($existingRecipient->getId() === $recipient->getId()){
  733.                         $recipient->setType($formattedType);
  734.                         $recipient->setTitle($title);
  735.                         $recipient->setCompany($company);
  736.                         $recipient->setSources($sources);
  737.                         $recipient->getUser()->setEmail($email);
  738.                         $recipient->getUser()->setFirstname($firstname);
  739.                         $recipient->getUser()->setLastname($lastname);
  740.                         $em->persist($recipient->getUser());
  741.                         $em->persist($recipient);
  742.                     }
  743.                 }
  744.             } else {
  745.                 $existingUser $em->getRepository(User::class)->findOneBy(array('email' => $email));
  746.                 if(!$existingUser){
  747.                     $u = new User();
  748.                     $u->setFirstname($firstname);
  749.                     $u->setLastname($lastname);
  750.                     if (!$firstname || $firstname == "") {
  751.                         $u->setFirstname($lastname);
  752.                     }
  753.                     if (!$lastname || $lastname == "") {
  754.                         $u->setLastname($firstname);
  755.                     }
  756.                     $u->setEmail($email);
  757.                     $u->setUsername($email);
  758.                     $u->setLocale($user->getLocale());
  759.                     $plainpassword substrstr_shuffle'abcdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789' ), 010 );
  760.                     $password $passwordHasher->hashPassword(
  761.                         $u,
  762.                         $plainpassword
  763.                     );
  764.                     $u->setPassword($password);
  765.                     $em->persist($u);
  766.                     $em->flush();
  767.                 } else {
  768.                     $u $existingUser;
  769.                     // Update fields if guest user
  770.                     if(!in_array('ROLE_COSS_USER'$u->getRoles())){
  771.                         $u->setFirstname($firstname);
  772.                         $u->setLastname($lastname);
  773.                         $em->persist($u);
  774.                     }
  775.                 }
  776.                 $newRecipient = new Recipient();
  777.                 $newRecipient->setAppUser($user);
  778.                 $newRecipient->setUser($u);
  779.                 $newRecipient->setStatus(RecipientRepository::STATUS_PENDING);
  780.                 $newRecipient->setType($formattedType);
  781.                 $newRecipient->setTitle($title);
  782.                 $newRecipient->setCompany($company);
  783.                 $newRecipient->setSources($sources);
  784.                 $em->persist($newRecipient);
  785.             }
  786.             $em->flush();
  787.             if(isset($newRecipient)){
  788.                 $recipient $newRecipient;
  789.             }
  790.             $recipientFormatted = array(
  791.                 "id" => $recipient->getId(),
  792.                 "firstname" => $recipient->getUser()->getFirstname(),
  793.                 "lastname" => $recipient->getUser()->getLastname(),
  794.                 "email" => $recipient->getUser()->getEmail(),
  795.                 "type" => $recipient->getType(),
  796.                 "title" => $recipient->getTitle(),
  797.                 "company" => $recipient->getCompany(),
  798.                 "status" => $recipient->getStatus(),
  799.                 "sources" => $recipient->getSources(),
  800.                 "last_recall_date" => $recipient->getLastRecallDate()
  801.             );
  802.             return View::create($recipientFormatted200);
  803.         } else {
  804.             return View::create(array(), 400);
  805.         }
  806.     }
  807.     /**
  808.      * @Delete("/api/recipients/{id}")
  809.      */
  810.     public function deleteRecipientAction(Request $requestEntityManagerInterface $em$id=null)
  811.     {
  812.         $user $this->getUser();
  813.         $request->setLocale($user->getLocale());
  814.         if(in_array('ROLE_COSS_USER'$user->getRoles())) {
  815.             if($id){
  816.                 $existingRecipients $em->getRepository(Recipient::class)->findExistingRecipients($user);
  817.                 $recipient $em->getRepository(Recipient::class)->find($id);
  818.                 foreach ($existingRecipients as $existingRecipient){
  819.                     if($existingRecipient->getId() === $recipient->getId()){
  820.                         $em->remove($recipient);
  821.                     }
  822.                 }
  823.             }
  824.             return View::create(array(), 200);
  825.         } else {
  826.             return View::create(array(), 400);
  827.         }
  828.     }
  829.     /**
  830.      * @Patch("/api/update/feedback/count")
  831.      */
  832.     public function updateFeedbackCountAction(Request $requestEntityManagerInterface $em)
  833.     {
  834.         $user $this->getUser();
  835.         $request->setLocale($user->getLocale());
  836.         $user->setNewFeedbackCount(0);
  837.         $em->persist($user);
  838.         $em->flush();
  839.         return View::create(array(), 200);
  840.     }
  841.     /**
  842.      * @Patch("/api/update/badge/count")
  843.      */
  844.     public function updateBadgeCountAction(Request $requestEntityManagerInterface $em)
  845.     {
  846.         $user $this->getUser();
  847.         $request->setLocale($user->getLocale());
  848.         $user->setNewBadgeCount(0);
  849.         $em->persist($user);
  850.         $em->flush();
  851.         return View::create(array(), 200);
  852.     }
  853.     /**
  854.      * @Patch("/api/choose/skillspath")
  855.      */
  856.     public function chooseSkillsPathAction(Request $requestEntityManagerInterface $em)
  857.     {
  858.         $user $this->getUser();
  859.         $request->setLocale($user->getLocale());
  860.         $skillsPathId $request->request->get('skills_path_id',false);
  861.         $skillsPath $em->getRepository(SkillsPath::class)->find($skillsPathId);
  862.         if($skillsPath){
  863.             $user->setSkillsPath($skillsPath);
  864.         }
  865.         foreach ($user->getSkills() as $s){
  866.             $user->removeSkill($s);
  867.         }
  868.         
  869.         $em->persist($user);
  870.         $em->flush();
  871.         return View::create(array(), 200);
  872.     }
  873.     /**
  874.      * @Post("/api/check/licence/access")
  875.      */
  876.     public function checkLicenceAccessAction(Request $request)
  877.     {
  878.         $user $this->getUser();
  879.         $request->setLocale($user->getLocale());
  880.         $today = new DateTime();
  881.         if(!$user->getLicenceStartDate() || !$user->getLicenceEndDate()){
  882.             $request->getSession()->invalidate();
  883.             return View::create(array("access" => "false"), 400);
  884.         } else {
  885.             if($user->getLicenceStartDate() <= $today && $user->getLicenceEndDate() >= $today){
  886.                 return View::create(array("access" => "true"), 200);
  887.             } else {
  888.                 if($user->getLicenceStartDate() >= $today){
  889.                     $request->getSession()->invalidate();
  890.                     return View::create(array("access" => "false"), 400);
  891.                 } else {
  892.                     if($user->getLicenceEndDate() <= $today){
  893.                         if($user->getBadgesAccess()){
  894.                             return View::create(array("access" => "expired"), 200);
  895.                         } else {
  896.                             $request->getSession()->invalidate();
  897.                             return View::create(array("access" => "false"), 400);
  898.                         }
  899.                     } else {
  900.                         return View::create(array("access" => "true"), 200);
  901.                     }
  902.                 }
  903.             }
  904.         }
  905.     }
  906.     /**
  907.      * @Patch("/api/recall/validator")
  908.      */
  909.     public function recallValidatorAction(Request $requestEntityManagerInterface $emMailerManager $mailerManager)
  910.     {
  911.         $user $this->getUser();
  912.         $request->setLocale($user->getLocale());
  913.         if($user->getValidator()){
  914.             $lastValidatorRecall $user->getLastValidatorRecall();
  915.             $now = new DateTime();
  916.             if ($lastValidatorRecall) {
  917.                 $lastValidatorRecall->modify('+12 hour');
  918.             }
  919.             if (!$lastValidatorRecall || $now >= $lastValidatorRecall) {
  920.                 if(!$lastValidatorRecall){
  921.                     $mailerManager->sendRecipientListChanged($user->getValidator(), $user);
  922.                 } else {
  923.                     $mailerManager->sendRecipientListChangedRecall($user->getValidator(), $user);
  924.                 }
  925.                 $user->setLastValidatorRecall(new DateTime());
  926.                 $em->persist($user);
  927.                 $em->flush();
  928.                 return View::create(array('status' => 'email_sent'), 200);
  929.             } else {
  930.                 return View::create(array('status' => 'not_available'), 200);
  931.             }
  932.         } else {
  933.             $lastCossRecall $user->getLastCossRecall();
  934.             $now = new DateTime();
  935.             if ($lastCossRecall) {
  936.                 $lastCossRecall->modify('+12 hour');
  937.             }
  938.             if (!$lastCossRecall || $now >= $lastCossRecall) {
  939.                 $mailerManager->sendCOSSRecipientListChanged($user);
  940.                 $user->setLastCossRecall(new DateTime());
  941.                 $em->persist($user);
  942.                 $em->flush();
  943.                 return View::create(array('status' => 'email_sent'), 200);
  944.             } else {
  945.                 return View::create(array('status' => 'not_available'), 200);
  946.             }
  947.         }
  948.     }
  949.     /**
  950.      * @Get("/api/recall/recipients")
  951.      */
  952.     public function recallRecipientsAction(Request $requestEntityManagerInterface $emMailerManager $mailerManager)
  953.     {
  954.         $user $this->getUser();
  955.         $request->setLocale($user->getLocale());
  956.         $recipients $em->getRepository(Recipient::class)->findExistingRecipients($user);
  957.         foreach ($recipients as $recipient){
  958.             $yesterday = new DateTime();
  959.             $yesterday->modify("-1 day");
  960.             if($recipient->getLastRecallDate() <= $yesterday){
  961.                 $mailerManager->sendFeedbackRecap($recipient->getUser(), 'recall');
  962.             }
  963.         }
  964.         return View::create(array(), 200);
  965.     }
  966.     /**
  967.      * @Patch("/api/recommendation/{id}")
  968.      */
  969.     public function patchRecommendationAction(Request $requestEntityManagerInterface $em$id)
  970.     {
  971.         $user $this->getUser();
  972.         $request->setLocale($user->getLocale());
  973.         $recommendation $em->getRepository(Recommendation::class)->find($id);
  974.         if($recommendation) {
  975.             $action $request->request->get('action');
  976.             if($action){
  977.                 switch($action){
  978.                     case "accept":
  979.                         $recommendation->setStatus(RecommendationRepository::STATUS_ACCEPTED);
  980.                         $em->persist($recommendation);
  981.                         $em->flush();
  982.                         break;
  983.                     case "delete":
  984.                         $em->remove($recommendation);
  985.                         $em->flush();
  986.                         break;
  987.                     default:
  988.                         return View::create(array(), 400);
  989.                         break;
  990.                 }
  991.                 return View::create(array('status' => 'recommendation_saved'), 200);
  992.             } else {
  993.                 return View::create(array(), 400);
  994.             }
  995.         } else {
  996.             return View::create(array(), 400);
  997.         }
  998.     }
  999.     /**
  1000.      * @Get("/api/open/badge/class/{token}", name="open_badge_class")
  1001.      */
  1002.     public function getBadgeClass($tokenEntityManagerInterface $entityManager)
  1003.     {
  1004.         // Fetch badge details from the database
  1005.         $badges $entityManager->getRepository(Badge::class)->findBy(array('token' => $token));
  1006.         if ($badges) {
  1007.             $badge $badges[0];
  1008.             $skill $badge->getSkill();
  1009.             $publicLink $this->generateUrl('badges_detail', array('token' => $token), UrlGeneratorInterface::ABSOLUTE_URL);
  1010.             $jsonLink $this->generateUrl('open_badge_class', array('token' => $token), UrlGeneratorInterface::ABSOLUTE_URL);
  1011.             $issuerLink $this->generateUrl('open_badge_issuer', array(), UrlGeneratorInterface::ABSOLUTE_URL);
  1012.             $imageLink $this->generateUrl('open_badge_bake', array('token' => $token), UrlGeneratorInterface::ABSOLUTE_URL);
  1013.             $badgeJson = [
  1014.                 "@context" => "https://w3id.org/openbadges/v2",
  1015.                 "type" => "BadgeClass",
  1016.                 "id" => $jsonLink,
  1017.                 "name" => $skill->getTitle(),
  1018.                 "description" => $skill->getDescription() ? $skill->getDescription() : "Pas de description",
  1019.                 "issuer" => $issuerLink,
  1020.                 "criteria" => $publicLink,
  1021.                 "image" => $imageLink
  1022.             ];
  1023.             return new JsonResponse($badgeJson);
  1024.         }
  1025.         return new JsonResponse(array());
  1026.     }
  1027.     /**
  1028.      * @Get("/api/open/badge/issuer", name="open_badge_issuer")
  1029.      */
  1030.     public function getBadgeIssuer()
  1031.     {
  1032.         $issuerJsonLink $this->generateUrl('open_badge_issuer', array(), UrlGeneratorInterface::ABSOLUTE_URL);
  1033.         $issuerJson = [
  1034.             "@context" => "https://w3id.org/openbadges/v2",
  1035.             "type" => "Issuer",
  1036.             "id" => $issuerJsonLink,
  1037.             "name" => "COSS",
  1038.             "url" => "https://globalcoss.com",
  1039.             "email" => "contact@globalcoss.com"
  1040.         ];
  1041.         return new JsonResponse($issuerJson);
  1042.     }
  1043.     /**
  1044.      * @Get("/api/open/badge/assertion/{token}", name="open_badge_assertion")
  1045.      */
  1046.     public function getBadgeAssertion($tokenEntityManagerInterface $entityManagerCossManager $cossManager)
  1047.     {
  1048.         // Fetch badge details from the database
  1049.         $badges $entityManager->getRepository(Badge::class)->findBy(array('token' => $token));
  1050.         if ($badges) {
  1051.             $badge $badges[0];
  1052.             $badgeJson $cossManager->getOpenBadgeJson($badge);
  1053.             return new JsonResponse($badgeJson);
  1054.         }
  1055.         return new JsonResponse(array());
  1056.     }
  1057.     /**
  1058.      * @Get("/api/open/badge/bake/{token}", name="open_badge_bake")
  1059.      */
  1060.     public function openBadgeBake($tokenEntityManagerInterface $entityManagerCossManager $cossManagerUserManager $userManagerParameterBagInterface $parameterBag)
  1061.     {
  1062.         // Fetch badge details from the database
  1063.         $badges $entityManager->getRepository(Badge::class)->findBy(array('token' => $token));
  1064.         if ($badges) {
  1065.             $badge $badges[0];
  1066.             $skill $badge->getSkill();
  1067.             $projectDir $parameterBag->get('kernel.project_dir');
  1068.             $outputPngPath $projectDir '/public/badges/'.$badge->getUser()->getId().'/baked/' $badge->getToken().'-badge-baked.png';   // Baked badge PNG
  1069.             if(!file_exists($outputPngPath)){
  1070.                 $image $cossManager->bakeOpenBadge($badge$skill$outputPngPath);
  1071.                 if($image){
  1072.                     $response = new Response();
  1073.                     $response->headers->set('Content-Type''image/png');
  1074.                     $response->setContent($image);
  1075.                     return $response;
  1076.                 } else {
  1077.                     return new Response('Failed to bake the badge'Response::HTTP_INTERNAL_SERVER_ERROR);
  1078.                 }
  1079.             } else {
  1080.                 try{
  1081.                     $image = new Imagick($outputPngPath);
  1082.                     $response = new Response();
  1083.                     $response->headers->set('Content-Type''image/png');
  1084.                     $response->setContent($image->getImageBlob());
  1085.                     return $response;
  1086.                 } catch(ImagickException $e){
  1087.                     return new Response('Failed to open the badge'Response::HTTP_INTERNAL_SERVER_ERROR);
  1088.                 }
  1089.             }
  1090.         } else {
  1091.             return new Response('No badge found'Response::HTTP_INTERNAL_SERVER_ERROR);
  1092.         }
  1093.     }
  1094.     /**
  1095.      * @Get("/api/faq")
  1096.      */
  1097.     public function getFAQAction(Request $requestEntityManagerInterface $entityManager)
  1098.     {
  1099.         $user $this->getUser();
  1100.         $request->setLocale($user->getLocale());
  1101.         $faq $entityManager->getRepository(FAQQuestion::class)->findBy(array(), array('sortOrder' => 'ASC'));
  1102.         return View::create(array('data' => $faq));
  1103.     }
  1104. }