<?php
namespace OceanExpertBundle\Controller;
use Doctrine\ORM\AbstractQuery;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use OceanExpertBundle\Entity\Groups;
use OceanExpertBundle\Entity\MemberGroups;
use OceanExpertBundle\Utils\SSP;
use Symfony\Component\Process\Process;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
class GroupController extends AbstractController
{
/**
* @todo add function description
*
* @return Response
*/
public function indexAction(): Response
{
return new Response('Group Index');
}
/**
* return all groups
*
* @param int $id id of the group for wich the permission will be checked
*
* @return Response
*/
public function allGroupsAction(int $id): Response
{
$twigTemplate = 'Group/groups.html.twig';
return $this->viewAllGroups($id, $twigTemplate);
}
/**
* do the real work to show all the groups
* will be used by both GroupsController and AdminController to show the list of groups
*
* @param int $id id of the group for wich the permission will be checked
* @param string $twigTemplate template to be used
*
* @return Response
*/
public function viewAllGroups(int $id, string $twigTemplate): Response
{
$isGroupAdmin = 0;
if (true === $this->get('security.authorization_checker')->isGranted('ROLE_USER')) {
$isGroupAdmin = $this->hasEditPermission($id);
}
/*
//let's check if the logged-in user has a 'real' profile
//the mandatory profile fields are all filled and the expert is active
$em = $this->getDoctrine()->getManager();
$userId = $this->get('security.token_storage')->getToken()->getUser()->getId();
if (!SecurityController::checkUserProfile($em, $userId)) {
return $this->redirect(
$this->generateUrl(
'user_profile_edit'
)
);
}
*/
$groupTree = $this->getDoctrine()
->getRepository('OceanExpertBundle:Groups')
->createQueryBuilder('e')
->select('e.idGroup, e.groupname, e.idParentgroup, e.groupOrder')
->where('e.idGroup = :groupId')
->setParameter(':groupId',$id)
->getQuery()
->getResult(AbstractQuery::HYDRATE_ARRAY);
$allgroups = self::allGroups($this->getDoctrine());
$groups = self::descendantsOf($id, $allgroups);
if ($groups == '') {
//@todo what happens here??
$groupTree[0]['children'] = array();
} else {
$groupTree[0]['children'] = $this->buildTree($groups,$id);
}
//@todo should be a dynamic list
$filtergroups = array(
31 => 'IOC',
315 => 'MPR',
47 => 'Capacity Development',
138 => 'HAB',
127 => 'OOS',
32 => 'GOOS',
46 => 'IODE',
269 => 'OBIS',
291 => 'ICAN',
78 => 'JCOMM',
169 => 'TSUNAMI',
234 => 'ITIC',
236 => 'Integrated Coastal Research',
);
return $this->render(
$twigTemplate,
array(
'data' => array(
'isGroupAdmin' => $isGroupAdmin,
'groups' => json_encode(
array($groupTree)
),
'filtergroups' => $filtergroups,
'treeGroup' => $id
)
)
);
}
/**
* @return Response
*/
public function addGroupsAction(Request $request)
{
$parentGroup = $request->request->get('parentId');
$groupName = $request->request->get('groupname');
$groupName = preg_replace('/[^a-zA-Z0-9\s\-\(\)]/', '', $groupName);
$group = new Groups();
$group->setGroupname($groupName);
$group->setIdParentgroup($parentGroup);
$group->setGroupOrder(0);
$group->setHasSite(0);
$group->setOfficialBody(0);
$group->setIdMstemplate(1);
$em = $this->getDoctrine()->getManager();
$em->persist($group);
$em->flush();
$groupId = $group->getIdGroup();
//why would be do a query for that??
//$groupName = $group->getGroupname();
return new JsonResponse(
array(
'status' => 1,
'childGroup' => $groupId,
'groupName' => $groupName
)
);
}
/**
* @return Response
*/
public function saveGroupOrderAction(Request $request)
{
$order = $request->request->get('order');
$groupOrders = json_decode($order);
foreach($groupOrders->groups as $groupData) {
$group = $this->getDoctrine()->getRepository('OceanExpertBundle:Groups')->findOneBy(array('idGroup' => $groupData->groupId));
$em = $this->getDoctrine()->getManager();
if ($group) {
$group->setIdParentgroup($groupData->parentId);
$group->setGroupOrder($groupData->order);
$em->persist($group);
$em->flush();
}
}
return new JsonResponse(array('status'=>1));
}
/**
* @return Response
*/
public function deleteGroupAction(Request $request)
{
$groupId = $request->request->get('groupId');
$em = $this->getDoctrine()->getManager();
$group = $this->getDoctrine()
->getRepository('OceanExpertBundle:Groups')
->findOneBy(
array(
'idGroup' => $groupId
)
);
$em->remove($group);
$em->flush();
$updateGroup = $this->getDoctrine()
->getRepository('OceanExpertBundle:MemberGroups')
->findBy(
array(
'idGroup' => $groupId
)
);
if ($updateGroup) {
foreach ($updateGroup as $groups) {
$em->remove($groups);
}
$em->flush();
}
return new JsonResponse(array('status'=>1));
}
/**
* @param $ar
* @param null $pid
*
* @return array
*/
public function buildTree( $ar, $pid = null )
{
$op = array();
$i=1;
foreach( $ar as $item ) {
if ( $item['idParentgroup'] == $pid ) {
$op[$i] = array(
'groupname' => preg_replace('/[^a-zA-Z0-9\s\-\(\)]/', '', $item['groupname']),
'idParentgroup' => $item['idParentgroup'],
'idGroup' => $item['idGroup'],
'groupOrder' => $item['groupOrder']
);
// using recursion
$children = $this->buildTree( $ar, $item['idGroup'] );
if ( $children ) {
$op[$i]['children'] = $children;
}
}
$i++;
}
return $op;
}
/**
* show the members of the group with the given group id
*
* @param int $groupId id of the group
*
* @return Response
*/
public function viewGroupAction(int $groupId): Response
{
$twigTemplate = 'Group/editGroup.html.twig';
return $this->viewGroup($groupId, $twigTemplate);
}
/**
* get the data of the group
* call the correct template
* this is used by this controller and by the AdminController
*
* @param int $groupId
* @param string $twigTemplate
*
* @return Response
*/
public function viewGroup(int $groupId, string $twigTemplate): Response
{
if (true === $this->get('security.authorization_checker')->isGranted('ROLE_USER')) {
$isGroupAdmin = $this->hasEditPermission($groupId);
} else {
$isGroupAdmin = 0;
}
/*
//let's check if the logged-in user has a 'real' profile
//the mandatory profile fields are all filled and the expert is active
$em = $this->getDoctrine()->getManager();
$userId = $this->get('security.token_storage')->getToken()->getUser()->getId();
if (!SecurityController::checkUserProfile($em, $userId)) {
return $this->redirect(
$this->generateUrl(
'user_profile_edit'
)
);
}
*/
//collect all the info about the group, the ancestors and subgroups
$allGroups = self::allGroups($this->getDoctrine());
$ancestors = array_reverse($this->getAncestors($groupId, $this->getDoctrine()));
$subgroups = self::descendantsOf($groupId, $allGroups);
if ($group = $this->getGroupDetailsById($groupId, $this->getDoctrine())) {
$user = $this->getDoctrine()
->getRepository('OceanExpertBundle:Indiv')
->findOneBy(
array(
'idInd' => $this
->get('security.token_storage')
->getToken()
->getUser()
)
);
$templates = array(
'1' => 'like normal search results',
'2' => 'with photos (if available)',
'3' => 'grouped by country'
);
$html = $this->renderView(
$twigTemplate,
array(
'data' => array(
'user' => $user,
'isGroupAdmin' => $isGroupAdmin,
'group' => $group,
'templates' => $templates,
'ancestors' => $ancestors,
'subgroups' => $subgroups
)
)
);
return new Response(
$html,
200,
array(
'Cache-Control' => 'no-cache, must-revalidate, post-check=0, pre-check=0'
)
);
} else {
return $this->render('Exception/error404.html.twig');
}
}
/**
* @param $id
*
* @return Response
*/
public function editGroupAction($id)
{
$ancestors = array_reverse($this->getAncestors($id, $this->getDoctrine()));
return $this->render(
'Group/editGroup.html.twig',
array(
'data' => array(
'ancestors' => $ancestors
)
)
);
}
/**
* save the new group settings
*
* @param Request $request
*
* @return JsonResponse
*/
public function saveGroupAction(Request $request): JsonResponse
{
$groupId = $request->request->get('groupid');
$groupName = $request->request->get('groupname');
$groupName = preg_replace('/[^a-zA-Z0-9\s\-\(\)]/', '', $groupName);
$description = $request->request->get('description');
$officialBody = $request->request->get('officialbody');
$template = $request->request->get('template');
$group = $this->getDoctrine()
->getRepository('OceanExpertBundle:Groups')
->findOneBy(
array(
'idGroup' => $groupId
)
);
if ($group) {
$em = $this->getDoctrine()->getManager();
$group->setGroupname($groupName);
$group->setDescription($description);
$group->setOfficialBody($officialBody);
$group->setIdMstemplate($template);
$em->persist($group);
$em->flush();
return new JsonResponse(
array(
'status' => 1,
'message' => 'Group updated'
)
);
} else {
return new JsonResponse(
array(
'status' => 0,
'message' => 'cannot find group with id ' . $groupId
)
);
}
}
/**
* save the new order of the members of a group
*
* @param Request $request
*
* @return JsonResponse
*/
public function saveGroupMemberOrderAction(Request $request): JsonResponse
{
$groupId = $request->request->get('groupid');
$memberOrder = json_decode($request->request->get('order'));
$em = $this->getDoctrine()->getManager();
foreach ($memberOrder as $order) {
$group = $this->getDoctrine()
->getRepository('OceanExpertBundle:MemberGroups')
->findOneBy(
array(
'idGroup' => $groupId,
'idInd' =>$order->idInd
)
);
if ($group) {
$group->setMemberOrder($order->newData);
$em->persist($group);
$em->flush();
} else {
return new JsonResponse(
array(
'status' => 0,
'message' => "cannot find group with id '$groupId' for expert '" . $order->idInd . "'"
)
);
}
}
return new JsonResponse(
array(
'status' => 1,
'message' => 'Group order saved'
)
);
}
/**
* @return mixed
*/
public static function allGroups($doctrine) {
//$groups = $this->getDoctrine()
return $doctrine
->getRepository('OceanExpertBundle:Groups')
->createQueryBuilder('e')
->select('e.idGroup, e.groupname, e.idParentgroup, e.groupOrder')
->addOrderBy('e.idParentgroup', 'ASC')
->addOrderBy('e.groupOrder', 'ASC')
->getQuery()
->getResult(AbstractQuery::HYDRATE_ARRAY);
}
/**
* @param $parentGroupId
* @param $groups
*
* @return array
*/
public static function childgroupsof($parentGroupId, $groups): array
{
$i=0;
$children = array();
foreach ($groups as $childGroup) {
if ($childGroup['idParentgroup'] == $parentGroupId) {
$children[$i]['idGroup'] = $childGroup['idGroup'];
$children[$i]['groupname'] = $childGroup['groupname'];
$children[$i]['idParentgroup'] = $childGroup['idParentgroup'];
$children[$i]['groupOrder'] = $childGroup['groupOrder'];
$i++;
}
}
return $children;
}
/**
* get all the groups that are a descendant of this group
*
* @param int $parentGroupId
* @param array $groups all the groups to check
*
* @return array
*/
public static function descendantsOf(int $parentGroupId, array $groups): array
{
$result = array();
$children = GroupController::childgroupsof($parentGroupId, $groups);
if ($children) {
$result = $children;
for ($i = 0; $i < count($children); $i++) {
$desc = GroupController::descendantsOf($children[$i]['idGroup'], $groups);
if ($desc) {
$result = GroupController::insertIntoAt($desc, $result, $children[$i]);
}
}
}
return $result;
}
/**
* @param $subarray
* @param $array
* @param $element
*
* @return mixed
*/
private static function insertIntoAt($subarray, $array, $element)
{
for($i = 0; $i < count($array); $i++) {
if ($array[$i] == $element) {
array_splice($array, $i+1, 0, $subarray);
return $array;
}
}
return $array;
}
/**
* get the list of groups where this group is a member of
*
* @param int $groupId the (sub)group to start with
*
* @return array
*/
public static function getAncestors(int $groupId, $doctrine): array
{
//this is useless and overwritten
//$group = $this->getGroupArrayById($groupId);
$i = 0;
$ancestors = array();
do {
$group = self::getGroupArrayById($groupId, $doctrine);
if (!$group
|| !is_array($group)
|| !count($group)
) {
//this will result in an endless loop
break;
}
$groupId = $group['idParentgroup'];
$ancestors[] = $group;
$i++;
} while($group['idParentgroup'] != 0);
return $ancestors;
}
/**
* get the information about a group as an associative array
*
* @param int $groupId
*
* @return array
*/
static function getGroupArrayById($groupId, $doctrine)
{
//$group = $this->getDoctrine()
$group = $doctrine
->getRepository('OceanExpertBundle:Groups')
->createQueryBuilder('e')
->select('e.idGroup, e.groupname, e.idParentgroup, e.groupOrder')
->where('e.idGroup = :groupid')
->setParameter('groupid',$groupId)
->getQuery()
->getResult(AbstractQuery::HYDRATE_ARRAY);
if (is_array($group)
&& isset($group['0'])
) {
return $group['0'];
} else {
return array();
}
}
/**
* get the details of a group with given group id
*
* @param int $groupId id of the group
*
* @return mixed
*/
static function getGroupDetailsById(int $groupId, $doctrine)
{
//$group = $this->getDoctrine()
$group = $doctrine
->getRepository('OceanExpertBundle:Groups')
->createQueryBuilder('e')
->select('e')
->where('e.idGroup = :groupid')
->setParameter('groupid', $groupId)
->getQuery()
->getResult(AbstractQuery::HYDRATE_ARRAY);
if ($group
&& is_array($group)
&& isset($group['0'])
) {
$group = $group['0'];
if (!isset($group['description'])
|| $group['description'] == ''
) {
$group['description'] = 'no description for this group';
}
if (!isset($group['officialBody'])
|| $group['officialBody'] == ''
) {
$group['officialBody'] = 'no Official Body info for this group';
}
return $group;
} else {
return false;
}
}
/**
* @param $groupId
* @return mixed
*/
function getGroupExpertsById($groupId)
{
$memberId = $this->getDoctrine()
->getRepository('OceanExpertBundle:MemberGroups')
->createQueryBuilder('g')
->select('g.idInd,g.idGroup,g.role,g.isLeader')
->where('g.idGroup = :groupid')
->setParameter('groupid',$groupId)
->getQuery()
->getResult();
return $memberId;
}
/**
* get an array of all the subgroups under a given group
* this is a recursive function that will keep on digging till nothing is found anymore
*
* @param int $groupId id of the parent group
*
* @return array|boolean
**/
function getAllSubGroups(int $groupId)
{
$subGroupIds = $this->getDoctrine()
->getRepository('OceanExpertBundle:Groups')
->createQueryBuilder('g')
->select('g.idGroup')
->where('g.idParentgroup = :groupId')
->setParameter('groupId', $groupId)
->getQuery()
->getResult();
if (is_array($subGroupIds)
&& count($subGroupIds)
) {
foreach ($subGroupIds as $subGroupId) {
$allGroupIds[] = $subGroupId['idGroup'];
$subSubGroups = $this->getAllSubGroups($subGroupId['idGroup']);
if ($subSubGroups != false) {
$allGroupIds = array_merge($allGroupIds, $subSubGroups);
}
}
return $allGroupIds;
} else {
return false;
}
}
/**
* get a list of all email addresses of the members of a group
* AND all the subgroups
*
* @param Request $request
*
* @return Response
*/
function getGroupExpertsAddressesAction(Request $request): Response
{
$addresses = array();
$groupId = (int) $request->get('groupId');
$allGroupIds = $this->getAllSubGroups($groupId);
if (is_array($allGroupIds)) {
$allGroupIds[] = $groupId;
} else {
$allGroupIds = array($groupId);
}
foreach ($allGroupIds as $groupId) {
/*
$allExpertData = $this->getDoctrine()
->getRepository('OceanExpertBundle:Indiv')
->createQueryBuilder('i')
->select('i.idInd, i.fname, i.mname, i.sname, i.email1, i.email2, mg.idGroup, c.country')
->leftJoin('OceanExpertBundle:MemberGroups', 'mg', 'WITH', 'mg.idInd = i.idInd')
->leftJoin('OceanExpertBundle:Countries', 'c', 'WITH', 'c.idCountry = i.idNationality')
->where('i.status = 1')
->andwhere('i.retired = 0')
->andwhere('i.deceased = 0')
->andWhere('mg.idGroup = :groupId')
->setParameter('groupId', $groupId)
->getQuery()
->getResult();
*/
//get the data of the members of the group
//use the SSP class to get the data, so we have the same data as in the datatable
//we need this data
$columns = array(
array('db' => 'email1', 'dt' => 0),
array('db' => 'email2', 'dt' => 1),
array('db' => 'fname', 'dt' => 2),
array('db' => 'mname', 'dt' => 3),
array('db' => 'sname', 'dt' => 4),
array('db' => 'country', 'dt' => 5)
);
$ssp = new SSP();
$allExpertData = $ssp->simple(
array(
'group' => $groupId
),
$this->getDoctrine()->getManager(),
'email1',
$columns
);
$allExpertData = $allExpertData['data'];
//get the data in the correct format
//if there is a second address, use that one
foreach ($allExpertData as $expertData) {
if (isset($expertData[1])
&& $expertData[1] != ''
) {
$email = $expertData[1];
} else {
$email = $expertData[0];
}
$addresses[$email] = array(
'email' => $email,
'fname' => $expertData[2],
'mname' => $expertData[3],
'sname' => $expertData[4],
'country' => htmlspecialchars_decode($expertData[5], ENT_QUOTES)
);
}
}
//create the csv file
$response = $this->render(
'Group/showAddresses.html.twig',
array(
'data' => array(
'addresses' => $addresses
)
)
);
$response->headers->set(
'Content-Type',
'text/csv'
);
$response->headers->set(
'Content-Disposition',
'attachment; filename="OceanExpertGroup' . $groupId . 'Addresses_' . date('Ymd') . '.csv"');
return $response;
}
/**
* @param Request $request
* @param int $id
* @param int $groupId
* @param int $i
*
* @return array
*/
function getExpertDetailsById(Request $request, $id, $groupId = null, $i = 1): array
{
$member = $this->getDoctrine()
->getRepository('OceanExpertBundle:Indiv')
->createQueryBuilder('i')
->select('i.idInd,i.fname,i.sname,i.email1,i.jobtitle,ins.idInst,ins.instName,ins.instNameEng,i.useInstAddr,ci.country as insCountry,c.country')
->leftJoin('OceanExpertBundle:IndivInstitution', 'ii', 'WITH', 'ii.idInd = i.idInd')
->leftJoin('OceanExpertBundle:Institutions', 'ins', 'WITH', 'ii.idInst = ins.idInst')
->leftJoin('OceanExpertBundle:Countries', 'c', 'WITH', 'i.countryCode = c.idCountry')
->leftJoin('OceanExpertBundle:Countries', 'ci', 'WITH', 'ins.countryCode = ci.idCountry')
->where('i.idInd = :id')
->andWhere('i.status = 1')
->setParameter('id',$id)
->getQuery()
->getResult();
$grouprole= '';
$groupOrder= '';
$primaryGroup= '';
if ($groupId) {
$memberGroup = $this->getDoctrine()
->getRepository('OceanExpertBundle:MemberGroups')
->findOneBy(
array(
'idGroup' => $groupId,
'idInd' => $id
)
);
$groupOrder = $i;
if ($memberGroup) {
$primaryGroup = $groupId;
$grouprole = $memberGroup->getRole();
$leader = $memberGroup->getIsLeader();
$groupOrder = $i;
if ( $memberGroup->getMemberOrder() != null) {
$groupOrder = $memberGroup->getMemberOrder();
}
} else {
$primaryGroup = '';
$grouprole = '';
$leader = '';
}
}
$memberdata = array();
if ($member) {
$memberdata['idInd'] = $member[0]['idInd'];
$memberdata['fname'] = $member[0]['fname'];
$memberdata['sname'] = $member[0]['sname'];
if (file_exists('uploads/profile/profile_' . $member[0]['idInd'].'.png')) {
$memberdata['image'] = $request->getBasePath() . '/uploads/profile/profile_' . $member[0]['idInd'].'.png';
} else {
$memberdata['image'] = $request->getBasePath() . '/assets/uploads/default.png';
}
$memberdata['name'] = $member[0]['fname'].' '.$member[0]['sname'];
$memberdata['jobtitle'] = $member[0]['jobtitle'];
$memberdata['idInst'] = $member[0]['idInst'];
$memberdata['instName'] = $member[0]['instName'];
$memberdata['instNameEng'] = $member[0]['instNameEng'];
$memberdata['useInstAddr'] = $member[0]['useInstAddr'];
if ($member[0]['useInstAddr'] === 1) {
$memberdata['country'] = $member[0]['insCountry'];
$memberdata['countryCode'] = $member[0]['insCountryCode'];
} else {
$memberdata['country'] = $member[0]['country'];
$memberdata['countryCode'] = $member[0]['countryCode'];
}
$memberdata['insCountry'] = $member[0]['insCountry'];
$memberdata['groupRole'] = $grouprole;
$memberdata['groupOrder'] = $groupOrder;
$memberdata['primaryGroup'] = $primaryGroup;
$memberdata['leader'] = isset($leader)?$leader:'';
}
return $memberdata;
}
/**
* @param $id
* @param Request $request
*
* @return Response
*/
public function getGroupDataAction($id, Request $request)
{
$isGroupAdmin = $this->hasEditPermission($id);
$file = $request->getBasePath() . 'groups/' . $id . '.json';
$members = file_get_contents($file);
$memberData = json_decode($members, true);
if ($request->request->get('action') == 'remove') {
foreach ($request->request->get('data') as $index => $item) {
$this->removeMemberFromGroup($item['idInd'], $id, $request);
}
}
if ($request->request->get('action') == 'edit') {
foreach ($request->request->get('data') as $index => $item) {
$this->editMemberGroupRole($item['idInd'], $id, $item['groupRole'], $request);
}
}
$i = 1;
foreach ($memberData['data'] as $key => $member) {
if ($member['groupOrder'] == '') {
$member['groupOrder'] = $i;
$i++;
}
}
return new JsonResponse($members);
}
/**
* @param int $groupId id of the group
* @param Request $request
*
* @todo do we still need this???
*
* @return Response
*/
public function rebuildGroupsAction(int $groupId, Request $request): Response
{
set_time_limit(0);
if ($this->container->has('profiler'))
{
$this->container->get('profiler')->disable();
}
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'SELECT gs.idGroup
FROM OceanExpertBundle\Entity\Groups gs
WHERE gs.idGroup > 30 ');
$result = $query->getResult();
if (count($result) == 0) {
echo 'Finished';
exit();
}
$ids = array_map('current', $result);
if ($request->query->get('count')) {
$count = $request->query->get('count');
} else {
$count = 0;
}
if (!isset($ids[$count])) {
echo 'Array finished';
exit();
}
$groupId = $ids[$count];
$allGroups = self::allGroups($this->getDoctrine());
$doctrine = $this->getDoctrine();
$em = $doctrine->getManager();
if ($groupId == 99999) {
$groups = self::descendantsOf($groupId,$allGroups);
} else {
$groups = array(
array(
'idGroup' => $groupId
)
);
}
$subgroups = self::descendantsOf($groups[0]['idGroup'],$allGroups);
$subgroups[] = $this->getGroupArrayById($groupId, $doctrine);
$i = 0;
$allmembers = array();
foreach ($subgroups as $group) {
$members = $this->getGroupExpertsById($group['idGroup']);
if ($members) {
foreach ($members as $member ) {
if ($groupId == $member['idGroup'] ) {
$allmembers[$i]['id'] = '';
$allmembers[$i]['idInd'] = $member['idInd'];
$allmembers[$i]['idGroup'] = $groupId;
$allmembers[$i]['mainGroup'] = $group['idGroup'];
$allmembers[$i]['isLeader'] = $member['isLeader'];
$allmembers[$i]['role'] = $member['role'];
$allmembers[$i]['lname'] = '';
} else {
$allmembers[$i]['id'] = '';
$allmembers[$i]['idInd'] = $member['idInd'];
$allmembers[$i]['idGroup'] = $groupId;
$allmembers[$i]['mainGroup'] = $group['idGroup'];
$allmembers[$i]['isLeader'] = '';
$allmembers[$i]['role'] = '';
$allmembers[$i]['lname'] = '';
}
$i++;
}
}
}
$allmembers = $this->array_msort(
$allmembers,
array(
'role' => SORT_DESC,
'isLeader' => SORT_DESC
)
);
$uniquemembers = $this->unique_multidim_array(
$allmembers,
'idInd'
);
$file = 'groups/' . $groupId . '.csv';
$fp = fopen($file, 'w');
foreach ($uniquemembers as $member) {
fputcsv($fp, $member);
}
fclose($fp);
/*
* Upload CSV Files in database
*/
$dbhost = $this->container->getParameter('database_host');
$dbuser = $this->container->getParameter('database_user');
$dbpass = $this->container->getParameter('database_password');
$connParams = $em->getConnection()->getParams();
//@todo what the hell is this doing here???? remove this Arno 06/04/2022
/*
$pdoConn = new \PDO(
'mysql:host=' . $dbhost . ';dbname=' . $connParams['dbname'],
$dbuser,
$dbpass,
array(
\PDO::MYSQL_ATTR_LOCAL_INFILE => true
)
);
$sql = "DELETE FROM group_members_ids
WHERE id_group = '$groupId'";
$stmt = $pdoConn->prepare($sql);
$stmt->execute();
$sql = "SET FOREIGN_KEY_CHECKS=0";
$stmt = $pdoConn->prepare($sql);
$stmt->execute();
$sql = "LOAD DATA LOCAL INFILE '$file' IGNORE
INTO TABLE group_members_ids
FIELDS TERMINATED BY ','
ENCLOSED BY '\"'
ESCAPED BY '\"'";
$stmt = $pdoConn->prepare($sql);
$stmt->execute();
*/
unlink($file);
$count ++;
return $this->render(
'Group/rebuildGroup.html.twig',
array(
'count' => $count
)
);
}
/**
* @todo do we still need this????
* if so remove code for group_members table!!!
*
* @param Request $request
*
* @return Response
*/
public function updateMemberIdsAction(Request $request): Response
{
if ($request->query->get('count')) {
$count = $request->query->get('count');
} else {
$count = 0;
}
$message = array();
$em = $this->getDoctrine()->getManager();
$limit =100;
$offset = $count * $limit;
$members = $em->createQueryBuilder()
->select('i.idInd')
->from('OceanExpertBundle:GroupMembersIds', 'i')
->where('i.idInd is NOT NULL')
->andWhere('i.lname is NOT NULL')
->setMaxResults($limit)
->setFirstResult($offset)
->getQuery()->getResult();
if (count($members) ==0) {
echo 'All data has been populated.';
exit();
}
foreach ($members as $member) {
$memberdetail = $this->getDoctrine()
->getRepository('OceanExpertBundle:Indiv')
->findOneByIdInd($member['idInd']);
if ($memberdetail) {
$memberId = $this->getDoctrine()
->getRepository('OceanExpertBundle:GroupMembersIds')
->findByIdInd($memberdetail->getIdInd());
if ($memberId) {
foreach ($memberId as $item) {
$item->setLname($memberdetail->getSname());
$em->persist($item);
$em->flush();
}
}
}
}
$count = $count+1;
return $this->render(
'OceanExpertBundle:Group:rebuild.group.htm.twig',
array(
'count' => $count
)
);
}
/**
* @todo this should be deleted, uses the wrong tables Arno 06/04/2022
*
* @param Request $request
*
* @return Response
*/
public function updateGroupMembersAction(Request $request): Response
{
$message = array();
$smember = $this->getDoctrine()
->getRepository('OceanExpertBundle:GroupMembersIds')
->findOneBy(
array(),
array(
'isLeader' => 'DESC',
'role' => 'DESC',
'lname' => 'ASC'
)
);
if (!$smember) {
echo 'All data has been populated.';
exit();
}
$members = $this->getDoctrine()
->getRepository('OceanExpertBundle:GroupMembersIds')
->findBy(
array(
'idGroup' => $smember->getIdGroup()
),
array(
'isLeader' => 'DESC',
'role' => 'DESC',
'lname' => 'ASC'
),
100
);
$em = $this->getDoctrine()->getManager();
foreach ($members as $member) {
$memberDetails = $this->getExpertDetailsById(
$request,
$member->getIdInd(),
$member->getIdGroup()
);
$addMember = $this->getDoctrine()
->getRepository('OceanExpertBundle:GroupMembers')
->findBy(
array(
'idInd' => $member->getIdInd(),
'idGroup' => $member->getIdGroup()
)
);
$em->remove($member);
$em->flush();
}
return $this->render(
'OceanExpertBundle:Group:rebuild.group.htm.twig'
);
}
/**
* @param int $id id of the expert to be removed
* @param int $groupId id of the group from where the expert should be removed
*
* @return void
*/
function removeMemberFromGroup(int $id, int $groupId, Request $request)
{
$em = $this->getDoctrine()->getManager();
$member = $this->getDoctrine()
->getRepository('OceanExpertBundle:MemberGroups')
->findOneBy(
array(
'idInd' => $id,
'idGroup' => $groupId
)
);
$em->remove($member);
$em->flush();
$this->rebuildGroupsAction($groupId, $request);
}
/**
* @param int $id
* @param int $groupId
* @param string $role
* @param Request $request
*
* @return void
*/
function editMemberGroupRole(int $id, int $groupId, string $role, Request $request)
{
$em = $this->getDoctrine()->getManager();
$member = $this->getDoctrine()
->getRepository('OceanExpertBundle:MemberGroups')
->findOneBy(
array(
'idInd' => $id,
'idGroup' => $groupId
)
);
$member->setRole($role);
$em->persist($member);
$em->flush();
$this->rebuildGroupsAction($groupId, $request);
}
/**
* membership to a group gives some people more power
* @todo : this is not a maintainable way of managing roles!!!!!!
*
* @param int $groupId id of the group to check
*
* @return bool
*/
function hasEditPermission(int $groupId): bool
{
$loggedUser = $this->get('security.token_storage')->getToken()->getUser();
$allAdminGroups = array(
//31 => array(161),
//315 => array(57),
//47 => array(57),
//138 => array(249),
//127 => array(34,35,307),
//32 => array(34,35,307),
//46 => array(57),
//269 => array(57),
//291 => array(292),
//78 => array(79),
//169 => array(239),
//234 => array(57),
//236 => array(247),
537 => array(564) //members of 'OBON Group Admins' have edit permission for the 'OBON' group
);
if (array_key_exists($groupId, $allAdminGroups)) {
$adminGroup = $allAdminGroups[$groupId];
$userGroups = $this->getDoctrine()
->getRepository('OceanExpertBundle:MemberGroups')
->findBy(
array(
'idInd' => $loggedUser->getId()
)
);
foreach ($userGroups as $groups) {
if (in_array($groups->getIdGroup(), $adminGroup)) {
return true;
}
}
}
return false;
}
/**
* @return JsonResponse
*/
function getAllGroupJsonAction(): JsonResponse
{
$groups = $this->getDoctrine()
->getRepository('OceanExpertBundle:Groups')
->createQueryBuilder('e')
->select('e.idGroup, e.groupname, e.idParentgroup, e.groupOrder')
->addOrderBy('e.groupname', 'ASC')
->getQuery()
->getResult(AbstractQuery::HYDRATE_ARRAY);
return new JsonResponse($groups);
}
/**
* @param Request $request
* @param int $id id of the expert to be added to the group, defaults to 0
* @param int $groupId id of the group where we want to add the expert to, defaults to 0
*
* @return JsonResponse
*/
function addGroupMemberAction(Request $request, $id = 0, $groupId = 0): JsonResponse
{
if (!$id
&& !$groupId
) {
$groupId = $request->request->get('groupid');
$id = $request->request->get('userid');
$groupRole = $request->request->get('grouprole');
} else {
$groupRole = '';
}
$em = $this->getDoctrine()->getManager();
$member = $this->getDoctrine()
->getRepository('OceanExpertBundle:MemberGroups')
->findOneBy(
array(
'idInd' => $id,
'idGroup' => $groupId
)
);
if (!$member) {
$member = new MemberGroups();
$member->setIdInd($id);
$member->setIdGroup($groupId);
$member->setRole($groupRole);
$member->setMemberOrder(0);
$member->setIsLeader(0);
$em->persist($member);
$em->flush();
}
//check if we are in all the parent groups also
//if not add this expert to the parent groups
//@todo is that a good idea???
/*
foreach ($this->getAncestors($groupId) as $childGroup) {
$memberGroup = $this->getDoctrine()
->getRepository('OceanExpertBundle:MemberGroups')
->findOneBy(
array(
'idInd'=>$id,
'idGroup' => $childGroup['idGroup']
)
);
if (!$memberGroup) {
$this->addGroupMemberAction($id, $childGroup['idGroup'], $request);
}
/*
if (!$memberGroup) {
$maxorder = $em->createQueryBuilder()
->select('MAX(e.groupOrder)')
->from('OceanExpertBundle:GroupMembers', 'e')
->where('e.idGroup = :groupid')
->setParameter('groupid',$childGroup['idGroup'])
->getQuery()
->getSingleScalarResult();
$order = $maxorder+1;
$memberdata = $this->getExpertDetailsById($id);
$memberGroup = new GroupMembers();
$memberGroup->setIdInd($id);
$memberGroup->setIdGroup($childGroup['idGroup']);
$memberGroup->setFname($memberdata['fname']);
$memberGroup->setLname($memberdata['sname']);
$memberGroup->setImage($memberdata['image']);
if ($childGroup['idGroup']==$groupId) {
$memberGroup->setGroupRole($groupRole);
} else {
$memberGroup->setGroupRole('');
}
$memberGroup->setIdInst($memberdata['idInst']);
$memberGroup->setInstName($memberdata['instName']);
$memberGroup->setInstNameEng($memberdata['instNameEng']);
$memberGroup->setUseInstAddr($memberdata['useInstAddr']);
$memberGroup->setInsCountry($memberdata['insCountry']);
$memberGroup->setCountry($memberdata['country']);
$memberGroup->setGroupOrder($order);
$memberGroup->setMainGroup($groupId);
$em->persist($memberGroup);
$em->flush();
}
}
//end inner comment
*/
return new JsonResponse(
array(
'status' => 1,
'message' => 'Member added to group'
)
);
}
/**
* @todo remove code for group_members
*
* @param Request $request
* @param array $data
* @param int $groupId id of the group where to add the experts, defaults to 0
*
* @return JsonResponse
*/
function addBulkGroupMemberAction(Request $request, $data = array(), $groupId = 0): JsonResponse
{
$groupId = $request->request->get('groupid');
$memberdata = $request->request->get('memberdata');
$memberdataArr = json_decode($memberdata);
foreach ($memberdataArr as $addmemberdata) {
$em = $this->getDoctrine()->getManager();
$member = $this->getDoctrine()
->getRepository('OceanExpertBundle:MemberGroups')
->findOneBy(
array(
'idInd' => $addmemberdata->id,
'idGroup' => $groupId
)
);
if (!$member) {
$member = new MemberGroups();
$member->setIdInd($addmemberdata->id);
$member->setIdGroup($groupId);
$member->setRole($addmemberdata->role);
$member->setMemberOrder(0);
$member->setIsLeader(0);
$em->persist($member);
$em->flush();
}
/*
foreach ($this->getAncestors($groupId) as $childGroup) {
$groupMember = $this->getDoctrine()
->getRepository('OceanExpertBundle:GroupMembers')
->findOneBy(
array(
'idInd' => $addmemberdata->id,
'idGroup' => $childGroup['idGroup']
)
);
if (!$groupMember) {
$maxorder = $em->createQueryBuilder()
->select('MAX(e.groupOrder)')
->from('OceanExpertBundle:GroupMembers', 'e')
->where('e.idGroup = :groupid')
->setParameter('groupid',$childGroup['idGroup'])
->getQuery()
->getSingleScalarResult();
$order = $maxorder+1;
$memberdata = $this->getExpertDetailsById($addmemberdata->id);
$groupMember = new GroupMembers();
$groupMember->setIdInd($addmemberdata->id);
$groupMember->setIdGroup($childGroup['idGroup']);
$groupMember->setFname($memberdata['fname']);
$groupMember->setLname($memberdata['sname']);
$groupMember->setImage($memberdata['image']);
if ($childGroup['idGroup']==$groupId) {
$groupMember->setGroupRole($addmemberdata->role);
} else {
$groupMember->setGroupRole('');
}
$groupMember->setIdInst($memberdata['idInst']);
$groupMember->setInstName($memberdata['instName']);
$groupMember->setInstNameEng($memberdata['instNameEng']);
$groupMember->setUseInstAddr($memberdata['useInstAddr']);
$groupMember->setInsCountry($memberdata['insCountry']);
$groupMember->setCountry($memberdata['country']);
$groupMember->setGroupOrder($order);
$groupMember->setMainGroup($groupId);
$em->persist($groupMember);
$em->flush();
}
}
*/
}
return new JsonResponse(
array(
'status' => 1,
'message' => 'Member added to group'
)
);
}
/**
* @return Response
*/
public function setGroupRoleAction(Request $request)
{
$memberID = $request->request->get('memberid');
$groupID = $request->request->get('groupid');
$role = $request->request->get('role');
$member = $this->getDoctrine()
->getRepository('OceanExpertBundle:MemberGroups')
->findOneBy(
array(
'idInd' => $memberID,
'idGroup' => $groupID
)
);
if ($member) {
$em = $this->getDoctrine()->getManager();
$member->setRole($role);
$em->persist($member);
$em->flush();
} else {
return new JsonResponse(
array(
'status' => 0,
'message' => "Expert '$memberID' not found in group '$groupID'"
)
);
}
return new JsonResponse(
array(
'status' => 1,
'message' => 'Role updated successfully.'
)
);
}
/**
* @return Response
*/
public function deleteGroupMemberAction(Request $request)
{
$memberids = $request->request->get('memberids');
$groupId = $request->request->get('groupid');
foreach ($memberids as $idInd) {
$member = $this->getDoctrine()
->getRepository('OceanExpertBundle:MemberGroups')
->findOneBy(
array(
'idInd' => $idInd,
'idGroup' => $groupId
)
);
if ($member) {
$em = $this->getDoctrine()->getManager();
$em->remove($member);
$em->flush();
}
}
return new JsonResponse(
array(
'status' => 1,
'message' => 'Members deleted successfully.'
)
);
}
/**
* add expert to group(s)
*
* @param Request $request
*
* @return Response
*/
public function setGroupsAction(Request $request): Response
{
$id = $request->request->get('userId');
$groups = $request->request->get('groups');
$message = '';
$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) {
$this->addGroupMemberAction($request, $id, $value);
}
}
} else {
$updateGroup = $this->getDoctrine()
->getRepository('OceanExpertBundle:MemberGroups')
->findBy(
array(
'idInd' => $id
)
);
$em = $this->getDoctrine()->getEntityManager();
foreach ($updateGroup as $groups) {
$em->remove($groups);
}
$em->flush();
}
} else {
$message = json_encode(array(
'status' => 2,
'error' => 'you do not have the correct rights to do this'
));
}
return new Response($message);
}
/**
* @param $array
* @param $cols
*
* @return array
*/
function array_msort($array, $cols): array
{
$colarr = array();
foreach ($cols as $col => $order) {
$colarr[$col] = array();
foreach ($array as $k => $row) { $colarr[$col]['_'.$k] = strtolower($row[$col]); }
}
$eval = 'array_multisort(';
foreach ($cols as $col => $order) {
$eval .= '$colarr[\''.$col.'\'],'.$order.',';
}
$eval = substr($eval,0,-1).');';
eval($eval);
$ret = array();
foreach ($colarr as $col => $arr) {
foreach ($arr as $k => $v) {
$k = substr($k,1);
if (!isset($ret[$k])) $ret[$k] = $array[$k];
$ret[$k][$col] = $array[$k][$col];
}
}
return $ret;
}
/**
* @param $array
* @param $key
*
* @return array
*/
function unique_multidim_array($array, $key): array
{
$temp_array = array();
$i = 0;
$key_array = array();
foreach($array as $val) {
if (!in_array($val[$key], $key_array)) {
$key_array[$i] = $val[$key];
$temp_array[$i] = $val;
}
$i++;
}
return $temp_array;
}
/**
* @todo : check what is going on here and if this is used Arno 5/07/22
*
* @return JsonResponse
*/
public function sendGroupEmailAction(): JsonResponse
{
$message = array();
$process = new Process(array('php ../app/console oceanexpert:create-users'));
$process->start();
while ($process->isRunning()) {
// waiting for process to finish
}
echo $process->getOutput();
return new JsonResponse(
array(
'status' => 1,
'message' => $message
)
);
}
/**
* @param EntityManagerInterface $entityManager
*
* @return JsonResponse
*/
public function dataTablesServerProcessingAction(
$groupId,
EntityManagerInterface $entityManager
): JsonResponse {
//dump($request);
//die();
// Table's primary key
$primaryKey = self::getPrimaryKey();
// Array of database columns which should be read and sent back to DataTables.
// The `db` parameter represents the column name in the database, while the `dt`
// parameter represents the DataTables column identifier. In this case simple
// indexes
$columns = self::getColumns();
//check if we got some info from the request itself
//pass this to the method
//this used to be done by passing $_GET which is not the correct way
//not useable for the API calls
$request = array();
//we are looking for these parameters
$params = array(
'order',
'columns',
'search',
'group',
'start',
'length',
'draw',
'_'
);
foreach($params as $param) {
$request[$param] = '';
if (isset($_GET[$param])) {
$request[$param] = $_GET[$param];
}
}
$ssp = new SSP();
$data = $ssp->simple(
$request,
$entityManager,
$primaryKey,
$columns
);
return new JsonResponse($data);
}
/**
* give back the list of colums we need for the datatables
* this is done by a get method as this is used by the API also
*
* @return array
*/
public static function getColumns(): array
{
return array(
array( 'db' => 'id', 'dt' => 'id' ),
array( 'db' => 'memberOrder', 'dt' => 'groupOrder' ),
array( 'db' => 'idInd', 'dt' => 'DT_RowId' ),
array( 'db' => 'idInd', 'dt' => 'idInd' ),
array( 'db' => 'fname', 'dt' => 'fname' ),
array( 'db' => 'sname', 'dt' => 'sname' ),
array( 'db' => 'image', 'dt' => 'image' ),
array( 'db' => 'idInst', 'dt' => 'idInst' ),
array( 'db' => 'instName', 'dt' => 'instName' ),
array( 'db' => 'fullname', 'dt' => 'name' ),
array( 'db' => 'status', 'dt' => 'status' ),
array( 'db' => 'deceased', 'dt' => 'deceased' ),
array( 'db' => 'retired', 'dt' => 'retired' ),
array( 'db' => 'doNotInvite', 'dt' => 'doNotInvite' ),
array( 'db' => 'role', 'dt' => 'groupRole' ),
array( 'db' => 'country', 'dt' => 'country' )
);
}
/**
* give back the primary key we need for the datatables
* this is done by a get method as this is used by the API also
*
* @return string
*/
public static function getPrimaryKey(): string
{
return 'idInd';
}
}