src/OceanExpertBundle/Controller/InstitutionController.php line 400

Open in your IDE?
  1. <?php
  2. namespace OceanExpertBundle\Controller;
  3. use CommerceGuys\Addressing\Formatter\DefaultFormatter;
  4. use CommerceGuys\Addressing\Model\Address;
  5. use CommerceGuys\Addressing\Repository\AddressFormatRepository;
  6. use CommerceGuys\Addressing\Repository\CountryRepository;
  7. use CommerceGuys\Addressing\Repository\SubdivisionRepository;
  8. use DateTime;
  9. use Doctrine\ORM\AbstractQuery;
  10. use Doctrine\ORM\Query;
  11. use Exception;
  12. use OceanExpertBundle\Controller\Api\ApiReportsController;
  13. use OceanExpertBundle\Entity\Institutions;
  14. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  15. use Symfony\Component\HttpFoundation\JsonResponse;
  16. use Symfony\Component\HttpFoundation\Request;
  17. use Symfony\Component\HttpFoundation\Response;
  18. class InstitutionController extends AbstractController
  19. {
  20.     /**
  21.      * get the list of all institutes for a given countryCode/Id
  22.      *
  23.      * @param Request $request
  24.      *
  25.      * @return JsonResponse
  26.      */
  27.     public function getInstitutionByCountryAction(Request $request): JsonResponse
  28.     {
  29.         $instituteList = array();
  30.         if ($request->query->get('countryCode') == NULL) {
  31.             $instituteList = array(
  32.                 'institution' => 'Select Country First.'
  33.             );
  34.         } else {
  35.             $countryCode $request->query->get('countryCode');
  36.             $repo $this->getDoctrine()
  37.                 ->getRepository('OceanExpertBundle:Institutions');
  38.             $query $repo->createQueryBuilder('a')
  39.                 ->select('distinct a.instName, a.idInst, a.instAddress, a.city, a.state, a.postcode, a.idInst, a.activated')
  40.                 ->where('a.countryCode = :code')
  41.                 ->andWhere('a.activated in (0,1)')
  42.                 ->orderBy('a.instName''ASC')
  43.                 ->setParameter('code'$countryCode);
  44.             if ($request->query->get('search') !== '') {
  45.                 $query $query->andWhere('a.instName like :search')
  46.                     ->setParameter('search''%' $request->query->get('search') . '%');
  47.             }
  48.             $query $query->getQuery();
  49.             $instituteList $query->getResult();
  50.         }
  51.         return new JsonResponse($instituteList);
  52.     }
  53.     /**
  54.      * get the information about an institute with a given id
  55.      *
  56.      * @param Request $request
  57.      *
  58.      * @return JsonResponse
  59.      */
  60.     public function getInstitutionAddressAction(Request $request): Response
  61.     {
  62.         $instituteDetails = array();
  63.         if ($request->query->get('instName') != NULL) {
  64.             $idInst $request->query->get('instName');
  65.             $repo $this->getDoctrine()
  66.                 ->getRepository('OceanExpertBundle:Institutions');
  67.             $query $repo->createQueryBuilder('a')
  68.                 ->select('
  69.                     a.instName, 
  70.                     a.instAddress, 
  71.                     a.addr2,
  72.                     a.postcode, 
  73.                     a.city, 
  74.                     a.state, 
  75.                     a.countryCode,
  76.                     a.instTel
  77.                     ')
  78.                 ->where('a.idInst = :idInst')
  79.                 // ->setParameter('title',$title)
  80.                 ->setParameter('idInst'$idInst)
  81.                 ->getQuery();
  82.             $instituteDetails $query->getResult();
  83.             return new JsonResponse($instituteDetails);
  84.         } else {
  85.             return new JsonResponse(
  86.                 array(
  87.                     'status' => 0,
  88.                     'message' => 'need an id of the institute'
  89.                 )
  90.             );
  91.         }
  92.     }
  93.     public function addInstitutionAction(Request $request): Response
  94.     {
  95.         $data $request->request->all();
  96.         $security_context $this->get('security.authorization_checker');
  97.         if ($security_context->isGranted('IS_AUTHENTICATED_FULLY')) {
  98.             $em $this->getDoctrine()->getManager();
  99.             $userId $this->get('security.token_storage')->getToken()->getUser()->getId();
  100.             //let's check if the logged-in user has a 'real' profile
  101.             //the mandatory profile fields are all filled and the expert is active
  102.             // Arno 21/06/23 : we will not check this for the time being see alse #521
  103.             //if people cannot create their institute while registering they will not make / add it later
  104.             /*
  105.             if (!SecurityController::checkUserProfile($em, $userId)) {
  106.                 return $this->redirect(
  107.                     $this->generateUrl(
  108.                         'user_profile_edit'
  109.                     )
  110.                 );
  111.             }
  112.             */
  113.             //this is here to prevent breaking inst creation by something else that 'edit/create profile'
  114.             if (null !== $request->request->get('icountrycode')) {
  115.                 //this is correct and used by 'edit/create profile'
  116.                 $countryCode $request->request->get('icountrycode');
  117.             } else {
  118.                 //this may be incorrect as we need the country code of the inst
  119.                 //and on some page this is mixed with country code of the expert
  120.                 $countryCode $request->request->get('countryCode');
  121.             }
  122.             if (trim($request->request->get("iedmo")) == ''
  123.                 || !is_numeric($request->request->get("iedmo"))
  124.             ) {
  125.                 $edmo_code 0;
  126.             } else {
  127.                 $edmo_code $request->request->get("iedmo");
  128.             }
  129.             $instituteDetails = array();
  130.             $repo $this->getDoctrine()
  131.                 ->getRepository('OceanExpertBundle:Institutions');
  132.             $query $repo->createQueryBuilder('a')
  133.                 ->select('a.idInst, a.instName, a.instAddress, a.city, a.state, a.postcode, a.instTel')
  134.                 ->where('a.instName like :name')
  135.                 ->andWhere('a.countryCode = :countryCode')
  136.                 ->setParameter('name'$request->request->get('instName'))
  137.                 ->setParameter('countryCode'$countryCode)
  138.                 ->getQuery();
  139.             $instituteDetails $query->getResult();
  140.             if (count($instituteDetails) == 0) {
  141.                 try {
  142.                     $institute = new Institutions();
  143.                     $institute->setCountryCode($countryCode);
  144.                     $institute->setInstName($request->request->get('instName'));
  145.                     $institute->setInstNameEng($request->request->get('instNameEng'));
  146.                     $institute->setInstTypeID($request->request->get('instType'));
  147.                     $institute->setParentId($request->request->get('parentinstitute'));
  148.                     if (null == $institute->getParentId()) {
  149.                         $institute->setParentId(0);
  150.                     }
  151.                     $institute->setInstAddress($request->request->get('iaddress'));
  152.                     $institute->setAcronym($request->request->get('iacronym'));
  153.                     $institute->setAddr2($request->request->get('iaddress2'));
  154.                     $institute->setPostcode($request->request->get('ipostcode'));
  155.                     $institute->setCity($request->request->get('icity'));
  156.                     $institute->setState($request->request->get('istate'));
  157.                     $institute->setInstTel($request->request->get('icontact'));
  158.                     $institute->setInstFax($request->request->get('ifax'));
  159.                     $institute->setInstEmail($request->request->get('iemail'));
  160.                     $institute->setInstURL($request->request->get('iwebsite'));
  161.                     $institute->setEdmoCode($edmo_code);
  162.                     $institute->setActivities($request->request->get('iactivity'));
  163.                     if (null !== $request->request->get('isearegion')
  164.                         && is_array($request->request->get('isearegion'))
  165.                         && count($request->request->get('isearegion')) > 1
  166.                     ) {
  167.                         $iseaRegion implode(','$request->request->get('isearegion'));
  168.                     } else {
  169.                         $iseaRegion '';
  170.                     }
  171.                     $institute->setInstRegion($iseaRegion);
  172.                     $institute->setPopularity(0);
  173.                     if ($this->get('security.authorization_checker')->isGranted('ROLE_LME')) {
  174.                         $institute->setActivated(1);
  175.                     } else {
  176.                         $institute->setActivated(0);
  177.                     }
  178.                     $institute->setFDateEntered(new DateTime('now'));
  179.                     $institute->setLDateUpdated(new DateTime('now'));
  180.                     $institute->setCreatedBy($userId);
  181.                     $em $this->getDoctrine()->getManager();
  182.                     $em->persist($institute); //marks object to be saved in the next transaction.
  183.                     $em->flush(); //performs all saves and transactions.
  184.                     $logoFilename 'instituteLogo.jpg';
  185.                     $logoDirectory 'uploads/institutes/' $institute->getIdInst() . '/';
  186.                     if (null != $request->files->get('instLogo')) {
  187.                         $file $request->files->get('instLogo');
  188.                         $file->move($logoDirectory$logoFilename);
  189.                         $institute->setInstLogo($logoFilename);
  190.                     } else {
  191.                         if (isset($data['textLogo']) && $data['textLogo'] == '') {
  192.                             $institute->setInstLogo('');
  193.                             $filename $logoDirectory $logoFilename;
  194.                             if (file_exists($filename)) {
  195.                                 unlink($filename);
  196.                             }
  197.                         }
  198.                     }
  199.                     $em->persist($institute);
  200.                     $em->flush();
  201.                     return new JsonResponse(
  202.                         array(
  203.                             'status' => 1,
  204.                             'id' => $institute->getIdInst(),
  205.                             'message' => '<br /><br /><h3 class="text-success">institute created</h3>
  206.                                 Your new institute has been created successfully<br />
  207.                                 and should be already selected in the list of institutes.<br />
  208.                                 If this is not the case, please select your newly created institute in the list.
  209.                                 <br /><br />'
  210.                         )
  211.                     );
  212.                 } catch (Exception $e) {
  213.                     return new JsonResponse(
  214.                         array(
  215.                             'status' => 0,
  216.                             'message' => 'Error in adding Institute. Please try again later.'
  217.                         )
  218.                     );
  219.                 }
  220.             } else {
  221.                 foreach ($instituteDetails as $instituteDetail) {
  222.                     $existingInstitutes[] = '<a 
  223.                             href="/institute/' $instituteDetail['idInst'] . '" 
  224.                             target="_new">' .
  225.                         $instituteDetail['instName'] .
  226.                     '</a>';
  227.                 }
  228.                 $existingInstitutes implode(','$existingInstitutes);
  229.                 return new JsonResponse(
  230.                     array(
  231.                         'status' => 2,
  232.                         'message' => "Institute name/acronym already exists. ($existingInstitutes)"
  233.                     )
  234.                 );
  235.             }
  236.         } else {
  237.             return new JsonResponse(
  238.                 array(
  239.                     'status' => 2,
  240.                     'message' => 'you do not have the correct rights to do this'
  241.                 )
  242.             );
  243.         }
  244.     }
  245.     /**
  246.      * get all existing institutes
  247.      *
  248.      * @return Response
  249.      */
  250.     public function getAllInstitutions(): Response
  251.     {
  252.         $institutesQuery $this->getAllInstitutionsQuery();
  253.         $institutesTmp $institutesQuery->execute();
  254.         $institutes = array();
  255.         foreach($institutesTmp as $institute) {
  256.             $institutes[$institute['idInst']] = $institute;
  257.         }
  258.         return new Response(json_encode($institutes));
  259.     }
  260.     /**
  261.      * get the query to get all existing institutes
  262.      *
  263.      * @param string $query
  264.      *
  265.      */
  266.     private function getAllInstitutionsQuery(
  267.         $query ''
  268.     ) {
  269.         //get the institutes
  270.         $repo $this->getDoctrine()
  271.             ->getRepository('OceanExpertBundle:Institutions');
  272.         $institutes $repo->createQueryBuilder('i');
  273.         $institutes->select('
  274.             i.idInst, 
  275.             i.parentId,
  276.             i.instTypeId,
  277.             i.instName,
  278.             i.instNameEng,
  279.             i.countryCode,
  280.             c.country,
  281.             it.insttypeName'
  282.         );
  283.         $institutes->leftJoin(
  284.             'OceanExpertBundle:Countries',
  285.             'c',
  286.             'WITH',
  287.             'i.countryCode = c.idCountry');
  288.         $institutes->leftJoin(
  289.             'OceanExpertBundle:Insttypes',
  290.             'it',
  291.             'WITH',
  292.             'i.instTypeId = it.idInsttype');
  293.         //non-admin users only get the active ones
  294.         if (!$this->get('security.authorization_checker')->isGranted('ROLE_SUPERADMIN')
  295.             && !$this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')
  296.         ) {
  297.             $institutes->where('i.activated = 1');
  298.         }
  299.         if (trim($query) != '') {
  300.             $institutes->andwhere('i.instName LIKE :query OR i.instNameEng LIKE :query');
  301.             $institutes->setParameter(
  302.                 'query',
  303.                 '%' trim($query) . '%'
  304.             );
  305.         }
  306.         //store all the found institutes to be able to find the name of the parents
  307.         $institutesQuery $institutes->getQuery();
  308.         return $institutesQuery;
  309.     }
  310.     /**
  311.      * show all existing institutes
  312.      *
  313.      * @param Request $request
  314.      *
  315.      * @return Response|void
  316.      */
  317.     function viewInstitutesActionRequest $request ): Response
  318.     {
  319.         $limits = array(
  320.             10 => 10,
  321.             25 => 25,
  322.             50 => 50,
  323.             100 => 100,
  324.             500 => 500
  325.         );
  326.         $limit $request->query->get('limit'10);
  327.         $query $request->query->get('search''');
  328.         $orderby $request->query->get('orderby''order');
  329.         $dir $request->query->get('dir''asc');
  330.         //store all the found institutes to be able to find the name of the parents
  331.         $institutesQuery $this->getAllInstitutionsQuery($query);
  332.         $institutesTmp $institutesQuery->execute();
  333.         foreach($institutesTmp as $institute) {
  334.             $parentInstitutes[$institute['idInst']] = $institute['instName'];
  335.         }
  336.         $paginator $this->get('knp_paginator');
  337.         $data $paginator->paginate(
  338.             $institutesQuery,
  339.             $request->query->getInt('page'1),
  340.             $limit,
  341.             array(
  342.                 'pageParameterName' => 'page',
  343.                 'sortDirectionParameterName' => 'dir',
  344.                 'defaultSortDirection' => 'desc'
  345.             )
  346.         );
  347.         $data->setCustomParameters([
  348.             'limits' => $limits,
  349.             'title' => 'Institutes'
  350.         ]);
  351.         return $this->render(
  352.             'Institute/viewInstitutes.html.twig',
  353.             array(
  354.                 'institutesData' => $data,
  355.                 'parentInstitutes' => $parentInstitutes
  356.             )
  357.         );
  358.     }
  359.     public function viewInstitutionAction($instIdRequest $request)
  360.     {
  361.         //dump($instId);
  362.         if (!is_numeric($instId)) {
  363.             return $this->render(
  364.                 'Exception/error.html.twig',
  365.                 array(
  366.                     'message' => 'We need at least an institute id to view/edit an institute.'
  367.                 )
  368.             );
  369.         }
  370.         /*
  371.          * container to hold to OIH/ODIS JSON-LD info
  372.          * see also https://book.oceaninfohub.org/thematics/expinst/README.html
  373.          * in the end we will need something like
  374.          * {
  375.                 "@context": {
  376.                     "@vocab": "https://schema.org/"
  377.                 },
  378.                 "@id": "https://example.org/id/org/x",
  379.                 "@type": "Organization",
  380.                 "address": {
  381.                     "@type": "PostalAddress",
  382.                     "addressLocality": "Paris, France",
  383.                     "postalCode": "F-75002",
  384.                     "streetAddress": "38 avenue de l'Opera"
  385.                 },
  386.                 "email": "secretariat(at)example.org",
  387.                 "name": "Organization X",
  388.                 "description": "Description of org ...",
  389.                 "telephone": "( 33 1) 42 68 53 00",
  390.                 "member": [
  391.                     {
  392.                         "@type": "Organization",
  393.                         "name": "Organization A",
  394.                         "description": "Org A is a potential parent organization of Org X"
  395.                     }
  396.                 ],
  397.                 "identifier": {
  398.                     "@id": "https://grid.ac/institutes/grid.475727.4",
  399.                     "@type": "PropertyValue",
  400.                     "description": "UN Department of Economic and Social Affairs Sustainable Development",
  401.                     "propertyID": "https://registry.identifiers.org/registry/grid",
  402.                     "url": "https://grid.ac/institutes/grid.475727.4"
  403.                 }
  404.             }
  405.          */
  406.         $OIHData = array(
  407.             '@context' => array(
  408.                 '@vocab' => 'https://schema.org/'
  409.             ),
  410.             '@id' => "https://oceanexpert.org/institute/$instId",
  411.             '@type' => 'Organization'
  412.         );
  413.         $qb $this->getDoctrine()->getManager()->createQueryBuilder();
  414.         $qb->add(
  415.             'select',
  416.             'ins.idInst,
  417.             ins.instTypeId, 
  418.             ins.instName, 
  419.             ins.instNameEng, 
  420.             ins.instAddress, 
  421.             ins.addr2, 
  422.             ins.city, 
  423.             ins.state, 
  424.             ins.postcode, 
  425.             ins.countryCode, 
  426.             ins.acronym, 
  427.             ins.instLogo, 
  428.             ins.instTel, 
  429.             ins.instFax, 
  430.             ins.instEmail, 
  431.             ins.instUrl, 
  432.             ins.edmoCode,
  433.             ins.instRegion, 
  434.             ins.activities, 
  435.             ins.popularity, 
  436.             ins.activated, 
  437.             ins.fDateEntered, 
  438.             ins.lDateUpdated, 
  439.             ins.createdBy, 
  440.             ins.lastEditBy,
  441.             it.insttypeName,
  442.             c.country, 
  443.             c.countryCode as instCtryCode,
  444.             ins.parentId as parentIdInst, 
  445.             p.instName as parentInstName, 
  446.             p.instNameEng as parentInstNameEng, 
  447.             p.acronym as parentAcronym, 
  448.             p.instLogo as parentInstLogo')
  449.             ->add(
  450.                 'from',
  451.                 'OceanExpertBundle:Institutions ins')
  452.             ->leftJoin(
  453.                 'OceanExpertBundle:Insttypes',
  454.                 'it',
  455.                 'WITH',
  456.                 'it.idInsttype = ins.instTypeId')
  457.             ->leftJoin(
  458.                 'OceanExpertBundle:Countries',
  459.                 'c',
  460.                 'WITH',
  461.                 'c.idCountry = ins.countryCode')
  462.             ->leftJoin(
  463.                 'OceanExpertBundle:Institutions',
  464.                 'p',
  465.                 'WITH',
  466.                 'p.idInst = ins.parentId AND p.activated = 1')
  467.             ->where('ins.idInst = :instId')
  468.             ->setParameter(
  469.                 'instId',
  470.                 $instId
  471.             );
  472.         /*
  473.         $institute = $this->getDoctrine()
  474.             ->getRepository('OceanExpertBundle:Institutions')
  475.             ->findOneByIdInst($instId);
  476.         */
  477.         //get some info about the user asking this info
  478.         $userId '-1';
  479.         $security_context $this->get('security.authorization_checker');
  480.         if ($security_context->isGranted('IS_AUTHENTICATED_FULLY')) {
  481.             $userId $this->get('security.token_storage')->getToken()->getUser()->getId();
  482.         }
  483.         /*
  484.         if (isset($institute)
  485.             && (($security_context->isGranted('ROLE_GLOBAL_EDITOR'))
  486.                 or ($userId == $institute->getCreatedBy())
  487.                 or ($userId == $institute->getLastEditBy())
  488.             )
  489.         ) {
  490.             //@todo what happens here??? Arno 23/06/2021
  491.         } else {
  492.         }
  493.         */
  494.         if (!$security_context->isGranted('ROLE_GLOBAL_EDITOR') ) {
  495.             $qb->andWhere('ins.activated = 1');
  496.         }
  497.         $institute $qb->getQuery()->getResult();
  498.         if (!$institute) {
  499.             return $this->render(
  500.                 'Exception/error.html.twig',
  501.                 array(
  502.                     'message' => 'the institute with id "' $instId '" does not exist or has not been approved by an OceanExpert editor (yet)'
  503.                 )
  504.             );
  505.         } else {
  506.             $institute $institute[0];
  507.         }
  508.         $OIHData['name'] = $institute['instName'];
  509.         if (isset($institute['instUrl'])
  510.             && $institute['instUrl'] != ''
  511.         ) {
  512.             $OIHData['url'] = $institute['instUrl'];
  513.         } else {
  514.             $OIHData['url'] = "https://oceanexpert.org/institute/$instId";
  515.         }
  516.         if (isset($institute['instTel'])
  517.             && $institute['instTel'] != ''
  518.         ) {
  519.             $OIHData['telephone'] = $institute['instTel'];
  520.         }
  521.         if (isset($institute['parentIdInst'])
  522.             && $institute['parentIdInst'] !== ''
  523.             && $institute['parentIdInst'] !== 0
  524.         ) {
  525.             $OIHData['memberOf'] = array(
  526.                 '@type' => 'Organization',
  527.                 '@id' => 'https://oceanexpert.org/institute/' $institute['parentIdInst'],
  528.                 'url' => 'https://oceanexpert.org/institute/' $institute['parentIdInst'],
  529.                 'name' => $institute['parentInstName']
  530.             );
  531.         }
  532.         //get the members of the institute
  533.         $qb $this->getDoctrine()->getManager()->createQueryBuilder();
  534.         $qb->add(
  535.             'select',
  536.             'i.idInd,
  537.             i.fname,
  538.             i.mname,
  539.             i.sname,
  540.             i.jobtitle,
  541.             i.deceased,
  542.             i.retired, 
  543.             i.qualityChecked')
  544.             ->add(
  545.                 'from',
  546.                 'OceanExpertBundle:Indiv i')
  547.             ->leftJoin(
  548.                 'OceanExpertBundle:IndivInstitution',
  549.                 'iins',
  550.                 'WITH',
  551.                 'iins.idInd = i.idInd')
  552.             ->leftJoin(
  553.                 'OceanExpertBundle:Institutions',
  554.                 'ins',
  555.                 'WITH',
  556.                 'ins.idInst = iins.idInst')
  557.             ->where('ins.idInst = :instId')
  558.             ->andWhere('i.status = 1')
  559.             ->orderBy(
  560.                 'i.sname',
  561.                 'ASC')
  562.             ->setParameter(
  563.                 'instId',
  564.                 $instId
  565.             );
  566.         $instituteMembers $qb->getQuery()->getResult();
  567.         if (is_array($instituteMembers)) {
  568.             foreach ($instituteMembers as $member) {
  569.                 $OIHData['member'][] = array(
  570.                     'member' => array(
  571.                         '@type' => 'Person',
  572.                         '@id' => 'https://oceanexpert.org/expert/' $member['idInd'],
  573.                         'url' => 'https://oceanexpert.org/expert/' $member['idInd'],
  574.                         'name' => $member['fname'] . ' ' $member['mname'] . ' ' $member['sname']
  575.                     )
  576.                 );
  577.             }
  578.         }
  579.         //what page with members are we showing
  580.         $paginator $this->get('knp_paginator');
  581.         $memberLimit $request->query->getInt('mlimit'5);
  582.         $memberPage $request->query->getInt('members'1);
  583.         if (!in_array($memberLimit, array(510"All"))) {
  584.             $memberLimit 5;
  585.             $memberPage 1;
  586.         }
  587.         if ($memberLimit == "All") {
  588.             $memberLimit 9999;
  589.             $memberPage 1;
  590.         }
  591.         $members $paginator->paginate(
  592.             $instituteMembers,
  593.             $memberPage,
  594.             $memberLimit,
  595.             array(
  596.                 'pageParameterName' => 'members',
  597.                 'sortDirectionParameterName' => 'dir'
  598.             )
  599.         );
  600.         //get the members of the child institutes
  601.         $qb $this->getDoctrine()->getManager()->createQueryBuilder();
  602.         $qb->add(
  603.             'select',
  604.             'i.idInd,
  605.             i.fname,
  606.             i.mname,
  607.             i.sname,
  608.             i.jobtitle,
  609.             i.deceased,
  610.             i.retired, 
  611.             i.qualityChecked, 
  612.             ins.idInst,
  613.             ins.instName')
  614.             ->add(
  615.                 'from',
  616.                 'OceanExpertBundle:Indiv i')
  617.             ->leftJoin(
  618.                 'OceanExpertBundle:IndivInstitution',
  619.                 'iins',
  620.                 'WITH',
  621.                 'iins.idInd = i.idInd')
  622.             ->leftJoin(
  623.                 'OceanExpertBundle:Institutions',
  624.                 'ins',
  625.                 'WITH',
  626.                 'ins.idInst = iins.idInst')
  627.             ->where('ins.parentId = :instId')
  628.             ->andWhere('i.status = 1')
  629.             ->andWhere('ins.activated = 1')
  630.             ->orderBy(
  631.                 'i.sname',
  632.                 'ASC')
  633.             ->setParameter(
  634.                 'instId',
  635.                 $instId
  636.             );
  637.         $childInstituteMembers $qb->getQuery()->getResult();
  638.         if (is_array($childInstituteMembers)) {
  639.             foreach ($childInstituteMembers as $member) {
  640.                 $instUrl 'https://oceanexpert.org/institute/' $member['idInst'];
  641.                 $instName $member['instName'];
  642.                 $OIHData['member'][] = array(
  643.                     'member' => array(
  644.                         '@type' => 'Person',
  645.                         '@id' => 'https://oceanexpert.org/expert/' $member['idInd'],
  646.                         'url' => 'https://oceanexpert.org/expert/' $member['idInd'],
  647.                         'name' => $member['fname'] . ' ' $member['mname'] . ' ' $member['sname'],
  648.                         'description' => "is member of '$instName' ($instUrl), a child of this organization"
  649.                     )
  650.                 );
  651.             }
  652.         }
  653.         //what page with child members are we showing
  654.         $childMemberLimit $request->query->get('cmlimit');
  655.         if (!in_array($childMemberLimit, array(510"All"))) {
  656.             $childMemberLimit 5;
  657.         }
  658.         if ($childMemberLimit == "All") {
  659.             $childMemberLimit 9999;
  660.         }
  661.         $childMembers $paginator->paginate(
  662.             $childInstituteMembers,
  663.             $request->query->getInt('childmembers'1),
  664.             $childMemberLimit,
  665.             array(
  666.                 'pageParameterName' => 'childmembers',
  667.                 'sortDirectionParameterName' => 'dir'
  668.             )
  669.         );
  670.         //get the child institutes
  671.         $qb $this->getDoctrine()->getManager()->createQueryBuilder();
  672.         $qb->add(
  673.             'select',
  674.             'ins.idInst,
  675.             ins.instTypeId, 
  676.             ins.instName, 
  677.             ins.instNameEng, 
  678.             ins.instAddress, 
  679.             ins.addr2, 
  680.             ins.city, 
  681.             ins.state, 
  682.             ins.postcode, 
  683.             ins.countryCode, 
  684.             ins.acronym, 
  685.             ins.instLogo, 
  686.             ins.instTel, 
  687.             ins.instFax, 
  688.             ins.instEmail, 
  689.             ins.instUrl, 
  690.             ins.edmoCode,
  691.             ins.instRegion, 
  692.             ins.activities, 
  693.             ins.popularity, 
  694.             ins.activated, 
  695.             ins.fDateEntered, 
  696.             ins.lDateUpdated, 
  697.             ins.createdBy, 
  698.             ins.lastEditBy,
  699.             it.insttypeName,
  700.             c.country, 
  701.             c.countryCode as instCtryCode')
  702.             ->add(
  703.                 'from',
  704.                 'OceanExpertBundle:Institutions ins')
  705.             ->leftJoin(
  706.                 'OceanExpertBundle:Insttypes',
  707.                 'it',
  708.                 'WITH',
  709.                 'it.idInsttype = ins.instTypeId')
  710.             ->leftJoin(
  711.                 'OceanExpertBundle:Countries',
  712.                 'c',
  713.                 'WITH',
  714.                 'c.idCountry = ins.countryCode')
  715.             ->where('ins.parentId = :instId')
  716.             ->andWhere('ins.activated = 1')
  717.             ->orderBy(
  718.                 'ins.instName',
  719.                 'ASC')
  720.             ->setParameter(
  721.                 'instId',
  722.                 $instId);
  723.         $childInstitutes $qb->getQuery()->getResult();
  724.         if (is_array($childInstitutes)) {
  725.             foreach ($childInstitutes as $member) {
  726.                 $OIHData['member'][] = array(
  727.                     'member' => array(
  728.                         '@type' => 'Organization',
  729.                         '@id' => 'https://oceanexpert.org/institute/' $member['idInst'],
  730.                         'url' => 'https://oceanexpert.org/institute/' $member['idInst'],
  731.                         'name' => $member['instName']
  732.                     )
  733.                 );
  734.             }
  735.         }
  736.         //what page with child institutes are we showing
  737.         $childInstitutes = array();
  738.         $childInstituteLimit $request->query->get('cilimit');
  739.         if (!in_array($childInstituteLimit, array(510"All"))) {
  740.             $childInstituteLimit 5;
  741.         }
  742.         if ($childInstituteLimit == "All") {
  743.             $childInstituteLimit 9999;
  744.         }
  745.         $childInstitutes $paginator->paginate(
  746.             $childInstitutes,
  747.             $request->query->getInt('childinstitutes'1),
  748.             $childInstituteLimit,
  749.             array(
  750.                 'pageParameterName' => 'childinstitutes',
  751.                 'sortDirectionParameterName' => 'dir'
  752.             )
  753.         );
  754.         //get the sea regions of the institute
  755.         $repository $this->getDoctrine()
  756.             ->getRepository('OceanExpertBundle:Regions');
  757.         $institute['seaRegions'] = $repository->createQueryBuilder('r')
  758.             ->select(
  759.                 'r.idRegion, 
  760.                 r.name')
  761.             ->where('r.idRegion IN (:seaRegions)')
  762.             ->setParameter(
  763.                 'seaRegions',
  764.                 array_values(
  765.                     explode(
  766.                         ',',
  767.                         $institute['instRegion']
  768.                     )
  769.                 )
  770.             )
  771.             ->getQuery()->getResult();
  772.         //get the list of all available sea regions
  773.         $institute['availableSeaRegions'] = $this->getDoctrine()
  774.             ->getRepository('OceanExpertBundle:Regions')
  775.             ->createQueryBuilder('e')
  776.             ->select('e.idRegion as id, e.name')
  777.             ->orderBy('e.name')
  778.             ->getQuery()
  779.             ->getResult(AbstractQuery::HYDRATE_ARRAY);
  780.         //what are we trying to do here - edit or view
  781.         $routeName $request->get('_route');
  782.         if ($routeName == 'edit_institute'
  783.             || $routeName == 'edit_institution'
  784.         ) {
  785.             $securityContext $this->container->get('security.authorization_checker');
  786.             if ($securityContext->isGranted('IS_AUTHENTICATED_FULLY')) {
  787.                 $user $this->container->get('security.token_storage')->getToken()->getUser();
  788.                 //let's check if the logged-in user has a 'real' profile
  789.                 //the mandatory profile fields are all filled and the expert is active
  790.                 $em $this->getDoctrine()->getManager();
  791.                 $userId $this->get('security.token_storage')->getToken()->getUser()->getId();
  792.                 if (!SecurityController::checkUserProfile($em$userId)) {
  793.                     return $this->redirect(
  794.                         $this->generateUrl(
  795.                             'user_profile_edit'
  796.                         )
  797.                     );
  798.                 }
  799.                 if ($user->getId() == $institute['createdBy']
  800.                     || $this->get('security.authorization_checker')->isGranted('ROLE_GLOBAL_EDITOR')
  801.                 ) {
  802.                     if (!empty($data $request->request->all())) {
  803.                         $em $this->getDoctrine()->getManager();
  804.                         $inst $em
  805.                             ->getRepository('OceanExpertBundle:Institutions')
  806.                             ->findOneBy(
  807.                                 array(
  808.                                     'idInst' => $instId
  809.                                 )
  810.                             );
  811.                         if ($inst) {
  812.                             if (trim($data['iedmo']) == ''
  813.                                 || !is_numeric($data['iedmo'])
  814.                             ) {
  815.                                 $edmo_code 0;
  816.                             } else {
  817.                                 $edmo_code $data['iedmo'];
  818.                             }
  819.                             $inst->setInstTypeId($data['instType']);
  820.                             $inst->setInstName($data['instName']);
  821.                             $inst->setInstNameEng($data['instNameEng']);
  822.                             $inst->setInstAddress($data['iaddress']);
  823.                             $inst->setAddr2($data['iaddressline2']);
  824.                             $inst->setCity($data['icity']);
  825.                             $inst->setState($data['istate']);
  826.                             $inst->setPostcode($data['ipostcode']);
  827.                             $inst->setCountryCode($data['icountryCode']);
  828.                             $inst->setAcronym($data['iacronym']);
  829.                             $inst->setInstTel($data['icontact']);
  830.                             $inst->setInstFax($data['ifax']);
  831.                             $inst->setInstEmail($data['iemail']);
  832.                             $inst->setInstUrl($data['iwebsite']);
  833.                             $inst->setEdmoCode($edmo_code);
  834.                             $inst->setActivities($data['iactivity']);
  835.                             if ($data['parentinstitute'] === '' ) {
  836.                                 $data['parentinstitute'] = 0;
  837.                             }
  838.                             $inst->setParentId($data['parentinstitute']);
  839.                             if (isset($data['studyregion'])
  840.                                 && count($data['studyregion']) > 0
  841.                             ) {
  842.                                 $inst->setInstRegion(implode(','$data['studyregion']));
  843.                             } else {
  844.                                 $inst->setInstRegion('');
  845.                             }
  846.                             $inst->setLDateUpdated(new DateTime("now"));
  847.                             $inst->setLastEditBy($user->getId());
  848.                             if (null != $request->files->get('instLogo')) {
  849.                                 $file $request->files->get('instLogo');
  850.                                 $filename 'instituteLogo.jpg';
  851.                                 $directory 'uploads/institutes/' $instId '/';
  852.                                 $file->move($directory$filename);
  853.                                 $inst->setInstLogo($filename);
  854.                             } else {
  855.                                 if (isset($data['textLogo'])
  856.                                     && $data['textLogo'] === ''
  857.                                 ) {
  858.                                     $inst->setInstLogo('');
  859.                                     $filename 'uploads/institutes/' $inst->getIdInst() . '/instituteLogo.jpg';
  860.                                     if (file_exists($filename)) {
  861.                                         unlink($filename);
  862.                                     }
  863.                                 }
  864.                             }
  865.                             $em->persist($inst);
  866.                             $em->flush();
  867.                             return $this->redirect(
  868.                                 $this->generateUrl(
  869.                                     'edit_institute_success',
  870.                                     array(
  871.                                         'idInst' => $instId
  872.                                     )
  873.                                 )
  874.                             );
  875.                         } else {
  876.                             return $this->render(
  877.                                 'Exception/error.html.twig',
  878.                                 array(
  879.                                     'message' => 'you are trying to edit an institute with id "' $instId '" that does not exist'
  880.                                 )
  881.                             );
  882.                         }
  883.                     }
  884.                     $countries $this->getDoctrine()
  885.                         ->getRepository('OceanExpertBundle:Countries')
  886.                         ->findBy(
  887.                             [],
  888.                             ['country' => 'ASC']
  889.                         );
  890.                     //get the list of all known institutes
  891.                     $instituteTypes = [];
  892.                     $instTypes $this->getDoctrine()
  893.                         ->getRepository('OceanExpertBundle:InstTypes')
  894.                         ->findAll();
  895.                     foreach ($instTypes as $instType) {
  896.                         $instituteTypes[] = array(
  897.                             'id' => $instType->getIdInsttype(),
  898.                             'name' => $instType->getInsttypeName()
  899.                         );
  900.                     }
  901.                     $countryInstitutes $this->getDoctrine()
  902.                         ->getRepository('OceanExpertBundle:Institutions')
  903.                         ->findBy(
  904.                             array(
  905.                                 'countryCode' => $institute['countryCode']
  906.                             ),
  907.                             array(
  908.                                 'instName' => 'ASC'
  909.                             )
  910.                         );
  911.                     return $this->render(
  912.                         'Institute/editInstitute.html.twig',
  913.                         array(
  914.                             'institute' => $institute,
  915.                             'instituteTypes' => $instituteTypes,
  916.                             'countries' => $countries,
  917.                             'countryInstitutes' => $countryInstitutes,
  918.                         )
  919.                     );
  920.                 } else {
  921.                     return $this->render(
  922.                         'Exception/error.html.twig',
  923.                         array(
  924.                             'message' => 'you do not have sufficient rights to edit the institute with id "' $instId '"'
  925.                         )
  926.                     );
  927.                 }
  928.             } else {
  929.                 return $this->render(
  930.                     'Exception/error.html.twig',
  931.                     array(
  932.                         'message' => 'you need to log in to edit the institute with id "' $instId '"'
  933.                     )
  934.                 );
  935.             }
  936.         }
  937.         //show the institute info
  938.         $addressFormatRepository = new AddressFormatRepository();
  939.         $countryRepository = new CountryRepository();
  940.         $subdivisionRepository = new SubdivisionRepository();
  941.         $formatter = new DefaultFormatter($addressFormatRepository$countryRepository$subdivisionRepository);
  942.         $address = new Address();
  943.         $address $address
  944.             ->withCountryCode($institute['instCtryCode'])
  945.             ->withAdministrativeArea($institute['state'])
  946.             ->withLocality($institute['city'])
  947.             ->withPostalCode($institute['postcode'])
  948.             ->withAddressLine2($institute['addr2'])
  949.             ->withAddressLine1($institute['instAddress']);
  950.         $institute['address'] = $formatter->format($address);
  951.         //make the address
  952.         $streetAddress $institute['instAddress'];
  953.         if (trim($institute['addr2']) != '') {
  954.             $streetAddress .= ', ' trim($institute['addr2']);
  955.         }
  956.         $address $streetAddress ', ' .
  957.             $institute['postcode'] . ' ' $institute['city'] . ', ' .
  958.             $institute['country'];
  959.         $OIHData['location'] = array(
  960.             '@type' => 'Place',
  961.             'address' => trim($address)
  962.         );
  963.         $OIHData['address'] = array(
  964.             '@type' => 'PostalAddress',
  965.             'addressLocality' => $institute['city'] . ', ' $institute['country'],
  966.             'postalCode' => $institute['postcode'],
  967.             'streetAddress' => $streetAddress
  968.         );
  969.         /*
  970.         $OIHData['location'] = array(
  971.             '@type' => 'Place',
  972.             'address' => array(
  973.                 '@type' => 'PostalAddress',
  974.                 'addressLocality' => $institute['city'] . ', ' . $institute['country'],
  975.                 'postalCode' => $institute['postcode'],
  976.                 'streetAddress' => $streetAddress
  977.             )
  978.         );
  979.         */
  980.         if ($institute['createdBy']) {
  981.             $institute['createdId'] = $institute['createdBy'];
  982.             $institute['createdBy'] = $this->getUserById($institute['createdBy']);
  983.         }
  984.         if ($institute['lastEditBy']) {
  985.             $institute['lastEditId'] = $institute['lastEditBy'];
  986.             $institute['lastEditBy'] = $this->getUserById($institute['lastEditBy']);
  987.         }
  988.         $limits = array(
  989.             'memberlimit' => array(
  990.                 'options' => array(
  991.                     '5' => 5,
  992.                     '10' => 10,
  993.                     '9999' => 'All'
  994.                 ),
  995.                 'selected' => $memberLimit
  996.             ),
  997.             'childmemberlimit' => array(
  998.                 'options' => array(
  999.                     '5' => 5,
  1000.                     '10' => 10,
  1001.                     '9999' => 'All'
  1002.                 ),
  1003.                 'selected' => $childMemberLimit
  1004.             ),
  1005.             'childinstitutelimit' => array(
  1006.                 'options' => array(
  1007.                     '5' => 5,
  1008.                     '10' => 10,
  1009.                     '9999' => 'All'
  1010.                 ),
  1011.                 'selected' => $childInstituteLimit
  1012.             ),
  1013.         );
  1014.         $OIHData json_encode(
  1015.             $OIHData,
  1016.             JSON_UNESCAPED_UNICODE JSON_UNESCAPED_SLASHES JSON_NUMERIC_CHECK
  1017.         );
  1018.         return $this->render(
  1019.             'Institute/viewInstitute.html.twig',
  1020.             array(
  1021.                 'OIHData' => $OIHData,
  1022.                 'institute' => $institute,
  1023.                 'members' => $members,
  1024.                 'limits' => $limits,
  1025.                 'childmembers' => $childMembers,
  1026.                 'childinstitutes' => $childInstitutes
  1027.             )
  1028.         );
  1029.     }
  1030.     public function getUserById($id '')
  1031.     {
  1032.         $updatedBy $this->getDoctrine()->getRepository('OceanExpertBundle:Indiv')->findOneByIdInd($id);
  1033.         if ($updatedBy) {
  1034.             $name $updatedBy->getfname() . " " $updatedBy->getsname();
  1035.         } else {
  1036.             $name false;
  1037.         }
  1038.         return $name;
  1039.     }
  1040.     public function activateInstituteAction($instituteId)
  1041.     {
  1042.         $security_context $this->get('security.authorization_checker');
  1043.         if ($security_context->isGranted('ROLE_GLOBAL_EDITOR')) {
  1044.             if ($instituteId) {
  1045.                 $institute $this->getDoctrine()
  1046.                     ->getRepository('OceanExpertBundle:Institutions')
  1047.                     ->findOneByIdInst($instituteId);
  1048.                 if ($institute) {
  1049.                     $institute->setActivated(1);
  1050.                     $institute->setLDateUpdated(new DateTime("now"));
  1051.                     $institute->setLastEditBy(
  1052.                         $this->get('security.token_storage')
  1053.                             ->getToken()
  1054.                             ->getUser()
  1055.                             ->getId()
  1056.                     );
  1057.                     $em $this->getDoctrine()->getManager();
  1058.                     $em->persist($institute); //marks object to be saved in the next transaction.
  1059.                     $em->flush(); //performs all saves and transactions.
  1060.                 }
  1061.                 return new JsonResponse(
  1062.                     array(
  1063.                         'status' => true,
  1064.                         'msg' => 'Record updated successfully'
  1065.                     )
  1066.                 );
  1067.             } else {
  1068.                 return new Response('Cannot update record.');
  1069.             }
  1070.         }
  1071.         return new Response('Cannot update record.');
  1072.     }
  1073.     public function deactivateInstituteAction($instituteId)
  1074.     {
  1075.         $security_context $this->get('security.authorization_checker');
  1076.         if ($security_context->isGranted('ROLE_GLOBAL_EDITOR')) {
  1077.             if ($instituteId) {
  1078.                 $institute $this->getDoctrine()
  1079.                     ->getRepository('OceanExpertBundle:Institutions')
  1080.                     ->findOneByIdInst($instituteId);
  1081.                 if ($institute) {
  1082.                     $institute->setActivated(0);
  1083.                     $institute->setLDateUpdated(new DateTime("now"));
  1084.                     $institute->setLastEditBy(
  1085.                         $this->get('security.token_storage')
  1086.                             ->getToken()
  1087.                             ->getUser()
  1088.                             ->getId());
  1089.                     $em $this->getDoctrine()->getManager();
  1090.                     $em->persist($institute); //marks object to be saved in the next transaction.
  1091.                     $em->flush(); //performs all saves and transactions.
  1092.                 }
  1093.                 return new JsonResponse(
  1094.                     array(
  1095.                         'status' => true,
  1096.                         'msg' => 'updated successfully'
  1097.                     )
  1098.                 );
  1099.             } else {
  1100.                 return new Response('Cannot update record.');
  1101.             }
  1102.         }
  1103.         return new Response('Cannot update record.');
  1104.     }
  1105.     /**
  1106.      * show this page when the institute has been edited successfully
  1107.      *
  1108.      * @param int $idInst
  1109.      *
  1110.      * @return Response
  1111.      */
  1112.     public function editInstituteSuccessAction($idInst)
  1113.     {
  1114.         return $this->render(
  1115.             'Institute/editInstituteSuccess.html.twig',
  1116.             array(
  1117.                 'idInst' => $idInst
  1118.             )
  1119.         );
  1120.     }
  1121.     /**
  1122.      * @param Request $request
  1123.      *
  1124.      * @return JsonResponse
  1125.      */
  1126.     public function getInstitutionsAjaxAction(Request $request)
  1127.     {
  1128.         if (!null == $request->query->get('q')) {
  1129.             $inst $request->query->get('q');
  1130.             $em $this->getDoctrine()->getManager();
  1131.             $qb $em->createQueryBuilder();
  1132.             $qb->select('i.idInst as id,i.instName');
  1133.             $qb->from('OceanExpertBundle:Institutions''i');
  1134.             $qb->where('i.instName like :name OR i.acronym like :name');
  1135.             if (!null == $request->query->get('instId')) {
  1136.                 $qb->andWhere('i.idInst != :instId');
  1137.                 $qb->setParameter('instId'$request->query->get('instId'));
  1138.             }
  1139.             $qb->andWhere('i.activated = 1');
  1140.             $qb->setParameter('name''%' $inst '%');
  1141.             $qb->setParameter('name''%' $inst '%');
  1142.             $qb->orderBy('i.instName''ASC');
  1143.             $institutes $qb->getQuery()->getResult();
  1144.             $data = array();
  1145.             if ($institutes) {
  1146.                 $data = array(
  1147.                     'incomplete_results' => false,
  1148.                     'items' => $institutes,
  1149.                     'total_count' => count($institutes),
  1150.                 );
  1151.             } else {
  1152.                 $data = array(
  1153.                     'incomplete_results' => false,
  1154.                     'items' => array(),
  1155.                     'total_count' => 0,
  1156.                 );
  1157.             }
  1158.             return new JsonResponse($data);
  1159.         }
  1160.         return new JsonResponse();
  1161.     }
  1162. }