src/Controller/SiteController.php line 1218

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