src/OceanExpertBundle/Controller/ProfileController.php line 1415

Open in your IDE?
  1. <?php
  2. namespace OceanExpertBundle\Controller;
  3. use DateTime;
  4. use Doctrine\ORM\AbstractQuery;
  5. use Doctrine\ORM\Query;
  6. use Exception;
  7. use FOS\UserBundle\Mailer\MailerInterface;
  8. use FOS\UserBundle\Model\UserManagerInterface;
  9. use FOS\UserBundle\Util\TokenGeneratorInterface;
  10. use OceanExpertBundle\Entity\Indiv;
  11. use OceanExpertBundle\Entity\Institutions;
  12. use OceanExpertBundle\Entity\MemberEditsCountry;
  13. use OceanExpertBundle\Entity\MemberEditsInstitution;
  14. use OceanExpertBundle\Entity\MemberGroups;
  15. use OceanExpertBundle\Entity\ProfileImages;
  16. use OceanExpertBundle\Entity\IndivMeta;
  17. use Psr\Container\ContainerExceptionInterface;
  18. use Psr\Container\NotFoundExceptionInterface;
  19. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  20. use Symfony\Component\HttpFoundation\RedirectResponse;
  21. use Symfony\Component\HttpFoundation\Request;
  22. use Symfony\Component\HttpFoundation\Response;
  23. use CommerceGuys\Addressing\Model\Address;
  24. use CommerceGuys\Addressing\Formatter\DefaultFormatter;
  25. use CommerceGuys\Addressing\Repository\AddressFormatRepository;
  26. use CommerceGuys\Addressing\Repository\CountryRepository;
  27. use CommerceGuys\Addressing\Repository\SubdivisionRepository;
  28. use Symfony\Component\HttpFoundation\JsonResponse;
  29. class ProfileController extends AbstractController
  30. {
  31.     private UserManagerInterface $fosUserManager;
  32.     private TokenGeneratorInterface $fosTokenGenerator;
  33.     private MailerInterface $fosMailer;
  34.     public function __construct(
  35.         UserManagerInterface $fosUserManager,
  36.         TokenGeneratorInterface $fosTokenGenerator,
  37.         MailerInterface $fosMailer
  38.     ){
  39.         $this->fosUserManager $fosUserManager;
  40.         $this->fosTokenGenerator $fosTokenGenerator;
  41.         $this->fosMailer $fosMailer;
  42.     }
  43.     /**
  44.      * @param string  $user
  45.      * @param Request $request
  46.      *
  47.      * @return Response
  48.      */
  49.     public function viewProfileAction(Request $requeststring $user ''): Response
  50.     {
  51.         //we'll need these anyhow
  52.         $eventData '';
  53.         $adminOption = array();
  54.         $metadata = array();
  55.         $loggedUser $this->get('security.token_storage')->getToken()->getUser();
  56.         $isLoggedIn $this->get('security.authorization_checker')->isGranted('ROLE_USER');
  57.         if ($isLoggedIn
  58.             && $user == 'me'
  59.         ) {
  60.             //get the user id from the currently logged in user
  61.             $user $loggedUser->getId();
  62.         } elseif (!is_numeric($user)) {
  63.             //try to find the user id by looking at the login credentials
  64.             $searchUser $this->fosUserManager->findUserByUsername($user);
  65.             if ($searchUser) {
  66.                 $user $searchUser->getId();
  67.             } else {
  68.                 return new Response("no idea what to do with user '$user', not found in DB");
  69.             }
  70.         }
  71.         //by now we are sure we are using the idInd
  72.         $idInd $user;
  73.         $qb $this->getDoctrine()
  74.             ->getManager()
  75.             ->createQueryBuilder()
  76.             ->add(
  77.                 'select',
  78.                 'indiv AS expertInfo, 
  79.                 p.name AS imageName, 
  80.                 p.path AS imagePath,
  81.                 inst.idInst,
  82.                 inst.instName,
  83.                 inst.countryCode AS instCountryCode,
  84.                 inst.state AS instState,
  85.                 inst.city AS instCity,
  86.                 inst.postcode AS instPostcode,
  87.                 inst.instAddress AS instAddr1,
  88.                 inst.addr2 AS instAddr2')
  89.             ->add(
  90.                 'from',
  91.                 'OceanExpertBundle:Indiv indiv'
  92.             )->leftJoin(
  93.                 'OceanExpertBundle:ProfileImages',
  94.                 'p',
  95.                 'WITH',
  96.                 'p.idInd = indiv.idInd'
  97.             )->leftJoin(
  98.                 'OceanExpertBundle:IndivInstitution',
  99.                 'idins',
  100.                 'WITH',
  101.                 'indiv.idInd = idins.idInd'
  102.             )->leftJoin(
  103.                 'OceanExpertBundle:Institutions',
  104.                 'inst',
  105.                 'WITH',
  106.                 'idins.idInst = inst.idInst'
  107.             )->where(
  108.                 'indiv.idInd = :userId'
  109.             )->setParameter(
  110.                 'userId',
  111.                 $idInd
  112.             );
  113.         if ($this->get('security.authorization_checker')->isGranted('ROLE_GLOBAL_EDITOR')
  114.             || ($isLoggedIn
  115.                 && $idInd == $loggedUser->getId()
  116.             )
  117.         ) {
  118.             //@todo what should be here? Arno 10/06/2021
  119.         } else {
  120.             $qb->andWhere('indiv.status = 1');
  121.         }
  122.         $expert $qb->getQuery()
  123.             ->getResult(AbstractQuery::HYDRATE_ARRAY);
  124.         /*
  125.          * collect the data we need for the OIH JSON-LD in this array
  126.          * in the end we will need something like
  127.          * {
  128.             "@context": {
  129.                 "@vocab": "https://schema.org/"
  130.             },
  131.             "@id": "https://example.org/id/x",
  132.             "@type": "Person",
  133.             "name": "Jane Doe",
  134.             "jobTitle": "Professor",
  135.             "telephone": "(425) 123-4567",
  136.             "url": "http://www.janedoe.com",
  137.             "knowsAbout": [
  138.                 "Invasive species in brackish water",
  139.                 "https://www.wikidata.org/wiki/Q183368",
  140.                 {
  141.                   "@id": "https://example.org/id/course/x",
  142.                   "@type": "Course",
  143.                   "description": "In this course ...",
  144.                   "url": "URL to the course"
  145.                 }
  146.             ],
  147.             "identifier": {
  148.                 "@id": "https://orcid.org/0000-0002-2257-9127",
  149.                 "@type": "PropertyValue",
  150.                 "propertyID": "https://registry.identifiers.org/registry/orcid",
  151.                 "url": "https://orcid.org/0000-0002-2257-9127",
  152.                 "description": "Optional description of this record..."
  153.             }
  154.           }
  155.          */
  156.         $OIHData = array(
  157.             '@context' => array(
  158.                 '@vocab' => 'https://schema.org/'
  159.             ),
  160.             '@id' => 'https://oceanexpert.org/expert/' $idInd,
  161.             '@type' => 'Person'
  162.         );
  163.         if (
  164.             isset($expert[0]['expertInfo'])
  165.             && is_array($expert[0]['expertInfo']))
  166.         {
  167.             //this is easier to read
  168.             foreach($expert[0] as $key => $info) {
  169.                 $expert[$key] = $info;
  170.             }
  171.             unset($expert[0]);
  172.             $em $this->getDoctrine();
  173.             $metadata $this->getMetaData($idInd);
  174.             $jobtype $this->getJobTypes($idInd);
  175.             $expert['jobType'] = $jobtype['jobtype'];
  176.             //add to OIH
  177.             $jobTypes explode('\r'$expert['jobType']);
  178.             foreach ($jobTypes as $jobType) {
  179.                 $OIHData['knowsAbout'][] = trim($jobType);
  180.             }
  181.             $expert['groups'] = $this->getUserGroups($idInd);
  182.             //make the name for OIH
  183.             //for the website this is done in the profile.html.twig template
  184.             $userNameParts = array();
  185.             foreach (array('fname','mname','sname') as $namePart) {
  186.                 if (isset($expert['expertInfo'][$namePart])
  187.                     && $expert['expertInfo'][$namePart] != ''
  188.                 ) {
  189.                     $userNameParts[] = trim($expert['expertInfo'][$namePart]);
  190.                 }
  191.             }
  192.             $OIHData['name'] = implode(' '$userNameParts);
  193.             //what is the working location of the expert
  194.             $addressFormatRepository = new AddressFormatRepository();
  195.             $countryRepository = new CountryRepository();
  196.             $subdivisionRepository = new SubdivisionRepository();
  197.             $formatter = new DefaultFormatter(
  198.                 $addressFormatRepository,
  199.                 $countryRepository,
  200.                 $subdivisionRepository
  201.             );
  202.             $instituteAddressInfo = array();
  203.             if (array_key_exists('idInst'$expert)
  204.                 && !is_null($expert['idInst'])
  205.             ) {
  206.                 $instituteAddressInfo['addr1'] = $expert['instAddr2'];
  207.                 $instituteAddressInfo['addr2'] = $expert['instAddr1'];
  208.                 $instituteAddressInfo['postcode'] = $expert['instPostcode'];
  209.                 $instituteAddressInfo['city'] = $expert['instCity'];
  210.                 $instituteAddressInfo['state'] = $expert['instState'];
  211.                 //$instituteAddressInfo['countryCode'] = $this->getCountryFromId($expert['instCountryCode']);
  212.                 $instituteAddressInfo['countryCode'] = $this->getCountryCodeFromId($expert['instCountryCode']);
  213.             }
  214.             //dump($expert['expertInfo']);
  215.             //dump($expert['expertInfo']['countryCode']);
  216.             //dump($this->getCountryFromId($expert['expertInfo']['countryCode']));
  217.             //dump($this->getCountryCodeFromId($expert['expertInfo']['countryCode']));
  218.             //die();
  219.             if (!$expert['expertInfo']['useInstAddr']
  220.                 && isset($expert['expertInfo']['countryCode'])
  221.             ) {
  222.                 $expertAddressInfo['addr1'] = $expert['expertInfo']['addr2'];
  223.                 $expertAddressInfo['addr2'] = $expert['expertInfo']['addr1'];
  224.                 $expertAddressInfo['postcode'] = $expert['expertInfo']['postcode'];
  225.                 $expertAddressInfo['city'] =$expert['expertInfo']['city'];
  226.                 $expertAddressInfo['state'] = $expert['expertInfo']['state'];
  227.                 //$expertAddressInfo['countryCode'] = $this->getCountryFromId($expert['expertInfo']['countryCode']);
  228.                 $expertAddressInfo['countryCode'] = $this->getCountryCodeFromId($expert['expertInfo']['countryCode']);
  229.             } elseif ($expert['expertInfo']['useInstAddr']
  230.                 && isset($instituteAddressInfo['countryCode'])
  231.             ) {
  232.                 //the expert wants to use the address of the institute
  233.                 $expertAddressInfo $instituteAddressInfo;
  234.             }
  235.             $expert['workLocation'] = 'no or invalid worklocation found';
  236.             if (isset($expertAddressInfo['countryCode'])
  237.                 && $expertAddressInfo['countryCode'] != ''
  238.                 && $expertAddressInfo['countryCode'] !== 0
  239.             ) {
  240.                 $worklocation = new Address();
  241.                 $worklocation $worklocation
  242.                     ->withAddressLine1($expertAddressInfo['addr1'])
  243.                     ->withAddressLine2($expertAddressInfo['addr2'])
  244.                     ->withPostalCode($expertAddressInfo['postcode'])
  245.                     ->withLocality($expertAddressInfo['city'])
  246.                     ->withAdministrativeArea($expertAddressInfo['state'])
  247.                     ->withCountryCode($expertAddressInfo['countryCode']);
  248.                 try {
  249.                     $expert['workLocation'] = $formatter->format($worklocation);
  250.                 } catch (Exception $e) {
  251.                     //dump($e);
  252.                     var_dump($expertAddressInfo);
  253.                     var_dump($worklocation);
  254.                     //die();
  255.                 }
  256.                 //dump($worklocation);
  257.                 //die();
  258.             }
  259.             //make the address for OIH
  260.             //@todo must be moved after the part that defines the worklocation
  261.             $addressParts = array();
  262.             foreach (array('addr1','addr2') as $addressPart) {
  263.                 if (isset($expertAddressInfo[$addressPart])
  264.                     && $expertAddressInfo[$addressPart] != ''
  265.                 ) {
  266.                     $addressParts[] = trim($expertAddressInfo[$addressPart]);
  267.                 }
  268.             }
  269.             $OIHAddress implode(', '$addressParts);
  270.             if (isset($expertAddressInfo['postcode'])
  271.                 && $expertAddressInfo['postcode'] != ''
  272.             ) {
  273.                 $OIHAddress .= ', ' $expertAddressInfo['postcode'];
  274.             }
  275.             if (isset($expertAddressInfo['city'])
  276.                 && $expertAddressInfo['city'] != ''
  277.             ) {
  278.                 $OIHAddress .= ' ' $expertAddressInfo['city'];
  279.             }
  280.             //the $expertAddressInfo already takes the correct working location info depending on useInstAddr
  281.             $OIHLatitude '';
  282.             $OIHLongitude '';
  283.             if (isset($expertAddressInfo['countryCode'])
  284.                 && $expertAddressInfo['countryCode'] != ''
  285.             ) {
  286.                 $OIHCountries $this->getCountryFromIds(
  287.                         explode(
  288.                             ',',
  289.                             $expertAddressInfo['countryCode']
  290.                         )
  291.                     );
  292.                 //we can only gave one country for the workinglocation
  293.                 $OIHAddress .= ', ' $OIHCountries[0]['country'];
  294.                 $OIHLatitude $OIHCountries[0]['latitude'];
  295.                 $OIHLongitude $OIHCountries[0]['longitude'];
  296.             }
  297.             $OIHData['workLocation'] = array(
  298.                 '@type' => 'Place',
  299.                 'address' => trim($OIHAddress),
  300.                 'geo' => array(
  301.                     '@type' => 'GeoCoordinates',
  302.                     'latitude' => $OIHLatitude,
  303.                     'longitude' => $OIHLongitude
  304.                 )
  305.             );
  306.             if ($OIHLatitude != '') {
  307.                 $OIHData['workLocation']['geo']['latitude'] = $OIHLatitude;
  308.             }
  309.             if ($OIHLongitude != '') {
  310.                 $OIHData['workLocation']['geo']['longitude'] = $OIHLongitude;
  311.             }
  312.             /*
  313.                 "geo": {
  314.                     "@type": "GeoCoordinates",
  315.                     "latitude": 39.3280,
  316.                     "longitude": 120.1633
  317.                 }
  318.             */
  319.             //get the languages for OIH
  320.             //we expect
  321.             /*
  322.             "knowsLanguage": {
  323.                 "@type": "Language",
  324.                 "name": "Spanish",
  325.                 "alternateName": "es"
  326.             }
  327.             */
  328.             $allLanguages $this->getDoctrine()
  329.                 ->getRepository('OceanExpertBundle:Languages')
  330.                 ->findAll();
  331.             //dump($allLanguages);
  332.             if (isset($expert['expertInfo']['languages'])) {
  333.                 $knowsLanguages explode(','$expert['expertInfo']['languages']);
  334.                 foreach ($knowsLanguages as $knowsLanguage) {
  335.                     $OIHData['knowsLanguage'][] = array(
  336.                         '@type' => 'Language',
  337.                         'name' => trim($knowsLanguage)
  338.                     );
  339.                 }
  340.             }
  341.             if (isset($expert['expertInfo']['jobtitle'])) {
  342.                 $expert['jobtitle'] = $this->getJobTypeByCodes(
  343.                     explode(
  344.                         ',',
  345.                         $expert['expertInfo']['jobtitle'])
  346.                 );
  347.                 $OIHData['jobTitle'] = trim($expert['expertInfo']['jobtitle']);
  348.             }
  349.             if (isset($expert['0']['lastEditBy'])) {
  350.                 $expert['lastEditBy'] = $this->getUpdatedBy($expert['0']['lastEditBy']);
  351.             }
  352.             if (isset($expert['0']['createdBy'])) {
  353.                 $expert['createdBy'] = $this->getUpdatedBy($expert['0']['createdBy']);
  354.             }
  355.             $expert['subjectArea'] = $this->getSubjectAreas($idInd);
  356.             if ($expert['subjectArea']
  357.                 && $expert['subjectArea'] != ''
  358.             ) {
  359.                 $subjectAreas explode(','$expert['subjectArea']);
  360.                 foreach ($subjectAreas as $subjectArea) {
  361.                     $OIHData['knowsAbout'][] = trim($subjectArea);
  362.                 }
  363.             }
  364.             /*
  365.              * nationality
  366.              * we expect something like
  367.              * "nationality": {
  368.                 "@type": "Country",
  369.                 "name": "Fiji",
  370.                 "identifier": {
  371.                     "@type": "PropertyValue",
  372.                     "name": "ISO 3166-1 alpha-2 code",
  373.                     "value": "FJ",
  374.                     "propertyID": [
  375.                         "https://unece.org/trade/cefact/unlocode-code-list-country-and-territory",
  376.                         "ISO 3166-1:2020"
  377.                     ]
  378.                 }
  379.         },
  380.              */
  381.             if (isset($expert['expertInfo']['idNationality'])) {
  382.                 $nationalities $this->getCountryFromIds(
  383.                     explode(
  384.                         ',',
  385.                         $expert['expertInfo']['idNationality']
  386.                     )
  387.                 );
  388.                 foreach($nationalities as $OIHNationality) {
  389.                     $expert['nationality'][]  = trim($OIHNationality['country']);
  390.                     $OIHData['nationality'][] = array(
  391.                         '@type' => 'Country',
  392.                         'name' => trim($OIHNationality['country'])
  393.                     );
  394.                     /*
  395.                      * #808
  396.                      *
  397.                     $OIHData['nationality'][] = array(
  398.                         '@type' => 'DefinedTerm',
  399.                         'url' => 'https://unece.org/trade/cefact/unlocode-code-list-country-and-territory',
  400.                         'inDefinedTermSet' => 'UN/LOCODE Code List by Country and Territory',
  401.                         'name' => trim($OIHNationality['country']),
  402.                         'termCode' =>trim($OIHNationality['countryCode'])
  403.                     );
  404.                     */
  405.                 }
  406.                 if (isset($expert['nationality'])
  407.                     && is_array($expert['nationality'])
  408.                 ) {
  409.                     $expert['nationality'] = implode(
  410.                         ',',
  411.                         $expert['nationality']
  412.                     );
  413.                 }
  414.             }
  415.             foreach (array('url1''url2''url3') as $urlId) {
  416.                 if (isset($expert['expertInfo'][$urlId])
  417.                     && trim($expert['expertInfo'][$urlId]) != ''
  418.                 ) {
  419.                     $OIHData['url'][] = trim($expert['expertInfo'][$urlId]);
  420.                 }
  421.             }
  422.             if (isset($expert['expertInfo']['studyregion'])) {
  423.                 $expert['studyregion'] = $this->getResearchAreaByCodes(
  424.                     explode(
  425.                         ',',
  426.                         $expert['expertInfo']['studyregion']
  427.                     )
  428.                 );
  429.             }
  430.             if (isset($expert['expertInfo']['qualityCheckedBy'])) {
  431.                 $expert['qcby'] = $this->getUpdatedBy($expert['expertInfo']['qualityCheckedBy']);
  432.             }
  433.             if (isset($expert['expertInfo']['doNoInviteBy'])
  434.                 && isset($expert['expertInfo']['doNoInviteBy']) != 0
  435.             ) {
  436.                 $expert['doNoInviteBy'] = $this->getUpdatedBy($expert['expertInfo']['doNoInviteBy']);
  437.             }
  438.             if (isset($expert['expertInfo']['twitter'])) {
  439.                 $twitterUser $expert['expertInfo']['twitter'];
  440.                 if (preg_match('/(@.+)/'$twitterUser$matches)) {
  441.                     $twitterUser 'https://twitter.com/' $matches[1];
  442.                 }
  443.                 $expert['twitter'] = $twitterUser;
  444.             }
  445.             //$em->getManager()->getRepository('OceanExpertBundle:MemberGroups');
  446.             $query $em->getManager()
  447.                 ->createQueryBuilder('m')
  448.                 ->select('m.idGroup')
  449.                 ->add('from','OceanExpertBundle:MemberGroups m')
  450.                 ->where('m.idInd =:idInd')
  451.                 ->setParameter('idInd'$idInd)
  452.                 ->getQuery();
  453.             $groups $query->getResult();
  454.             $expert['groupids'] = array_column($groups'idGroup');
  455.             //$em->getRepository('OceanExpertBundle:MemberEditsCountry');
  456.             $query $em->getManager()
  457.                 ->createQueryBuilder('m')
  458.                 ->select('m.idCountry')
  459.                 ->add('from','OceanExpertBundle:MemberEditsCountry m')
  460.                 ->where('m.idInd =:idInd')
  461.                 ->setParameter('idInd'$idInd)
  462.                 ->getQuery();
  463.             $countries $query->getResult();
  464.             $expert['countries'] = array_column($countries'idCountry');
  465.             //$em->getRepository('OceanExpertBundle:MemberEditsInstitution');
  466.             $expert['canEditOwnInst'] = 0;
  467.             if (isset($expert['idInst'])) {
  468.                 $query $em->getManager()
  469.                     ->createQueryBuilder('m')
  470.                     ->select('m')
  471.                     ->add('from','OceanExpertBundle:MemberEditsInstitution m')
  472.                     ->where('m.idInd =:idInd')
  473.                     ->andWhere('m.idInst =:idInst')
  474.                     ->setParameters(
  475.                         array(
  476.                             'idInst' => $expert['idInst'],
  477.                             'idInd' => $idInd
  478.                         )
  479.                     )
  480.                     ->getQuery();
  481.                 $canEditOwnInst $query->getOneOrNullResult(AbstractQuery::HYDRATE_ARRAY);
  482.                 if (is_array($canEditOwnInst)
  483.                     && count($canEditOwnInst)
  484.                 ) {
  485.                     $expert['canEditOwnInst'] = 1;
  486.                 }
  487.             }
  488.             $fosUserData $this->fosUserManager
  489.                 ->findUserBy(
  490.                     array(
  491.                         'id' => $idInd
  492.                     )
  493.                 );
  494.             if ($fosUserData) {
  495.                 $expert['roles'] = $fosUserData->getRoles();
  496.                 $expert['username'] = $fosUserData->getUsername();
  497.                 $expert['id'] = $fosUserData->getId();
  498.                 $expert['email'] = $fosUserData->getEmail();
  499.                 $userLink $this->generateUrl(
  500.                     'view_profile',
  501.                     array(
  502.                         'user' => $expert['id']
  503.                     )
  504.                 );
  505.                 $expert['profileUrl'] = $request->getUriForPath($userLink);
  506.             }
  507.             $adminOption['countries'] = $this->getDoctrine()
  508.                 ->getRepository('OceanExpertBundle:Countries')
  509.                 ->findBy(
  510.                     [],
  511.                     ['country' => 'ASC']
  512.                 );
  513.             if (isset($expert[1]['path'])) {
  514.                 $expert['imgPath'] = $request
  515.                     ->getUriForPath('/uploads/profile/' $expert[1]['path']);
  516.             }
  517.             $adminOption['userGroups'] = $this->getDoctrine()
  518.                 ->getRepository('OceanExpertBundle:Groups')
  519.                 ->findBy(
  520.                     [],
  521.                     ['groupname' => 'ASC']
  522.                 );
  523.             /*
  524.              * #552
  525.              * overruled by #808 and the new pattern definition
  526.              *
  527.              * we want something like this
  528.              * {
  529.                   "@id": "https://example.org/id/course/x",
  530.                   "@type": "Course",
  531.                   "description": "In this course ...",
  532.                   "url": "URL to the course"
  533.                 }
  534.              */
  535.             $OIHEventData $this->getExpertEventParticipation(
  536.                 $idInd,
  537.                 $request
  538.             );
  539.             if ($this->container->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
  540.                 $eventData =$OIHEventData;
  541.             }
  542.             foreach ($OIHEventData as $event) {
  543.                 //we only want to see the courses, not all meetings!!!!
  544.                 if ($event['idEventtype'] == 4) {
  545.                     $OIHData['knowsAbout'][] = array(
  546.                         '@id' => 'https://www.oceanexpert.org/event/' $event['idEvent'],
  547.                         '@type' => 'Course',
  548.                         'description' => $event['title'],
  549.                         'url' => 'https://www.oceanexpert.org/event/' $event['idEvent'],
  550.                         'endDate' => $event['endOn'],
  551.                         'startDate' => $event['startOn']
  552.                     );
  553.                 }
  554.             }
  555.             if (isset($metadata['orcid'])
  556.                 && $metadata['orcid'] != ''
  557.             ) {
  558.                 $OIHData['identifier'][] = array(
  559.                     '@id' => $metadata['orcid'],
  560.                     '@type' => 'PropertyValue',
  561.                     'propertyID' => 'https://registry.identifiers.org/registry/orcid',
  562.                     'url' => 'https://orcid.org/' $metadata['orcid']
  563.                 );
  564.             }
  565.             if (isset($metadata['researcherid'])
  566.                 && $metadata['researcherid'] != ''
  567.             ) {
  568.                 $OIHData['identifier'][] = array(
  569.                     '@id' => $metadata['researcherid'],
  570.                     '@type' => 'PropertyValue',
  571.                     'propertyID' => 'https://www.researcherid.com',
  572.                     'url' => 'https://www.researcherid.com/' $metadata['researcherid']
  573.                 );
  574.             }
  575.             if (isset($metadata['researcharea'])
  576.                 && $metadata['researcharea'] != ''
  577.             ) {
  578.                 $researchArea str_replace('\r'', ' $metadata['researcharea']);
  579.                 $researchArea str_replace('  '' ' $researchArea);
  580.                 $OIHData['knowsAbout'][] = $researchArea;
  581.             }
  582.         }  else {
  583.             //we did not find user info
  584.             //this can be a new profile
  585.             //check if we can find login credentials
  586.             $searchUser $this->fosUserManager
  587.                 ->findUserBy(
  588.                     array(
  589.                         'id' => $idInd
  590.                     )
  591.                 );
  592.             //we found credentials
  593.             //only show info for global editors or for the user himself
  594.             //else the profile data can never be completed
  595.             if (!null == $searchUser
  596.                 && ($this->get('security.authorization_checker')->isGranted('ROLE_GLOBAL_EDITOR'))
  597.                 || ($isLoggedIn
  598.                     && ($idInd == $loggedUser->getId())
  599.                 )
  600.             ) {
  601.                 $expert['expertInfo']['idInd'] = $idInd;
  602.                 $expert['username'] = $searchUser->getUsername();
  603.                 $expert['error'] = 'Incomplete Profile.';
  604.             } else {
  605.                 $expert = array(
  606.                     'error' => 'User not found.'
  607.                 );
  608.             }
  609.         }
  610.         $OIHData json_encode(
  611.             $OIHData,
  612.             JSON_UNESCAPED_UNICODE JSON_UNESCAPED_SLASHES JSON_NUMERIC_CHECK
  613.         );
  614.         //dump($expert);
  615.         return $this->render(
  616.             'Profile/profile.html.twig',
  617.             array(
  618.                 'OIHData' => $OIHData,
  619.                 'expert' => $expert,
  620.                 'metadata' => $metadata,
  621.                 'adminOption' => $adminOption,
  622.                 'eventData' => $eventData
  623.             )
  624.         );
  625.     }
  626.     /**
  627.      * get the data of an expert to show on the profile page
  628.      *
  629.      * @param Request $request
  630.      *
  631.      * @return Response
  632.      *
  633.      * @throws ContainerExceptionInterface
  634.      * @throws NotFoundExceptionInterface
  635.      *
  636.      * @todo fix missing $data
  637.      *
  638.      */
  639.     public function userProfileAction(Request $request): Response
  640.     {
  641.         $data $request->request->all();
  642.         $username '';
  643.         if ($this->container->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
  644.             $username $this->get('security.token_storage')->getToken()->getUser()->getUsername();
  645.         }
  646.         if (!isset($data['userEmail'])) {
  647.             if ($username !== '') {
  648.                 return $this->redirect('expert/' $username);
  649.             } else {
  650.                 //no such user, strange...
  651.                 $message "Cannot find user without email address and without username.";
  652.                 return $this->render(
  653.                     'Exception/error.html.twig',
  654.                     array(
  655.                         'message' => $message
  656.                     )
  657.                 );
  658.             }
  659.         }
  660.         //this should have been checked before
  661.         //but better be safe than sorry
  662.         $data['userEmail'] = filter_var(
  663.             $data['userEmail'],
  664.             FILTER_SANITIZE_EMAIL
  665.         );
  666.         $userId $this->fosUserManager->findUserByEmail($data['userEmail'])->getId();
  667.         unset($data['_wysihtml5_mode']);
  668.         $data array_filter($data);
  669.         if (isset($data['researcharea'])) {
  670.             $data['research'] = $this->getResearchAreaByCodes($data['researcharea']);
  671.         }
  672.         if (isset($data['studyregion'])) {
  673.             $data['study'] = $this->getResearchAreaByCodes($data['studyregion']);
  674.         } else {
  675.             $data['studyregion'] = array();
  676.         }
  677.         if (null !== ($data['country'])) {
  678.             $data['countryName'] = $this->getCountryByCode($data['country']);
  679.         }
  680.         if (null !== ($data['jobtype'])) {
  681.             $data['job'] = $this->getJobTypeByCodes($data['jobtype']);
  682.         }
  683.         if ($data['regType'] == '1') {
  684.             $data['type'] = "Organization";
  685.         } else {
  686.             $data['type'] = "Personal";
  687.             $data['country'] = $data['country2'];
  688.             $data['locality'] = isset($data['city2']) ? $data['city2'] : '';
  689.             $data['administrative_area_level_1'] = isset($data['state2']) ? $data['state2'] : '';
  690.             $data['postal_code'] = isset($data['postcode2']) ? $data['postcode2'] : '';
  691.             $data['box'] = isset($data['box2']) ?: '';
  692.             $data['route'] = isset($data['address2']) ? $data['address2'] : '';
  693.             $data['addrline2'] = isset($data['addrline2']) ? $data['addrline2'] : '';
  694.         }
  695.         if (null !== $request->files->get('file')) {
  696.             $file $request->files->get('file');
  697.             $filetype $request->files->get('file')->guessClientExtension();
  698.             $filename "profile_" $userId "." $filetype;
  699.             $em $this->getDoctrine()->getManager();
  700.             $item $em->getRepository('OceanExpertBundle:ProfileImages')->findOneBy(array('idInd' => $userId));
  701.             if ($item) {
  702.                 $item->setFile($file);
  703.                 $item->setName($filename);
  704.                 $item->setPath($filename);
  705.                 $item->upload();
  706.                 $em->persist($item);
  707.                 $em->flush();
  708.                 $data['profileId'] = $item->getId();
  709.             } else {
  710.                 $profile = new ProfileImages();
  711.                 $profile->setFile($file);
  712.                 $profile->setName($filename);
  713.                 $profile->setPath($filename);
  714.                 $profile->setIdInd($userId);
  715.                 $profile->upload();
  716.                 $em->persist($profile);
  717.                 $em->flush();
  718.                 if ($profile) {
  719.                     $data['profileId'] = $profile->getId();
  720.                 }
  721.             }
  722.         }
  723.         try {
  724.             /*
  725.              * this is incorrect
  726.              * see also#659
  727.              *
  728.             $privateaddress = isset($data['route'])?trim($data['route']) . '<br />':'';
  729.             $privateaddress .= isset($data['addrline2'])?trim($data['addrline2']) . '<br />':'';
  730.             $privateaddress .= isset($data['postal_code'])?trim($data['postal_code']).", ":'';
  731.             $privateaddress .= isset($data['locality'])?trim($data['locality']).", ":'';
  732.             $privateaddress .= isset($data['administrative_area_level_1'])?trim($data['administrative_area_level_1']) . '<br />':'';
  733.             $privateaddress .= isset($data['country'])?trim($this->getCountryByCode($data['country'])) . '<br />':'';
  734.             */
  735.             $indiv = new Indiv();
  736.             $indiv->setTitle(isset($data['title']) ? $data['title'] : '');
  737.             $indiv->setFname(isset($data['firstname']) ? $data['firstname'] : '');
  738.             $indiv->setMname(isset($data['middlename']) ? $data['middlename'] : '');
  739.             $indiv->setSname(isset($data['lastname']) ? $data['lastname'] : '');
  740.             $indiv->setRegType(isset($data['reg-type']) ? $data['reg-type'] : '');
  741.             $indiv->setIdentifier('');
  742.             $indiv->setUseInstAddr(isset($data['useinstaddress']) ? $data['useinstaddress'] : 0);
  743.             /*
  744.              * this is incorrect
  745.              * see also#659
  746.              */
  747.             $indiv->setPrivateAddress('');
  748.             $indiv->setCity(isset($data['locality']) ? $data['locality'] : '');
  749.             $indiv->setAddr1(isset($data['route']) ? $data['route'] : '');
  750.             $indiv->setAddr2(isset($data['addrline2']) ? $data['addrline2'] : '');
  751.             $indiv->setState(isset($data['administrative_area_level_1']) ? $data['administrative_area_level_1'] : '');
  752.             $indiv->setPostcode(isset($data['postal_code']) ? $data['postal_code'] : '');
  753.             $indiv->setCountryCode(isset($data['country']) ? $data['country'] : '');
  754.             $indiv->setIDNationality(isset($data['id_nationality']) ? $data['id_nationality'] : 0);
  755.             $indiv->setGender(isset($data['gender']) ? $data['gender'] : '');
  756.             $indiv->setTel(isset($data['phone']) ? $data['phone'] : '');
  757.             //we are already in a condition where we are sure the $data['userEmail'] exists
  758.             //and is well-formed
  759.             $indiv->setEmail1($data['userEmail']);
  760.             if (isset($data['alternateEmail'])
  761.                 && $data['alternateEmail'] !== ''
  762.                 && filter_var($data['alternateEmail'], FILTER_VALIDATE_EMAIL)
  763.             ) {
  764.                 $data['alternateEmail'] = filter_var(
  765.                     $data['alternateEmail'],
  766.                     FILTER_SANITIZE_EMAIL
  767.                 );
  768.             } else {
  769.                 $data['alternateEmail'] = '';
  770.             }
  771.             $indiv->setEmail2($data['alternateEmail']);
  772.             $indiv->setEmail3(isset($data['']) ? $data[''] : '');
  773.             $indiv->setUrl1(isset($data['website-personal']) ? $data['website-personal'] : '');
  774.             $indiv->setUrl2(isset($data['website-institution']) ? $data['website-institution'] : '');
  775.             $indiv->setLinkedin(isset($data['linkedin']) ? $data['linkedin'] : '');
  776.             $indiv->setFacebook(isset($data['facebook']) ? $data['facebook'] : '');
  777.             $indiv->setTwitter(isset($data['twitter']) ? $data['twitter'] : '');
  778.             $indiv->setOther(isset($data['other']) ? $data['other'] : '');
  779.             $indiv->setDegree(isset($data['degree']) ? $data['degree'] : '');
  780.             $indiv->setJobtitle(isset($data['job']) ? $data['job'] : '');
  781.             $indiv->setDept(isset($data['department']) ? $data['department'] : '');
  782.             $indiv->setStudyregion(isset($data['study']) ? $data['study'] : '');
  783.             $indiv->setLanguages(implode(','$data['languages']));
  784.             $indiv->setComments(isset($data['comments']) ? $data['comments'] : '');
  785.             $indiv->setSkills(isset($data['skills']) ? $data['skills'] : '');
  786.             $indiv->setIdImagefile(isset($data['profileId']) ? $data['profileId'] : null);
  787.             $indiv->setFDateEnt(new DateTime('now'));
  788.             $indiv->setLDateUpd(new DateTime('now'));
  789.             $indiv->setCreatedBy(isset($data['']) ? $data[''] : 0);
  790.             $indiv->setLastEditBy(isset($data['']) ? $data[''] : 0);
  791.             $indiv->setFax(isset($data['']) ? $data[''] : '');
  792.             $indiv->setUrl3(isset($data['']) ? $data[''] : '');
  793.             $indiv->setUrlsChecked(new DateTime('now'));
  794.             $indiv->setFlickr(isset($data['']) ? $data[''] : '');
  795.             $indiv->setActiveng(isset($data['']) ? $data[''] : '');
  796.             $indiv->setActivother(isset($data['']) ? $data[''] : '');
  797.             $indiv->setDoNotInvite(isset($data['']) ? $data[''] : 0);
  798.             $indiv->setAdminComments(isset($data['']) ? $data[''] : '');
  799.             $indiv->setIsGlobal(isset($data['']) ? $data[''] : 0);
  800.             $indiv->setStatus(isset($data['']) ? $data[''] : 0);
  801.             $indiv->setStatusLastChanged(new DateTime());
  802.             $indiv->setDeceased(isset($data['']) ? $data[''] : 0);
  803.             $indiv->setRetired(isset($data['']) ? $data[''] : 0);
  804.             $em $this->getDoctrine()->getManager();
  805.             $em->persist($indiv); //marks object to be saved in the next transaction.
  806.             $em->flush(); //performs all saves and transactions.
  807.             if (!isset($data['orcid'])) {
  808.                 $data['orcid'] = '';
  809.             }
  810.             if (!isset($data['researcherid'])) {
  811.                 $data['researcherid'] = '';
  812.             }
  813.             if (!isset($data['google-scholar'])) {
  814.                 $data['google-scholar'] = '';
  815.             }
  816.             if (!isset($data['researchgate'])) {
  817.                 $data['researchgate'] = '';
  818.             }
  819.             if (!isset($data['others'])) {
  820.                 $data['others'] = '';
  821.             }
  822.             if (!isset($data['researcharea'])) {
  823.                 $data['researcharea'] = array();
  824.             }
  825.             if ($indiv->getIdInd()) {
  826.                 $usermeta = array(
  827.                     'orcid' => $data['orcid'],
  828.                     'researcherid' => $data['researcherid'],
  829.                     'researcharea' => implode(', '$data['researcharea']),
  830.                     'google-scholar' => $data['google-scholar'],
  831.                     'researchgate' => $data['researchgate'],
  832.                     'others' => $data['others']
  833.                 );
  834.                 $usermeta array_filter($usermeta);
  835.                 foreach ($usermeta as $key => $value) {
  836.                     $chkmeta $em->getRepository('OceanExpertBundle:IndivMeta')
  837.                         ->findOneBy(
  838.                             array(
  839.                                 'indivId' => $indiv->getIdInd(),
  840.                                 'metaOption' => $key
  841.                             )
  842.                         );
  843.                     if ($chkmeta) {
  844.                         $chkmeta->setMetaValue($value);
  845.                         $em->persist($chkmeta);
  846.                         $em->flush();
  847.                     } else {
  848.                         $meta = new IndivMeta();
  849.                         $meta->setIndivId($indiv->getIdInd());
  850.                         $meta->setMetaOption($key);
  851.                         $meta->setMetaValue($value);
  852.                         $em $this->getDoctrine()->getManager();
  853.                         $em->persist($meta);
  854.                         $em->flush();
  855.                     }
  856.                 }
  857.             }
  858.         } catch (Exception $e) {
  859.             //return error message
  860.             $message $e->getMessage();
  861.             return $this->render(
  862.                 'Exception/error.html.twig',
  863.                 array(
  864.                     'message' => $message
  865.                 )
  866.             );
  867.         }
  868.         return $this->redirect(
  869.             $this->generateUrl(
  870.                 'profile_status'
  871.             )
  872.         );
  873.     }
  874.     /**
  875.      * edit an existing user profile
  876.      *
  877.      * @param int|null $userId the id of the profile to edit
  878.      *
  879.      * @return Response
  880.      *
  881.      * @throws \Psr\Container\ContainerExceptionInterface
  882.      * @throws \Psr\Container\NotFoundExceptionInterface
  883.      */
  884.     public function editAction(int $userId null): Response
  885.     {
  886.         //only logged-in users can get the right to edit
  887.         //this is only a first check (see #493)
  888.         if (!$this->get('security.authorization_checker')->isGranted('ROLE_USER')) {
  889.             $url $this->container->get('router')->generate('frontend_homepage');
  890.             return new RedirectResponse($url);
  891.         }
  892.         //we will always need to know the current user to be sure that not everybody can change another account
  893.         $user $this->get('security.token_storage')->getToken()->getUser();
  894.         if ($userId == '') {
  895.             //this is the simplest case
  896.             //no userid is given so edit the profile from the person that is logged in
  897.             $userId $user->getId();
  898.         }
  899.         //we want to edit an existing user, so this user must have an entry in the fos_user db
  900.         $fosUserData $this->fosUserManager
  901.             ->findUserBy(
  902.                 array(
  903.                     'id'=>$userId
  904.                 )
  905.             );
  906.         if (!$fosUserData) {
  907.             //no such user, strange...
  908.             $message "There is no user with this id ($userId).";
  909.             return $this->render(
  910.                 'Exception/error.html.twig',
  911.                 array(
  912.                     'message' => $message
  913.                 )
  914.             );
  915.         }
  916.         //here it gets tricky
  917.         //who can edit, what profile??
  918.         if ($userId == $user->getId() //no problem, everybody can adapt his/here own profile
  919.             || $this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')) //no problem, admin users can change the profiles of others
  920.         {
  921.             $em $this->getDoctrine()->getManager();
  922.             $indiv =  $this->getDoctrine()
  923.                 ->getRepository('OceanExpertBundle:Indiv')
  924.                 ->findOneByIdInd($userId);
  925.             if(!$indiv) {
  926.                 //create a new profile as it does not exist yet
  927.                 //this happens when people subscribe and want to complete their profile
  928.                 $indiv = new Indiv();
  929.                 $indiv->setTitle('');
  930.                 $indiv->setFname('');
  931.                 $indiv->setMname('');
  932.                 $indiv->setSname('');
  933.                 $indiv->setIdentifier('');
  934.                 $indiv->setRegType('');
  935.                 $indiv->setUseInstAddr(0);
  936.                 $indiv->setPrivateAddress('');
  937.                 $indiv->setAddr1('');
  938.                 $indiv->setAddr2('');
  939.                 $indiv->setCity('');
  940.                 $indiv->setState('');
  941.                 $indiv->setPostcode('');
  942.                 $indiv->setIdNationality('');
  943.                 $indiv->setTel('');
  944.                 $indiv->setFax('');
  945.                 $indiv->setEmail2('');
  946.                 $indiv->setEmail3('');
  947.                 $indiv->setUrl1('');
  948.                 $indiv->setUrl2('');
  949.                 $indiv->setUrl3('');
  950.                 $indiv->setGender('');
  951.                 $indiv->setLinkedin('');
  952.                 $indiv->setFacebook('');
  953.                 $indiv->setFlickr('');
  954.                 $indiv->setTwitter('');
  955.                 $indiv->setOther('');
  956.                 $indiv->setDegree('');
  957.                 $indiv->setActiveng('');
  958.                 $indiv->setActivother('');
  959.                 $indiv->setJobtitle('');
  960.                 $indiv->setDept('');
  961.                 $indiv->setStudyregion('');
  962.                 $indiv->setLanguages('');
  963.                 $indiv->setSkills('');
  964.                 $indiv->setComments('');
  965.                 $indiv->setDoNotInvite('');
  966.                 $indiv->setAdminComments('');
  967.                 $indiv->setIsGlobal(1);
  968.                 $indiv->setStatus(0);
  969.                 $indiv->setDeceased(0);
  970.                 $indiv->setRetired(0);
  971.                 $indiv->setIdInd($userId);
  972.                 $indiv->setCountryCode(21);
  973.                 //check email again and again
  974.                 $fosUserEmail $fosUserData->getEmail();
  975.                 if (filter_var$fosUserEmailFILTER_VALIDATE_EMAIL)) {
  976.                     $fosUserEmail filter_var(
  977.                         $fosUserEmail,
  978.                         FILTER_SANITIZE_EMAIL
  979.                     );
  980.                 } else {
  981.                     $message "this ($fosUserEmail) is not a valid email address";
  982.                     return $this->render(
  983.                         'Exception/error.html.twig',
  984.                         array(
  985.                             'message' => $message
  986.                         )
  987.                     );
  988.                 }
  989.                 $indiv->setEmail1($fosUserEmail);
  990.                 $em->persist($indiv);
  991.                 $em->flush();
  992.             }
  993.         } else {
  994.             //this is not correct #491
  995.             $message 'You do not have the correct rights (your are not this person and you are not an admin user) to edit this profile.';
  996.             return $this->render(
  997.                 'Exception/error.html.twig',
  998.                 array(
  999.                     'message' => $message
  1000.                 )
  1001.             );
  1002.         }
  1003.         $qb $this->getDoctrine()
  1004.             ->getManager()
  1005.             ->createQueryBuilder();
  1006.         $qb->add('select''i, ins, p, c')
  1007.             ->add('from''OceanExpertBundle:Indiv i')
  1008.             ->leftJoin('OceanExpertBundle:ProfileImages''p''WITH''p.idInd = i.idInd')
  1009.             ->leftJoin('OceanExpertBundle:IndivInstitution''idins''WITH''i.idInd = idins.idInd')
  1010.             ->leftJoin('OceanExpertBundle:Institutions''ins''WITH''idins.idInst = ins.idInst')
  1011.             ->leftJoin('OceanExpertBundle:Countries''c''WITH''c.idCountry = i.countryCode')
  1012.             ->where('i.idInd = :userId')
  1013.             ->setParameter('userId'$userId);
  1014.         //get the expert data as far as we can find it
  1015.         $expert $qb->getQuery()->getResult(AbstractQuery::HYDRATE_ARRAY);
  1016.         //dump($expert);
  1017.         //die();
  1018.         $metadata $this->getMetaData($userId);
  1019.         $jobType $this->getJobTypes($userId);
  1020.         $expert['jobType'] = $jobType['jobId'];
  1021.         $expert['userId'] = $userId;
  1022.         $expert['subjectArea'] = $this->getSubjectAreas($userId);
  1023.         $expert['roles'] = $fosUserData->getRoles();
  1024.         $expert['username'] = $fosUserData->getUsername();
  1025.         $expert['email'] = $fosUserData->getEmail();
  1026.         //get some data for the rest of the form
  1027.         $countries $this->getDoctrine()
  1028.             ->getRepository('OceanExpertBundle:Countries')
  1029.             ->findBy(
  1030.                 [],
  1031.                 ['country' => 'ASC']
  1032.             );
  1033.         $locales $this->getDoctrine()
  1034.             ->getRepository('OceanExpertBundle:Locale')
  1035.             ->findBy(
  1036.                 [],
  1037.                 ['locale' => 'ASC']
  1038.             );
  1039.         $studyregions $this->getDoctrine()
  1040.             ->getRepository('OceanExpertBundle:Regions')
  1041.             ->findBy(
  1042.                 [],
  1043.                 ['name' => 'ASC']
  1044.             );
  1045.         $instituteSeaRegion $this->getDoctrine()
  1046.             ->getRepository('OceanExpertBundle:Regions')
  1047.             ->seaRegions();
  1048.         $allSubjects $this->getDoctrine()
  1049.             ->getRepository('OceanExpertBundle:Subjects')
  1050.             ->findBy(
  1051.                 [],
  1052.                 ['subname' => 'ASC']
  1053.             );
  1054.         $allJobtypes $this->getDoctrine()
  1055.             ->getRepository('OceanExpertBundle:Jobtypes')
  1056.             ->findBy(
  1057.                 [],
  1058.                 ['idJob' => 'ASC']
  1059.             );
  1060.         //dump($expert);
  1061.         //die();
  1062.         return $this->render('Profile/editProfile.html.twig', array(
  1063.             'expert' => $expert,
  1064.             'countries' => $countries,
  1065.             'locales' => $locales,
  1066.             //is not used
  1067.             //'nationalities' => $countries,
  1068.             'metadata' => $metadata,
  1069.             'studyregions' => $studyregions,
  1070.             'availableSeaRegions' => $instituteSeaRegion,
  1071.             'allSubjects' => $allSubjects,
  1072.             'allJobtypes' => $allJobtypes
  1073.         ));
  1074.     }
  1075.     public function updateProfileTimeAction(Request $request): Response
  1076.     {
  1077.         $security_context $this->get('security.authorization_checker');
  1078.         if ($security_context->isGranted('ROLE_USER')) {
  1079.             $userId $request->request->get('userId');
  1080.             if ($userId) {
  1081.                 $indiv $this->getDoctrine()->getRepository('OceanExpertBundle:Indiv')->findOneByIdInd($userId);
  1082.                 if ($indiv) {
  1083.                     $indiv->setLDateUpd(new DateTime('now'));
  1084.                     $indiv->setLastEditBy($security_context->getToken()->getUser()->getId());
  1085.                     $em $this->getDoctrine()->getManager();
  1086.                     $em->persist($indiv); //marks object to be saved in the next transaction.
  1087.                     $em->flush(); //performs all saves and transactions.
  1088.                 }
  1089.                 return new Response("updated successfully");
  1090.             } else {
  1091.                 return new Response("cannot update");
  1092.             }
  1093.         }
  1094.         return new Response("cannot update");
  1095.     }
  1096.     /**
  1097.      * activate the user with the given id
  1098.      *
  1099.      * @param int $userId
  1100.      *
  1101.      * @return JsonResponse
  1102.      */
  1103.     public function activateUserAction(int $userId): JsonResponse
  1104.     {
  1105.         $security_context $this->get('security.authorization_checker');
  1106.         if ($security_context->isGranted('ROLE_GLOBAL_EDITOR')) {
  1107.             if ($userId) {
  1108.                 $indiv $this->getDoctrine()
  1109.                     ->getRepository('OceanExpertBundle:Indiv')
  1110.                     ->findOneByIdInd($userId);
  1111.                 if ($indiv) {
  1112.                     $indiv->setStatus(1);
  1113.                     $indiv->setStatusLastChanged(new DateTime('now'));
  1114.                     $em $this->getDoctrine()->getManager();
  1115.                     $em->persist($indiv); //marks object to be saved in the next transaction.
  1116.                     $em->flush(); //performs all saves and transactions.
  1117.                 }
  1118.                 return new JsonResponse(
  1119.                     array(
  1120.                         'status' => true,
  1121.                         'msg' => "updated successfully"
  1122.                     )
  1123.                 );
  1124.             } else {
  1125.                 return new JsonResponse(
  1126.                     array(
  1127.                         'status' => false,
  1128.                         'msg' => "cannot update"
  1129.                     )
  1130.                 );
  1131.             }
  1132.         }
  1133.         return new JsonResponse(
  1134.             array(
  1135.                 'status' => false,
  1136.                 'msg' => "you do not have sufficient privileges to perform this action"
  1137.             )
  1138.         );
  1139.     }
  1140.     /**
  1141.      * deactivate the user with the given id
  1142.      *
  1143.      * @param int $userId
  1144.      *
  1145.      * @return Response
  1146.      */
  1147.     public function deactivateUserAction($userId): Response
  1148.     {
  1149.         if (!$userId
  1150.             || $userId == ''
  1151.             || !is_numeric($userId)
  1152.         ) {
  1153.             $message[] = array(
  1154.                 'id' => $userId,
  1155.                 'status' => 0,
  1156.                 'message' => 'incorrect or no user id given'
  1157.             );
  1158.         }
  1159.         $userId intval($userId);
  1160.         $security_context $this->get('security.authorization_checker');
  1161.         $message = array();
  1162.         $authorId $this->get('security.token_storage')
  1163.                 ->getToken()
  1164.                 ->getUser()
  1165.                 ->getId();
  1166.         if ($security_context->isGranted('ROLE_GLOBAL_EDITOR')
  1167.             || $userId === $authorId
  1168.         ) {
  1169.             $em $this->getDoctrine()->getManager();
  1170.             //disable the login
  1171.             $FOSUser $em
  1172.                 ->getRepository('OceanExpertBundle:FosUser')
  1173.                 ->findOneById($userId);
  1174.             if ($FOSUser) {
  1175.                 $FOSUser->setEnabled(0);
  1176.                 $FOSUser->setUpdatedAt(new DateTime('now'));
  1177.                 $em->persist($FOSUser);
  1178.                 $em->flush();
  1179.             } else {
  1180.                 $message[] = array(
  1181.                     'id' => $userId,
  1182.                     'status' => 0,
  1183.                     'message' => "no user found in fos_user table with id $userId"
  1184.                 );
  1185.             }
  1186.             //deactivate the expert
  1187.             $indiv $em
  1188.                 ->getRepository('OceanExpertBundle:Indiv')
  1189.                 ->findOneByIdInd($userId);
  1190.             if ($indiv) {
  1191.                 $comments $indiv->getComments() . "this user($userId) has been deactivated by user with id $authorId ";
  1192.                 $indiv
  1193.                     ->setStatus(3)
  1194.                     ->setComments($comments)
  1195.                     ->setStatusLastChanged(new DateTime('now'));
  1196.                 $em->persist($indiv); //marks object to be saved in the next transaction.
  1197.                 $em->flush(); //performs all saves and transactions.
  1198.             } else {
  1199.                 $message[] = array(
  1200.                     'id' => $userId,
  1201.                     'status' => 0,
  1202.                     'message' => "no user found in indiv table with idInd $userId"
  1203.                 );
  1204.             }
  1205.             if (!count($message)) {
  1206.                 //no error messages yet so all should be fine
  1207.                 $message[] = array(
  1208.                     'id' => $userId,
  1209.                     'status' => true,
  1210.                     'message' => "user with idInd $userId deactivated"
  1211.                 );
  1212.             }
  1213.         } else {
  1214.             $message[] = array(
  1215.                 'id' => $userId,
  1216.                 'status' => 0,
  1217.                 'message' => 'you do not have enough rights to do this'
  1218.             );
  1219.         }
  1220.         return new JsonResponse($message);
  1221.     }
  1222.     public function getNationalityFromId($id)
  1223.     {
  1224.         $em $this->getDoctrine()->getRepository('OceanExpertBundle:Nationality')->findOneById($id);
  1225.         if ($em == null) {
  1226.             return false;
  1227.         } else {
  1228.             return $em->getNationality();
  1229.         }
  1230.     }
  1231.     public function getCountryFromId($id)
  1232.     {
  1233.         $em $this->getDoctrine()->getRepository('OceanExpertBundle:Countries')->findOneByIdCountry($id);
  1234.         if ($em == null) {
  1235.             return false;
  1236.         } else {
  1237.             return $em->getCountry();
  1238.         }
  1239.     }
  1240.     public function getCountryCodeFromId($id)
  1241.     {
  1242.         $em $this->getDoctrine()
  1243.             ->getRepository('OceanExpertBundle:Countries')
  1244.             ->findOneByIdCountry($id);
  1245.         if ($em == null) {
  1246.             return false;
  1247.         } else {
  1248.             return $em->getCountryCode();
  1249.         }
  1250.     }
  1251.     /**
  1252.      * get the country info for the given id's or country codes
  1253.      *
  1254.      * @param array $countryArr
  1255.      *
  1256.      * @return array
  1257.      */
  1258.     public function getCountryFromIds(array $countryArr): array
  1259.     {
  1260.         $em $this->getDoctrine()
  1261.             ->getRepository('OceanExpertBundle:Countries');
  1262.         $query $em->createQueryBuilder('c')
  1263.             ->select('c.country, c.countryCode, c.longitude, c.latitude')
  1264.             ->where('c.idCountry in (:idCountry)')
  1265.             ->orWhere('c.countryCode in (:idCountry)')
  1266.             ->setParameter('idCountry'$countryArr)
  1267.             ->getQuery();
  1268.         return $query->getResult();
  1269.     }
  1270.     /**
  1271.      * @todo is this used???? Arno 06/09/24
  1272.      *
  1273.      * @param $value
  1274.      *
  1275.      * @return string
  1276.      */
  1277.     /*
  1278.     public function csvComma($value = '')
  1279.     {
  1280.         return "'" . implode("','", explode(",", $value)) . "'";
  1281.     }
  1282.     */
  1283.     public function getJobTypeByCodes($jobArr)
  1284.     {
  1285.         $em $this->getDoctrine()
  1286.             ->getRepository('OceanExpertBundle:Jobtypes');
  1287.         $query $em->createQueryBuilder('a')
  1288.             ->select('a.jobname')
  1289.             ->where('a.idJob in (:jobArr)')
  1290.             ->setParameter('jobArr'$jobArr)
  1291.             ->getQuery();
  1292.         $jobs $query->getResult();
  1293.         $jobList array_column($jobs'jobname');
  1294.         return implode(', '$jobList);
  1295.     }
  1296.     public function getResearchAreaByCodes($codeArr)
  1297.     {
  1298.         $em $this->getDoctrine()
  1299.             ->getRepository('OceanExpertBundle:Regions');
  1300.         $query $em->createQueryBuilder('a')
  1301.             ->select('a.name')
  1302.             ->where('a.idRegion in (:codeArr)')
  1303.             ->setParameter('codeArr'$codeArr)
  1304.             ->getQuery();
  1305.         $regions $query->getResult();
  1306.         $regionsList array_column($regions'name');
  1307.         return implode(', '$regionsList);
  1308.     }
  1309.     /**
  1310.      * get all the meta data for a given userId
  1311.      * this data comes as a key-value pair
  1312.      *
  1313.      * @param int $userId the userId of the expert
  1314.      *
  1315.      * @return array
  1316.      */
  1317.     public function getMetaData(int $userId): array
  1318.     {
  1319.         $qb $this->getDoctrine()->getManager()->createQueryBuilder();
  1320.         $qb->add('select''m.metaOption,m.metaValue')
  1321.             ->add('from''OceanExpertBundle:IndivMeta m')
  1322.             ->where('m.indivId = :userId')
  1323.             ->setParameter('userId'$userId);
  1324.         $meta $qb->getQuery()->getResult(AbstractQuery::HYDRATE_ARRAY);
  1325.         $metadata = array();
  1326.         foreach ($meta as $value) {
  1327.             $metadata[$value['metaOption']] = $value['metaValue'];
  1328.         }
  1329.         return $metadata;
  1330.     }
  1331.     /**
  1332.      * get all the different job types for a given userId
  1333.      *
  1334.      * @param int $userId the userId of the expert
  1335.      *
  1336.      * @return array
  1337.      */
  1338.     public function getJobTypes(int $userId): array
  1339.     {
  1340.         $qb $this->getDoctrine()->getManager()->createQueryBuilder();
  1341.         $qb->add('select''jt.jobname,jt.idJob')
  1342.             ->add('from''OceanExpertBundle:IndivJobtype j')
  1343.             ->leftJoin('OceanExpertBundle:Jobtypes''jt''WITH''jt.idJob = j.idJob')
  1344.             ->where('j.idInd = :userId')
  1345.             ->setParameter('userId'$userId);
  1346.         $meta $qb->getQuery()->getResult(AbstractQuery::HYDRATE_ARRAY);
  1347.         $jobTypes implode(
  1348.             '\r',
  1349.             array_column(
  1350.                 $meta,
  1351.                 'jobname'
  1352.             )
  1353.         );
  1354.         $jobId implode(
  1355.             ',',
  1356.             array_column(
  1357.                 $meta,
  1358.                 'idJob'
  1359.             )
  1360.         );
  1361.         return array(
  1362.             'jobtype' => $jobTypes,
  1363.             'jobId' => $jobId
  1364.         );
  1365.     }
  1366.     public function getUserGroups($userId)
  1367.     {
  1368.         $qb $this->getDoctrine()->getManager()->createQueryBuilder();
  1369.         $qb->add('select''g.groupname, g.idGroup')
  1370.             ->add('from''OceanExpertBundle:MemberGroups mg')
  1371.             ->leftJoin('OceanExpertBundle:Groups''g''WITH''mg.idGroup = g.idGroup')
  1372.             ->where('mg.idInd = :userId')
  1373.             ->setParameter('userId'$userId)
  1374.             ->orderBy('g.groupname','ASC');
  1375.         return $qb->getQuery()->getResult(AbstractQuery::HYDRATE_ARRAY);
  1376.     }
  1377.     /**
  1378.      * get all the subject areas for a given userId
  1379.      *
  1380.      * @param int $userId the userId of the expert
  1381.      *
  1382.      * @return string
  1383.      */
  1384.     public function getSubjectAreas(int $userId): string
  1385.     {
  1386.         $qb $this->getDoctrine()->getManager()->createQueryBuilder();
  1387.         $qb->add('select''s.subname,s.idSub')
  1388.             ->add('from''OceanExpertBundle:IndivSubjects ivs')
  1389.             ->leftJoin('OceanExpertBundle:Subjects''s''WITH''s.idSub = ivs.idSub')
  1390.             ->where('ivs.idInd = :userId')
  1391.             ->setParameter('userId'$userId);
  1392.         $meta $qb->getQuery()->getResult(AbstractQuery::HYDRATE_ARRAY);
  1393.         return implode(
  1394.             ',',
  1395.             array_column(
  1396.                 $meta,
  1397.                 'subname'
  1398.             )
  1399.         );
  1400.     }
  1401.     public function getUpdatedBy($id '')
  1402.     {
  1403.         $updatedBy $this->getDoctrine()->getRepository('OceanExpertBundle:Indiv')->findOneByIdInd($id);
  1404.         if ($updatedBy) {
  1405.             $name $updatedBy->getfname() . " " strtoupper($updatedBy->getsname());
  1406.         } else {
  1407.             $name false;
  1408.         }
  1409.         return $name;
  1410.     }
  1411.     public function qccontrolAction(Request $request): Response
  1412.     {
  1413.         $id $request->request->get('userId');
  1414.         $action $request->request->get('action');
  1415.         $return '';
  1416.         $security_context $this->get('security.authorization_checker');
  1417.         if ($security_context->isGranted('ROLE_GLOBAL_EDITOR')) {
  1418.             $author $this->get('security.token_storage')->getToken()->getUser()->getId();
  1419.             $updatedBy $this->getDoctrine()->getRepository('OceanExpertBundle:Indiv')->findOneByIdInd($id);
  1420.             if ($action == 1) {
  1421.                 $updatedBy->setQualityCheckedBy($author);
  1422.                 $updatedBy->setQualityCheckedDate(new DateTime('now'));
  1423.                 $updatedBy->setQualityChecked(1);
  1424.                 $return "This record has been marked as quality controlled on <strong>" date('F j, Y') . "</strong> by <strong>" $this->getUpdatedBy($author)."</strong>";
  1425.             } else {
  1426.                 $updatedBy->setQualityCheckedBy(null);
  1427.                 $updatedBy->setQualityCheckedDate(null);
  1428.                 $updatedBy->setQualityChecked(0);
  1429.                 $return "This record has not been quality controlled";
  1430.             }
  1431.             $updatedBy->setLDateUpd(new DateTime('now'));
  1432.             $updatedBy->setLastEditBy($author);
  1433.             $em $this->getDoctrine()->getManager();
  1434.             $em->persist($updatedBy); //marks object to be saved in the next transaction.
  1435.             $em->flush(); //performs all saves and transactions.
  1436.         }
  1437.         return new Response($return);
  1438.     }
  1439.     public function setRetiredAction(Request $request): Response
  1440.     {
  1441.         $id $request->request->get('userId');
  1442.         $date $request->request->get('retiredDate');
  1443.         $retiredStatus $request->request->get('retiredStatus');
  1444.         $security_context $this->get('security.authorization_checker');
  1445.         if ($security_context->isGranted('ROLE_USER')) {
  1446.             $author $this->get('security.token_storage')->getToken()->getUser()->getId();
  1447.             $updateRecord $this->getDoctrine()->getRepository('OceanExpertBundle:Indiv')->findOneByIdInd($id);
  1448.             if ($updateRecord) {
  1449.                 if ($retiredStatus == 1) {
  1450.                     $updateRecord->setRetired(1);
  1451.                     if (trim($date) == '') {
  1452.                         $updateRecord->setRetiredDate(null);
  1453.                     } else {
  1454.                         $updateRecord->setRetiredDate(DateTime::createFromFormat('Y-m-d'$date));
  1455.                     }
  1456.                 } else {
  1457.                     $updateRecord->setRetired(0);
  1458.                     $updateRecord->setRetiredDate(null);
  1459.                 }
  1460.             }
  1461.             $updateRecord->setLDateUpd(new DateTime('now'));
  1462.             $updateRecord->setLastEditBy($author);
  1463.             $em $this->getDoctrine()->getManager();
  1464.             $em->persist($updateRecord); //marks object to be saved in the next transaction.
  1465.             $em->flush(); //performs all saves and transactions.
  1466.         }
  1467.         return new Response($date);
  1468.     }
  1469.     public function setDeceasedAction(Request $request): Response
  1470.     {
  1471.         $id $request->request->get('userId');
  1472.         $date $request->request->get('deceasedDate');
  1473.         $deceasedStatus $request->request->get('deceasedStatus');
  1474.         $return '';
  1475.         $security_context $this->get('security.authorization_checker');
  1476.         if ($security_context->isGranted('ROLE_GLOBAL_EDITOR')) {
  1477.             $author $this->get('security.token_storage')->getToken()->getUser()->getId();
  1478.             $updateRecord $this->getDoctrine()
  1479.                 ->getRepository('OceanExpertBundle:Indiv')
  1480.                 ->findOneByIdInd($id);
  1481.             if ($updateRecord) {
  1482.                 if ($deceasedStatus == 1) {
  1483.                     $updateRecord->setDeceased(1);
  1484.                     if (trim($date) == '') {
  1485.                         $updateRecord->setDeceasedDate(null);
  1486.                     } else {
  1487.                         $updateRecord->setDeceasedDate(DateTime::createFromFormat('Y-m-d'$date));
  1488.                     }
  1489.                 } else {
  1490.                     $updateRecord->setDeceased(0);
  1491.                     $updateRecord->setDeceasedDate(null);
  1492.                 }
  1493.             }
  1494.             $updateRecord->setLDateUpd(new DateTime('now'));
  1495.             $updateRecord->setLastEditBy($author);
  1496.             $em $this->getDoctrine()->getManager();
  1497.             $em->persist($updateRecord); //marks object to be saved in the next transaction.
  1498.             $em->flush(); //performs all saves and transactions.
  1499.         }
  1500.         return new Response($return);
  1501.     }
  1502.     public function setDoNotInviteAction(Request $request): Response
  1503.     {
  1504.         $id $request->request->get('userId');
  1505.         $status $request->request->get('status');
  1506.         $return '';
  1507.         $security_context $this->get('security.authorization_checker');
  1508.         if ($security_context->isGranted('ROLE_USER')) {
  1509.             $author $this->get('security.token_storage')->getToken()->getUser()->getId();
  1510.             $updateRecord $this->getDoctrine()
  1511.                 ->getRepository('OceanExpertBundle:Indiv')
  1512.                 ->findOneByIdInd($id);
  1513.             if ($updateRecord) {
  1514.                 if ($status == 1) {
  1515.                     $updateRecord->setDoNotInvite(1);
  1516.                     $updateRecord->setDoNoInviteBy($author);
  1517.                     $updateRecord->setDoNoInviteOn(new DateTime('now'));
  1518.                     $return 'This record has been set as do not invite on <strong>' date('F j, Y') . '</strong>';
  1519.                     $return .= 'by <strong>' $this->getUpdatedBy($author) . '</strong>';
  1520.                 } else {
  1521.                     $updateRecord->setDoNotInvite(0);
  1522.                     $updateRecord->setDoNoInviteBy(0);
  1523.                     $updateRecord->setDoNoInviteOn(NULL);
  1524.                     $return 'Please select "Yes" to add this member to the do not invite list.';
  1525.                 }
  1526.             }
  1527.             $updateRecord->setLDateUpd(new DateTime('now'));
  1528.             $updateRecord->setLastEditBy($author);
  1529.             $em $this->getDoctrine()->getManager();
  1530.             $em->persist($updateRecord); //marks object to be saved in the next transaction.
  1531.             $em->flush(); //performs all saves and transactions.
  1532.         }
  1533.         return new Response($return);
  1534.     }
  1535.     public function setAdmincommentsAction(Request $request): Response
  1536.     {
  1537.         $id $request->request->get('userId');
  1538.         $comments $request->request->get('comments');
  1539.         $return '';
  1540.         if (trim($comments) != '') {
  1541.             $security_context $this->get('security.authorization_checker');
  1542.             if ($security_context->isGranted('ROLE_GLOBAL_EDITOR')) {
  1543.                 $author $this->get('security.token_storage')->getToken()->getUser()->getId();
  1544.                 $updateRecord $this->getDoctrine()
  1545.                     ->getRepository('OceanExpertBundle:Indiv')
  1546.                     ->findOneByIdInd($id);
  1547.                 $comments .= '<br />';
  1548.                 $comments .= '(Added by ' $this->getUpdatedBy($author);
  1549.                 $comments .= ' on ' date('d-m-y');
  1550.                 $comments .= ')<br /><br />';
  1551.                 $comments .= $updateRecord->getAdminComments();
  1552.                 if ($updateRecord) {
  1553.                     $updateRecord->setAdminComments($comments);
  1554.                 }
  1555.                 $updateRecord->setLDateUpd(new DateTime('now'));
  1556.                 $updateRecord->setLastEditBy($author);
  1557.                 $em $this->getDoctrine()->getManager();
  1558.                 $em->persist($updateRecord); //marks object to be saved in the next transaction.
  1559.                 $em->flush(); //performs all saves and transactions.
  1560.                 $return $comments;
  1561.             }
  1562.         }
  1563.         return new Response($return);
  1564.     }
  1565.     public function setGroupsAction(Request $request): Response
  1566.     {
  1567.         $id $request->request->get('userId');
  1568.         $groups $request->request->get('groups');
  1569.         $return '';
  1570.         $security_context $this->get('security.authorization_checker');
  1571.         if ($security_context->isGranted('ROLE_GLOBAL_EDITOR')) {
  1572.             $author $this->get('security.token_storage')
  1573.                 ->getToken()
  1574.                 ->getUser()
  1575.                 ->getId();
  1576.             $updateRecord $this->getDoctrine()
  1577.                 ->getRepository('OceanExpertBundle:Indiv')
  1578.                 ->findOneByIdInd($id);
  1579.             if ($updateRecord) {
  1580.                 $updateRecord->setLDateUpd(new DateTime('now'));
  1581.                 $updateRecord->setLastEditBy($author);
  1582.                 $em $this->getDoctrine()->getManager();
  1583.                 $em->persist($updateRecord); //marks object to be saved in the next transaction.
  1584.                 $em->flush(); //performs all saves and transactions.
  1585.             }
  1586.             if (is_array($groups)) {
  1587.                 $em $this->getDoctrine()->getManager();
  1588.                 $results $em->createQueryBuilder()
  1589.                     ->add('select''m')
  1590.                     ->add('from''OceanExpertBundle:MemberGroups m')
  1591.                     ->where('m.idGroup not in (:groups)')
  1592.                     ->andWhere('m.idInd =:idInd')
  1593.                     ->setParameters(array('groups' => $groups'idInd' => $id))
  1594.                     ->getQuery()->getResult();
  1595.                 foreach ($results as $result) {
  1596.                     $em->remove($result);
  1597.                 }
  1598.                 $em->flush();
  1599.                 foreach ($groups as $value) {
  1600.                     $updateGroup $this->getDoctrine()
  1601.                         ->getRepository('OceanExpertBundle:MemberGroups')
  1602.                         ->find(
  1603.                             array(
  1604.                                 'idInd' => $id,
  1605.                                 'idGroup' => $value
  1606.                             )
  1607.                         );
  1608.                     if (!$updateGroup) {
  1609.                         $addGroups = new MemberGroups();
  1610.                         $addGroups->setIdInd($id);
  1611.                         $addGroups->setIdGroup($value);
  1612.                         $addGroups->setRole('');
  1613.                         $addGroups->setMemberOrder(NULL);
  1614.                         $addGroups->setIsLeader(0);
  1615.                         $em $this->getDoctrine()->getManager();
  1616.                         $em->persist($addGroups); //marks object to be saved in the next transaction.
  1617.                         $em->flush(); //performs all saves and transactions.
  1618.                     }
  1619.                 }
  1620.             } else {
  1621.                 $updateGroup $this->getDoctrine()
  1622.                     ->getRepository('OceanExpertBundle:MemberGroups')
  1623.                     ->findBy(array('idInd' => $id));
  1624.                 $em $this->getDoctrine()->getEntityManager();
  1625.                 foreach ($updateGroup as $groups) {
  1626.                     $em->remove($groups);
  1627.                 }
  1628.                 $em->flush();
  1629.             }
  1630.         }
  1631.         return new Response($return);
  1632.     }
  1633.     public function setPrivilegesAction(Request $request): Response
  1634.     {
  1635.         //get all the values from the request
  1636.         //these values are send from profile.html.twig $("#addPrivileges").click(function () {....
  1637.         $id $request->request->get('userId');
  1638.         $countries $request->request->get('countries');
  1639.         $ownInstitute $request->request->get('ownInstitute');
  1640.         $countryList $request->request->get('countryList');
  1641.         $editor $request->request->get('editor');
  1642.         $security_context $this->get('security.authorization_checker');
  1643.         if ($security_context->isGranted('ROLE_GLOBAL_EDITOR')) {
  1644.             $return = array(
  1645.                 'status' => 0,
  1646.                 'message' => array()
  1647.             );
  1648.             //who is doing this update
  1649.             $author $this->get('security.token_storage')
  1650.                 ->getToken()
  1651.                 ->getUser()
  1652.                 ->getId();
  1653.             //what record needs to be updated
  1654.             $updateRecord $this->getDoctrine()
  1655.                 ->getRepository('OceanExpertBundle:Indiv')
  1656.                 ->findOneByIdInd($id);
  1657.             if ($updateRecord) {
  1658.                 $updateRecord->setLDateUpd(new DateTime('now'));
  1659.                 $updateRecord->setLastEditBy($author);
  1660.                 $em $this->getDoctrine()->getManager();
  1661.                 $em->persist($updateRecord); //marks object to be saved in the next transaction.
  1662.                 $em->flush(); //performs all saves and transactions.
  1663.             }
  1664.             if ($ownInstitute == 1) {
  1665.                 $updateInstEdit $this->getDoctrine()
  1666.                     ->getRepository('OceanExpertBundle:MemberEditsInstitution')
  1667.                     ->findOneBy(array(
  1668.                             'idInd' => $id,
  1669.                             'idInst' => $this->getIndivInstitute($id)
  1670.                         )
  1671.                     );
  1672.                 if (!$updateInstEdit) {
  1673.                     $updateInstEdit = new MemberEditsInstitution();
  1674.                     $updateInstEdit->setIdInd($id);
  1675.                     $updateInstEdit->setIdInst($this->getIndivInstitute($id));
  1676.                 } else {
  1677.                     $updateInstEdit->setIdInst($this->getIndivInstitute($id));
  1678.                 }
  1679.                 $em->persist($updateInstEdit); //marks object to be saved in the next transaction.
  1680.                 $em->flush(); //performs all saves and transactions.
  1681.                 $return['message'][] = 'update own institute activated';
  1682.             } else {
  1683.                 $qb $em->createQueryBuilder();
  1684.                 $query $qb->delete('OceanExpertBundle:MemberEditsInstitution''m')
  1685.                     ->where('m.idInd = :id')
  1686.                     ->andWhere('m.idInst = :idInst')
  1687.                     ->setParameters(
  1688.                         array(
  1689.                             'id' => $id,
  1690.                             'idInst' => $this->getIndivInstitute($id)
  1691.                         )
  1692.                     )
  1693.                     ->getQuery();
  1694.                 $query->execute();
  1695.                 $em->flush();
  1696.                 $return['message'][] = 'update own institute removed';
  1697.             }
  1698.             if (is_array($countries)
  1699.                 && $countryList == 1
  1700.             ) {
  1701.                 $em $this->getDoctrine()->getManager();
  1702.                 $results $em->createQueryBuilder()
  1703.                     ->add('select''m')
  1704.                     ->add('from''OceanExpertBundle:MemberEditsCountry m')
  1705.                     ->where('m.idCountry not in (:countries)')
  1706.                     ->andWhere('m.idInd =:idInd')
  1707.                     ->setParameters(
  1708.                         array(
  1709.                             'countries' => $countries,
  1710.                             'idInd' => $id
  1711.                         )
  1712.                     )
  1713.                     ->getQuery()->getResult();
  1714.                 foreach ($results as $result) {
  1715.                     $em->remove($result);
  1716.                 }
  1717.                 $em->flush();
  1718.                 foreach ($countries as $value) {
  1719.                     $updateCountries $this->getDoctrine()
  1720.                         ->getRepository('OceanExpertBundle:MemberEditsCountry')
  1721.                         ->find(array(
  1722.                                 'idInd' => $id,
  1723.                                 'idCountry' => $value
  1724.                             )
  1725.                         );
  1726.                     if (!$updateCountries) {
  1727.                         $addCountry = new MemberEditsCountry();
  1728.                         $addCountry->setIdInd($id);
  1729.                         $addCountry->setIdCountry($value);
  1730.                         $em $this->getDoctrine()->getManager();
  1731.                         $em->persist($addCountry); //marks object to be saved in the next transaction.
  1732.                         $em->flush(); //performs all saves and transactions.
  1733.                     }
  1734.                 }
  1735.                 $return['message'][] = 'countries added';
  1736.             } else {
  1737.                 $updateGroup $this->getDoctrine()
  1738.                     ->getRepository('OceanExpertBundle:MemberEditsCountry')
  1739.                     ->findBy(array('idInd' => $id));
  1740.                 $em $this->getDoctrine()->getEntityManager();
  1741.                 foreach ($updateGroup as $groups) {
  1742.                     $em->remove($groups);
  1743.                 }
  1744.                 $em->flush();
  1745.                 $return['message'][] = 'countries removed';
  1746.             }
  1747.             $user$em->getRepository('OceanExpertBundle:User')
  1748.                 ->findOneBy(
  1749.                     array(
  1750.                         'id' => $id
  1751.                     )
  1752.                 );
  1753.             if($editor == 1) {
  1754.                 $user->addRole("ROLE_GLOBAL_EDITOR");
  1755.                 $return['message'][] = 'global editor activated';
  1756.             } elseif ($editor == 0) {
  1757.                 $user->removeRole('ROLE_GLOBAL_EDITOR');
  1758.                 $return['message'][] = 'global editor removed';
  1759.             }
  1760.             $em->persist($user);
  1761.             $em->flush();
  1762.         } else {
  1763.             $return = array(
  1764.                 'status' => 1,
  1765.                 'error' => 'you have no rights to do this'
  1766.             );
  1767.         }
  1768.         return new Response(json_encode($return));
  1769.     }
  1770.     public function resetPasswordLinkAction(Request $request): Response
  1771.     {
  1772.         if ($request->query->get('username')) {
  1773.             $username $request->query->get('username');
  1774.         } else {
  1775.             $username $request->request->get('username');
  1776.         }
  1777.         $user $this->fosUserManager->findUserByUsernameOrEmail($username);
  1778.         if (null === $user) {
  1779.             $return "Error in sending email. User not found.";
  1780.             return new Response($return);
  1781.         }
  1782.         if (null === $user->getConfirmationToken()) {
  1783.             $user->setConfirmationToken($this->fosTokenGenerator->generateToken());
  1784.         }
  1785.         $this->fosMailer->sendResettingEmailMessage($user);
  1786.         $user->setPasswordRequestedAt(new DateTime());
  1787.         $this->fosUserManager->updateUser($user);
  1788.         $return "Password reset link send successfully.";
  1789.         if ($request->query->get('username')) {
  1790.             $email $user->getEmail();
  1791.             if (false !== $pos strpos($email'@')) {
  1792.                 $email '...' substr($email$pos);
  1793.             }
  1794.             return new RedirectResponse(
  1795.                 $this->generateUrl(
  1796.                     'fos_user_resetting_check_email',
  1797.                     array('email' => $email)
  1798.                 )
  1799.             );
  1800.         }
  1801.         return new Response($return);
  1802.     }
  1803.     public function getIndivInstitute($idInd)
  1804.     {
  1805.         $getInstId $this->getDoctrine()
  1806.             ->getRepository('OceanExpertBundle:IndivInstitution')
  1807.             ->findOneByIdInd($idInd);
  1808.         if ($getInstId) {
  1809.             return $getInstId->getIdInst();
  1810.         } else {
  1811.             return 0;
  1812.         }
  1813.     }
  1814.     /**
  1815.      * @return Response
  1816.      */
  1817.     public function assignRolesAction(Request $request): Response
  1818.     {
  1819.         $username =  $request->request->get('username');
  1820.         $allAssignedRoles = array();
  1821.         $allRevokedRoles = array();
  1822.         $em $this->getDoctrine()->getManager();
  1823.         $user$em->getRepository("OceanExpertBundle:User")
  1824.             ->findOneBy(
  1825.                 array(
  1826.                     'username' => $username
  1827.                 )
  1828.             );
  1829.         if ($request->request->get('superadmin')==1) {
  1830.             $user->addRole('ROLE_SUPERADMIN');
  1831.             $allAssignedRoles[] = 'ROLE_SUPERADMIN';
  1832.         } else {
  1833.             $user->removeRole('ROLE_SUPERADMIN');
  1834.             $allRevokedRoles[] = 'ROLE_SUPERADMIN';
  1835.         }
  1836.         if ($request->request->get('oceancdadmin')==1) {
  1837.             $user->addRole('ROLE_OCEANCD');
  1838.             $allAssignedRoles[] = 'ROLE_OCEANCD';
  1839.         } else {
  1840.             $user->removeRole('ROLE_OCEANCD');
  1841.             $allRevokedRoles[] = 'ROLE_OCEANCD';
  1842.         }
  1843.         if ($request->request->get('odiscatadmin')==1) {
  1844.             $user->addRole('ROLE_ODISCATADMIN');
  1845.             $allAssignedRoles[] = 'ROLE_ODISCATADMIN';
  1846.         } else {
  1847.             $user->removeRole('ROLE_ODISCATADMIN');
  1848.             $allRevokedRoles[] = 'ROLE_ODISCATADMIN';
  1849.         }
  1850.         if ($request->request->get('administrator')==1) {
  1851.             $user->addRole('ROLE_ADMIN');
  1852.             $allAssignedRoles[] = 'ROLE_ADMIN';
  1853.         } else {
  1854.             $user->removeRole('ROLE_ADMIN');
  1855.             $allRevokedRoles[] = 'ROLE_ADMIN';
  1856.         }
  1857.         if ($request->request->get('manager')==1) {
  1858.             $user->addRole('ROLE_MANAGER');
  1859.             $allAssignedRoles[] = 'ROLE_MANAGER';
  1860.         } else {
  1861.             $user->removeRole('ROLE_MANAGER');
  1862.             $allRevokedRoles[] = 'ROLE_MANAGER';
  1863.         }
  1864.         if ($request->request->get('lme')==1) {
  1865.             $user->addRole('ROLE_LME');
  1866.             $allAssignedRoles[] = 'ROLE_LME';
  1867.         } else {
  1868.             $user->removeRole('ROLE_LME');
  1869.             $allRevokedRoles[] = 'ROLE_LME';
  1870.         }
  1871.         $em->persist($user);
  1872.         $em->flush();
  1873.         return new JsonResponse(
  1874.             array(
  1875.                 'status' => ,
  1876.                 'message' => 'Role(s) assigned successfully',
  1877.                 'username' => $username,
  1878.                 'assigned' => implode(','$allAssignedRoles),
  1879.                 'revoked' => implode(', '$allRevokedRoles),
  1880.                 'user' => $user
  1881.             )
  1882.         );
  1883.     }
  1884.     /**
  1885.      * @return JsonResponse
  1886.      */
  1887.     public function getExpertsAjaxAction(Request $request): Response
  1888.     {
  1889.         if (!null == $request->query->get('q')) {
  1890.             $query $request->query->get('q');
  1891.             $em $this->getDoctrine()->getManager();
  1892.             $connection $em->getConnection();
  1893.             $statement $connection->prepare("SELECT 
  1894.                 i.id_ind AS id, 
  1895.                 i.fname, 
  1896.                 i.sname, 
  1897.                 i.jobtitle,
  1898.                 inst.inst_name,
  1899.                 c.country 
  1900.             FROM indiv i
  1901.             LEFT JOIN countries c ON c.id_country =  i.country_code
  1902.             LEFT JOIN indiv_institution ii ON ii.id_ind = i.id_ind
  1903.             LEFT JOIN institutions inst ON inst.id_inst = ii.id_inst
  1904.             LEFT JOIN countries ic ON ic.id_country =  inst.country_code
  1905.             WHERE ( MATCH (fname,sname) AGAINST (:searchterm IN BOOLEAN MODE) 
  1906.                 OR fname like '%$query%' 
  1907.                 OR fname like '%$query%' 
  1908.                 OR sname like '%$query%' 
  1909.                 OR sname like '%$query%') 
  1910.                 AND status = 1;
  1911.             ");
  1912.             $statement->bindValue('searchterm'$query);
  1913.             $statement->execute();
  1914.             $query $statement->fetchAll();
  1915.             $data = array();
  1916.             if($query) {
  1917.                 $data = array(
  1918.                     'incomplete_results' => false,
  1919.                     'items' => $query,
  1920.                     'total_count' => count($query),
  1921.                 );
  1922.             }
  1923.             return new JsonResponse($data);
  1924.         }
  1925.         return new JsonResponse(array());
  1926.     }
  1927.     /**
  1928.      * @param int     $idInd
  1929.      * @param Request $request
  1930.      *
  1931.      * @return mixed
  1932.      */
  1933.     function getExpertEventParticipation(int $idIndRequest $request) {
  1934.         $em $this->getDoctrine()->getManager();
  1935.         $participation $em->createQueryBuilder()
  1936.             ->add('select''ep.idEvent')
  1937.             ->add('from''OceanExpertBundle:EventParticipants ep')
  1938.             ->where('ep.idInd =:idInd')
  1939.             ->setParameters(array('idInd' => $idInd ))
  1940.             ->getQuery()->getResult();
  1941.         $participation array_column($participation"idEvent");
  1942.         $contacts $em->createQueryBuilder()
  1943.             ->add('select''ec.idEvent')
  1944.             ->add('from''OceanExpertBundle:EventContacts ec')
  1945.             ->where('ec.idInd =:idInd')
  1946.             ->setParameters(array('idInd' => $idInd ))
  1947.             ->getQuery()->getResult();
  1948.         $contacts array_column($contacts"idEvent");
  1949.         $staff $em->createQueryBuilder()
  1950.             ->add('select''es.idEvent')
  1951.             ->add('from''OceanExpertBundle:EventStaff es')
  1952.             ->where('es.idInd =:idInd')
  1953.             ->setParameters(array('idInd' => $idInd ))
  1954.             ->getQuery()->getResult();
  1955.         $staff array_column($staff"idEvent");
  1956.         $results array_merge($participation,$contacts,$staff);
  1957.         $results array_unique($results);
  1958.         $qb $this->getDoctrine()->getManager()->createQueryBuilder();
  1959.         $qb->add('select''e.idEvent, e.title, e.idEventtype, e.startOn, e.endOn, e.address, e.city, e.state, e.postcode, c.country')
  1960.             ->add('from''OceanExpertBundle:Events e')
  1961.             ->leftJoin('OceanExpertBundle:Countries''c''WITH''e.idCountry = c.idCountry')
  1962.             ->where('e.idEvent in (:idEvent)')
  1963.             ->andWhere('e.status = 1')
  1964.             ->orderBy('e.startOn''DESC')
  1965.             ->setParameter('idEvent'$results );
  1966.         $resultData $qb->getQuery()->getResult();
  1967.         $paginator $this->get('knp_paginator');
  1968.         $members $paginator->paginate(
  1969.             $resultData,
  1970.             $request->query->getInt('page'1),
  1971.             5,
  1972.             array(
  1973.                 'pageParameterName' => 'page',
  1974.                 'sortDirectionParameterName' => 'dir'
  1975.             )
  1976.         );
  1977.         //@todo some code goes here (i.e. your symfony request dispatching)
  1978.         return $members;
  1979.     }
  1980. }