<?php
namespace OceanExpertBundle\Controller;
use DateTime;
use Doctrine\ORM\AbstractQuery;
use Doctrine\ORM\Query;
use FOS\UserBundle\Mailer\MailerInterface;
use FOS\UserBundle\Model\UserManagerInterface;
use FOS\UserBundle\Util\TokenGeneratorInterface;
use OceanExpertBundle\Entity\Indiv;
use OceanExpertBundle\Entity\MemberEditsCountry;
use OceanExpertBundle\Entity\MemberEditsInstitution;
use OceanExpertBundle\Entity\MemberGroups;
use OceanExpertBundle\Entity\ProfileImages;
use OceanExpertBundle\Entity\IndivMeta;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use CommerceGuys\Addressing\Model\Address;
use CommerceGuys\Addressing\Formatter\DefaultFormatter;
use CommerceGuys\Addressing\Repository\AddressFormatRepository;
use CommerceGuys\Addressing\Repository\CountryRepository;
use CommerceGuys\Addressing\Repository\SubdivisionRepository;
use Symfony\Component\HttpFoundation\JsonResponse;
class ProfileController extends AbstractController
{
private UserManagerInterface $fosUserManager;
private TokenGeneratorInterface $fosTokenGenerator;
private MailerInterface $fosMailer;
public function __construct(
UserManagerInterface $fosUserManager,
TokenGeneratorInterface $fosTokenGenerator,
MailerInterface $fosMailer
){
$this->fosUserManager = $fosUserManager;
$this->fosTokenGenerator = $fosTokenGenerator;
$this->fosMailer = $fosMailer;
}
/**
* @param string $user
* @param Request $request
*
* @return Response
*/
public function viewProfileAction(Request $request, string $user = ''): Response
{
$loggedUser = $this->get('security.token_storage')->getToken()->getUser();
$isLoggedIn = $this->get('security.authorization_checker')->isGranted('ROLE_USER');
if ($isLoggedIn
&& $user == 'me'
) {
//get the user id from the currently logged in user
$user = $loggedUser->getId();
} elseif (!is_numeric($user)) {
//try to find the user id
//try to find the user id by looking at the login credentials
$searchUser = $this->fosUserManager->findUserByUsername($user);
if ($searchUser) {
$user = $searchUser->getId();
} else {
//last try to find the user id
$searchUser = $this->fosUserManager->findUserByUsername($user);
if ($searchUser) {
$user = $searchUser->getId();
} else {
return new Response("no idea what to do with user '$user', not found in DB");
}
}
}
$qb = $this->getDoctrine()
->getManager()
->createQueryBuilder()
->add('select', 'i,ins,p')
->add('from', 'OceanExpertBundle:Indiv i')
->leftJoin('OceanExpertBundle:ProfileImages', 'p', 'WITH', 'p.idInd = i.idInd')
->leftJoin('OceanExpertBundle:IndivInstitution', 'idins', 'WITH', 'i.idInd = idins.idInd')
->leftJoin('OceanExpertBundle:Institutions', 'ins', 'WITH', 'idins.idInst = ins.idInst')
->where('i.idInd = :userId')
->setParameter('userId', $user);
if ($this->get('security.authorization_checker')->isGranted('ROLE_GLOBAL_EDITOR')
|| ($isLoggedIn
&& $user == $loggedUser->getId()
)
) {
//@todo what should be here? Arno 10/06/2021
} else {
$qb->andWhere('i.status = 1');
}
$expert = $qb->getQuery()
->getResult(AbstractQuery::HYDRATE_ARRAY);
$metadata = array();
$usermeta = array();
/*
* collect the data we need for the OIH JSON-LD in this array
* in the end we will need something like
* {
"@context": {
"@vocab": "https://schema.org/"
},
"@id": "https://example.org/id/x",
"@type": "Person",
"name": "Jane Doe",
"jobTitle": "Professor",
"telephone": "(425) 123-4567",
"url": "http://www.janedoe.com",
"knowsAbout": [
{
"@type": "Text",
"description": "Invasive species in brackish water"
},
{
"@type": "URL",
"url": "https://www.wikidata.org/wiki/Q183368"
},
{
"@id": "https://example.org/id/course/x",
"@type": "Course",
"description": "In this course ...",
"url": "URL to the course"
}
],
"identifier": {
"@id": "https://orcid.org/0000-0002-2257-9127",
"@type": "PropertyValue",
"propertyID": "https://registry.identifiers.org/registry/orcid",
"url": "https://orcid.org/0000-0002-2257-9127",
"description": "Optional description of this record..."
}
}
*/
$OIHData = array(
'@context' => array(
'@vocab' => 'https://schema.org/'
),
'@id' => 'https://oceanexpert.org/expert/' . $user,
'@type' => 'Person'
);
if ($expert
&& count($expert) > 0
) {
$metadata = $this->getMetaData($user);
$jobtype = $this->getJobTypes($user);
$expert['jobType'] = $jobtype['jobtype'];
$jobTypes = explode('\r', $expert['jobType']);
foreach ($jobTypes as $jobType) {
$OIHData['knowsAbout'][] = array(
'@type' => 'Text',
'description' => trim($jobType)
);
}
$expert['groups'] = $this->getUserGroups($user);
$usermeta = $this->getMetaData($user);
} else {
$userExists = $this->fosUserManager->findUserBy(array('id' => $user));
if (!null == $userExists
&& ($this->get('security.authorization_checker')->isGranted('ROLE_GLOBAL_EDITOR'))
|| ($isLoggedIn
&& ($user == $loggedUser->getId())
)
) {
$searchUser = $this->fosUserManager->findUserBy(array('id'=>$user));
$expert[0]['idInd'] = $user;
$expert['username'] = $searchUser->getUsername();
$expert['error'] = "Incomplete Profile.";
return $this->render(
'Profile/profile.html.twig',
array(
'expert' => $expert
)
);
} else {
$expert['error'] = 'User not found.';
}
}
if (isset($expert)
&& isset($expert[0])
&& is_array($expert[0])
) {
//make the name
//for the website this is done in the profile.html.twig template
$userNameParts = array();
foreach (array('fname','mname','sname') as $namePart) {
if (isset($expert[0][$namePart])
&& $expert[0][$namePart] != ''
) {
$userNameParts[] = trim($expert[0][$namePart]);
}
}
$OIHData['name'] = implode(' ', $userNameParts);
//make the address
$addressParts = array();
foreach (array('addr1','addr2') as $addressPart) {
if (isset($expert[0][$addressPart])
&& $expert[0][$addressPart] != ''
) {
$addressParts[] = trim($expert[0][$addressPart]);
}
}
$address = implode(', ', $addressParts);
if (isset($expert[0]['postcode'])
&& $expert[0]['postcode'] != ''
) {
$address .= ', ' . $expert[0]['postcode'];
}
if (isset($expert[0]['city'])
&& $expert[0]['city'] != ''
) {
$address .= ' ' . $expert[0]['city'];
}
if (isset($expert[0]['countryCode'])
&& $expert[0]['countryCode'] != ''
) {
$address .= ', ' . $this->getCountryFromIds(
explode(
',',
$expert[0]['countryCode']
)
);
}
$OIHData['workLocation'] = array(
'@type' => 'Place',
'address' => trim($address)
);
if (isset($expert[0]['languages'])) {
/*
* never used, remove
* Arno 30/07/2021
*
$qb1 = $this->getDoctrine()->getManager()->createQueryBuilder();
$qb1->add('select', 'l')
->add('from', 'OceanExpertBundle:Locale l')
->where('l.locCode in (:locCode)')
->setParameter('locCode', explode(',', $expert[0]['languages']));
$userLangs = $qb1->getQuery()->getResult(Query::HYDRATE_ARRAY);
*/
$knowsLanguages = explode(',', $expert[0]['languages']);
foreach ($knowsLanguages as $knowsLanguage) {
$OIHData['knowsLanguage'][] = array(
'@type' => 'Text',
'name' => trim($knowsLanguage)
);
}
}
if (isset($expert[0]['jobtitle'])) {
$expert['jobtitle'] = $this->getJobTypeByCodes(explode(',', $expert[0]['jobtitle']));
$OIHData['jobTitle'] = trim($expert[0]['jobtitle']);
}
if (isset($expert['0']['lastEditBy'])) {
$expert['lastEditBy'] = $this->getUpdatedBy($expert['0']['lastEditBy']);
}
if (isset($expert['0']['createdBy'])) {
$expert['createdBy'] = $this->getUpdatedBy($expert['0']['createdBy']);
}
$expert['subjectArea'] = $this->getSubjectAreas($user);
if ($expert['subjectArea']
&& $expert['subjectArea'] != ''
) {
$subjectAreas = explode(',', $expert['subjectArea']);
foreach ($subjectAreas as $subjectArea) {
$OIHData['knowsAbout'][] = array(
'@type' => 'Text',
'description' => trim($subjectArea)
);
}
}
if (isset($expert[0]['idNationality'])) {
$expert['nationality'] = $this->getCountryFromIds(
explode(
',',
$expert[0]['idNationality']
)
);
$expertCountryCode = $this->getCountryCodeFromId($expert[0]['idNationality']);
if (trim($expert['nationality'] != '')) {
$OIHData['nationality'][] = array(
'@type' => 'Country',
'name' => trim($expert['nationality'])
);
$OIHData['nationality'][] = array(
'@type' => 'DefinedTerm',
'url' => 'https://unece.org/trade/cefact/unlocode-code-list-country-and-territory',
'inDefinedTermSet' => 'UN/LOCODE Code List by Country and Territory',
'name' => trim($expert['nationality']),
'termCode' => trim($expertCountryCode)
);
}
}
foreach (array('url1', 'url2', 'url3') as $urlId) {
if (isset($expert[0][$urlId])
&& trim($expert[0][$urlId]) != ''
) {
$OIHData['url'][] = trim($expert[0][$urlId]);
}
}
if (isset($expert[0]['studyregion'])) {
$expert['studyregion'] = $this->getResearchAreaByCodes(
explode(
',',
$expert[0]['studyregion']
)
);
}
if (isset($expert[0]['countryCode'])) {
$expert['expertCountry'] = $this->getCountryFromId($expert[0]['countryCode']);
$expert['exrtCtryCode'] = $this->getCountryCodeFromId($expert[0]['countryCode']);
}
if (isset($expert[2]['countryCode'])) {
$expert['instituteCountry'] = $this->getCountryFromId($expert[2]['countryCode']);
$expert['instCtryCode'] = $this->getCountryCodeFromId($expert[2]['countryCode']);
}
if (isset($expert[0]['qualityCheckedBy'])) {
$expert['qcby'] = $this->getUpdatedBy($expert[0]['qualityCheckedBy']);
}
if (isset($expert[0]['doNoInviteBy'])
&& isset($expert[0]['doNoInviteBy'])!=0
) {
$expert['doNoInviteBy'] = $this->getUpdatedBy($expert[0]['doNoInviteBy']);
}
if (isset($expert[0]['twitter'])) {
$twitterUser = $expert[0]['twitter'];
/*
if (strpos($twitterUser, '@') !== false) {
$arrVal = preg_split('@', $twitterUser);
$twitterUser = "https://twitter.com/@" . $arrVal[1];
}
*/
if (preg_match('/(@.+)/', $twitterUser, $matches)) {
$twitterUser = 'https://twitter.com/' . $matches[1];
}
$expert['twitter'] = $twitterUser;
}
if (isset($expert[0]['idInd'])) {
$addressFormatRepository = new AddressFormatRepository();
$countryRepository = new CountryRepository();
$subdivisionRepository = new SubdivisionRepository();
$formatter = new DefaultFormatter(
$addressFormatRepository,
$countryRepository,
$subdivisionRepository
);
$itemId = $expert[0]['idInd'];
$em = $this->getDoctrine()
->getRepository('OceanExpertBundle:MemberGroups');
$query = $em->createQueryBuilder('m')
->select('m.idGroup')
->where('m.idInd =:idInd')
->setParameter('idInd', $itemId)
->getQuery();
$groups = $query->getResult();
$expert['groupids'] = array_column($groups, 'idGroup');
$em = $this->getDoctrine()
->getRepository('OceanExpertBundle:MemberEditsCountry');
$query = $em->createQueryBuilder('m')
->select('m.idCountry')
->where('m.idInd =:idInd')
->setParameter('idInd', $itemId)
->getQuery();
$countries = $query->getResult();
$expert['countries'] = array_column($countries, 'idCountry');
$em = $this->getDoctrine()
->getRepository('OceanExpertBundle:MemberEditsInstitution');
$expert['canEditOwnInst'] = 0;
if (isset($expert[2]['idInst'])) {
$query = $em->createQueryBuilder('m')
->select('m')
->where('m.idInd =:idInd')
->andWhere('m.idInst =:idInst')
->setParameters(
array(
'idInst' => $expert[2]['idInst'],
'idInd' => $itemId
)
)
->getQuery();
$canEditOwnInst = $query->getOneOrNullResult(AbstractQuery::HYDRATE_ARRAY);
if (is_array($canEditOwnInst)
&& count($canEditOwnInst)
) {
$expert['canEditOwnInst'] = 1;
}
}
$address = new Address();
$address = $address
->withCountryCode($expert['exrtCtryCode'])
->withAdministrativeArea($expert[0]['state'])
->withLocality($expert[0]['city'])
->withPostalCode($expert[0]['postcode'])
->withAddressLine2($expert[0]['addr2'])
->withAddressLine1($expert[0]['addr1']);
$expert['expertAddress'] = $formatter->format($address);
if (array_key_exists('instCtryCode',$expert)) {
$address = new Address();
$address = $address
->withCountryCode($expert['instCtryCode'])
->withAdministrativeArea($expert[2]['state'])
->withLocality($expert[2]['city'])
->withPostalCode($expert[2]['postcode'])
->withAddressLine2($expert[2]['addr2'])
->withAddressLine1($expert[2]['instAddress']);
$expert['instAddress'] = $formatter->format($address);
}
}
$fosUserData = $this->fosUserManager
->findUserBy(
array(
'id'=>$user
)
);
if ($fosUserData) {
$expert['roles']=$fosUserData->getRoles();
$expert['username'] = $fosUserData->getUsername();
$expert['email'] = $fosUserData->getEmail();
$userLink = $this->generateUrl(
'view_profile',
array(
'user' => $fosUserData->getUsername()
)
);
$expert['profileUrl'] = $request->getUriForPath($userLink);
$expert['username'] = $fosUserData->getUsername();
}
$adminOption['countries'] = $this->getDoctrine()
->getRepository('OceanExpertBundle:Countries')
->findBy(
[],
['country' => 'ASC']
);
if (isset($expert[1]['path'])) {
$expert['imgPath'] = $request
->getUriForPath('/uploads/profile/' . $expert[1]['path']);
}
$adminOption['userGroups'] = $this->getDoctrine()
->getManager()
->getRepository('OceanExpertBundle:Groups')
->findBy([], ['groupname' => 'ASC']);
$eventData = '';
if ($this->container->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
$eventData = $this->getExpertEventParticipation($user, $request);
}
$OIHEventData = $this->getExpertEventParticipation($user, $request);
/*
* #552
*
foreach ($OIHEventData as $event) {
$OIHData['knowsAbout'][] = array(
'@type' => 'Event',
'identifier' => 'https://www.oceanexpert.org/event/' . $event['idEvent'],
'url' => 'https://www.oceanexpert.org/event/' . $event['idEvent'],
'description' => $event['title'],
'endDate' => $event['endOn'],
'startDate' => $event['startOn']
);
}
*/
if (isset($metadata['orcid'])
&& $metadata['orcid'] != ''
) {
$OIHData['identifier'][] = array(
'@id' => $metadata['orcid'],
'@type' => 'PropertyValue',
'propertyID' => 'https://registry.identifiers.org/registry/orcid',
'url' => 'https://orcid.org/' . $metadata['orcid']
);
}
if (isset($metadata['researcherid'])
&& $metadata['researcherid'] != ''
) {
$OIHData['identifier'][] = array(
'@id' => $metadata['researcherid'],
'@type' => 'PropertyValue',
'propertyID' => 'https://www.researcherid.com',
'url' => 'https://www.researcherid.com/' . $metadata['researcherid']
);
}
if (isset($usermeta['researcharea'])
&& $usermeta['researcharea'] != ''
) {
$OIHData['knowsAbout'][] = array(
'@type' => 'Text',
'description' => $usermeta['researcharea']
);
}
//dump($OIHData);
//die;
}
$OIHData = json_encode(
$OIHData,
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK
);
return $this->render(
'Profile/profile.html.twig',
array(
'OIHData' => $OIHData,
'expert' => $expert,
'usermeta' => $usermeta,
'metadata' => $metadata,
'adminOption' => $adminOption,
'eventData' => $eventData
)
);
}
/**
* @todo fix missing $data
*/
public function userProfileAction(Request $request): Response
{
if (!isset($data['userEmail'])) {
if ($this->container->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
$username = $this->get('security.token_storage')->getToken()->getUser()->getUsername();
return $this->redirect('expert/' . $username);
}
}
if (isset($data['userEmail'])) {
$data = $request->request->all();
$userId = $this->fosUserManager->findUserByEmail($data['userEmail'])->getId();
unset($data['_wysihtml5_mode']);
$data = array_filter($data);
if (isset($data['researcharea'])) {
$data['research'] = $this->getResearchAreaByCodes($data['researcharea']);
}
if (isset($data['studyregion'])) {
$data['study'] = $this->getResearchAreaByCodes($data['studyregion']);
} else {
$data['studyregion'] = array();
}
if (null !== ($data['country'])) {
$data['countryName'] = $this->getCountryByCode($data['country']);
}
if (null !== ($data['jobtype'])) {
$data['job'] = $this->getJobTypeByCodes($data['jobtype']);
}
if ($data['reg-type'] == '1') {
$data['type'] = "Organisation";
} else {
$data['type'] = "Personal";
$data['country'] = $data['country2'];
$data['locality'] = isset($data['city2']) ? $data['city2'] : '';
$data['administrative_area_level_1'] = isset($data['state2']) ? $data['state2'] : '';
$data['postal_code'] = isset($data['postcode2']) ? $data['postcode2'] : '';
$data['box'] = isset($data['box2']) ?: '';
$data['route'] = isset($data['address2']) ? $data['address2'] : '';
$data['addrline2'] = isset($data['addrline2']) ? $data['addrline2'] : '';
}
if (null !== $request->files->get('file')) {
$file = $request->files->get('file');
$filetype = $request->files->get('file')->guessClientExtension();
$filename = "profile_" . $userId . "." . $filetype;
$em = $this->getDoctrine()->getManager();
$item = $em->getRepository('OceanExpertBundle:ProfileImages')->findOneBy(array('idInd' => $userId));
if ($item) {
$item->setFile($file);
$item->setName($filename);
$item->setPath($filename);
$item->upload();
$em->persist($item);
$em->flush();
$data['profileId'] = $item->getId();
} else {
$profile = new ProfileImages();
$profile->setFile($file);
$profile->setName($filename);
$profile->setPath($filename);
$profile->setIdInd($userId);
$profile->upload();
$em->persist($profile);
$em->flush();
if ($profile) {
$data['profileId'] = $profile->getId();
}
}
}
try {
$privateaddress = isset($data['route'])?trim($data['route']) . '<br />':'';
$privateaddress .= isset($data['addrline2'])?trim($data['addrline2']) . '<br />':'';
$privateaddress .= isset($data['postal_code'])?trim($data['postal_code']).", ":'';
$privateaddress .= isset($data['locality'])?trim($data['locality']).", ":'';
$privateaddress .= isset($data['administrative_area_level_1'])?trim($data['administrative_area_level_1']) . '<br />':'';
$privateaddress .= isset($data['country'])?trim($this->getCountryByCode($data['country'])) . '<br />':'';
$indiv = new Indiv();
$indiv->setTitle(isset($data['title']) ? $data['title'] : '');
$indiv->setFname(isset($data['firstname']) ? $data['firstname'] : '');
$indiv->setMname(isset($data['middlename']) ? $data['middlename'] : '');
$indiv->setSname(isset($data['lastname']) ? $data['lastname'] : '');
$indiv->setRegType(isset($data['reg-type']) ? $data['reg-type'] : '');
$indiv->setIdentifier('');
$indiv->setUseInstAddr(isset($data['instaddress']) ? $data['instaddress'] : 0);
$indiv->setPrivateAddress($privateaddress);
$indiv->setCity(isset($data['locality']) ? $data['locality'] : '');
$indiv->setAddr1(isset($data['route']) ? $data['route'] : '');
$indiv->setAddr2(isset($data['addrline2']) ? $data['addrline2'] : '');
$indiv->setState(isset($data['administrative_area_level_1']) ? $data['administrative_area_level_1'] : '');
$indiv->setPostcode(isset($data['postal_code']) ? $data['postal_code'] : '');
$indiv->setCountryCode(isset($data['country']) ? $data['country'] : '');
$indiv->setIDNationality(isset($data['id_nationality']) ? $data['id_nationality'] : 0);
$indiv->setGender(isset($data['gender']) ? $data['gender'] : '');
$indiv->setTel(isset($data['phone']) ? $data['phone'] : '');
//we are already in a condition where we are sure the $data['userEmail'] exists
$indiv->setEmail1($data['userEmail']);
$indiv->setEmail2(isset($data['alternateEmail']) ? $data['alternateEmail'] : '');
$indiv->setUrl1(isset($data['website-personal']) ? $data['website-personal'] : '');
$indiv->setUrl2(isset($data['website-institution']) ? $data['website-institution'] : '');
$indiv->setLinkedin(isset($data['linkedin']) ? $data['linkedin'] : '');
$indiv->setFacebook(isset($data['facebook']) ? $data['facebook'] : '');
$indiv->setTwitter(isset($data['twitter']) ? $data['twitter'] : '');
$indiv->setOther(isset($data['other']) ? $data['other'] : '');
$indiv->setDegree(isset($data['degree']) ? $data['degree'] : '');
$indiv->setJobtitle(isset($data['job']) ? $data['job'] : '');
$indiv->setDept(isset($data['department']) ? $data['department'] : '');
$indiv->setStudyregion(isset($data['study']) ? $data['study'] : '');
$indiv->setLanguages(implode(',', $data['languages']));
$indiv->setComments(isset($data['comments']) ? $data['comments'] : '');
$indiv->setSkills(isset($data['skills']) ? $data['skills'] : '');
$indiv->setIdImagefile(isset($data['profileId']) ? $data['profileId'] : null);
$indiv->setFDateEnt(new DateTime('now'));
$indiv->setLDateUpd(new DateTime('now'));
$indiv->setCreatedBy(isset($data['']) ? $data[''] : 0);
$indiv->setLastEditBy(isset($data['']) ? $data[''] : 0);
$indiv->setFax(isset($data['']) ? $data[''] : '');
$indiv->setEmail2(isset($data['']) ? $data[''] : '');
$indiv->setEmail3(isset($data['']) ? $data[''] : '');
$indiv->setUrl3(isset($data['']) ? $data[''] : '');
$indiv->setUrlsChecked(new DateTime('now'));
$indiv->setFlickr(isset($data['']) ? $data[''] : '');
$indiv->setActiveng(isset($data['']) ? $data[''] : '');
$indiv->setActivother(isset($data['']) ? $data[''] : '');
$indiv->setDoNotInvite(isset($data['']) ? $data[''] : 0);
$indiv->setAdminComments(isset($data['']) ? $data[''] : '');
$indiv->setIsGlobal(isset($data['']) ? $data[''] : 0);
$indiv->setStatus(isset($data['']) ? $data[''] : 0);
$indiv->setStatusLastChanged(new DateTime());
$indiv->setDeceased(isset($data['']) ? $data[''] : 0);
$indiv->setRetired(isset($data['']) ? $data[''] : 0);
$em = $this->getDoctrine()->getManager();
$em->persist($indiv); //marks object to be saved in the next transaction.
$em->flush(); //performs all saves and transactions.
if (!isset($data['orcid'])) {
$data['orcid'] = '';
}
if (!isset($data['researcherid'])) {
$data['researcherid'] = '';
}
if (!isset($data['google-scholar'])) {
$data['google-scholar'] = '';
}
if (!isset($data['researchgate'])) {
$data['researchgate'] = '';
}
if (!isset($data['others'])) {
$data['others'] = '';
}
if (!isset($data['researcharea'])) {
$data['researcharea'] = array();
}
if ($indiv->getIdInd()) {
$usermeta = array(
'orcid' => $data['orcid'],
'researcherid' => $data['researcherid'],
'researcharea' => implode(', ', $data['researcharea']),
'google-scholar' => $data['google-scholar'],
'researchgate' => $data['researchgate'],
'others' => $data['others']
);
$usermeta = array_filter($usermeta);
foreach ($usermeta as $key => $value) {
$chkmeta = $em->getRepository('OceanExpertBundle:IndivMeta')
->findOneBy(
array(
'indivId' => $indiv->getIdInd(),
'metaOption' => $key
)
);
if ($chkmeta) {
$chkmeta->setMetaValue($value);
$em->persist($chkmeta);
$em->flush();
} else {
$meta = new IndivMeta();
$meta->setIndivId($indiv->getIdInd());
$meta->setMetaOption($key);
$meta->setMetaValue($value);
$em = $this->getDoctrine()->getManager();
$em->persist($meta);
$em->flush();
}
}
}
} catch (Exception $e) {
//@todo what happens here Arno 10/06/2021
}
}
return $this->redirect($this->generateUrl('profile_status'));
}
/**
* edit an existing user profile
*
* @param int|null $userId the id of the profile to edit
*
* @return Response
*
* @throws \Psr\Container\ContainerExceptionInterface
* @throws \Psr\Container\NotFoundExceptionInterface
*/
public function editAction(int $userId = null): Response
{
//only logged-in users can get the right to edit
//this is only a first check (see #493)
if (!$this->get('security.authorization_checker')->isGranted('ROLE_USER')) {
$url = $this->container->get('router')->generate('frontend_homepage');
return new RedirectResponse($url);
}
//we will alway need to know the current user to be sure that not everybody can change another account
$user = $this->get('security.token_storage')->getToken()->getUser();
if ($userId == '') {
//this is the simplest case
//no userid is given so edit the profile from the person that is logged in
$userId = $user->getId();
}
//we want to edit an existing user, so this user must have an entry in the fos_user db
$fosUserData = $this->fosUserManager
->findUserBy(
array(
'id'=>$userId
)
);
if (!$fosUserData) {
//no such user, strange...
$message = "There is no user with this id ($userId).";
return $this->render(
'Default/error.html.twig',
array(
'message' => $message
)
);
}
//here it gets tricky
//who can edit, what profile??
if ($userId == $user->getId() //no problem, everybody can adapt his/here own profile
|| $this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')) //no problem, admin users can change the profiles of others
{
$em = $this->getDoctrine()->getManager();
$indiv = $this->getDoctrine()
->getRepository('OceanExpertBundle:Indiv')
->findOneByIdInd($userId);
if(!$indiv) {
//create a new profile as it does not exist yet
//this happens when people subscribe and want to complete their profile
$indiv = new Indiv();
$indiv->setTitle('');
$indiv->setFname('');
$indiv->setMname('');
$indiv->setSname('');
$indiv->setIdentifier('');
$indiv->setRegType('');
$indiv->setUseInstAddr(0);
$indiv->setPrivateAddress('');
$indiv->setAddr1('');
$indiv->setAddr2('');
$indiv->setCity('');
$indiv->setState('');
$indiv->setPostcode('');
$indiv->setIdNationality('');
$indiv->setTel('');
$indiv->setFax('');
$indiv->setEmail2('');
$indiv->setEmail3('');
$indiv->setUrl1('');
$indiv->setUrl2('');
$indiv->setUrl3('');
$indiv->setGender('');
$indiv->setLinkedin('');
$indiv->setFacebook('');
$indiv->setFlickr('');
$indiv->setTwitter('');
$indiv->setOther('');
$indiv->setDegree('');
$indiv->setActiveng('');
$indiv->setActivother('');
$indiv->setJobtitle('');
$indiv->setDept('');
$indiv->setStudyregion('');
$indiv->setLanguages('');
$indiv->setSkills('');
$indiv->setComments('');
$indiv->setDoNotInvite('');
$indiv->setAdminComments('');
$indiv->setIsGlobal(1);
$indiv->setStatus(0);
$indiv->setDeceased(0);
$indiv->setRetired(0);
$indiv->setIdInd($userId);
$indiv->setCountryCode(21);
$indiv->setEmail1($fosUserData->getEmail());
$em->persist($indiv);
$em->flush();
}
} else {
//this is not correct #491
$message = 'You do not have the correct rights (your are not this person and you are not an admin user) to edit this profile.';
return $this->render(
'Default/error.html.twig',
array(
'message' => $message
)
);
}
$qb = $this->getDoctrine()
->getManager()
->createQueryBuilder();
$qb->add('select', 'i, ins, p, c')
->add('from', 'OceanExpertBundle:Indiv i')
->leftJoin('OceanExpertBundle:ProfileImages', 'p', 'WITH', 'p.idInd = i.idInd')
->leftJoin('OceanExpertBundle:IndivInstitution', 'idins', 'WITH', 'i.idInd = idins.idInd')
->leftJoin('OceanExpertBundle:Institutions', 'ins', 'WITH', 'idins.idInst = ins.idInst')
->leftJoin('OceanExpertBundle:Countries', 'c', 'WITH', 'c.idCountry = i.countryCode')
->where('i.idInd = :userId')
->setParameter('userId', $userId);
//get the expert data as far as we can find it
$expert = $qb->getQuery()->getResult(AbstractQuery::HYDRATE_ARRAY);
$metadata = $this->getMetaData($userId);
$jobType = $this->getJobTypes($userId);
$expert['jobType'] = $jobType['jobId'];
$expert['userId'] = $userId;
$expert['subjectArea'] = $this->getSubjectAreas($userId);
$expert['roles'] = $fosUserData->getRoles();
$expert['username'] = $fosUserData->getUsername();
$expert['email'] = $fosUserData->getEmail();
//get some data for the rest of the form
$countries = $this->getDoctrine()
->getRepository('OceanExpertBundle:Countries')
->findBy(
[],
['country' => 'ASC']
);
$locales = $this->getDoctrine()
->getRepository('OceanExpertBundle:Locale')
->findBy(
[],
['locale' => 'ASC']
);
$studyregions = $this->getDoctrine()
->getRepository('OceanExpertBundle:Regions')
->findBy(
[],
['name' => 'ASC']
);
$instituteSeaRegion = $this->getDoctrine()
->getRepository('OceanExpertBundle:Regions')
->seaRegions();
$allSubjects = $this->getDoctrine()
->getRepository('OceanExpertBundle:Subjects')
->findBy(
[],
['subname' => 'ASC']
);
return $this->render('Profile/editProfile.html.twig', array(
'expert' => $expert,
'countries' => $countries,
'locales' => $locales,
'nationalities' => $countries,
'metadata' => $metadata,
'studyregions' => $studyregions,
'availableSeaRegions' => $instituteSeaRegion,
'allSubjects' => $allSubjects
));
}
public function updateProfileTimeAction(Request $request): Response
{
$security_context = $this->get('security.authorization_checker');
if ($security_context->isGranted('ROLE_USER')) {
$userId = $request->request->get('userId');
if ($userId) {
$indiv = $this->getDoctrine()->getRepository('OceanExpertBundle:Indiv')->findOneByIdInd($userId);
if ($indiv) {
$indiv->setLDateUpd(new DateTime('now'));
$indiv->setLastEditBy($security_context->getToken()->getUser()->getId());
$em = $this->getDoctrine()->getManager();
$em->persist($indiv); //marks object to be saved in the next transaction.
$em->flush(); //performs all saves and transactions.
}
return new Response("updated successfully");
} else {
return new Response("cannot update");
}
}
return new Response("cannot update");
}
public function activateUserAction($userId): Response
{
$security_context = $this->get('security.authorization_checker');
if ($security_context->isGranted('ROLE_GLOBAL_EDITOR')) {
if ($userId) {
$indiv = $this->getDoctrine()
->getRepository('OceanExpertBundle:Indiv')
->findOneByIdInd($userId);
if ($indiv) {
$indiv->setStatus(1);
$indiv->setStatusLastChanged(new DateTime('now'));
$em = $this->getDoctrine()->getManager();
$em->persist($indiv); //marks object to be saved in the next transaction.
$em->flush(); //performs all saves and transactions.
}
return new JsonResponse(
array(
'status' => true,
'msg' => "updated successfully"
)
);
} else {
return new Response("cannot update");
}
}
return new Response($userId);
}
public function deactivateUserAction($userId): Response
{
$security_context = $this->get('security.authorization_checker');
$message = array();
if ($security_context->isGranted('ROLE_GLOBAL_EDITOR')) {
if ($userId) {
$em = $this->getDoctrine()->getManager();
//disable the login
$FOSUser = $em
->getRepository('OceanExpertBundle:FosUser')
->findOneById($userId);
if ($FOSUser) {
$FOSUser->setEnabled(0);
$FOSUser->setUpdatedAt(new DateTime('now'));
$em->persist($FOSUser);
$em->flush();
} else {
$message[] = array(
'id' => $userId,
'status' => 0,
'message' => "no user found in fos_user table with id $userId"
);
}
//deactivate the expert
$indiv = $em
->getRepository('OceanExpertBundle:Indiv')
->findOneByIdInd($userId);
if ($indiv) {
$indiv->setStatus(3);
$indiv->setStatusLastChanged(new DateTime('now'));
$em->persist($indiv); //marks object to be saved in the next transaction.
$em->flush(); //performs all saves and transactions.
} else {
$message[] = array(
'id' => $userId,
'status' => 0,
'message' => "no user found in indiv table with idInd $userId"
);
}
if (!count($message)) {
//no error messages yet so all should be fine
$message[] = array(
'id' => $userId,
'status' => true,
'message' => "user with idInd $userId deactivated"
);
}
} else {
$message[] = array(
'id' => $userId,
'status' => 0,
'message' => 'incorrect or no user id given'
);
}
} else {
$message[] = array(
'id' => $userId,
'status' => 0,
'message' => 'you do not have enough rights to do this'
);
}
return new JsonResponse($message);
}
public function getNationalityFromId($id)
{
$em = $this->getDoctrine()->getRepository('OceanExpertBundle:Nationality')->findOneById($id);
if ($em == null) {
return false;
} else {
return $em->getNationality();
}
}
public function getCountryFromId($id)
{
$em = $this->getDoctrine()->getRepository('OceanExpertBundle:Countries')->findOneByIdCountry($id);
if ($em == null) {
return false;
} else {
return $em->getCountry();
}
}
public function getCountryCodeFromId($id)
{
$em = $this->getDoctrine()
->getRepository('OceanExpertBundle:Countries')
->findOneByIdCountry($id);
if ($em == null) {
return false;
} else {
return $em->getCountryCode();
}
}
public function getCountryFromIds($countryArr)
{
$em = $this->getDoctrine()
->getRepository('OceanExpertBundle:Countries');
$query = $em->createQueryBuilder('c')
->select('c.country')
->where('c.idCountry in (:idCountry)')
->setParameter('idCountry', $countryArr)
->getQuery();
$countries = $query->getResult();
$countryList = array_column($countries, 'country');
return implode(', ', $countryList);
}
public function csvComma($value = '')
{
return "'" . implode("','", explode(",", $value)) . "'";
}
public function getJobTypeByCodes($jobArr)
{
$em = $this->getDoctrine()
->getRepository('OceanExpertBundle:Jobtypes');
$query = $em->createQueryBuilder('a')
->select('a.jobname')
->where('a.idJob in (:jobArr)')
->setParameter('jobArr', $jobArr)
->getQuery();
$jobs = $query->getResult();
$jobList = array_column($jobs, 'jobname');
return implode(', ', $jobList);
}
public function getResearchAreaByCodes($codeArr)
{
$em = $this->getDoctrine()
->getRepository('OceanExpertBundle:Regions');
$query = $em->createQueryBuilder('a')
->select('a.name')
->where('a.idRegion in (:codeArr)')
->setParameter('codeArr', $codeArr)
->getQuery();
$regions = $query->getResult();
$regionsList = array_column($regions, 'name');
return implode(', ', $regionsList);
}
/**
* get all the meta data for a given userId
* this data comes as a key-value pair
*
* @param int $userId the userId of the expert
*
* @return array
*/
public function getMetaData(int $userId): array
{
$qb = $this->getDoctrine()->getManager()->createQueryBuilder();
$qb->add('select', 'm.metaOption,m.metaValue')
->add('from', 'OceanExpertBundle:IndivMeta m')
->where('m.indivId = :userId')
->setParameter('userId', $userId);
$meta = $qb->getQuery()->getResult(AbstractQuery::HYDRATE_ARRAY);
$metadata = array();
foreach ($meta as $value) {
$metadata[$value['metaOption']] = $value['metaValue'];
}
return $metadata;
}
/**
* get all the different job types for a given userId
*
* @param int $userId the userId of the expert
*
* @return array
*/
public function getJobTypes(int $userId): array
{
$qb = $this->getDoctrine()->getManager()->createQueryBuilder();
$qb->add('select', 'jt.jobname,jt.idJob')
->add('from', 'OceanExpertBundle:IndivJobtype j')
->leftJoin('OceanExpertBundle:Jobtypes', 'jt', 'WITH', 'jt.idJob = j.idJob')
->where('j.idInd = :userId')
->setParameter('userId', $userId);
$meta = $qb->getQuery()->getResult(AbstractQuery::HYDRATE_ARRAY);
$jobTypes = implode(
'\r',
array_column(
$meta,
'jobname'
)
);
$jobId = implode(
',',
array_column(
$meta,
'idJob'
)
);
return array(
'jobtype' => $jobTypes,
'jobId' => $jobId
);
}
public function getUserGroups($userId) {
$qb = $this->getDoctrine()->getManager()->createQueryBuilder();
$qb->add('select', 'g.groupname, g.idGroup')
->add('from', 'OceanExpertBundle:MemberGroups mg')
->leftJoin('OceanExpertBundle:Groups', 'g', 'WITH', 'mg.idGroup = g.idGroup')
->where('mg.idInd = :userId')
->setParameter('userId', $userId)
->orderBy('g.groupname','ASC');
return $qb->getQuery()->getResult(AbstractQuery::HYDRATE_ARRAY);
}
/**
* get all the subject areas for a given userId
*
* @param int $userId the userId of the expert
*
* @return string
*/
public function getSubjectAreas(int $userId): string
{
$qb = $this->getDoctrine()->getManager()->createQueryBuilder();
$qb->add('select', 's.subname,s.idSub')
->add('from', 'OceanExpertBundle:IndivSubjects ivs')
->leftJoin('OceanExpertBundle:Subjects', 's', 'WITH', 's.idSub = ivs.idSub')
->where('ivs.idInd = :userId')
->setParameter('userId', $userId);
$meta = $qb->getQuery()->getResult(AbstractQuery::HYDRATE_ARRAY);
return implode(
',',
array_column(
$meta,
'subname'
)
);
}
public function getUpdatedBy($id = '')
{
$updatedBy = $this->getDoctrine()->getRepository('OceanExpertBundle:Indiv')->findOneByIdInd($id);
if ($updatedBy) {
$name = $updatedBy->getfname() . " " . strtoupper($updatedBy->getsname());
} else {
$name = false;
}
return $name;
}
public function qccontrolAction(Request $request): Response
{
$id = $request->request->get('userId');
$action = $request->request->get('action');
$return = '';
$security_context = $this->get('security.authorization_checker');
if ($security_context->isGranted('ROLE_GLOBAL_EDITOR')) {
$author = $this->get('security.token_storage')->getToken()->getUser()->getId();
$updatedBy = $this->getDoctrine()->getRepository('OceanExpertBundle:Indiv')->findOneByIdInd($id);
if ($action == 1) {
$updatedBy->setQualityCheckedBy($author);
$updatedBy->setQualityCheckedDate(new DateTime('now'));
$updatedBy->setQualityChecked(1);
$return = "This record has been marked as quality controlled on <strong>" . date('F j, Y') . "</strong> by <strong>" . $this->getUpdatedBy($author)."</strong>";
} else {
$updatedBy->setQualityCheckedBy(null);
$updatedBy->setQualityCheckedDate(null);
$updatedBy->setQualityChecked(0);
$return = "This record has not been quality controlled";
}
$updatedBy->setLDateUpd(new DateTime('now'));
$updatedBy->setLastEditBy($author);
$em = $this->getDoctrine()->getManager();
$em->persist($updatedBy); //marks object to be saved in the next transaction.
$em->flush(); //performs all saves and transactions.
}
return new Response($return);
}
public function setRetiredAction(Request $request): Response
{
$id = $request->request->get('userId');
$date = $request->request->get('retiredDate');
$retiredStatus = $request->request->get('retiredStatus');
$security_context = $this->get('security.authorization_checker');
if ($security_context->isGranted('ROLE_USER')) {
$author = $this->get('security.token_storage')->getToken()->getUser()->getId();
$updateRecord = $this->getDoctrine()->getRepository('OceanExpertBundle:Indiv')->findOneByIdInd($id);
if ($updateRecord) {
if ($retiredStatus == 1) {
$updateRecord->setRetired(1);
if (trim($date) == '') {
$updateRecord->setRetiredDate(null);
} else {
$updateRecord->setRetiredDate(DateTime::createFromFormat('Y-m-d', $date));
}
} else {
$updateRecord->setRetired(0);
$updateRecord->setRetiredDate(null);
}
}
$updateRecord->setLDateUpd(new DateTime('now'));
$updateRecord->setLastEditBy($author);
$em = $this->getDoctrine()->getManager();
$em->persist($updateRecord); //marks object to be saved in the next transaction.
$em->flush(); //performs all saves and transactions.
}
return new Response($date);
}
public function setDeceasedAction(Request $request): Response
{
$id = $request->request->get('userId');
$date = $request->request->get('deceasedDate');
$deceasedStatus = $request->request->get('deceasedStatus');
$return = '';
$security_context = $this->get('security.authorization_checker');
if ($security_context->isGranted('ROLE_GLOBAL_EDITOR')) {
$author = $this->get('security.token_storage')->getToken()->getUser()->getId();
$updateRecord = $this->getDoctrine()
->getRepository('OceanExpertBundle:Indiv')
->findOneByIdInd($id);
if ($updateRecord) {
if ($deceasedStatus == 1) {
$updateRecord->setDeceased(1);
if (trim($date) == '') {
$updateRecord->setDeceasedDate(null);
} else {
$updateRecord->setDeceasedDate(DateTime::createFromFormat('Y-m-d', $date));
}
} else {
$updateRecord->setDeceased(0);
$updateRecord->setDeceasedDate(null);
}
}
$updateRecord->setLDateUpd(new DateTime('now'));
$updateRecord->setLastEditBy($author);
$em = $this->getDoctrine()->getManager();
$em->persist($updateRecord); //marks object to be saved in the next transaction.
$em->flush(); //performs all saves and transactions.
}
return new Response($return);
}
public function setDoNotInviteAction(Request $request): Response
{
$id = $request->request->get('userId');
$status = $request->request->get('status');
$return = '';
$security_context = $this->get('security.authorization_checker');
if ($security_context->isGranted('ROLE_USER')) {
$author = $this->get('security.token_storage')->getToken()->getUser()->getId();
$updateRecord = $this->getDoctrine()
->getRepository('OceanExpertBundle:Indiv')
->findOneByIdInd($id);
if ($updateRecord) {
if ($status == 1) {
$updateRecord->setDoNotInvite(1);
$updateRecord->setDoNoInviteBy($author);
$updateRecord->setDoNoInviteOn(new DateTime('now'));
$return = 'This record has been set as do not invite on <strong>' . date('F j, Y') . '</strong>';
$return .= 'by <strong>' . $this->getUpdatedBy($author) . '</strong>';
} else {
$updateRecord->setDoNotInvite(0);
$updateRecord->setDoNoInviteBy(0);
$updateRecord->setDoNoInviteOn(NULL);
$return = 'Please select "Yes" to add this member to the do not invite list.';
}
}
$updateRecord->setLDateUpd(new DateTime('now'));
$updateRecord->setLastEditBy($author);
$em = $this->getDoctrine()->getManager();
$em->persist($updateRecord); //marks object to be saved in the next transaction.
$em->flush(); //performs all saves and transactions.
}
return new Response($return);
}
public function setAdmincommentsAction(Request $request): Response
{
$id = $request->request->get('userId');
$comments = $request->request->get('comments');
$return = '';
if (trim($comments) != '') {
$security_context = $this->get('security.authorization_checker');
if ($security_context->isGranted('ROLE_GLOBAL_EDITOR')) {
$author = $this->get('security.token_storage')->getToken()->getUser()->getId();
$updateRecord = $this->getDoctrine()
->getRepository('OceanExpertBundle:Indiv')
->findOneByIdInd($id);
$comments .= '<br />';
$comments .= '(Added by ' . $this->getUpdatedBy($author);
$comments .= ' on ' . date('d-m-y');
$comments .= ')<br /><br />';
$comments .= $updateRecord->getAdminComments();
if ($updateRecord) {
$updateRecord->setAdminComments($comments);
}
$updateRecord->setLDateUpd(new DateTime('now'));
$updateRecord->setLastEditBy($author);
$em = $this->getDoctrine()->getManager();
$em->persist($updateRecord); //marks object to be saved in the next transaction.
$em->flush(); //performs all saves and transactions.
$return = $comments;
}
}
return new Response($return);
}
public function setGroupsAction(Request $request): Response
{
$id = $request->request->get('userId');
$groups = $request->request->get('groups');
$return = '';
$security_context = $this->get('security.authorization_checker');
if ($security_context->isGranted('ROLE_GLOBAL_EDITOR')) {
$author = $this->get('security.token_storage')
->getToken()
->getUser()
->getId();
$updateRecord = $this->getDoctrine()
->getRepository('OceanExpertBundle:Indiv')
->findOneByIdInd($id);
if ($updateRecord) {
$updateRecord->setLDateUpd(new DateTime('now'));
$updateRecord->setLastEditBy($author);
$em = $this->getDoctrine()->getManager();
$em->persist($updateRecord); //marks object to be saved in the next transaction.
$em->flush(); //performs all saves and transactions.
}
if (is_array($groups)) {
$em = $this->getDoctrine()->getManager();
$results = $em->createQueryBuilder()
->add('select', 'm')
->add('from', 'OceanExpertBundle:MemberGroups m')
->where('m.idGroup not in (:groups)')
->andWhere('m.idInd =:idInd')
->setParameters(array('groups' => $groups, 'idInd' => $id))
->getQuery()->getResult();
foreach ($results as $result) {
$em->remove($result);
}
$em->flush();
foreach ($groups as $value) {
$updateGroup = $this->getDoctrine()
->getRepository('OceanExpertBundle:MemberGroups')
->find(
array(
'idInd' => $id,
'idGroup' => $value
)
);
if (!$updateGroup) {
$addGroups = new MemberGroups();
$addGroups->setIdInd($id);
$addGroups->setIdGroup($value);
$addGroups->setRole('');
$addGroups->setMemberOrder(NULL);
$addGroups->setIsLeader(0);
$em = $this->getDoctrine()->getManager();
$em->persist($addGroups); //marks object to be saved in the next transaction.
$em->flush(); //performs all saves and transactions.
}
}
} else {
$updateGroup = $this->getDoctrine()
->getRepository('OceanExpertBundle:MemberGroups')
->findBy(array('idInd' => $id));
$em = $this->getDoctrine()->getEntityManager();
foreach ($updateGroup as $groups) {
$em->remove($groups);
}
$em->flush();
}
}
return new Response($return);
}
public function setPrivilegesAction(Request $request): Response
{
//get all the values from the request
//these values are send from profile.html.twig $("#addPrivileges").click(function () {....
$id = $request->request->get('userId');
$countries = $request->request->get('countries');
$ownInstitute = $request->request->get('ownInstitute');
$countryList = $request->request->get('countryList');
$editor = $request->request->get('editor');
$security_context = $this->get('security.authorization_checker');
if ($security_context->isGranted('ROLE_GLOBAL_EDITOR')) {
$return = array(
'status' => 0,
'message' => array()
);
//who is doing this update
$author = $this->get('security.token_storage')
->getToken()
->getUser()
->getId();
//what record needs to be updated
$updateRecord = $this->getDoctrine()
->getRepository('OceanExpertBundle:Indiv')
->findOneByIdInd($id);
if ($updateRecord) {
$updateRecord->setLDateUpd(new DateTime('now'));
$updateRecord->setLastEditBy($author);
$em = $this->getDoctrine()->getManager();
$em->persist($updateRecord); //marks object to be saved in the next transaction.
$em->flush(); //performs all saves and transactions.
}
if ($ownInstitute == 1) {
$updateInstEdit = $this->getDoctrine()
->getRepository('OceanExpertBundle:MemberEditsInstitution')
->findOneBy(array(
'idInd' => $id,
'idInst' => $this->getIndivInstitute($id)
)
);
if (!$updateInstEdit) {
$updateInstEdit = new MemberEditsInstitution();
$updateInstEdit->setIdInd($id);
$updateInstEdit->setIdInst($this->getIndivInstitute($id));
} else {
$updateInstEdit->setIdInst($this->getIndivInstitute($id));
}
$em->persist($updateInstEdit); //marks object to be saved in the next transaction.
$em->flush(); //performs all saves and transactions.
$return['message'][] = 'update own institute activated';
} else {
$qb = $em->createQueryBuilder();
$query = $qb->delete('OceanExpertBundle:MemberEditsInstitution', 'm')
->where('m.idInd = :id')
->andWhere('m.idInst = :idInst')
->setParameters(
array(
'id' => $id,
'idInst' => $this->getIndivInstitute($id)
)
)
->getQuery();
$query->execute();
$em->flush();
$return['message'][] = 'update own institute removed';
}
if (is_array($countries)
&& $countryList == 1
) {
$em = $this->getDoctrine()->getManager();
$results = $em->createQueryBuilder()
->add('select', 'm')
->add('from', 'OceanExpertBundle:MemberEditsCountry m')
->where('m.idCountry not in (:countries)')
->andWhere('m.idInd =:idInd')
->setParameters(
array(
'countries' => $countries,
'idInd' => $id
)
)
->getQuery()->getResult();
foreach ($results as $result) {
$em->remove($result);
}
$em->flush();
foreach ($countries as $value) {
$updateCountries = $this->getDoctrine()
->getRepository('OceanExpertBundle:MemberEditsCountry')
->find(array(
'idInd' => $id,
'idCountry' => $value
)
);
if (!$updateCountries) {
$addCountry = new MemberEditsCountry();
$addCountry->setIdInd($id);
$addCountry->setIdCountry($value);
$em = $this->getDoctrine()->getManager();
$em->persist($addCountry); //marks object to be saved in the next transaction.
$em->flush(); //performs all saves and transactions.
}
}
$return['message'][] = 'countries added';
} else {
$updateGroup = $this->getDoctrine()
->getRepository('OceanExpertBundle:MemberEditsCountry')
->findBy(array('idInd' => $id));
$em = $this->getDoctrine()->getEntityManager();
foreach ($updateGroup as $groups) {
$em->remove($groups);
}
$em->flush();
$return['message'][] = 'countries removed';
}
$user= $em->getRepository('OceanExpertBundle:User')
->findOneBy(
array(
'id' => $id
)
);
if($editor == 1) {
$user->addRole("ROLE_GLOBAL_EDITOR");
$return['message'][] = 'global editor activated';
} elseif ($editor == 0) {
$user->removeRole('ROLE_GLOBAL_EDITOR');
$return['message'][] = 'global editor removed';
}
$em->persist($user);
$em->flush();
} else {
$return = array(
'status' => 1,
'error' => 'you have no rights to do this'
);
}
return new Response(json_encode($return));
}
public function resetPasswordLinkAction(Request $request): Response
{
if ($request->query->get('username')) {
$username = $request->query->get('username');
} else {
$username = $request->request->get('username');
}
$user = $this->fosUserManager->findUserByUsernameOrEmail($username);
if (null === $user) {
$return = "Error in sending email. User not found.";
return new Response($return);
}
if (null === $user->getConfirmationToken()) {
$user->setConfirmationToken($this->fosTokenGenerator->generateToken());
}
$this->fosMailer->sendResettingEmailMessage($user);
$user->setPasswordRequestedAt(new DateTime());
$this->fosUserManager->updateUser($user);
$return = "Password reset link send successfully.";
if ($request->query->get('username')) {
$email = $user->getEmail();
if (false !== $pos = strpos($email, '@')) {
$email = '...' . substr($email, $pos);
}
return new RedirectResponse(
$this->generateUrl(
'fos_user_resetting_check_email',
array('email' => $email)
)
);
}
return new Response($return);
}
public function getIndivInstitute($idInd)
{
$getInstId = $this->getDoctrine()
->getRepository('OceanExpertBundle:IndivInstitution')
->findOneByIdInd($idInd);
if ($getInstId) {
return $getInstId->getIdInst();
} else {
return 0;
}
}
/**
* @return Response
*/
public function assignRolesAction(Request $request): Response
{
$username = $request->request->get('username');
$em = $this->getDoctrine()->getManager();
$user= $em->getRepository("OceanExpertBundle:User")
->findOneBy(array('username' => $username));
if ($request->request->get('superadmin')==1) {
$user->addRole('ROLE_SUPERADMIN');
} else {
$user->removeRole('ROLE_SUPERADMIN');
}
if ($request->request->get('administrator')==1) {
$user->addRole('ROLE_ADMIN');
} else {
$user->removeRole('ROLE_ADMIN');
}
if ($request->request->get('manager')==1) {
$user->addRole('ROLE_MANAGER');
} else {
$user->removeRole('ROLE_MANAGER');
}
if ($request->request->get('lme')==1) {
$user->addRole('ROLE_LME');
} else {
$user->removeRole('ROLE_LME');
}
$em->persist($user);
$em->flush();
return new JsonResponse(
array(
'status' => 1 ,
'message' => 'Role assigned successfully',
'roles' => $username,
'user' => $user
)
);
}
/**
* @return JsonResponse
*/
public function getExpertsAjaxAction(Request $request): Response
{
if (!null == $request->query->get('q')) {
$query = $request->query->get('q');
$em = $this->getDoctrine()->getManager();
$connection = $em->getConnection();
$statement = $connection->prepare("SELECT
i.id_ind AS id,
i.fname,
i.sname,
i.jobtitle,
inst.inst_name,
c.country
FROM indiv i
LEFT JOIN countries c ON c.id_country = i.country_code
LEFT JOIN indiv_institution ii ON ii.id_ind = i.id_ind
LEFT JOIN institutions inst ON inst.id_inst = ii.id_inst
LEFT JOIN countries ic ON ic.id_country = inst.country_code
WHERE ( MATCH (fname,sname) AGAINST (:searchterm IN BOOLEAN MODE)
OR fname like '%$query%'
OR fname like '%$query%'
OR sname like '%$query%'
OR sname like '%$query%')
AND status = 1;
");
$statement->bindValue('searchterm', $query);
$statement->execute();
$query = $statement->fetchAll();
$data = array();
if($query) {
$data = array(
'incomplete_results' => false,
'items' => $query,
'total_count' => count($query),
);
}
return new JsonResponse($data);
}
return new JsonResponse(array());
}
function getExpertEventParticipation($idInd, $request) {
$em = $this->getDoctrine()->getManager();
$participation = $em->createQueryBuilder()
->add('select', 'ep.idEvent')
->add('from', 'OceanExpertBundle:EventParticipants ep')
->where('ep.idInd =:idInd')
->setParameters(array('idInd' => $idInd ))
->getQuery()->getResult();
$participation = array_column($participation, "idEvent");
$contacts = $em->createQueryBuilder()
->add('select', 'ec.idEvent')
->add('from', 'OceanExpertBundle:EventContacts ec')
->where('ec.idInd =:idInd')
->setParameters(array('idInd' => $idInd ))
->getQuery()->getResult();
$contacts = array_column($contacts, "idEvent");
$staff = $em->createQueryBuilder()
->add('select', 'es.idEvent')
->add('from', 'OceanExpertBundle:EventStaff es')
->where('es.idInd =:idInd')
->setParameters(array('idInd' => $idInd ))
->getQuery()->getResult();
$staff = array_column($staff, "idEvent");
$results = array_merge($participation,$contacts,$staff);
$results = array_unique($results);
$qb = $this->getDoctrine()->getManager()->createQueryBuilder();
$qb->add('select', 'e.idEvent,e.title, e.startOn, e.endOn, e.address, e.city, e.state, e.postcode, c.country')
->add('from', 'OceanExpertBundle:Events e')
->leftJoin('OceanExpertBundle:Countries', 'c', 'WITH', 'e.idCountry = c.idCountry')
->where('e.idEvent in (:idEvent)')
->andWhere('e.status = 1')
->orderBy('e.startOn', 'DESC')
->setParameter('idEvent', $results );
$resultData = $qb->getQuery()->getResult();
$paginator = $this->get('knp_paginator');
$members = $paginator->paginate(
$resultData,
$request->query->getInt('page', 1),
5,
array(
'pageParameterName' => 'page',
'sortDirectionParameterName' => 'dir'
)
);
//@todo some code goes here (i.e. your symfony request dispatching)
return $members;
}
}