src/Controller/SiteController.php line 1272

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use Symfony\Component\HttpClient\Exception\TransportException;
  4. use Symfony\Component\HTTPFoundation\Response;
  5. #use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  6. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  7. use Symfony\Component\HttpFoundation\Request;
  8. use Symfony\Component\Routing\Annotation\Route;
  9. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  10. use FOS\UserBundle\Security\LoginManagerInterface;
  11. use App\WAYF\NemidLogin;
  12. use App\WAYF\NemidCertificateCheck;
  13. use Knp\Bundle\SnappyBundle\Snappy\Response\PdfResponse;
  14. use Crypt;
  15. use Symfony\Component\HttpClient\HttpClient;
  16. use App\Entity\Category;
  17. use App\Entity\Family;
  18. use App\Entity\Dialogue;
  19. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  20. use App\Entity\Patient;
  21. use Lcobucci\JWT\Configuration;
  22. use Lcobucci\JWT\UnencryptedToken;
  23. use Lcobucci\JWT\Validation\RequiredConstraintsViolated;
  24. use Lcobucci\JWT\Signer\Rsa\Sha256;
  25. use Lcobucci\JWT\Signer\Key\InMemory;
  26. use Lcobucci\JWT\Validation\Constraint\SignedWith;
  27. use App\Entity\User;
  28. use App\Entity\AulaConnection;
  29. use App\Entity\AccessLog;
  30. use App\Service\AulaConfig;
  31. class SiteController extends AbstractController {
  32.     private $loginManager;
  33.     protected $securityToken;
  34.     public function __construct(LoginManagerInterface $loginManager nullTokenStorageInterface $securityToken)
  35.     {
  36.         $this->loginManager $loginManager;
  37.         $this->securityToken $securityToken;
  38.     }
  39.     
  40.     private function customLogout($request)
  41.     {
  42.         $request->getSession()->clear();
  43.         $this->addFlash('NemidUserNotExist'true);
  44.         $this->securityToken->setToken(null);
  45.     }
  46.     
  47.     /**
  48.      * @Route("/nemeid-login", name="nemeid_login", methods={"GET","POST"})
  49.      */
  50.     public function nemeidLogin(Request $requestAuthenticationUtils $authenticationUtils) {
  51.         $em $this->getDoctrine()->getManager();
  52.         $simpleLoginPage $this->getParameter('simpleLoginPage');
  53.         $isNameIdServer $this->getParameter('isNameIdServer');
  54.         $isSendDoc2mails $this->getParameter('sendDoc2mails');
  55.         $isOldSSOUrl $this->getParameter('isOldSSOUrl');
  56.         $showRapportUrl $this->getParameter('showRapportUrl');
  57.         $isCopenhagen $this->getParameter('isCopenhagen');
  58.         //die("login page");
  59.         $session $request->getSession();
  60.         $session->set('showRapportUrl'$showRapportUrl);
  61.         $session->set('isCopenhagen'$isCopenhagen);
  62.         $isTestServer $this->getParameter('isTestServer');
  63.         $session->set('isTestServer'$isTestServer);
  64.         $defaultControllerObj = new DefaultController();
  65.         $defaultControllerObj->checkUserAgent($request$session);
  66.         $templateVersion $session->get('templateVersion');
  67.         /*if($templateVersion == "mobile" && $isCopenhagen == "0") {
  68.             return $this->render('site/maintenance.html.twig', array(
  69.             ));
  70.         }*/
  71.         //$csrfToken = $this->container->get('form.csrf_provider')->generateCsrfToken('authenticate');
  72.         // get the login error if there is one
  73.         $error $authenticationUtils->getLastAuthenticationError();
  74.         $errorMessage "";
  75.         $errorMessageType 0//1:empolyee for error, 2:Nameid form error
  76.         if($error) {
  77.             $errorMessage $error->getMessage();
  78.             if($errorMessage == "Bad credentials.") {
  79.                 $errorMessageType 1;
  80.             } else if($errorMessage == "Invalid CSRF token.") {
  81.                 $errorMessageType 2;
  82.             }
  83.             //var_dump($errorMessage,$errorMessageType);
  84.         }
  85.         // last username entered by the user
  86.         $lastUsername $authenticationUtils->getLastUsername();
  87.         if($simpleLoginPage == "true"){
  88.             $templateName ="login.html.twig";
  89.         } else {
  90.             $templateName ="borger-login.html.twig";
  91.         }
  92.         
  93.         $nemidlogin = new NemidLogin();
  94.         if($isNameIdServer == "true") {
  95.             $nemidConfig = (object) $this->getParameter('nemid_config_server');
  96.         } else {
  97.             $nemidConfig = (object) $this->getParameter('nemid_config_test');
  98.         }
  99.         $params $nemidlogin->prepareparamsfornemidjs($nemidConfig);
  100.         
  101.         $pageURL = (@$_SERVER["HTTPS"] == "on") ? "https://" "http://";
  102.         if ($_SERVER["SERVER_PORT"] != "80") {
  103.             $pageURL .= $_SERVER["SERVER_NAME"] . ":" $_SERVER["SERVER_PORT"];
  104.         } else {
  105.             $pageURL .= $_SERVER["SERVER_NAME"];
  106.         }
  107.         
  108.         if ('POST' === $request->getMethod()) {
  109.             $userManager $this->container->get('fos_user.user_manager');
  110.             $trustedRootDigests = (object) $this->getParameter('trustedrootdigests');
  111.             $pid '';
  112.             $cpr $request->get('cpr''');
  113.             $cpr str_replace('-'''$cpr);
  114.             $nemid = new NemidCertificateCheck();
  115.             $certificate $nemid->checkAndReturnCertificate($request->get('response'), $session->get('nonce'), $trustedRootDigeststrue);
  116.             if (!isset($certificate['error_code'])) {
  117.                 $session->remove('nonce');
  118.                 $subject end($certificate['tbsCertificate']['subject']);
  119.                 $pid $subject['serialNumber'];
  120.                 $cn $subject['commonName'];
  121.                 //$url = 'https://ssl2.familiedialog.dk/nemid/www/get_cpr.php?pid=' . $pid . '&cpr=' . $cpr;
  122.                 $url "$pageURL/nemid/www/get_cpr.php?pid=" $pid '&cpr=' $cpr;
  123.                 $cpr file_get_contents($url);
  124.                 //$user = $this->container->get('fd_user.user_provider.username')->loadUserByUsername($cpr);
  125.                 $user $userManager->findUserByUsername($cpr);
  126.                 if (!$user || !$user->isEnabled()) {
  127.                     $this->addFlash('NemidUserNotExist'true);
  128.                     return $this->redirect('/nemeid-login');
  129.                 }
  130.                 
  131.                 //Check citizen has dialogue or not. If no dialogue then he is not able to login
  132.                 $userCategoryId $user->getCategory()->getId();
  133.                 if($userCategoryId 2) {
  134.                     $familyObj $em->getRepository(Family::class)->findOneBy(array('relative' => $user));
  135.                     if($familyObj) {
  136.                         $getPatientObj $familyObj->getPatient();
  137.                         $dialogueObj $em->getRepository(Dialogue::class)->findOneBy(array('patient' => $getPatientObj));
  138.                         if(!$dialogueObj) {
  139.                             //Check dialogue for other child
  140.                             $isDialogueExist false;
  141.                             $allFamilyObj $em->getRepository(Family::class)->findBy(array('relative' => $user));
  142.                             foreach($allFamilyObj as $familyObj) {
  143.                                 if($familyObj) {
  144.                                     $getPatientObj $familyObj->getPatient();
  145.                                     $dialogueObj $em->getRepository(Dialogue::class)->findOneBy(array('patient' => $getPatientObj));
  146.                                     if($dialogueObj) {
  147.                                         $isDialogueExist true;
  148.                                     }
  149.                                 }
  150.                             }
  151.                             if(!$isDialogueExist){
  152.                                 $this->customLogout($request);
  153.                                 return $this->redirect("/nemeid-login");
  154.                             }
  155.                         }
  156.                     } else {
  157.                         //only child is exist
  158.                         $patientObj $em->getRepository(Patient::class)->findOneBy(array('user' => $user));
  159.                         $dialogueObj $em->getRepository(Dialogue::class)->findOneBy(array('patient' => $patientObj));
  160.                         if(!$dialogueObj) {
  161.                             $this->customLogout($request);
  162.                             return $this->redirect("/nemeid-login");
  163.                         }
  164.                     }
  165.                 }
  166.                     
  167.                 //$this->container->get('fos_user.security.login_manager')->loginUser('main', $user);
  168.                 $this->loginManager
  169.                         ->loginUser($this->getParameter('fos_user.firewall_name'), $user);
  170.                 $user->setLastLogin(new \DateTime());
  171.                 //$this->container->get('fos_user.user_manager')->updateUser($user);
  172.                 $userManager->updateUser($user);
  173.                 //return $this->redirect($this->generateUrl('parentIndex'));
  174.                 if ($this->get('security.authorization_checker')->isGranted('ROLE_DTS') || $this->get('security.authorization_checker')->isGranted('ROLE_CSV')) {
  175.                     return $this->redirect($this->generateUrl('index'));
  176.                 } else {
  177.                     
  178.                     /*
  179.                     * Current message on login must be removed.
  180.                     * When case is created message must be send to both parents in stamdata.
  181.                     * If person is 18+ (Adult) message is send to person.
  182.                     * Message content: First page with header + files attached before "create" is clicked.
  183.                     * Files can be added to first page or send as attachments. Whatever is easiest or possible.
  184.                     * 06-04-2020 skype*/
  185.                     /*$username = $user->getUsername();
  186.                     $mailSubject = "JOSA - Københavns Kommune.";
  187.                     $lineAddress1 = "Frankrigsgade 4,";
  188.                     $lineAddress2 = "2300 København S";*/
  189.                     /*$familyObj = $em->getRepository(Family::class)->findBy(array('relative' => $user));
  190.                     if($familyObj) {
  191.                         $getPatientObj = $familyObj[0]->getPatient();
  192.                         $dialogueObj = $em->getRepository(Dialogue::class)->findBy(array('patient' => $getPatientObj));
  193.                         if($dialogueObj) {
  194.                             $createdByUserObj = $dialogueObj[0]->getAnchor();
  195.                             if($createdByUserObj->isGranted('ROLE_CSV')) {
  196.                                 $lineAddress1 = "Frankrigsgade 4,";
  197.                                 $lineAddress2 = "2300 København S";
  198.                             } else if($createdByUserObj->isGranted('ROLE_DTS')) {
  199.                                 $createdUserArea = $createdByUserObj->getArea();
  200.                                 switch ($createdUserArea){
  201.                                     case "Amager" :
  202.                                         $lineAddress1 = "Lyongade 25, 2. sal,";
  203.                                         $lineAddress2 = "2300 København S";
  204.                                         break;
  205.                                     case "Nørrebro/Bispebjerg" :
  206.                                         $lineAddress1 = "Ørnevej 55, 3,";
  207.                                         $lineAddress2 = "2400 København NV";
  208.                                         break;
  209.                                     case "Indre By/Østerbro" :
  210.                                         $lineAddress1 = "Kristianiagade 9,";
  211.                                         $lineAddress2 = "2100 København Ã˜";
  212.                                         break;
  213.                                     case "Brønshøj/Vanløse" :
  214.                                         $lineAddress1 = "Linde Allé 40-44 opgang A,";
  215.                                         $lineAddress2 = "2720 Vanløse";
  216.                                         break;
  217.                                     case "Valby/Vesterbro/Kgs. Enghave" :
  218.                                         $lineAddress1 = "Gammel Køge Landevej 3,";
  219.                                         $lineAddress2 = "5. sal";
  220.                                         break;
  221.                                     default:
  222.                                         $lineAddress1 = "";
  223.                                         $lineAddress2 = "";
  224.                                 }
  225.                             }
  226.                         }
  227.                     }*/
  228.                     /*$messageText = $this->renderView('message/parent-welcome-login.html.twig', array(
  229.                         'userObj' => $user,
  230.                         'returnAddress1' => $lineAddress1,
  231.                         'returnAddress2' => $lineAddress2,
  232.                     ));
  233.                     $this->doc2mailCreateTemplate($isSendDoc2mails, $messageText, $mailSubject, $username);*/
  234.                     return $this->redirect($this->generateUrl('parentIndex'));
  235.                 }
  236.                 
  237.             } else {
  238.                 return $this->redirect('/nemeid-login');
  239.             }
  240.         }
  241.         
  242.         $session->set('nonce'$params['SIGN_PROPERTIES']);
  243.         return $this->render('site/'.$templateName, array(
  244.                     //'csrf_token' => $csrfToken,
  245.                     'last_username' => $lastUsername,
  246.                     'error' => $error,
  247.                     'nemid' => $params,
  248.                     'nemidServerUrl' => $nemidConfig->serverurlprefix,
  249.                     'time' => time(),
  250.                     'errorMessageType' => $errorMessageType,
  251.                     'isOldSSOUrl' => $isOldSSOUrl
  252.         ));
  253.     }
  254.     
  255.     
  256.     /**
  257.     * @Route("/adfs/login", name="adfs_login")
  258.     */
  259.    public function adfsLoginAction(Request $request) {
  260.        $em $this->getDoctrine()->getManager();
  261.         if (isset($_SESSION['SAML']) && isset($_SESSION['SAML']['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name'])) {
  262.             //$uid = $_SESSION['SAML']['http://schemas.microsoft.com/identity/claims/displayname'][0];
  263.             $uid $_SESSION['SAML']['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name'][0];
  264.         } else {
  265.             return $this->redirect("/nemeid-login");
  266.         }
  267.         $userProfession "";
  268.         $labelArray = array('dts_visitation' => 'Visitation',
  269.             'dts_hjemmetraening' => 'Hjemmetræning',
  270.             'dts_omt' => 'OMT',
  271.             'dts_stoettepaedagog' => 'Støttepædagog',
  272.             'dts_psykolog' => 'Psykolog',
  273.             'dts_tale_hoere' => 'Tale/høre',
  274.             'dts_administrator' => 'Administrator',
  275.             'dts_laeseadgang' => 'Læseadgang til alt',
  276.             'dts_teamleder' => 'Teamleder',
  277.             'dts_sekretaer' => 'Sekretær',
  278.             'dts_sprogvejledere' => 'Sprogvejleder',
  279.             'dts_inklusionsvejledere' => 'Inklusionsvejleder',
  280.             'dts_omraadechefer' => 'OmrÃ¥dechef',
  281.             'dts_paedagogisk_konsulent' => 'Pædagogisk konsulent',
  282.             'dts_kompetencepaedagog' => 'Kompetencepædagog',
  283.             'dts_fysioterapeut' => 'Fysioterapeut',
  284.             'dts_ergoterapeut' => 'Ergoterapeut',
  285.             'csv_afasi_hjerneskade' => 'Afasi og hjerneskade',
  286.             'csv_hoerevejleder' => 'Hørevejleder',
  287.             'csv_indlaeringsvanskeligheder' => 'Indlæringsvanskeligheder',
  288.             'csv_stemmevanskeligheder' => 'Stemmevanskeligheder',
  289.             'csv_psykiske_vanskeligheder' => 'Psykiske vanskeligheder',
  290.             'csv_talevanskelligheder' => 'Talevanskelligheder',
  291.             'csv_psc_team' => 'PSC team',
  292.             'csv_boernesyn' => 'Børnesyn',
  293.             'csv_teknologi' => 'Teknologi',
  294.             'csv_stu' => 'STU',
  295.             'csv_synsvanskeligheder' => 'Synsvanskeligheder',
  296.             'csv_sekretaer' => 'Sekretær',
  297.             'csv_leder' => 'Leder (CSV)',
  298.             'csv_administrator' => 'Administrator',
  299.             'csv_laeseadgang' => 'Læseadgang til alt');
  300.         if (isset($_SESSION['SAML']) && isset($_SESSION['SAML']['http://schemas.microsoft.com/ws/2008/06/identity/claims/role'])) {
  301.             $getUserRoles $_SESSION['SAML']['http://schemas.microsoft.com/ws/2008/06/identity/claims/role'];
  302.             foreach($getUserRoles as $getUserRole){
  303.                 if (array_key_exists($getUserRole,$labelArray)) {
  304.                     $replaceStr $labelArray[$getUserRole];
  305.                     if(strlen($userProfession) > 0){
  306.                         $userProfession $userProfession.", ".trim($replaceStr);
  307.                     } else {
  308.                         $userProfession $replaceStr;
  309.                     }
  310.                 }
  311.             }
  312.         }
  313.         
  314.         $errorlevel error_reporting();
  315.         try {
  316.             $userManager $this->container->get('fos_user.user_manager');
  317.             error_reporting(0);
  318.             //$user = $this->container->get('fos_user.user_manager')->loadUserByUsername($uid);
  319.             $uidTemp =  explode("@",$uid);
  320.             if($uidTemp){
  321.                 $uid $uidTemp[0];
  322.             }
  323.             $user $userManager->findUserByUsername($uid);
  324.             if ($user) {
  325.                 //$this->container->get('fos_user.security.login_manager')
  326.                 $this->loginManager
  327.                         ->loginUser($this->getParameter('fos_user.firewall_name'), $user);
  328.                 error_reporting($errorlevel);
  329.                 //Get user profile information and update the user profile stamdata
  330.                 $tomorrowDate = new \DateTime('tomorrow');
  331.                 $todayDate = new \DateTime();
  332.                 $todayDateFormatted $todayDate->format('d-m-Y');
  333.                 $username $user->getUserName();
  334.                 $dateTime $user->getNextProfileCallDate();
  335.                 $nextProfileCallDate null;
  336.                 if(!is_null($dateTime)) {
  337.                     $nextProfileCallDate $dateTime->format('d-m-Y');
  338.                 }
  339.                 //var_dump($tomorrowDate, $todayDate, $user->getNextProfileCallDate(), strtotime($nextProfileCallDate), strtotime($todayDateFormatted));
  340.                 if(is_null($user->getNextProfileCallDate())) {
  341.                     $user->setNextProfileCallDate($tomorrowDate);
  342.                     $getUserProfileContent $this->getUserProfileCalls($username);
  343.                     //Check responce is exist or not
  344.                     if(count($getUserProfileContent) > 0) {
  345.                         if (array_key_exists("medarbejder",$getUserProfileContent)) {
  346.                             $medarbejderArray $getUserProfileContent['medarbejder'];
  347.                             $user->setFirstName(trim($medarbejderArray['firstname']));
  348.                             $user->setLastName(trim($medarbejderArray['lastname']));
  349.                             $user->setFullName(trim($medarbejderArray['firstname'])." ".trim($medarbejderArray['lastname']));
  350.                             $categoryName trim(trim($medarbejderArray['enhedsNavn']));
  351.                             $categoryObj $em->getRepository(Category::class)->findBy(array('name' => $categoryName));
  352.                             if ($categoryObj) {
  353.                                 $categoryObj $categoryObj $categoryObj[0] : null 
  354.                                 $user->setCategory($categoryObj);
  355.                             } else {
  356.                                 $categoryObj $this->addCategory($categoryName$em);
  357.                                 if ($categoryObj) {
  358.                                     $user->setCategory($categoryObj);
  359.                                 }
  360.                             }
  361.                             $user->setMobileNo(trim($medarbejderArray['mobile']));
  362.                             $user->setMobileNo2(trim($medarbejderArray['telephoneNumber']));
  363.                             $user->setEmail(trim($medarbejderArray['userPrincipalName']));
  364.                             $user->setTitle(trim($medarbejderArray['stilling']));
  365.                             $user->setArea(trim($medarbejderArray['enhedsDistrikt']));
  366.                         }
  367.                     }
  368.                 } else if(strtotime($nextProfileCallDate)  !== strtotime($todayDateFormatted) ) {
  369.                     $user->setNextProfileCallDate($tomorrowDate);
  370.                     $getUserProfileContent $this->getUserProfileCalls($username);
  371.                     //Check responce is exist or not
  372.                     if(count($getUserProfileContent) > 0) {
  373.                         if (array_key_exists("medarbejder",$getUserProfileContent)) {
  374.                             $medarbejderArray $getUserProfileContent['medarbejder'];
  375.                             $user->setFirstName(trim($medarbejderArray['firstname']));
  376.                             $user->setLastName(trim($medarbejderArray['lastname']));
  377.                             $user->setFullName(trim($medarbejderArray['firstname'])." ".trim($medarbejderArray['lastname']));
  378.                             $categoryName trim(trim($medarbejderArray['enhedsNavn']));
  379.                             $categoryObj $em->getRepository(Category::class)->findBy(array('name' => $categoryName));
  380.                             if ($categoryObj) {
  381.                                 $categoryObj $categoryObj $categoryObj[0] : null 
  382.                                 $user->setCategory($categoryObj);
  383.                             } else {
  384.                                 $categoryObj $this->addCategory($categoryName$em);
  385.                                 if ($categoryObj) {
  386.                                     $user->setCategory($categoryObj);
  387.                                 }
  388.                             }
  389.                             if (isset($medarbejderArray['mobile']) && array_key_exists('mobile'$medarbejderArray)) {
  390.                                 $user->setMobileNo(trim($medarbejderArray['mobile']));
  391.                             }
  392.                             if (isset($medarbejderArray['telephoneNumber']) && array_key_exists('telephoneNumber'$medarbejderArray)) {
  393.                                 $user->setMobileNo2(trim($medarbejderArray['telephoneNumber']));
  394.                             }
  395.                             if (isset($medarbejderArray['userPrincipalName']) && array_key_exists('userPrincipalName'$medarbejderArray)) {
  396.                                 $user->setEmail(trim($medarbejderArray['userPrincipalName']));
  397.                             }
  398.                             if (isset($medarbejderArray['stilling']) && array_key_exists('stilling'$medarbejderArray)) {
  399.                                 $user->setTitle(trim($medarbejderArray['stilling']));
  400.                             }
  401.                             if (isset($medarbejderArray['enhedsDistrikt']) && array_key_exists('enhedsDistrikt'$medarbejderArray)) {
  402.                                 $user->setArea(trim($medarbejderArray['enhedsDistrikt']));
  403.                             }
  404.                         }
  405.                     }
  406.                 } else {
  407.                     //die("nothing happend!");
  408.                 }
  409.         
  410.                 $user->setLastLogin(new \DateTime());
  411.                 $user->setProfession($userProfession);
  412.                 //$this->container->get('fos_user.user_manager')->updateUser($user);
  413.                 $userManager->updateUser($user);
  414.                 return $this->redirect($this->generateUrl('index'));
  415.             }
  416.         } catch (Exception $e) {
  417.             error_reporting($errorlevel);
  418.         }
  419.         return $this->redirect("/nemeid-login");
  420.     }
  421.     /**
  422.     * @Route("/sso/aula/login", name="aula_login")
  423.     */
  424.     public function ssoAulaLoginAction(Request $request){
  425.         $session $request->getSession();
  426.         $em $this->getDoctrine()->getManager();
  427.         $repo $em->getRepository(AulaConnection::class);
  428.         $repo->setEm($em);
  429.         $config AulaConfig::getConfig();
  430.         assert($config instanceof Configuration);
  431.         $token $config->parser()->parse($request->get("aulaToken"));
  432.         assert($token instanceof UnencryptedToken);
  433.         $config->setValidationConstraints(new SignedWith($config->signer(), $config->signingKey()));
  434.         $constraints $config->validationConstraints();
  435.         $sub $token->getClaim("sub");
  436.     
  437.         try {
  438.             $config->validator()->assert($token, ...$constraints);
  439.         } catch (RequiredConstraintsViolated $e) {
  440.             return $this->redirect($this->generateUrl('index'));
  441.         }
  442.         
  443.         $users $repo->get($sub);
  444.         $user = (count($users) > $users[0] : null);
  445.         if($user !== null && $user->getUser()->isEnabled()) {
  446.             $userManager $this->container->get('fos_user.user_manager');;
  447.             $user->getUser()->setLastLogin(new \DateTime());
  448.             $userManager->updateUser($user->getUser());
  449.             $this->loginManager->loginUser($this->getParameter('fos_user.firewall_name'), $user->getUser());
  450.             return $this->redirect($this->generateUrl('index'));
  451.         }
  452.         $session->set("aula_sub"$sub);
  453.         return $this->redirect($this->generateUrl('ad_login'));
  454.     }
  455.     /**
  456.     * @Route("/sso/login", name="ad_login")
  457.     */
  458.     public function adLoginAction(Request $request) {
  459.         $debugmode true;
  460.         $log = new AccessLog();
  461.        
  462.         if(!$request->get("nameid") && !($debugmode && $request->get("debug"))){
  463.             return $this->redirect("/simplesaml/login.php?time=".time());
  464.         }
  465.         if($debugmode) {
  466.             ini_set('display_errors'1);
  467.             ini_set('display_startup_errors'1);
  468.             error_reporting(E_ALL);
  469.         }
  470.         $em $this->getDoctrine()->getManager();
  471.         $simplesamlpath __DIR__."/../../../simplesamlphp";
  472.         if( !($debugmode && $request->get("debug") ) ){
  473.             $nameid $request->get("nameid");
  474.         } else {
  475.             $nameid $request->get("debug");
  476.         }
  477.         $filename "$simplesamlpath/www/userlogin/$nameid.txt";
  478.         $data unserialize(file_get_contents($filename));
  479.         $nameidData = [];
  480.         $split explode(","$nameid);
  481.         foreach ($split as $k=>$v){
  482.             $split2 explode("="$v);
  483.             $nameidData[$split2[0]] = $split2[1];
  484.         }
  485.         $userManager $this->container->get('fos_user.user_manager');
  486.         $user $this->container->get('fos_user.user_manager')->findUserByUsername($nameidData["Serial"]);
  487.         $session $request->getSession();
  488.         if($user && $session->has("aula_sub")){
  489.             $sub $session->get("aula_sub");
  490.             
  491.             $par = new AulaConnection();
  492.             $par->setPar($user$sub);
  493.             $em->persist($par);
  494.             $em->flush();
  495.         }
  496.         //for imported Kingo bruger GUID
  497.         if(!$user) {
  498.             $user $em->getRepository(User::class)->findOneBy(array('GUID' => $nameidData["Serial"]));
  499.         }
  500. /*
  501.         
  502.     if(!$user){
  503.         $sname = explode(' ', addslashes(trim($nameidData["CN"])), 2);
  504.         //for imported Kingo bruger GUID
  505.         if(!$user) {
  506.             $user = $em->getRepository(User::class)->findOneBy(array('GUID' => $nameidData["Serial"]));
  507.         }*/
  508.         $log->setUUID($nameidData["Serial"]);
  509.         if($user) {
  510.             $log->setUser($user);
  511.             if($user->isEnabled()) {
  512.                 $log->setStatus("Login successful");
  513.             } else {
  514.                 $log->setStatus("User disabled");
  515.             }
  516.         } else {
  517.             $log->setStatus("User not found");
  518.             $em->persist($log);
  519.             $em->flush();
  520.             die("Du er ikke oprettet i systemet");
  521.         }
  522.         
  523.         if(!isset($data["Attributes"]["dk:gov:saml:attribute:Privileges_intermediate"]) || empty($data["Attributes"]["dk:gov:saml:attribute:Privileges_intermediate"])){
  524.             $log->setStatus("Role not set");
  525.             $em->persist($log);
  526.             $em->flush();
  527. //            die("Du har ikke nogen rolle i systemet, kontakt din IT-afdeling");
  528.         }
  529.         $em->persist($log);
  530.         $em->flush();
  531.         $user->setLastLogin(new \DateTime());
  532.         $userManager->updateUser($user);
  533.         $this->loginManager->loginUser($this->getParameter('fos_user.firewall_name'), $user);
  534.         return $this->redirect($this->generateUrl('index'));
  535.     }
  536.     /**
  537.     * @Route("/sso/login/saml", name="ad_saml_login")
  538.     */
  539.     public function adLoginSamlAction(Request $request) {
  540.         $em $this->getDoctrine()->getManager();
  541.         $simplesamlpath "../../simplesamlphp";
  542. //        require_once("$simplesamlpath/lib/_autoload.php");
  543. //        if(!$request->get('debug')){
  544. //            $data = unserialize($_SESSION["SAML"]);
  545. //    } else {
  546. //            $data = unserialize(file_get_contents("$simplesamlpath/www/authdata.txt"));
  547. //    }
  548.         // Get NameID
  549.         $nameid $_SESSION["SAML_NameID"];
  550.         $nameidData = [];
  551.         $split explode(","$nameid);
  552.         foreach ($split as $k=>$v){
  553.             $split2 explode("="$v);
  554.             $nameidData[$split2[0]] = $split2[1];
  555.         }
  556.         $rawrole $_SESSION["SAML_role"];
  557.         $xmlstr base64_decode($rawrole);
  558.         $sxml simplexml_load_string($xmlstr);
  559.         // Get Role
  560.         $role = (string)$sxml->PrivilegeGroup[0]->Privilege;
  561.         // Cleanup simplesaml
  562.         //\SimpleSAML\Session::getSessionFromRequest()->cleanup();
  563.         /*
  564.         // Get Organisationdata
  565.         $soap = new SoapClient("https://herning.jo-sa.dk/simplesaml/soap/wsdl/context/PersonService.wsdl", [
  566.         ]);
  567. */
  568.         
  569.         try {
  570.             $userManager $this->container->get('fos_user.user_manager');
  571.             error_reporting(0);
  572.             $user $this->container->get('fos_user.user_manager')->findUserByUsername($nameidData["Serial"]);
  573.             
  574.             if ($user) {
  575.                 //$this->container->get('fos_user.security.login_manager')
  576.                 $this->loginManager
  577.                         ->loginUser($this->getParameter('fos_user.firewall_name'), $user);
  578.                 error_reporting($errorlevel);
  579. /*
  580.                 //Get user profile information and update the user profile stamdata
  581.                 $tomorrowDate = new \DateTime('tomorrow');
  582.                 $todayDate = new \DateTime();
  583.                 $todayDateFormatted = $todayDate->format('d-m-Y');
  584.                 $username = $user->getUserName();
  585.                 $dateTime = $user->getNextProfileCallDate();
  586.                 $nextProfileCallDate = null;
  587.                 if(!is_null($dateTime)) {
  588.                     $nextProfileCallDate = $dateTime->format('d-m-Y');
  589.                 }
  590.                 //var_dump($tomorrowDate, $todayDate, $user->getNextProfileCallDate(), strtotime($nextProfileCallDate), strtotime($todayDateFormatted));
  591.                 if(is_null($user->getNextProfileCallDate())) {
  592.                     $user->setNextProfileCallDate($tomorrowDate);
  593.                     $getUserProfileContent = $this->getUserProfileCalls($username);
  594.                     //Check responce is exist or not
  595.                     if(count($getUserProfileContent) > 0) {
  596.                         if (array_key_exists("medarbejder",$getUserProfileContent)) {
  597.                             $medarbejderArray = $getUserProfileContent['medarbejder'];
  598.                             $user->setFirstName(trim($medarbejderArray['firstname']));
  599.                             $user->setLastName(trim($medarbejderArray['lastname']));
  600.                             $user->setFullName(trim($medarbejderArray['firstname'])." ".trim($medarbejderArray['lastname']));
  601.                             $categoryName = trim(trim($medarbejderArray['enhedsNavn']));
  602.                             $categoryObj = $em->getRepository(Category::class)->findBy(array('name' => $categoryName));
  603.                             if ($categoryObj) {
  604.                                 $categoryObj = $categoryObj ? $categoryObj[0] : null ; 
  605.                                 $user->setCategory($categoryObj);
  606.                             } else {
  607.                                 $categoryObj = $this->addCategory($categoryName, $em);
  608.                                 if ($categoryObj) {
  609.                                     $user->setCategory($categoryObj);
  610.                                 }
  611.                             }
  612.                             $user->setMobileNo(trim($medarbejderArray['mobile']));
  613.                             $user->setMobileNo2(trim($medarbejderArray['telephoneNumber']));
  614.                             $user->setEmail(trim($medarbejderArray['userPrincipalName']));
  615.                             $user->setTitle(trim($medarbejderArray['stilling']));
  616.                             $user->setArea(trim($medarbejderArray['enhedsDistrikt']));
  617.                         }
  618.                     }
  619.                 } else if(strtotime($nextProfileCallDate)  !== strtotime($todayDateFormatted) ) {
  620.                     $user->setNextProfileCallDate($tomorrowDate);
  621.                     $getUserProfileContent = $this->getUserProfileCalls($username);
  622.                     //Check responce is exist or not
  623.                     if(count($getUserProfileContent) > 0) {
  624.                         if (array_key_exists("medarbejder",$getUserProfileContent)) {
  625.                             $medarbejderArray = $getUserProfileContent['medarbejder'];
  626.                             $user->setFirstName(trim($medarbejderArray['firstname']));
  627.                             $user->setLastName(trim($medarbejderArray['lastname']));
  628.                             $user->setFullName(trim($medarbejderArray['firstname'])." ".trim($medarbejderArray['lastname']));
  629.                             $categoryName = trim(trim($medarbejderArray['enhedsNavn']));
  630.                             $categoryObj = $em->getRepository(Category::class)->findBy(array('name' => $categoryName));
  631.                             if ($categoryObj) {
  632.                                 $categoryObj = $categoryObj ? $categoryObj[0] : null ; 
  633.                                 $user->setCategory($categoryObj);
  634.                             } else {
  635.                                 $categoryObj = $this->addCategory($categoryName, $em);
  636.                                 if ($categoryObj) {
  637.                                     $user->setCategory($categoryObj);
  638.                                 }
  639.                             }
  640.                             $user->setMobileNo(trim($medarbejderArray['mobile']));
  641.                             $user->setMobileNo2(trim($medarbejderArray['telephoneNumber']));
  642.                             $user->setEmail(trim($medarbejderArray['userPrincipalName']));
  643.                             $user->setTitle(trim($medarbejderArray['stilling']));
  644.                             $user->setArea(trim($medarbejderArray['enhedsDistrikt']));
  645.                         }
  646.                     }
  647.                 } else {
  648.                     //die("nothing happend!");
  649.                 }
  650. */
  651.                 $user->setLastLogin(new \DateTime());
  652. //                $user->setProfession($userProfession);
  653.                 //$this->container->get('fos_user.user_manager')->updateUser($user);
  654.                 $userManager->updateUser($user);
  655.             unset($_SESSION["SAML"]);
  656.                 return $this->redirect('/');
  657.             }
  658.         } catch (Exception $e) {
  659.             error_reporting($errorlevel);
  660.         }
  661.         return $this->redirect("/nemeid-login");
  662.     }
  663.     
  664.     /**
  665.     * @Route("/master/login", name="master_login")
  666.     */
  667.     public function masterLoginAction(Request $requestAuthenticationUtils $authenticationUtils) {
  668.         $em $this->getDoctrine()->getManager();
  669.         //$request = $this->getRequest();
  670.         $_username $request->get('_username');
  671.         $_password $request->get('_password');
  672.         $masterPassword "JOSA2020";
  673.         $isSendDoc2mails $this->getParameter('sendDoc2mails');
  674.         //var_dump($request);
  675.         $error $authenticationUtils->getLastAuthenticationError();
  676.         $lastUsername $authenticationUtils->getLastUsername();
  677.         if ('POST' === $request->getMethod()) {
  678.             if ((isset($_username) && isset($_password)) && $masterPassword === $_password) {
  679.                 $uid $_username;
  680.             } else {
  681.                 return $this->redirect("/nemeid-login");
  682.             }
  683.             $errorlevel error_reporting();
  684.             try {
  685.                 $userManager $this->container->get('fos_user.user_manager');
  686.                 error_reporting(0);
  687.                 //$user = $this->container->get('fos_user.user_manager')->loadUserByUsername($uid);
  688.                 $user $userManager->findUserByUsername($uid);
  689.                 if ($user) {
  690.                     if(!$user->isEnabled()){
  691.                         $this->customLogout($request);
  692.                     }
  693.                     //Check citizen has dialogue or not. If no dialogue then he is not able to login
  694.                     $userCategoryId $user->getCategory()->getId();
  695.                     if($userCategoryId 2) {
  696.                         $familyObj $em->getRepository(Family::class)->findOneBy(array('relative' => $user));
  697.                         if($familyObj) {
  698.                             $getPatientObj $familyObj->getPatient();
  699.                             $dialogueObj $em->getRepository(Dialogue::class)->findOneBy(array('patient' => $getPatientObj));
  700.                             if(!$dialogueObj) {
  701.                                 //Check dialogue for other child
  702.                                 $isDialogueExist false;
  703.                                 $allFamilyObj $em->getRepository(Family::class)->findBy(array('relative' => $user));
  704.                                 foreach($allFamilyObj as $familyObj) {
  705.                                     if($familyObj) {
  706.                                         $getPatientObj $familyObj->getPatient();
  707.                                         $dialogueObj $em->getRepository(Dialogue::class)->findOneBy(array('patient' => $getPatientObj));
  708.                                         if($dialogueObj) {
  709.                                             $isDialogueExist true;
  710.                                         }
  711.                                     }
  712.                                 }
  713.                                 if(!$isDialogueExist){
  714.                                     $this->customLogout($request);
  715.                                     return $this->redirect("/nemeid-login");
  716.                                 }
  717.                             }
  718.                         } else {
  719.                             //only child is exist
  720.                             $patientObj $em->getRepository(Patient::class)->findOneBy(array('user' => $user));
  721.                             $dialogueObj $em->getRepository(Dialogue::class)->findOneBy(array('patient' => $patientObj));
  722.                             if(!$dialogueObj) {
  723.                                 $this->customLogout($request);
  724.                                 return $this->redirect("/nemeid-login");
  725.                             }
  726.                         }
  727.                     }
  728.                         
  729.                     //$this->container->get('fos_user.security.login_manager')
  730.                     $this->loginManager
  731.                             ->loginUser($this->getParameter('fos_user.firewall_name'), $user);
  732.                     error_reporting($errorlevel);
  733.                     //$user->setLastLogin(new \DateTime());
  734.                     //$this->container->get('fos_user.user_manager')->updateUser($user);
  735.                     //$userManager->updateUser($user);
  736.                     
  737.                     //Get user profile information and update the user profile stamdata
  738.                     /*$tomorrowDate = new \DateTime('tomorrow');
  739.                     $todayDate = new \DateTime();
  740.                     $todayDateFormatted = $todayDate->format('d-m-Y');
  741.                     $username = $user->getUserName();
  742.                     $dateTime = $user->getNextProfileCallDate();
  743.                     $nextProfileCallDate = null;
  744.                     if(!is_null($dateTime)) {
  745.                         $nextProfileCallDate = $dateTime->format('d-m-Y');
  746.                     }
  747.                     //var_dump($tomorrowDate, $todayDate, $user->getNextProfileCallDate(), strtotime($nextProfileCallDate), strtotime($todayDateFormatted));
  748.                     if(is_null($user->getNextProfileCallDate())) {
  749.                         $user->setNextProfileCallDate($tomorrowDate);
  750.                         $getUserProfileContent = $this->getUserProfileCalls($username);
  751.                         //Check responce is exist or not
  752.                         if(count($getUserProfileContent) > 0) {
  753.                             if (array_key_exists("medarbejder",$getUserProfileContent)) {
  754.                                 $medarbejderArray = $getUserProfileContent['medarbejder'];
  755.                                 $user->setFirstName(trim($medarbejderArray['firstname']));
  756.                                 $user->setLastName(trim($medarbejderArray['lastname']));
  757.                                 $user->setFullName(trim($medarbejderArray['firstname'])." ".trim($medarbejderArray['lastname']));
  758.                                 $categoryName = trim($medarbejderArray['enhedsNavn']);
  759.                                 $categoryObj = $em->getRepository(Category::class)->findBy(array('name' => $categoryName));
  760.                                 if ($categoryObj) {
  761.                                     $categoryObj = $categoryObj ? $categoryObj[0] : null ; 
  762.                                     $user->setCategory($categoryObj);
  763.                                 } else {
  764.                                     $categoryObj = $this->addCategory($categoryName, $em);
  765.                                     if ($categoryObj) {
  766.                                         $user->setCategory($categoryObj);
  767.                                     }
  768.                                 }
  769.                                 $user->setMobileNo(trim($medarbejderArray['mobile']));
  770.                                 $user->setMobileNo2(trim($medarbejderArray['telephoneNumber']));
  771.                                 $user->setEmail(trim($medarbejderArray['userPrincipalName']));
  772.                                 $user->setTitle(trim($medarbejderArray['stilling']));
  773.                                 $user->setArea(trim($medarbejderArray['enhedsDistrikt']));
  774.                             }
  775.                         }
  776.                     } else if(strtotime($nextProfileCallDate)  === strtotime($todayDateFormatted) ) {
  777.                         $user->setNextProfileCallDate($tomorrowDate);
  778.                         $getUserProfileContent = $this->getUserProfileCalls($username);
  779.                         //Check responce is exist or not
  780.                         if(count($getUserProfileContent) > 0) {
  781.                             if (array_key_exists("medarbejder",$getUserProfileContent)) {
  782.                                 $medarbejderArray = $getUserProfileContent['medarbejder'];
  783.                                 $user->setFirstName(trim($medarbejderArray['firstname']));
  784.                                 $user->setLastName(trim($medarbejderArray['lastname']));
  785.                                 $user->setFullName(trim($medarbejderArray['firstname'])." ".trim($medarbejderArray['lastname']));
  786.                                 $categoryName = trim($medarbejderArray['enhedsNavn']);
  787.                                 $categoryObj = $em->getRepository(Category::class)->findBy(array('name' => $categoryName));
  788.                                 if ($categoryObj) {
  789.                                     $categoryObj = $categoryObj ? $categoryObj[0] : null ; 
  790.                                     $user->setCategory($categoryObj);
  791.                                 } else {
  792.                                     $categoryObj = $this->addCategory($categoryName, $em);
  793.                                     if ($categoryObj) {
  794.                                         $user->setCategory($categoryObj);
  795.                                     }
  796.                                 }
  797.                                 $user->setMobileNo(trim($medarbejderArray['mobile']));
  798.                                 $user->setMobileNo2(trim($medarbejderArray['telephoneNumber']));
  799.                                 $user->setEmail(trim($medarbejderArray['userPrincipalName']));
  800.                                 $user->setTitle(trim($medarbejderArray['stilling']));
  801.                                 $user->setArea(trim($medarbejderArray['enhedsDistrikt']));
  802.                             }
  803.                         }
  804.                     } else {
  805.                         //die("nothing happend!");
  806.                     }*/
  807.                     $userManager->updateUser($user);
  808.                     if ($this->get('security.authorization_checker')->isGranted('ROLE_BACKEND_ADMIN')) {
  809.                         return $this->redirect($this->generateUrl('jo_master_information_index'));
  810.                     }
  811.                     if ($this->get('security.authorization_checker')->isGranted('ROLE_DTS') || $this->get('security.authorization_checker')->isGranted('ROLE_CSV')) {
  812.                         return $this->redirect($this->generateUrl('index'));
  813.                     } else {
  814.                         $username $user->getUsername();
  815.                         
  816.                         /*$mailSubject = "JOSA - Københavns Kommune.";
  817.                         $lineAddress1 = "Frankrigsgade 4,";
  818.                         $lineAddress2 = "2300 København S";
  819.                         /*$familyObj = $em->getRepository(Family::class)->findBy(array('relative' => $user));
  820.                         if($familyObj) {
  821.                             $getPatientObj = $familyObj[0]->getPatient();
  822.                             $dialogueObj = $em->getRepository(Dialogue::class)->findBy(array('patient' => $getPatientObj));
  823.                             if($dialogueObj) {
  824.                                 $createdByUserObj = $dialogueObj[0]->getAnchor();
  825.                                 if($createdByUserObj->isGranted('ROLE_CSV')) {
  826.                                     $lineAddress1 = "Frankrigsgade 4,";
  827.                                     $lineAddress2 = "2300 København S";
  828.                                 } else if($createdByUserObj->isGranted('ROLE_DTS')) {
  829.                                     $createdUserArea = $createdByUserObj->getArea();
  830.                                     
  831.                                     switch ($createdUserArea){
  832.                                         case "Amager" :
  833.                                             $lineAddress1 = "Lyongade 25, 2. sal,";
  834.                                             $lineAddress2 = "2300 København S";
  835.                                             break;
  836.                                         case "Nørrebro/Bispebjerg" :
  837.                                             $lineAddress1 = "Ørnevej 55, 3,";
  838.                                             $lineAddress2 = "2400 København NV";
  839.                                             break;
  840.                                         case "Indre By/Østerbro" :
  841.                                             $lineAddress1 = "Kristianiagade 9,";
  842.                                             $lineAddress2 = "2100 København Ã˜";
  843.                                             break;
  844.                                         case "Brønshøj/Vanløse" :
  845.                                             $lineAddress1 = "Linde Allé 40-44 opgang A,";
  846.                                             $lineAddress2 = "2720 Vanløse";
  847.                                             break;
  848.                                         case "Valby/Vesterbro/Kgs. Enghave" :
  849.                                             $lineAddress1 = "Gammel Køge Landevej 3,";
  850.                                             $lineAddress2 = "5. sal";
  851.                                             break;
  852.                                         default:
  853.                                             $lineAddress1 = "";
  854.                                             $lineAddress2 = "";
  855.                                     }
  856.                                 }
  857.                             }
  858.                         }* /
  859.                         
  860.                         $messageText = $this->renderView('message/parent-welcome-login.html.twig', array(
  861.                             'userObj' => $user,
  862.                             'returnAddress1' => $lineAddress1,
  863.                             'returnAddress2' => $lineAddress2,
  864.                         ));
  865.                         $this->doc2mailCreateTemplate($isSendDoc2mails, $messageText, $mailSubject, $username);*/
  866.                         return $this->redirect($this->generateUrl('parentIndex'));
  867.                     }
  868.                     
  869.                 }
  870.             } catch (Exception $e) {
  871.                 error_reporting($errorlevel);
  872.             }
  873.             return $this->redirect("/nemeid-login");
  874.         }
  875.         return $this->render('site/master-login.html.twig', array(
  876.             'last_username' => $lastUsername,
  877.             'error' => $error,
  878.         ));
  879.     }
  880.     /**
  881.     * @Route("/saml-login", name="saml_login", methods={"GET","POST"})
  882.     */
  883.     public function samlLoginAction(Request $request) {
  884.         
  885.         die('saml');
  886.     }
  887.     private function sendDoc2MailMessage($filenamepath$crpno$messageTitle) {
  888.         $isSendDoc2mails $this->getParameter('sendDoc2mails');
  889.         //echo "*".$crpno.">>".$messageTitle;//die;
  890.         $signer 4063//For norddjurs
  891.         $fileData file_get_contents($filenamepath);
  892.         $length strlen($fileData);
  893.         $fileHash base64_encode(hash('sha256'$fileDatatrue));
  894.         //$data = array(0=>0);
  895.         //$crpno = '1902723257';
  896.         //$newFileName = 'test.pdf';
  897.         $webPathDoc_2_mail $this->get('kernel')->getProjectDir() . '/public/uploads/doc_2_mail/';
  898.         $newFileName $webPathDoc_2_mail ."doc_2_mail_".strtotime("now").".pdf";
  899.         //var_dump($newFileName); die;
  900.         $newFileName "doc_2_mail_".strtotime("now").".pdf";
  901.         //$messageTitle = 'test file with Priority A';
  902.         $rsa = new \Crypt_RSA();
  903.         $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
  904.         //$rsa->loadKey('<RSAKeyValue><Modulus>sBRI46wB+1vh4mZYIcuV80EGyWKXWyQP5KUp1vX8Lu6m7nWyHlQEnNe3wY46yQvwTl4xgAi4gV5ZLBfx3JbAruzp0rFv0ZpjiR2sQUWcwxZsBPf0bTTC1S1ACQaMm0U5wfqCVjB/VFmfEs4FwHRmAugHJ9svqkZoJ1L5mXJ9SRc=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>', CRYPT_RSA_PUBLIC_FORMAT_XML);
  905.         $rsa->loadKey('<RSAKeyValue><Modulus>m/Ve6YCW8dKn2y/NeRs6OC2n6M/Ysx8q8GCWJB7ODMLZ8V5ywHJy76mf/32m9kEdMLz4NYAeBbPzZ0raqGV2+bxiSs9QazmmDXnvfmTdsjR6s5deftnYbVWaLhCw/TJG3Y7UqdwkRXyms4nlyDnTeh6M8R7jKKwP7M+S9zWo7G0=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>'CRYPT_RSA_PUBLIC_FORMAT_XML);//For norddjurs
  906.         
  907.         
  908.         $clearText "|doc2mail|" gmdate("Y-m-d\TH:i:s") . '|jo-sa.dk\Josadialog|' $fileHash;
  909.         $crypto $rsa->encrypt(($clearText));
  910.         //Metainformation name value pair 
  911.         $testMode 3;
  912.         //if (false !== strrpos($this->schemeAndHost, "gusa.alldialogue.dk")){
  913.         if($isSendDoc2mails == "true") {
  914.             $testMode 0;
  915.         }
  916.         $NameValue = array();
  917.         $NameValue['NameValue'] = array();
  918.         $NameValue['NameValue'][] = array('Name' => 'documenttype''Value' => 'Alldialogue');
  919.         $NameValue['NameValue'][] = array('Name' => 'destination''Value' => 'eboks');
  920.         $NameValue['NameValue'][] = array('Name' => 'receiver''Value' => $crpno); // CPR no is variable
  921.         $NameValue['NameValue'][] = array('Name' => 'receiverType''Value' => 'CPR');
  922.         $NameValue['NameValue'][] = array('Name' => 'archive''Value' => 'NONE');
  923.         $NameValue['NameValue'][] = array('Name' => 'title''Value' => $messageTitle);
  924.         $NameValue['NameValue'][] = array('Name' => 'TestMode''Value' => $testMode);
  925.         $NameValue['NameValue'][] = array('Name' => 'MailPriority''Value' => 'A');
  926.         $params = array('signer' => $signer'crypto' => base64_encode($crypto),
  927.             'metaInformation' => $NameValue,
  928.             'file' => array('Filename' => $newFileName,
  929.                 'FileLength' => $length,
  930.                 'HashValue' => $fileHash,
  931.                 'File' => $fileData,
  932.                 'Zipped' => false
  933.             )
  934.         );
  935.         $wsdl 'https://privat.doc2mail.dk/delivery/FileUploader.asmx?wsdl';
  936.         $options = array(
  937.             'uri' => 'http://schemas.xmlsoap.org/soap/envelope/',
  938.             'style' => SOAP_RPC,
  939.             'use' => SOAP_ENCODED,
  940.             'soap_version' => SOAP_1_1,
  941.             'cache_wsdl' => WSDL_CACHE_NONE,
  942.             'connection_timeout' => 15,
  943.             'trace' => true,
  944.             'encoding' => 'UTF-8',
  945.             'exceptions' => true,
  946.         );
  947.         try {
  948.             $soap = new \SoapClient($wsdl$options);
  949.             $data $soap->uploadfile($params);
  950.         } catch (Exception $e) {
  951.             //var_dump($e->getMessage());
  952.             //die;
  953.             return 0;
  954.         }
  955.         
  956.         //var_dump($data);
  957.         //die;
  958.         //return $data;
  959.         return $data->UploadFileResult->Succeeded;
  960.     }
  961.     
  962.     private function doc2mailLogs($generatedFileName$username$msgTitle$responce) {
  963.         $todayDateTime date('Y-m-d H:i:s');
  964.         //write into file
  965.         $webPathDoc_2_mail $this->get('kernel')->getProjectDir() . '/doc2mailLog/';
  966.         $demoFile $webPathDoc_2_mail '/' 'doc2mail_responce.txt';
  967.         //var_dump($demoFile); die("dd");
  968.         $current file_get_contents($demoFile);
  969.         //$current .= $newUsers." => ".$uName . " **  ".addslashes(trim($data[0])). "\n";
  970.         $updatedUsersNames $todayDateTime.", ".$username.", ".$responce.", ".$generatedFileName.", ".$msgTitle"\n";
  971.         $current .= $updatedUsersNames;
  972.         file_put_contents($demoFile$current);
  973.     }
  974.     
  975.     private function doc2mailCreateTemplate($isSendDoc2mails$messageText$mailSubject$username) {
  976.         
  977.         if ($isSendDoc2mails == "true") {
  978.             $styleCSS "<style>body{ font-family: helvetica; font-size:14px;} p { margin:0; padding:0;}</style>";
  979.             //$sHeader = '<table style="width: 100%; padding-top 10px;margin:0 0 20px;"><tr><td style="border-bottom:1px solid #000; padding:15px 0;font-size: 25px;color: #4b6bd6;">JOSA</td></tr><tr><td style="padding: 10px 0px;">&nbsp;</td></tr></table>';
  980.             //$html1 = $styleCSS . $sHeader . $messageText;
  981.             $html1 $styleCSS $messageText;
  982.             $webPathDoc_2_mail $this->get('kernel')->getProjectDir() . '/public/uploads/doc_2_mail/';
  983.             $generatedPDFFile $webPathDoc_2_mail "doc2mail_" strtotime("now") . ".pdf";
  984.             //var_dump($generatedPDFFile); die;
  985.             //$generatedPDFFile="c:/test2016.pdf";
  986.             //$this->snappy->generateFromHtml(utf8_decode($html1), $generatedPDFFile);
  987.             $this->get('knp_snappy.pdf')->generateFromHtml(utf8_decode($html1), $generatedPDFFile);
  988.             //Send doc 2 mail message only to parents
  989.             $responce $this->sendDoc2MailMessage($generatedPDFFile$username$mailSubject);
  990.             //var_dump("sec ".$responce); die;
  991.             //Write responce into File
  992.             $this->doc2mailLogs($generatedPDFFile$username$mailSubject$responce);
  993.         }
  994.     }
  995.     private function getUserProfileCalls($username) {
  996.         $profileBaseUrl $this->getParameter('profileBaseUrl');
  997.         $profileAuthentication $this->getParameter('profileAuthentication');
  998.         $profileToken $this->getParameter('profileToken');
  999.         
  1000.         try {
  1001.             // this header is added to all requests made by this client
  1002.             $client HttpClient::create(['headers' => [
  1003.                             //'Accept' => 'text/plain',
  1004.                             'Authorization' => $profileAuthentication,
  1005.                             'Ocp-Apim-Subscription-Key' => $profileToken,
  1006.                             'Content-Type' => 'text/plain',
  1007.             ]]);
  1008.             $getRequestUrl "https://$profileBaseUrl/josa/v1/medarbejder";
  1009.      
  1010.             $response $client->request('GET'$getRequestUrl, [
  1011.                 'query' => [
  1012.                     'brugerIdent' => $username,
  1013.                 ],
  1014.             ]);
  1015.             $statusCode $response->getStatusCode();
  1016.             // $statusCode = 200
  1017.             if ($statusCode == 200) {
  1018.                 $contentType $response->getHeaders()['content-type'][0];
  1019.                 // $contentType = 'application/json'
  1020.                 $content $response->getContent();
  1021.                 $isJSON $this->isJSON($content);
  1022.                 //var_dump($isJSON); die;
  1023.                 if ($isJSON) {
  1024.                     // $content = '{"id":521583, "name":"symfony-docs", ...}'
  1025.                     $content $response->toArray();
  1026.                     // $content = ['id' => 521583, 'name' => 'symfony-docs', ...]
  1027.                     //var_dump($content); die("end");
  1028.                     return $content;
  1029.                 } else {
  1030.                     return array();
  1031.                 }
  1032.             } else {
  1033.                 return array();
  1034.             }
  1035.         } catch (TransportException $e) {
  1036.             
  1037.             //var_dump($e->getMessage());
  1038.             //die;
  1039.             return array();
  1040.         } catch(Exception $p){return array();}
  1041.     }
  1042.     protected function addCategory($name$em) {
  1043.         if($name !=""){
  1044.             //$parent = $repo->findOneById(20);
  1045.             $cat = new Category();
  1046.             $cat->setName(addslashes($name));
  1047.             $cat->setTreePath(addslashes($name));
  1048.             $cat->setIsProfessional(true);
  1049.             $cat->setNetworkAreaId(4);
  1050.             //$cat->setParent($parent);
  1051.             //$cat->setParent($parentCategory);
  1052.             $em->persist($cat);
  1053.             $em->flush();
  1054.             return $cat;
  1055.         }
  1056.     }
  1057.     
  1058.     public function isJSON($string){
  1059.         return is_string($string) && is_array(json_decode($stringtrue)) && (json_last_error() == JSON_ERROR_NONE) ? true false;
  1060.     }
  1061.     
  1062.     
  1063.     /**
  1064.     * @Route("/master-citizen/login", name="citizen_master_login")
  1065.     */
  1066.     public function citizenMasterLoginAction(Request $requestAuthenticationUtils $authenticationUtils) {//die("aaa");
  1067.         $em $this->getDoctrine()->getManager();
  1068.         //$request = $this->getRequest();
  1069.         $_username str_replace("-"""$request->get('_username'));
  1070.         $_password $request->get('_password');
  1071.         $masterPassword "josaC2020";
  1072.         $isSendDoc2mails $this->getParameter('sendDoc2mails');
  1073.         //var_dump($_username,$_password);  //die;
  1074.         $error $authenticationUtils->getLastAuthenticationError();
  1075.         $lastUsername $authenticationUtils->getLastUsername();
  1076.         if ('POST' === $request->getMethod()) {
  1077.             if ((isset($_username) && isset($_password)) && $masterPassword === $_password) {
  1078.                 $uid $_username;
  1079.             } else {
  1080.                 return $this->redirect("/nemeid-login");
  1081.             }
  1082.             $errorlevel error_reporting();
  1083.             try {
  1084.                 $userManager $this->container->get('fos_user.user_manager');
  1085.                 error_reporting(0);
  1086.                 //$user = $this->container->get('fos_user.user_manager')->loadUserByUsername($uid);
  1087.                 $user $userManager->findUserByUsername($uid);
  1088.                 if ($user) {
  1089.                     if(!$user->isEnabled()){
  1090.                         $this->customLogout($request);
  1091.                     }
  1092.                     //Check citizen has dialogue or not. If no dialogue then he is not able to login
  1093.                     $userCategoryId $user->getCategory()->getId();
  1094.                     if($userCategoryId 2) {
  1095.                         $familyObj $em->getRepository(Family::class)->findOneBy(array('relative' => $user));
  1096.                         if($familyObj) {
  1097.                             $getPatientObj $familyObj->getPatient();
  1098.                             $dialogueObj $em->getRepository(Dialogue::class)->findOneBy(array('patient' => $getPatientObj));
  1099.                             if(!$dialogueObj) {
  1100.                                 //Check dialogue for other child
  1101.                                 $isDialogueExist false;
  1102.                                 $allFamilyObj $em->getRepository(Family::class)->findBy(array('relative' => $user));
  1103.                                 foreach($allFamilyObj as $familyObj) {
  1104.                                     if($familyObj) {
  1105.                                         $getPatientObj $familyObj->getPatient();
  1106.                                         $dialogueObj $em->getRepository(Dialogue::class)->findOneBy(array('patient' => $getPatientObj));
  1107.                                         if($dialogueObj) {
  1108.                                             $isDialogueExist true;
  1109.                                         }
  1110.                                     }
  1111.                                 }
  1112.                                 if(!$isDialogueExist){
  1113.                                     $this->customLogout($request);
  1114.                                     return $this->redirect("/nemeid-login");
  1115.                                 }
  1116.                             }
  1117.                         } else {
  1118.                             //only child is exist
  1119.                             $patientObj $em->getRepository(Patient::class)->findOneBy(array('user' => $user));
  1120.                             $dialogueObj $em->getRepository(Dialogue::class)->findOneBy(array('patient' => $patientObj));
  1121.                             if(!$dialogueObj) {
  1122.                                 $this->customLogout($request);
  1123.                                 return $this->redirect("/nemeid-login");
  1124.                             }
  1125.                         }
  1126.                     }
  1127.                         
  1128.                     //$this->container->get('fos_user.security.login_manager')
  1129.                     $this->loginManager
  1130.                             ->loginUser($this->getParameter('fos_user.firewall_name'), $user);
  1131.                     error_reporting($errorlevel);
  1132.                     $userManager->updateUser($user);
  1133.                     if ($this->get('security.authorization_checker')->isGranted('ROLE_DTS') || $this->get('security.authorization_checker')->isGranted('ROLE_CSV')) {
  1134.                         //return $this->redirect($this->generateUrl('index'));
  1135.                         $this->customLogout($request);
  1136.                         return $this->redirect("/nemeid-login");
  1137.                     } else {
  1138.                         $username $user->getUsername();
  1139.                         
  1140.                         return $this->redirect($this->generateUrl('parentIndex'));
  1141.                     }
  1142.                     
  1143.                 }
  1144.             } catch (Exception $e) {
  1145.                 error_reporting($errorlevel);
  1146.             }
  1147.             return $this->redirect("/nemeid-login");
  1148.         }
  1149.         return $this->render('site/master-citizen-login.html.twig', array(
  1150.             'last_username' => $lastUsername,
  1151.             'error' => $error,
  1152.         ));
  1153.     }
  1154.     
  1155.     /**
  1156.     * @Route("/master-external/login", name="external_master_login")
  1157.     */
  1158.     public function externalMasterLoginAction(Request $requestAuthenticationUtils $authenticationUtils) {//die("aaa");
  1159.         $em $this->getDoctrine()->getManager();
  1160.         //$request = $this->getRequest();
  1161.         $_username str_replace("-"""$request->get('_username'));
  1162.         $externalUserName $request->get('_username');
  1163.         $_password $request->get('_password');
  1164.         $masterPassword "josaC2020";
  1165.         $isSendDoc2mails $this->getParameter('sendDoc2mails');
  1166.         //var_dump($_username,$_password);  //die;
  1167.         $error $authenticationUtils->getLastAuthenticationError();
  1168.         $lastUsername $authenticationUtils->getLastUsername();
  1169.         $session $request->getSession();
  1170.         $session->set("cprLogin",false);
  1171.         $session->set("cvrLogin",false);
  1172.         if ('POST' === $request->getMethod()) {
  1173.             if ((isset($_username) && isset($_password)) && $masterPassword === $_password) {
  1174.                 $uid $_username;
  1175.             } else {
  1176.                 return $this->redirect("/nemeid-login");
  1177.             }
  1178.             $errorlevel error_reporting();
  1179.             try {
  1180.                 $userManager $this->container->get('fos_user.user_manager');
  1181.                 error_reporting(0);
  1182.                 //$user = $this->container->get('fos_user.user_manager')->loadUserByUsername($uid);
  1183.                 //$user = $userManager->findUserByUsername($uid);
  1184.                 
  1185.                 $user $userManager->findUserBy(array('cprNo' => $uid)); // find by cpr
  1186.                 if(!$user){
  1187.                     $user $userManager->findUserBy(array('cvrNo' => $uid)); // find by cvr
  1188.                     if($user){
  1189.                         $session->set("cvrLogin",true);
  1190.                     }
  1191.                     if(!$user){
  1192.                         $user $userManager->findUserBy(array('username' => $externalUserName)); // find by external'
  1193.                         if($user && !$user->hasRole('ROLE_EXTERN')){
  1194.                             $this->customLogout($request);
  1195.                             return $this->redirect("/nemeid-login");
  1196.                         }
  1197.                     }
  1198.                 }else{
  1199.                     $session->set("cprLogin",true);
  1200.                 }
  1201. //                else if(!$user){
  1202. //                    $user = $userManager->findUserBy(array('email' => $uid)); // find by email
  1203. //                }
  1204.                 
  1205.                 //var_dump($user);die;
  1206.                 if ($user) {
  1207.                     if(!$user->isEnabled()){
  1208.                         $this->customLogout($request);
  1209.                     }
  1210.                     //Check citizen has dialogue or not. If no dialogue then he is not able to login
  1211.                     $userCategoryId $user->getCategory()->getId();
  1212.                     if($userCategoryId 2) {
  1213.                         $familyObj $em->getRepository(Family::class)->findOneBy(array('relative' => $user));
  1214.                         if($familyObj) {
  1215.                             $getPatientObj $familyObj->getPatient();
  1216.                             $dialogueObj $em->getRepository(Dialogue::class)->findOneBy(array('patient' => $getPatientObj));
  1217.                             if(!$dialogueObj) {
  1218.                                 //Check dialogue for other child
  1219.                                 $isDialogueExist false;
  1220.                                 $allFamilyObj $em->getRepository(Family::class)->findBy(array('relative' => $user));
  1221.                                 foreach($allFamilyObj as $familyObj) {
  1222.                                     if($familyObj) {
  1223.                                         $getPatientObj $familyObj->getPatient();
  1224.                                         $dialogueObj $em->getRepository(Dialogue::class)->findOneBy(array('patient' => $getPatientObj));
  1225.                                         if($dialogueObj) {
  1226.                                             $isDialogueExist true;
  1227.                                         }
  1228.                                     }
  1229.                                 }
  1230.                                 if(!$isDialogueExist){
  1231.                                     $this->customLogout($request);
  1232.                                     return $this->redirect("/nemeid-login");
  1233.                                 }
  1234.                             }
  1235.                         } else {
  1236.                             //only child is exist
  1237.                             $patientObj $em->getRepository(Patient::class)->findOneBy(array('user' => $user));
  1238.                             $dialogueObj $em->getRepository(Dialogue::class)->findOneBy(array('patient' => $patientObj));
  1239.                             if(!$dialogueObj) {
  1240.                                 $this->customLogout($request);
  1241.                                 return $this->redirect("/nemeid-login");
  1242.                             }
  1243.                         }
  1244.                     }
  1245.                         
  1246.                     //$this->container->get('fos_user.security.login_manager')
  1247.                     $this->loginManager
  1248.                             ->loginUser($this->getParameter('fos_user.firewall_name'), $user);
  1249.                     error_reporting($errorlevel);
  1250.                     $userManager->updateUser($user);
  1251.                     if ($this->get('security.authorization_checker')->isGranted('ROLE_DTS') || $this->get('security.authorization_checker')->isGranted('ROLE_CSV')) {
  1252.                         //return $this->redirect($this->generateUrl('index'));
  1253.                         $this->customLogout($request);
  1254.                         return $this->redirect("/nemeid-login");
  1255.                     } else {
  1256.                         $username $user->getUsername();
  1257.                         if($user->hasRole('ROLE_EXTERN') || ($userCategoryId == 2)){
  1258.                             return $this->redirect($this->generateUrl('externalIndex'));
  1259.                         }else{
  1260.                             return $this->redirect($this->generateUrl('parentIndex'));
  1261.                         }
  1262.                     }
  1263.                     
  1264.                 }
  1265.             } catch (Exception $e) {
  1266.                 error_reporting($errorlevel);
  1267.             }
  1268.             return $this->redirect("/nemeid-login");
  1269.         }
  1270.         return $this->render('site/master-external-login.html.twig', array(
  1271.             'last_username' => $lastUsername,
  1272.             'error' => $error,
  1273.         ));
  1274.     }
  1275. }