src/Controller/ProfileController.php line 294

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Entity\Role;
  5. use App\Utils\EmailSignature;
  6. use App\Utils\XmlRender;
  7. use App\Form\ChangePasswordFormType;
  8. use Doctrine\ORM\EntityManagerInterface;
  9. use App\Service\UserSession;
  10. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  11. use Symfony\Component\Filesystem\Filesystem;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\Response;
  14. use Symfony\Component\Routing\Annotation\Route;
  15. use Symfony\Component\Process\Process;
  16. use Symfony\Component\Process\Exception\ProcessFailedException;
  17. use Symfony\Component\Ldap\Adapter\ExtLdap\Adapter;
  18. use Symfony\Component\Ldap\Ldap;
  19. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  20. use Symfony\Component\Form\Form;
  21. use Sabre\VObject\Component\VCard;
  22. use Sabre\VObject\Document;
  23. class ProfileController extends AbstractController
  24. {
  25.     private $pdo;
  26.     #[Route('/profile'name'profile')]
  27.     public function profile(Request $requestUserSession $userSession): Response
  28.     {
  29.         if (!$user $this->getUser()) return $this->redirectToRoute('login');
  30.         else $userData $userSession->getEntryFromSession();
  31.         $type preg_split('/@/',$user->getUsername());
  32.         $vcard = new VCard([
  33.             'FN'  =>  mb_convert_case($userData->getFirstname(), MB_CASE_TITLE"UTF-8").' '.preg_replace(array('/\bVon\b/u','/\bDe\b/u'), array('von','de'), mb_convert_case($userData->getLastname(), MB_CASE_TITLE"UTF-8")),
  34.             'N'   => [ preg_replace(array('/\bVon\b/u','/\bDe\b/u'), array('von','de'), mb_convert_case($userData->getLastname(), MB_CASE_TITLE"UTF-8")),  mb_convert_case($userData->getFirstname(), MB_CASE_TITLE"UTF-8"), ''''''],
  35.             'ROLE'  => $userData->getDepartment(),
  36.             'TITLE'  => mb_convert_case($userData->getJob(), MB_CASE_TITLE"UTF-8"),
  37.             'NOTE'  => 'Site '.$userData->getOrganization(),
  38.         ]);
  39.         $vcard->add('ADR', [''''$userData->getStreet(), $userData->getCity(), ''$userData->getZipcode()], ['type' => 'work']);
  40.         if($type[1] == 'batiformes.com' || $type[1] == 'scorev.fr'$vcard->add('EMAIL'$user->getUsername(), ['type' => 'work']);
  41.         if($userData->getPhone() != ''$vcard->add('TEL'$userData->getPhone(), ['type' => 'work']);
  42.         if($userData->getMobile() != ''$vcard->add('TEL'$userData->getMobile(), ['type' => 'cell']);
  43.         if($userData->getFax() != ''$vcard->add('TEL'$userData->getFax(), ['type' => 'fax']);
  44.         if($userData->getOrganization() == 'SCOREV'){
  45.             $vcard->add('ORG''SCOREV');
  46.             $vcard->add('URL''https://www.scorev.fr', ['type' => 'work']);
  47.             $vcard->add('PHOTO''https://www.scorev.fr/assets/images/vcard/logo_vcard.jpg', ['type' => 'JPEG']);
  48.         }
  49.         if($userData->getOrganization() == 'TOLARTOIS'){
  50.             $vcard->add('ORG''TOLARTOIS');
  51.             $vcard->add('URL''https://www.tolartois.com', ['type' => 'work']);
  52.             $vcard->add('PHOTO''https://www.tolartois.com/assets/images/vcard/logo_vcard.jpg', ['type' => 'JPEG']);
  53.         }
  54.         if($userData->getOrganization() != 'TOLARTOIS' && $userData->getOrganization() != 'SCOREV'){
  55.             $vcard->add('ORG''Bati Formes');
  56.             $vcard->add('URL''https://www.batiformes.com', ['type' => 'work']);
  57.             $vcard->add('PHOTO''https://www.batiformes.com/assets/images/vcard/logo_vcard.jpg', ['type' => 'JPEG']);
  58.         }
  59.         $vcard $vcard->convert(Document::VCARD30);
  60.         $vcard base64_encode($vcard->serialize());
  61.         $nickhandle preg_split('/@/',$user->getUsername());
  62.         $qrcode $request->getScheme() . '://' $request->getHttpHost() . '/qr-code/png/' $userData->getWeb() . '/vcard/' preg_replace('/\./''-'$nickhandle[0]) . '.html';
  63.         $signature = new EmailSignature();
  64.         $email $signature->signature($userData,$user->getUsername(),$vcard);
  65.         $password $this->createForm(ChangePasswordFormType::class);
  66.         $password->handleRequest($request);
  67.         /*$defaultData = ['message' => 'Type your message here'];
  68.         $form = $this->createFormBuilder($defaultData)
  69.             ->add('name', TextType::class)
  70.             ->add('email', EmailType::class)
  71.             ->add('message', TextareaType::class)
  72.             ->add('send', SubmitType::class)
  73.             ->getForm();
  74.         $form->handleRequest($request);*/
  75.         return $this->render('profile/index.html.twig', [
  76.             'title_meta' => 'Mon compte utilisateur',
  77.             'page' => 'profile',
  78.             'user' => $userData,
  79.             'vcard' => $vcard,
  80.             'qrcode' => $qrcode,
  81.             'email' => $email,
  82.             'password' => $password->createView(),
  83.         ]);
  84.     }
  85.     #[Route('/profile/password'name'profile_pswd')]
  86.     public function profile_pswd(Request $requestAdapter $ldapAdapterEntityManagerInterface $entityManagerUserPasswordHasherInterface $passwordEncoder): Response
  87.     {
  88.         if (!$user $this->getUser()) return $this->redirectToRoute('login');
  89.         
  90.         $form $this->createForm(ChangePasswordFormType::class);
  91.         $form->handleRequest($request);
  92.         if ($form->isSubmitted()){
  93.             if (!$form->isValid()) {
  94.                 $data = [
  95.                     'alert' => 'error',
  96.                     'message' => $this->getErrorMessages($form)
  97.                 ];
  98.             }
  99.             if($form->isValid()) {
  100.                 $userpassword '{SHA}' base64_encode(sha1$form->get('plainPassword')->getData(), TRUE ));
  101.                 $ldap = new Ldap($ldapAdapter);
  102.                 $ldap->bind($this->getParameter('app.ldap_service_user').','.$this->getParameter('app.ldap_service_dn'), $this->getParameter('app.ldap_service_password'));
  103.                 $entryManager $ldap->getEntryManager();
  104.                 $query $ldap->query($this->getParameter('app.ldap_service_dn'), '(&(uid='.$user->getUsername().'))');
  105.                 $result $query->execute()->toArray();
  106.                 $entry $result[0];
  107.                 $entry->setAttribute('userPassword', [$userpassword]);
  108.                 $entryManager->update($entry);
  109.                 $password $passwordEncoder->hashPassword($this->getUser(), $form->get('plainPassword')->getData());
  110.                 $entityManager->getRepository(User::class)->upgradePassword($this->getUser(),$password);
  111.                 $bdd $this->getDatabaseConnection();
  112.                 $sabrePswdUpdate $bdd->prepare("UPDATE `users` SET `digesta1`= md5('".$user->getUsername().":BaikalDAV:".$form->get('plainPassword')->getData()."') WHERE `username`='".$user->getUsername()."' ");
  113.                 $sabrePswdUpdate->execute();
  114.                 $file '/opt/picapport/.picapport/users/user/'.$user->getUsername().'/'.$user->getUsername().'.xml';
  115.                 $xmlUser = new XmlRender();
  116.                 $xmlUser->user_edit($file,$form->get('plainPassword')->getData());
  117.                 $pathToPicApportScript "/home/websites/scripts/picapport.sh";
  118.                 $process = new Process(['sh'$pathToPicApportScript]);
  119.                 $process->run();
  120.                 $bdd null;
  121.                 $data = [
  122.                     'alert' => 'success',
  123.                     'message' => 'Votre mot de passe a été modifié.'
  124.                 ];
  125.             }
  126.         } else {
  127.             $data = [
  128.                 'alert' => 'error',
  129.                 'message' => 'Une erreur est intervenue.'
  130.             ];
  131.         }
  132.         return $this->json(
  133.             $data,
  134.             headers: ['Content-Type' => 'application/json;charset=UTF-8']
  135.         );
  136.     }
  137.     #[Route('/profile/add'name'profile_add')]
  138.     public function profile_add(Request $requestAdapter $ldapAdapterEntityManagerInterface $entityManagerUserSession $userSession): Response
  139.     {
  140.         $submittedToken $request->request->get('token');
  141.         if ($this->isCsrfTokenValid('picture-add'$submittedToken))
  142.         {
  143.             if ($_FILES['file']['size'] != '0') {
  144.                 $userSession->getEntryFromSession();
  145.                 $data file_get_contents($_FILES['file']['tmp_name']);
  146.                 $picture base64_encode($data);
  147.                 $ldap = new Ldap($ldapAdapter);
  148.                 $ldap->bind($this->getParameter('app.ldap_service_user').','.$this->getParameter('app.ldap_service_dn'), $this->getParameter('app.ldap_service_password'));
  149.                 $entryManager $ldap->getEntryManager();
  150.                 $query $ldap->query($this->getParameter('app.ldap_service_dn'), '(&(uid='.$this->getUser()->getUsername().'))');
  151.                 $result $query->execute()->toArray();
  152.                 $entry $result[0];
  153.                 $entryManager->addAttributeValues($entry'jpegPhoto', [$picture]);
  154.                 $userSession->addImageFromSession($picture);
  155.                 $data = [
  156.                     'alert' => 'success',
  157.                     'message' => 'data:image/jpeg;base64,'.$picture
  158.                 ];
  159.             }
  160.             else{
  161.                 $data = [
  162.                     'alert' => 'danger',
  163.                     'message' => "Aucun finchié n'a été récupéré."
  164.                 ];
  165.             }
  166.             return $this->json(
  167.                 $data,
  168.                 headers: ['Content-Type' => 'application/json;charset=UTF-8']
  169.             );
  170.         } else {
  171.             $data = [
  172.                 'alert' => 'danger',
  173.                 'message' => 'Problème de CRSF.'
  174.             ];
  175.             return $this->json(
  176.                 $data,
  177.                 headers: ['Content-Type' => 'application/json;charset=UTF-8']
  178.             );
  179.         }
  180.     }
  181.     #[Route('/profile/delete'name'profile_delete')]
  182.     public function profile_delete(Request $requestAdapter $ldapAdapterEntityManagerInterface $entityManagerUserSession $userSession): Response
  183.     {
  184.         $submittedToken $request->request->get('token');
  185.         if ($this->isCsrfTokenValid('picture-delete'$submittedToken))
  186.         {
  187.             $ldap = new Ldap($ldapAdapter);
  188.             $ldap->bind($this->getParameter('app.ldap_service_user').','.$this->getParameter('app.ldap_service_dn'), $this->getParameter('app.ldap_service_password'));
  189.             $entryManager $ldap->getEntryManager();
  190.             $query $ldap->query($this->getParameter('app.ldap_service_dn'), '(&(uid='.$this->getUser()->getUsername().'))');
  191.             $result $query->execute()->toArray();
  192.             $entry $result[0];
  193.             $entryManager->removeAttributeValues($entry'jpegPhoto', []);
  194.             $userSession->deleteImageFromSession();
  195.             $data = [
  196.                 'alert' => 'success',
  197.                 'message' => '/assets/images/avatar.jpg'
  198.             ];
  199.             return $this->json(
  200.                 $data,
  201.                 headers: ['Content-Type' => 'application/json;charset=UTF-8']
  202.             );
  203.         } else {
  204.             $data = [
  205.                 'alert' => 'danger',
  206.                 'message' => 'Problème de CRSF.'
  207.             ];
  208.             return $this->json(
  209.                 $data,
  210.                 headers: ['Content-Type' => 'application/json;charset=UTF-8']
  211.             );
  212.         }
  213.     }
  214.     #[Route('/profile/notify'name'profile_notify')]
  215.     public function profile_notify(Request $requestEntityManagerInterface $entityManager): Response
  216.     {
  217.         $submittedToken $request->request->get('token');
  218.         if ($this->isCsrfTokenValid('notifications-token'$submittedToken))
  219.         {
  220.             $user $this->getUser();
  221.             $notifications $user->getParameters();
  222.             foreach($notifications as $key => $value){
  223.                 if($key == $request->request->get('id')) {
  224.                     if($request->request->get('box') == 0$notification false;
  225.                     if($request->request->get('box') == 1$notification true;
  226.                     $notifications[$key] = $notification;
  227.                 }
  228.             }
  229.             $user->setParameters($notifications);
  230.             $entityManager->persist($user);
  231.             $entityManager->flush();
  232.     
  233.             $data = [
  234.                 'alert' => 'success',
  235.                 'message' => 'Vos péférences ont été updatées'
  236.             ];
  237.             return $this->json(
  238.                 $data,
  239.                 headers: ['Content-Type' => 'application/json;charset=UTF-8']
  240.             );
  241.         } else {
  242.             $data = [
  243.                 'alert' => 'error',
  244.                 'message' => 'Problème de CRSF.'
  245.             ];
  246.             return $this->json(
  247.                 $data,
  248.                 headers: ['Content-Type' => 'application/json;charset=UTF-8']
  249.             );
  250.         }
  251.     }
  252.     #[Route('/vcard/{_site}/{_id}'name'vcard')]
  253.     public function vcard(Adapter $ldapAdapterEntityManagerInterface $entityManagerstring $_sitestring $_id): Response
  254.     {
  255.         $ext '@batiformes.com';
  256.         if($_site == 'SCOREV'$ext '@scorev.fr';
  257.         $mail preg_replace('/-/','.',$_id).$ext;
  258.         $data = [];
  259.         
  260.         $ldap = new Ldap($ldapAdapter);
  261.         $ldap->bind($this->getParameter('app.ldap_service_user').','.$this->getParameter('app.ldap_service_dn'), $this->getParameter('app.ldap_service_password'));
  262.         $query $ldap->query($this->getParameter('app.ldap_service_dn'), '(&(uid='.$mail.'))');
  263.         $result $query->execute()->toArray();
  264.         $entry $result[0];
  265.         if(!empty($entry)){
  266.             $role $entityManager->getRepository(Role::class)->findOneBy(array("description" => $entry->getAttribute('o')[0]));
  267.             $vcard = new VCard([
  268.                 'FN'  =>  mb_convert_case($entry->getAttribute('givenName')[0], MB_CASE_TITLE"UTF-8").' '.preg_replace(array('/\bVon\b/u','/\bDe\b/u'), array('von','de'), mb_convert_case($entry->getAttribute('sn')[0], MB_CASE_TITLE"UTF-8")),
  269.                 'N'   => [ ucfirst($entry->getAttribute('sn')[0]),  mb_convert_case($entry->getAttribute('givenName')[0], MB_CASE_TITLE"UTF-8"), ''''''],
  270.                 'ROLE'  => $entry->getAttribute('departmentNumber')[0],
  271.                 'TITLE'  => mb_convert_case($entry->getAttribute('title')[0], MB_CASE_TITLE"UTF-8"),
  272.                 'NOTE'  => 'Site '.$entry->getAttribute('o')[0],
  273.             ]);
  274.             $vcard->add('ADR', [''''$role->getData()['direction'], $role->getData()['city'], ''$role->getData()['zipcode']], ['type' => 'work']);
  275.             $vcard->add('EMAIL'$mail, ['type' => 'work']);
  276.             if($entry->hasAttribute('telephoneNumber')) $vcard->add('TEL'$entry->getAttribute('telephoneNumber')[0], ['type' => 'work']);
  277.             if($entry->hasAttribute('mobile')) $vcard->add('TEL'$entry->getAttribute('mobile')[0], ['type' => 'cell']);
  278.             if($entry->hasAttribute('facsimileTelephoneNumber')) $vcard->add('TEL'$entry->getAttribute('facsimileTelephoneNumber')[0], ['type' => 'fax']);
  279.             if($_site == 'SCOREV'){
  280.                 $vcard->add('ORG''SCOREV');
  281.                 $vcard->add('URL''https://www.scorev.fr', ['type' => 'work']);
  282.                 $vcard->add('PHOTO''https://www.scorev.fr/assets/images/vcard/logo_vcard.jpg', ['type' => 'JPEG']);
  283.             }
  284.             if($_site == 'TOLARTOIS'){
  285.                 $vcard->add('ORG''TOLARTOIS');
  286.                 $vcard->add('URL''https://www.tolartois.com', ['type' => 'work']);
  287.                 $vcard->add('PHOTO''https://www.tolartois.com/assets/images/vcard/logo_vcard.jpg', ['type' => 'JPEG']);
  288.             }
  289.             if($_site != 'TOLARTOIS' && $_site != 'SCOREV'){
  290.                 $vcard->add('ORG''Bati Formes');
  291.                 $vcard->add('URL''https://www.batiformes.com', ['type' => 'work']);
  292.                 $vcard->add('PHOTO''https://www.batiformes.com/assets/images/vcard/logo_vcard.jpg', ['type' => 'JPEG']);
  293.             }
  294.             $vcard $vcard->convert(Document::VCARD30);
  295.     
  296.             $data['email'] = $mail;
  297.             $data['name'] = strtoupper($entry->getAttribute('sn')[0]);
  298.             $data['firstname'] = ucfirst($entry->getAttribute('givenName')[0]);
  299.             $data['activity'] = ucfirst($entry->getAttribute('title')[0]);
  300.             $data['mobile'] = ($entry->hasAttribute('mobile') ? $entry->getAttribute('mobile')[0] : '');
  301.             $data['mobileFormated'] = chunk_split($data['mobile'], 2" ");
  302.             $data['phone'] = ($entry->hasAttribute('telephoneNumber') ? $entry->getAttribute('telephoneNumber')[0] : '');
  303.             $data['phoneFormated'] = chunk_split($data['phone'], 2" ");
  304.             $data['street'] = $role->getData()['direction'];
  305.             $data['city'] = $role->getData()['city'];
  306.             $data['zipcode'] = $role->getData()['zipcode'];
  307.             $data['lat'] = $role->getData()['lat'];
  308.             $data['lng'] = $role->getData()['lng'];
  309.             $data['map'] = $role->getData()['gmap'];
  310.             $data['vcard'] = base64_encode($vcard->serialize());
  311.         }
  312.         return $this->json(
  313.             $data,
  314.             headers: ['Content-Type' => 'application/json;charset=UTF-8']
  315.         );
  316.     }
  317.     private function getDatabaseConnection()
  318.     { 
  319.         if ($this->pdo === null) {
  320.             $this->pdo = new \PDO('mysql:host=ma77924-001.dbaas.ovh.net:35815;dbname='.$this->getParameter('app.sabre_bdd'),'sabre','d4cvRR2bNvqsbmC68yPFJJa1ACw87DD');
  321.             $this->pdo->setAttribute(\PDO::ATTR_ERRMODE\PDO::ERRMODE_EXCEPTION);
  322.             $this->pdo->query("SET NAMES 'UTF8'"); 
  323.         }
  324.         return $this->pdo;
  325.     }
  326.     
  327.     // Generate an array contains a key -> value with the errors where the key is the name of the form field
  328.     protected function getErrorMessages(Form $form
  329.     {
  330.         $errors = array();
  331.         foreach ($form->getErrors() as $key => $error) {
  332.             $errors[] = $error->getMessage();
  333.         }
  334.         foreach ($form->all() as $child) {
  335.             if (!$child->isValid()) {
  336.                 $errors[$child->getName()] = $this->getErrorMessages($child);
  337.             }
  338.         }
  339.         return $errors;
  340.     }    
  341. }