src/OceanExpertBundle/Controller/ProfileController.php line 2089

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