<?php

/**
 * services actions.
 *
 * @package    foniva
 * @subpackage services
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class servicesActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
    
  }
  
  public function executeTenantinfo(sfWebRequest $request)
  {
   	$this->tenants = Doctrine_Query::create()
						->select('t.dbid, t.name, t.fullname, t.description,
									t.limit_agents, t.limit_nb_agents, t.limit_queues, t.limit_nb_queues,
									t.limit_inbounds, t.limit_nb_inbounds, t.limit_outbounds, t.limit_nb_outbounds,
									t.active,
									COUNT(ca.dbid) as nb_connected_agents')
						->from('ConfTenant t')
						->leftJoin('t.ConfAgent ca on t.dbid = ca.tenant_fk and ca.isconnected = "yes"')
						->where(1);
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->tenants = $this->tenants->andWhere('t.dbid = ?', fonivaFilter::getCurrentUserTenantId());
	$this->tenants = $this->tenants->andWhere('ca.isconnected = ?', 'yes');
	$this->tenants->groupBy('t.dbid');
				
	$this->tenants = $this->tenants->execute();
	/*
	if(!fonivaFilter::isCurrentUserSuperTenant())
	{
		$tenant = fonivaFilter::getCurrentUserTenant();
		array_push($this->tenants, $tenant);
	} 
	else
	{
		
	}
	*/
  }
  
  /* =================== */
  /* AGENTS              */
  /* =================== */
  public function executeAgentstatus(sfWebRequest $request)
  {	
	if($request->getParameter('username') == NULL || $request->getParameter('username') == '')
		$this->forward404('Missing username');
	
	$username = $request->getParameter('username');
	if(!fonivaFilter::isCurrentUserSuperTenant())
	{
		if(strpos($username, '@')	=== false)
			$username = $username.'@'.fonivaFilter::getCurrentUserTenant()->getName();
	}
	//echo $username;
	//exit();
	$this->forward404Unless($this->conf_agent = Doctrine::getTable('ConfAgent')->findOneByUsername($username), sprintf('Agent does not exist (%s).', $username));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $this->conf_agent->getTenantFk() == fonivaFilter::getCurrentUserTenantId(), sprintf('Agent does not exist (%s).', $username));
	
	$this->logagentstatus = Doctrine_Query::create()
								->select('le.agentstatus, le.notreadyreason, UNIX_TIMESTAMP(le.started_at) as started_at_timestamp')
								->from('LivelogAgentStatus le')
								->where('le.agentdbid = ?', $this->conf_agent->dbid)
								->orderBy('dbid desc')
								->limit(1)
								->execute();
	if(sizeof($this->logagentstatus) > 0)
		$this->logagentstatus = $this->logagentstatus[0];
	else 
		$this->logagentstatus = NULL;
  }
  
  public function executeAgents(sfWebRequest $request)
  {
	$username = $request->getParameter('username');
	if($username  && !fonivaFilter::isCurrentUserSuperTenant())
	{
		if(strpos($username, '@') === false)
			$username = $username.'@'.fonivaFilter::getCurrentUserTenant()->getName();
	}
	
	$this->groups = fonivaFilter::currentUserManagedGroups();
	
	$this->groups_list = array();
	$this->groupids_list = array('');
	foreach($this->groups as $g)
	{
		$this->groups_list[$g->getDbid()] = $g;
		array_push($this->groupids_list, $g->getDbid());
	}
	
	$this->teams = Doctrine_Query::create()
					->select('t.dbid, t.name, u.firstname, u.lastname')
					->from('ConfTeam t')
					->leftJoin('t.ConfUser u')
					->orderBy('t.name');
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->teams->where('t.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
	$this->teams = $this->teams->execute();
	
	
	$this->agents = Doctrine_Query::create()
						->select('a.dbid, a.shortusername, a.username, a.active, a.isconnected,
									a.group_fk, g.name as groupname,
									a.site_fk, s.name as sitename,
									a.team_fk, t.name as teamname,
									a.created_at, a.updated_at,
									i.firstname as firstname, i.lastname as lastname
								'
								)
						->from('ConfAgent a')
						->leftJoin('a.ConfGroup g ON g.dbid = a.group_fk')
						->leftJoin('a.ConfSite s ON s.dbid = a.site_fk')
						->leftJoin('a.ConfTeam t ON t.dbid = a.team_fk')
						->leftJoin('a.ConfAgentInfo i ON i.dbid = a.info_fk')
						->orderBy('a.username')
						->groupBy('a.dbid')
						->where('1');
	
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->agents->andwhere('a.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
		
	if(!fonivaFilter::canCurrentUserManageAllGroups())
		$this->agents->andwhere('a.group_fk in ?', array($this->groupids_list));
		
	if($username)
		$this->agents->andWhere('a.username = ?', $username);
	
	$this->agents = $this->agents->execute();
	
	$this->liveagentstatusarr = array();
	$this->liveagentstatus = Doctrine_Query::create()
						->select('l.agentdbid, l.agentstatus, l.notreadyreason, UNIX_TIMESTAMP(l.started_at) as currentstatus_since')
						->from('LivelogAgentStatus l')
						->execute();
	
	foreach($this->liveagentstatus as $s)
		$this->liveagentstatusarr[$s->agentdbid] = $s;
						
  }
  
  public function executeGroups(sfWebRequest $request)
  {
	$groupname = $request->getParameter('groupname');
	
	$this->groups = Doctrine_Query::create()
						->select('g.dbid, g.name, g.tenant_fk, g.created_at, g.updated_at, count(a.dbid) as nbagents')
						->from('ConfGroup g')
						->leftJoin('g.ConfAgent a ON a.group_fk = g.dbid')
						->orderBy('g.name')
						->groupBy('g.dbid')
						->where('1');
	
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->groups->andwhere('g.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
		
	if($groupname)
		$this->groups->andWhere('g.name = ?', $groupname);
	
	$this->groups = $this->groups->execute();
  }
  
  public function executeSites(sfWebRequest $request)
  {
	$sitename = $request->getParameter('sitename');
	
	$this->sites = Doctrine_Query::create()
						->select('s.dbid, s.name, s.tenant_fk, s.created_at, s.updated_at, count(a.dbid) as nbagents')
						->from('ConfSite s')
						->leftJoin('s.ConfAgent a ON a.site_fk = s.dbid')
						->orderBy('s.name')
						->groupBy('s.dbid')
						->where('1');
	
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->sites->andwhere('s.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
		
	if($sitename)
		$this->sites->andWhere('s.name = ?', $sitename);
	
	$this->sites = $this->sites->execute();
  }
  
  public function executeSkills(sfWebRequest $request)
  {
	$skillname = $request->getParameter('skillname');
	
	$this->skills = Doctrine_Query::create()
						->select('s.dbid, s.name, s.tenant_fk, s.created_at, s.updated_at, count(a.dbid) as nbagents')
						->from('ConfSkill s')
						->leftJoin('s.ConfAgentSkill a ON a.skill_fk = s.dbid')
						->orderBy('s.name')
						->groupBy('s.dbid')
						->where('a.active = "yes"');
	
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->skills->andwhere('s.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
		
	if($sitename)
		$this->skills->andWhere('s.name = ?', $skillname);
	
	$this->skills = $this->skills->execute();
  }
  
  
  public function executeQueues(sfWebRequest $request)
  {
	$queuename = $request->getParameter('queuename');
	
	$this->queues = Doctrine_Query::create()
						->select('q.dbid, q.name')
						->from('ConfQueue q')
						->orderBy('q.name')
						->where('1');
	
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->queues->andwhere('q.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
		
	if($queuename)
		$this->queues->andWhere('q.name = ?', $queuename);
	
	$this->queues = $this->queues->execute();
  }
  
  public function executeAgentcreate(sfWebRequest $request)
  {
	$username = $request->getParameter('username');
	$password = $request->getParameter('password');
	$email = $request->getParameter('email');
	$firstname = $request->getParameter('firstname');
	$lastname = $request->getParameter('lastname');
	$groupname = $request->getParameter('groupname');
	$sitename = $request->getParameter('sitename');
	$tenant = $request->getParameter('tenant');
	
	if(!$username)
	{
		$this->errmsg = 'Missing agent username';
		$this->setTemplate('APIError');
		return 'Err';
	}
	
	if(!$password)
  	{
		$this->errmsg = 'Missing agent password';
		$this->setTemplate('APIError');
		return 'Err';
	}
	
	//check 
	
	$groupdbid = NULL;
	if($groupname)
	{
		$group = Doctrine_Query::create()
						->select('g.dbid, g.name')
						->from('ConfGroup g')
						->where('g.name = ?', $groupname);
		if(!fonivaFilter::isCurrentUserSuperTenant())
			$group->andWhere('g.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
		$group = $group->execute();
		if(sizeof($group) > 0)
			$groupdbid = $group[0]->dbid;
		else
		{
			$this->errmsg = 'No such agent group "'.$groupname.'"';
			$this->setTemplate('APIError');
			return 'Err';
	    }
	}
	
	$sitedbid = NULL;
	if($sitename)
	{
		$site = Doctrine_Query::create()
						->select('s.dbid, s.name')
						->from('ConfSite s')
						->where('s.name = ?', $sitename);
		if(!fonivaFilter::isCurrentUserSuperTenant())
			$site->andWhere('s.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
		$site = $site->execute();
		if(sizeof($site) > 0)
			$sitedbid = $site[0]->dbid;
		else
		{
			$this->errmsg = 'No such site "'.$sitename.'"';
			$this->setTemplate('APIError');
			return 'Err';
	    }
	}
	
	$ctenant = NULL;
	if(fonivaFilter::isCurrentUserSuperTenant())
	{
		$ctenant = $tenant;
		//TODO : check if tenant exists
	}
	else
	{
		//if we are not a super tenant, set new user to current user
		$ctenant = fonivaFilter::getCurrentUserTenant();
	}
	$sf_username = $username;
	$jb_username = $username; //jabber cannot accept '@' in username
	if($ctenant != NULL)
	{
		$sf_username = $sf_username.'@'.$ctenant->getName();
		$jb_username = $jb_username.'_'.$ctenant->getName();
	}
	
	$agent = Doctrine::getTable('ConfAgent')->findOneByUsername($sf_username);
	if($agent)
	{
		$this->errmsg = 'Agent with username '.$username.' already exists.';
		$this->setTemplate('APIError');
		return 'Err';
	}
	
	$strippedusername = preg_replace("/[^a-zA-Z0-9\s]/", "", $jb_username);
	
	$conf_agent = new ConfAgent();
	$conf_agent->setUsername($sf_username);
	$conf_agent->setShortusername($username);
	$conf_agent->setExtension(sfConfig::get('app_agent_extensionprefix').$strippedusername);
	$conf_agent->setGroupFk($groupdbid);
	$conf_agent->setSiteFk($sitedbid);
	//if($form->getValue('hourlywage') != NULL)	//because maybe the user doesn have privilege
	//  $conf_agent->setHourlywage($form->getValue('hourlywage'));
	//$conf_agent->setActive($form->getValue('active'));
	$conf_agent->setLastmodifiedBy($this->getUser()->getUsername());
	
	if(fonivaFilter::isCurrentUserSuperTenant())
  	{
		//$conf_agent->setTenantFk($form->getValue('tenant_fk'));
	}
	else
		$conf_agent->setTenantFk(fonivaFilter::getCurrentUserTenantId());
	
	$newagent = $conf_agent->isNew();
	$conf_agent->setPbxUsername($conf_agent->getExtension());
	if($newagent) /* on new agent, generate pbx username and password */
	{
		$conf_agent->setPbxPassword($this->generateword(sfConfig::get('app_generator_pbxusernamelength')));
	}
	
	
	$sfu = $conf_agent->getsfGuardUser();
	if(!$sfu)
	{
		$sfu = new sfGuardUser();
	}
	
	$sfu->setUsername($sf_username);
	if($password != '')
	  $sfu->setPassword($password);
	$sfu->setIsActive('1');
	$sfu->save();
	
	$sfgs = $sfu->getsfGuardUserGroup();
	if(sizeof($sfgs) <= 0)
	{
	  $sfg = new sfGuardUserGroup();
	  $sfg->setUserId($sfu->getId());
	  $sfg->setGroupId(3); //todo : make this configurable
	  $sfg->save();
	}
	
	//security ips
	/*
	$agtsecurity = $form['securityloginform']->getValue();	  
	$ssip = $sfu->getSfGuardUserAllowedoriginips();
	if(sizeof($ssip) <= 0)
		$ssip = new SfGuardUserAllowedoriginips();
	else
		$ssip = $ssip[0];
	$ssip->setUserId($sfu->id);
	$ssip->setOriginIps($agtsecurity['origin_ips']); 
	$ssip->save();
	*/
	
	//add this user also in the specific USERTYPE_GROUP_ADMINPANELUSER
	if(!$sfu->hasGroup('USERTYPE_GROUP_AGENTPANELUSER'))
	{
	  $sfu->addGroupByName('USERTYPE_GROUP_AGENTPANELUSER');
	}
	
	$sfs = $conf_agent->getConfAgentSetting();
	if(!$sfs)
	$sfs = new ConfAgentSetting();
	
	/*$agtsettings = $form['settingform']->getValue();	  
	$sfs->setWrapupmode($agtsettings['wrapupmode']);
	$sfs->setWrapuptime($agtsettings['wrapuptime']);
	$sfs->setAutoreadyatstart($agtsettings['autoreadyatstart']);
	$sfs->setActivityatstartFk(($agtsettings['activityatstart_fk'] == '' ? NULL : $agtsettings['activityatstart_fk']));
	$sfs->setAutoreadyafteroutbound($agtsettings['autoreadyafteroutbound']);
	$sfs->setActivityafteroutboundFk(($agtsettings['activityafteroutbound_fk'] == '' ? NULL : $agtsettings['activityafteroutbound_fk']));
	//$sfs->setCanbrowse($agtsettings['canbrowse']);
	$sfs->setOutboundurl($agtsettings['outboundurl']);
	$sfs->setOpenurlInnewtab($agtsettings['openurl_innewtab']);
	$sfs->setBrowserHomepage($agtsettings['browser_homepage']);
	$sfs->setMandatoryCalldispositions($agtsettings['mandatory_calldispositions']);
	$sfs->setInheritfromparent($agtsettings['inheritfromparent']);
	*/
	$sfs->save();
	
	$sfi = $conf_agent->getConfAgentInfo();
	if(!$sfi)
	{
	$sfi = new ConfAgentInfo();  
	}
	
	//$agtinfos = $form['infoform']->getValue();
	$sfi->setFirstname($firstname);
	$sfi->setLastname($lastname);
	$sfi->setEmail($email);
	$sfi->save();
	
	
	
	
	/* create a jabber user so the agent can connect */
	$jbu = $conf_agent->getJbUser();
	if(!$jbu)
	{
		$jbu = new JbUser();  
	}
	$jbu->setType('agent');
	$jbu->setUsername($jb_username);
	if($password != '')
	  $jbu->setPassword(md5($password));
	//$jbu->setActive($form->getValue('active'));
	$jbu->save();
	
	/* save call dispositions */
	
	
	/* save call dispositions */
	/*
	$assigned_calldispositionarr = $request->getParameter('assigned_calldisposition');
	Doctrine_Query::create()
		->from('ConfAgentSettingCalldisposition')
		->where('setting_fk = ?', $sfs->getDbid())
		->delete()
		->execute();	  
	if(is_array($assigned_calldispositionarr) && sizeof($assigned_calldispositionarr) > 0)
	{
	  for($i = 0; $i < sizeof($assigned_calldispositionarr); $i++)
	  {
		$dispositionid = $assigned_calldispositionarr[$i];
		$asscalldisp = new ConfAgentSettingCalldisposition();
		$asscalldisp->setSettingFk($sfs->getDbid());
		$asscalldisp->setDispositionFk($dispositionid);
		$asscalldisp->save();
	  }
	}
	*/
	
	/* auto assign group */
	$this->dispatch_jabber_user_to_groups($jbu);
	
	//save the agent now 
	$conf_agent->setSettingFk($sfs->getDbid());
	$conf_agent->setInfoFk($sfi->getDbid());
	$conf_agent->setUserFk($sfu->getId());
	$conf_agent->setJbuserFk($jbu->getDbid());
	$conf_agent->save();
	
	
	
	//maybe this agent is connected ... send foniva message
	if($conf_agent->getIsconnected() == 'yes')
	{
		/* *********************** */
	   /* send to foniva server */
	   /* *********************** */
		fonivaFilter::foniva_send_toserver("MSG_AGENT_UPDATED", 
												"agentid", $conf_agent->getDbid());
	}
	
	//what ever the agent is connected or not, if it is a new agent, send this message to cti 
	//to tell him that the pbx informations has been updated and he need to send to the pbx
	if($newagent) 
	{
	   /* *********************** */
	   /* send to foniva server */
	   /* *********************** */
		fonivaFilter::foniva_send_toserver("MSG_AGENT_PBXINFOS_UPDATED", 
												"agentid", $conf_agent->getDbid());
	  
	}
	
	$this->agents = array();
	array_push($this->agents, $conf_agent);
	$this->setTemplate('agents'); 
	//$this->forward('services', 'agents'?username='.$username);
  }
  
  public function executeAgentdelete(sfWebRequest $request)
  {
	$username = $request->getParameter('username');
	
	if(!$username)
	{
		$this->errmsg = 'Missing agent username';
		$this->setTemplate('APIError');
		return 'Err';
	}
	
	$ctenant = NULL;
	if(fonivaFilter::isCurrentUserSuperTenant())
	{
		$ctenant = $tenant;
		//TODO : check if tenant exists
	}
	else
	{
		//if we are not a super tenant, set new user to current user
		$ctenant = fonivaFilter::getCurrentUserTenant();
	}
	$sf_username = $username;
	$jb_username = $username; //jabber cannot accept '@' in username
	if($ctenant != NULL)
	{
		$sf_username = $sf_username.'@'.$ctenant->getName();
		$jb_username = $jb_username.'_'.$ctenant->getName();
	}
	
	$agent = Doctrine::getTable('ConfAgent')->findOneByUsername($sf_username);
	if(!$agent)
	{
		$this->errmsg = 'Agent with username '.$username.' doesn\'t exist.';
		$this->setTemplate('APIError');
		return 'Err';
	}
	
		
    $agent->delete();
	if(($sfu = $agent->getsfGuardUser()))
		$sfu->delete();
	if(($sfgs = $sfu->getsfGuardUserGroup()))
		$sfgs->delete();
	if(($sfs = $agent->getConfAgentSetting()))
		$sfs->delete();
	if(($jbu = $agent->getJbUser()))
		$jbu->delete();
		
	/* *********************** */
	/* send to foniva server */
	/* *********************** */
	fonivaFilter::foniva_send_toserver("MSG_AGENT_PBXINFOS_DELETED", 
										"agentid", $agent->getDbid(),
										"extension", $agent->getExtension()	);
  }
  
  public function executeAgentsetgroup(sfWebRequest $request)
  {
	$username = $request->getParameter('username');
	$groupname = $request->getParameter('groupname');
	
	if(!$username)
	{
		$this->errmsg = 'Missing agent username';
		$this->setTemplate('APIError');
		return 'Err';
	}
	
	$groupdbid = NULL;
	if($groupname)
	{
		$group = Doctrine_Query::create()
						->select('g.dbid, g.name')
						->from('ConfGroup g')
						->where('g.name = ?', $groupname);
		if(!fonivaFilter::isCurrentUserSuperTenant())
			$group->andWhere('g.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
		$group = $group->execute();
		if(sizeof($group) > 0)
			$groupdbid = $group[0]->dbid;
		else
		{
			$this->errmsg = 'No such agent group "'.$groupname.'"';
			$this->setTemplate('APIError');
			return 'Err';
	    }
	}
	
	$ctenant = NULL;
	if(fonivaFilter::isCurrentUserSuperTenant())
	{
		$ctenant = $tenant;
		//TODO : check if tenant exists
	}
	else
	{
		//if we are not a super tenant, set new user to current user
		$ctenant = fonivaFilter::getCurrentUserTenant();
	}
	$sf_username = $username;
	$jb_username = $username; //jabber cannot accept '@' in username
	if($ctenant != NULL)
	{
		$sf_username = $sf_username.'@'.$ctenant->getName();
		$jb_username = $jb_username.'_'.$ctenant->getName();
	}
	
	$agent = Doctrine::getTable('ConfAgent')->findOneByUsername($sf_username);
	if(!$agent)
	{
		$this->errmsg = 'Agent with username '.$username.' doesn\'t exist.';
		$this->setTemplate('APIError');
		return 'Err';
	}
	
	$agent->setGroupFk($groupdbid);
	$agent->save();
	
	//maybe this agent is connected ... send foniva message
	if($agent->getIsconnected() == 'yes')
	{
		/* *********************** */
	   /* send to foniva server */
	   /* *********************** */
		fonivaFilter::foniva_send_toserver("MSG_AGENT_UPDATED", 
												"agentid", $agent->getDbid());
	}
	
	$this->agents = array();
	array_push($this->agents, $agent);
	$this->setTemplate('agents');	
  }
  
  public function executeAgentsetskill(sfWebRequest $request)
  {
	$username = $request->getParameter('username');
	$skillname = $request->getParameter('skillname');
	$skillscore = $request->getParameter('skillscore');
	
	if(!$username)
	{
		$this->errmsg = 'Missing agent username';
		$this->setTemplate('APIError');
		return 'Err';
	}
	
	$skilldbid = NULL;
	if($skillname)
	{
		$skill = Doctrine_Query::create()
						->select('g.dbid, g.name')
						->from('ConfSkill g')
						->where('g.name = ?', $skillname);
		if(!fonivaFilter::isCurrentUserSuperTenant())
			$skill->andWhere('g.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
		$skill = $skill->execute();
		if(sizeof($skill) > 0)
			$skilldbid = $skill[0]->dbid;
		else
		{
			$this->errmsg = 'No such agent skill "'.$skillname.'"';
			$this->setTemplate('APIError');
			return 'Err';
	    }
	}
	
	
	
	$ctenant = NULL;
	if(fonivaFilter::isCurrentUserSuperTenant())
	{
		$ctenant = $tenant;
		//TODO : check if tenant exists
	}
	else
	{
		//if we are not a super tenant, set new user to current user
		$ctenant = fonivaFilter::getCurrentUserTenant();
	}
	$sf_username = $username;
	$jb_username = $username; //jabber cannot accept '@' in username
	if($ctenant != NULL)
	{
		$sf_username = $sf_username.'@'.$ctenant->getName();
		$jb_username = $jb_username.'_'.$ctenant->getName();
	}
	
	$agent = Doctrine::getTable('ConfAgent')->findOneByUsername($sf_username);
	if(!$agent)
	{
		$this->errmsg = 'Agent with username '.$username.' doesn\'t exist.';
		$this->setTemplate('APIError');
		return 'Err';
	}
	
	Doctrine_Query::create()
		->update('ConfAgentSkill cs')
		->set('cs.active', '?', 'no')
		->where('cs.agent_fk = ? AND cs.skill_fk = ?', array($agent->dbid, $skilldbid))
		->execute();
	
	
		
	$changelog_skillstr = '';
	
	$asc = Doctrine_Query::create()
					->select('cs.dbid, cs.agent_fk, cs.skill_fk, cs.active')
					->from('ConfAgentSkill cs')
					->where('cs.agent_fk = ? AND cs.skill_fk = ?', array($agent->dbid, $skilldbid))
					->execute();
	
	if(sizeof($asc) > 0)
	{
		$asc = $asc[0];
		$asc->setAgentFk($agent->dbid);
		$asc->setSkillFk($skilldbid);
		$asc->setScore($skillscore);
		$asc->setActive('yes');
		$asc->save();
	}
	else
	{
		$asc = new ConfAgentSkill();
		$asc->setAgentFk($agent->dbid);
		$asc->setSkillFk($skilldbid);
		$asc->setScore($skillscore);
		$asc->setActive('yes');
		$asc->save();
	}
		
	$changelog_skillstr = 'Added '.$skill->name;
	
	$changelog = new LogAgentskillsChangelog();
	$changelog->setOccuredDate(date('Y-m-d H:i:s'));
	$changelog->setModifiedby($this->getUser()->getUsername());
	$changelog->setAgentdbid($agent->dbid);
	$changelog->setSkillsChangedto($changelog_skillstr);
	$changelog->save();
	
	//maybe this agent is connected ... send foniva message
	if($agent->getIsconnected() == 'yes')
	{
		/* *********************** */
	   /* send to foniva server */
	   /* *********************** */
		fonivaFilter::foniva_send_toserver("MSG_AGENT_UPDATED", 
												"agentid", $agent->getDbid());
	}
	
	$this->agents = array();
	array_push($this->agents, $agent);
	$this->setTemplate('agents');
  }
  
  public function executeAgentunsetskill(sfWebRequest $request)
  {	
	$username = $request->getParameter('username');
	$skillname = $request->getParameter('skillname');
	
	if(!$username)
	{
		$this->errmsg = 'Missing agent username';
		$this->setTemplate('APIError');
		return 'Err';
	}
	
	$skilldbid = NULL;
	if($skillname)
	{
		$skill = Doctrine_Query::create()
						->select('g.dbid, g.name')
						->from('ConfSkill g')
						->where('g.name = ?', $skillname);
		if(!fonivaFilter::isCurrentUserSuperTenant())
			$skill->andWhere('g.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
		$skill = $skill->execute();
		if(sizeof($skill) > 0)
			$skilldbid = $skill[0]->dbid;
		else
		{
			$this->errmsg = 'No such agent skill "'.$skillname.'"';
			$this->setTemplate('APIError');
			return 'Err';
	    }
	}
	
	$ctenant = NULL;
	if(fonivaFilter::isCurrentUserSuperTenant())
	{
		$ctenant = $tenant;
		//TODO : check if tenant exists
	}
	else
	{
		//if we are not a super tenant, set new user to current user
		$ctenant = fonivaFilter::getCurrentUserTenant();
	}
	$sf_username = $username;
	$jb_username = $username; //jabber cannot accept '@' in username
	if($ctenant != NULL)
	{
		$sf_username = $sf_username.'@'.$ctenant->getName();
		$jb_username = $jb_username.'_'.$ctenant->getName();
	}
	
	$agent = Doctrine::getTable('ConfAgent')->findOneByUsername($sf_username);
	if(!$agent)
	{
		$this->errmsg = 'Agent with username '.$username.' doesn\'t exist.';
		$this->setTemplate('APIError');
		return 'Err';
	}
	
	Doctrine_Query::create()
		->update('ConfAgentSkill cs')
		->set('cs.active', '?', 'no')
		->where('cs.agent_fk = ? AND cs.skill_fk = ?', array($agent->dbid, $skilldbid))
		->execute();
	
	
		
	$changelog_skillstr = '';
	
	$asc = Doctrine_Query::create()
					->select('cs.dbid, cs.agent_fk, cs.skill_fk, cs.active')
					->from('ConfAgentSkill cs')
					->where('cs.agent_fk = ? AND cs.skill_fk = ?', array($agent->dbid, $skilldbid))
					->execute();
	
	if(sizeof($asc) > 0)
	{
		$asc = $asc[0];
		$asc->setAgentFk($agent->dbid);
		$asc->setSkillFk($skilldbid);
		$asc->setActive('no');
		$asc->save();
	}
	else
	{
		$asc = new ConfAgentSkill();
		$asc->setAgentFk($agent->dbid);
		$asc->setSkillFk($skilldbid);
		$asc->setActive('no');
		$asc->save();
	}
		
	$changelog_skillstr = 'Removed '.$skill->name;
	
	$changelog = new LogAgentskillsChangelog();
	$changelog->setOccuredDate(date('Y-m-d H:i:s'));
	$changelog->setModifiedby($this->getUser()->getUsername());
	$changelog->setAgentdbid($agent->dbid);
	$changelog->setSkillsChangedto($changelog_skillstr);
	$changelog->save();
	
	//maybe this agent is connected ... send foniva message
	if($agent->getIsconnected() == 'yes')
	{
		/* *********************** */
	   /* send to foniva server */
	   /* *********************** */
		fonivaFilter::foniva_send_toserver("MSG_AGENT_UPDATED", 
												"agentid", $agent->getDbid());
	}
	
	$this->agents = array();
	array_push($this->agents, $agent);
	$this->setTemplate('agents');
  }
  
  
  
  /* =================== */
  /* OUTBOUND CAMPAIGNS         */
  /* =================== */
  public function executeOutboundcampaigns(sfWebRequest $request)
  {
	$this->campaigns = Doctrine_Query::create()
						->from('ConfCampaign c')
						->orderby('c.campaign_name')
						->where('1');
						
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->campaigns = $this->campaigns->andWhere('c.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
						
	$this->campaigns = $this->campaigns->execute();
  }
  
  public function executeCallinglistaddrecord(sfWebRequest $request)
  {
	$this->forward404Unless($this->conf_calling_list = Doctrine::getTable('ConfCallingList')->find($request->getParameter('dbid')), sprintf('Object conf_calling_list does not exist (%s).', $request->getParameter('dbid')));
	$this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $this->conf_calling_list->getConfCampaign()->getTenantFk() == fonivaFilter::getCurrentUserTenantId()); 
	
	$this->table_name = $this->conf_calling_list->calling_list_table_name;
	
	$this->number = $request->getParameter('number');
	$this->custom = $request->getParameter('custom');
	$this->timezone = $request->getParameter('timezone');
	$this->callback_date = $request->getParameter('callback_date');
	
	$rstatus = 'NOT_DIALED';
	if($request->getParameter('status') == 'CALLBACK')
		$rstatus = 'CALLBACK';
	if($request->getParameter('status') == 'COMPLETED')
		$rstatus = 'COMPLETED';
	$this->status = $rstatus;
	
	$manager = Doctrine_manager::getInstance();
	//echo sfConfig::get('app_callinglistdb_dsn');
	//exit();
	$clist_conn = $manager->openConnection(sfConfig::get('app_callinglistdb_dsn'));
	
	$psql = 'INSERT INTO '.$this->table_name.' (number, custom, timezone, status, callback_date) 
				VALUES ("'.mysql_escape_string($this->number).'", 
						"'.mysql_escape_string($this->custom).'", 
						"'.mysql_escape_string($this->timezone).'", 
						"'.mysql_escape_string($this->status).'", 
						'.($this->callback_date ? '"'.mysql_escape_string($this->callback_date).'"' : 'NULL').')';
	$clist_conn->execute($psql);
	
	// get last recordid
	$recorddbid = $clist_conn->lastInsertId();
	// update by other parameters
	$oparameters = $request->getGetParameters();
	$excludecols = array('dbid', 'status', 'number', 'custom', 'timezone', 'last_attempt_datetime', 
								'last_attempt_result', 'callback_date', 'nbattempts', 'created_at', 'updated_at');
	
	$sql = 'SHOW COLUMNS FROM '.$this->table_name;
	$pstatement = $clist_conn->execute($sql);
	$this->tablecolumns = $pstatement->fetchAll(PDO::FETCH_ASSOC);
	$columns = array();
	
	foreach($this->tablecolumns as $c)
	{
		if(!in_array($c['Field'], $excludecols))
			array_push($columns, ''.$c['Field'].'');
	}
	
	foreach($oparameters as $paramk => $paramv)
	{
		if(!in_array($paramk, $excludecols) && in_array($paramk, $columns))
		{
			try
			{
				$psql = 'UPDATE '.$this->table_name.' SET '.mysql_escape_string($paramk).' = "'.mysql_escape_string($paramv).'" WHERE dbid = "'.$recorddbid.'"';
				$clist_conn->execute($psql);
			}
			catch(Exception $e)
			{
				
			}
		}
	}
	
	$campaignid =  '';
	$campaign = $this->conf_calling_list->getConfCampaign();
	if($campaign != NULL)
	  $campaignid =  $campaign->getDbid();
	  
	if($campaignid != '')
	{
	  fonivaFilter::foniva_send_toserver("MSG_OUTBOUND_LISTS_ROWS_ADDED", "outboundid", $campaignid);
	}	
  }
  
  public function executeCallinglistgetrecord(sfWebRequest $request)
  {
	$this->forward404Unless($this->conf_calling_list = Doctrine::getTable('ConfCallingList')->find($request->getParameter('dbid')), sprintf('Object conf_calling_list does not exist (%s).', $request->getParameter('dbid')));
	$this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $this->conf_calling_list->getConfCampaign()->getTenantFk() == fonivaFilter::getCurrentUserTenantId()); 
	
	$this->table_name = $this->conf_calling_list->calling_list_table_name;
	
	$this->number = $request->getParameter('number');
	
	$manager = Doctrine_manager::getInstance();
	//echo sfConfig::get('app_callinglistdb_dsn');
	//exit();
	$clist_conn = $manager->openConnection(sfConfig::get('app_callinglistdb_dsn'));
	
	$psql = 'SELECT number, custom, timezone, status, callback_date, last_attempt_datetime, last_attempt_result, callback_date, nbattempts FROM '.$this->table_name.' 
						WHERE number = "'.mysql_escape_string($this->number).'"';
	$psql = $clist_conn->execute($psql);
	$this->rows = $psql->fetchAll(PDO::FETCH_ASSOC);
  }
  
  public function executeCallinglistdelrecord(sfWebRequest $request)
  {
	$this->forward404Unless($this->conf_calling_list = Doctrine::getTable('ConfCallingList')->find($request->getParameter('dbid')), sprintf('Object conf_calling_list does not exist (%s).', $request->getParameter('dbid')));
	$this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $this->conf_calling_list->getConfCampaign()->getTenantFk() == fonivaFilter::getCurrentUserTenantId()); 
	
	$this->table_name = $this->conf_calling_list->calling_list_table_name;
	
	$this->number = $request->getParameter('number');
	
	$manager = Doctrine_manager::getInstance();
	//echo sfConfig::get('app_callinglistdb_dsn');
	//exit();
	$clist_conn = $manager->openConnection(sfConfig::get('app_callinglistdb_dsn'));
	
	$psql = 'DELETE FROM '.$this->table_name.' 
						WHERE number = "'.mysql_escape_string($this->number).'"';
	//echo $psql;
	$psql = $clist_conn->execute($psql);
	$this->nbrowsaffected = $psql->rowCount();
  }
  
  public function executeCallinglistsetrecordstatus(sfWebRequest $request)
  {
	$this->forward404Unless($this->conf_calling_list = Doctrine::getTable('ConfCallingList')->find($request->getParameter('dbid')), sprintf('Object conf_calling_list does not exist (%s).', $request->getParameter('dbid')));
	$this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $this->conf_calling_list->getConfCampaign()->getTenantFk() == fonivaFilter::getCurrentUserTenantId()); 
	
	$this->table_name = $this->conf_calling_list->calling_list_table_name;
	
	$this->number = $request->getParameter('number');
	$this->status = $request->getParameter('status');
	$this->callback_date = ($request->getParameter('callback_date') != NULL) ? $request->getParameter('callback_date') : '';
	
	$rstatus = "COMPLETED";
	if($this->status == 'COMPLETED')
		$rstatus = "COMPLETED";
	else if($this->status == 'CALLBACK')
		$rstatus = "CALLBACK";
	
	
	$manager = Doctrine_manager::getInstance();
	//echo sfConfig::get('app_callinglistdb_dsn');
	//exit();
	$clist_conn = $manager->openConnection(sfConfig::get('app_callinglistdb_dsn'));
	
	$psql = 'UPDATE '.$this->table_name.' SET status = "'.mysql_escape_string($rstatus).'", callback_date = "'.mysql_escape_string($this->callback_date).'"
						WHERE number = "'.mysql_escape_string($this->number).'"';
	$psql = $clist_conn->execute($psql);
	$this->nbrowsaffected = $psql->rowCount();
  }
  
  /* =================== */
  /* REPORTTS            */
  /* =================== */
  
  public function executeReportqueuecalldetails(sfWebRequest $request)
  {
	  $this->reportcategory = 'QUEUE';
	  $this->queueformparse($request);
	  //$this->getreports('QUEUE');
	 // $this->buildqueuereportform($request);
	  
	  $fieldvalues = array();
	  $pdo = Doctrine_Manager::getInstance()->getCurrentConnection()->getDbh();
	  
	  $query = '';
	  $query_count = '';
	  
	  $query_fields = 'SELECT la.tracknumber, la.callername, la.callernumber, la.callednumber, la.queueresult, la.is_inbound, '.
								 'la.campaign_id, la.dialplan_id, la.queue_id, la.dialplan_type, la.queue_enter_time, '.
								 'la.queue_bridge_time, la.queue_exit_time, la.queue_agentdialing_result, la.queue_agentdialing_seconds, '.
								 'la.queue_agentanswered_seconds, la.agentdbid, la.groupdbid, (UNIX_TIMESTAMP(IFNULL(la.queue_bridge_time, la.queue_exit_time)) - UNIX_TIMESTAMP(la.queue_enter_time)) as customer_waittime , '.
								 'la.servicelevel, '.
								  'ca.username as agentusername, '.
								  'cai.firstname as agentfirstname, cai.lastname as agentlastname, '.
								  'cg.name as agentgroupname, '.
								  'cinb.inbound_name as inbound_name, '.
								  'coutb.campaign_name as outbound_name, '.
								  'cdia.dialplan as dialplanname, '.
								  'cque.name as queuename, '.
								  'lacallxfer.transferedto as xfer_transferedto, '.
								  'cdisp.calldisposition_name as cdisp_calldisposition_name ';
								  
	  $query_count_fields = 'SELECT COUNT(*) as nbtotalrecords';
	  
	  $queue_tables =  '				
						FROM log_queue_record la
						LEFT JOIN conf_agent ca ON la.agentdbid = ca.dbid
						LEFT JOIN conf_agent_info cai ON ca.info_fk = cai.dbid
						LEFT JOIN conf_group cg ON la.groupdbid = cg.dbid
						LEFT JOIN conf_inbound cinb ON cinb.dbid = la.campaign_id
						LEFT JOIN conf_campaign coutb ON coutb.dbid = la.campaign_id
						LEFT JOIN conf_queue cque ON cque.dbid = la.queue_id
						LEFT JOIN conf_dialplan cdia ON cdia.dbid = la.dialplan_id
						LEFT JOIN log_agent_calltransfer lacallxfer ON la.tracknumber = lacallxfer.tracknumber
						LEFT JOIN log_call_disposition cdisp ON la.tracknumber = cdisp.tracknumber
						';
	  $query_count_tables = '
						FROM log_queue_record la
						';
						
	  $query_filters = '
						 WHERE 
						(la.queue_enter_time >= :stat_startdate_ext and la.queue_enter_time <= :stat_enddate_ext )
						';
	  	
	  $fieldvalues['stat_startdate_ext'] = $this->stat_startdate_ext;
	  $fieldvalues['stat_enddate_ext'] = $this->stat_enddate_ext;
	  if(!fonivaFilter::isCurrentUserSuperTenant())
	  {
		  $query_filters .= ' AND la.tenant_fk = :tenantdbid ';
		  $fieldvalues['tenantdbid'] = fonivaFilter::getCurrentUserTenantId();
	  }
	  
	  if($this->stat_queue != '')
	  {
		  $query_filters .= ' AND la.queue_id = :stateltsvalue ';
		  $fieldvalues['stateltsvalue'] = $this->stat_queue;
	  } else if(!fonivaFilter::canCurrentUserManageAllQueues())
	  {
			  $query_filters .= ' AND la.queue_id IN (SELECT queue_fk FROM conf_user_assignedqueue WHERE user_fk = :currentuserid) ';
			  $fieldvalues['currentuserid'] = fonivaFilter::getCurrentUser()->getDbid();
	  }
	  
	  if($this->stat_searchcalleridnum != null && $this->stat_searchcalleridnum != '')
	  {
		  $query_filters .= ' AND la.callernumber = :searchcalleridnum';
		  $fieldvalues['searchcalleridnum'] = $this->stat_searchcalleridnum;
	  }
	  
	  if($this->stat_searchcallednum != null && $this->stat_searchcallednum != '')
	  {
		  $query_filters .= ' AND la.callednumber = :searchcallednum';
		  $fieldvalues['searchcallednum'] = $this->stat_searchcallednum;
	  }
	  
	  if($this->stat_searchtracknumber != null && $this->stat_searchtracknumber != '')
	  {
		  $query_filters .= ' AND la.tracknumber = :searchtracknumber';
		  $fieldvalues['searchtracknumber'] = $this->stat_searchtracknumber;
	  }
	  
	  if($this->stat_searchcalldirection != null && $this->stat_searchcalldirection != '')
	  {
		  $query_filters .= ' AND la.is_inbound = :searchcalldirection';
		  $fieldvalues['searchcalldirection'] = ($this->stat_searchcalldirection == 'INBOUND') ? 'yes' : 'no';
	  }
	  
	  if($this->stat_searchfrominboundid != null && $this->stat_searchfrominboundid != '')
	  {
		  $query_filters .= ' AND la.campaign_id = :searchfrominboundid';
		  $fieldvalues['searchfrominboundid'] = $this->stat_searchfrominboundid;
	  } 
	  else if($this->stat_searchfromoutboundid != null && $this->stat_searchfromoutboundid != '')
	  {
		  $query_filters .= ' AND la.campaign_id = :searchfromoutboundid';
		  $fieldvalues['searchfromoutboundid'] = $this->stat_searchfromoutboundid;
	  }
	  
	  if($this->stat_disposition != null && $this->stat_disposition != '')
	  {
		  $query_filters .= ' AND la.queueresult = :searchdisposition';
		  $fieldvalues['searchdisposition'] = $this->stat_disposition;
	  }
	  
	  
	  
	  
	  
	  $query_orderby = ' ORDER BY la.queue_enter_time, la.queue_id ';
	  
	  
	  $query = $query_fields.''.$queue_tables.''.$query_filters.''.$query_orderby;
	  
	  $query_count = $query_count_fields.''.$query_count_tables.''.$query_filters;
	
		//echo $query;
		//print_r($fieldvalues);
		//exit();
	  $query = $pdo->prepare($query);
	  $query_count = $pdo->prepare($query_count);
	 	 
	  $query->execute($fieldvalues);
	  $this->data = $query->fetchAll();
	  //echo sizeof($this->data); 
	  $this->setlayout(false);
  }
  
  public function queueformparse(sfWebRequest $request)
  {
	$this->stat_queue = $request->getParameter('queuedbid');
	//$this->csv_export = isset($rarray['csv_export']) && ($rarray['csv_export'] == 'on' || $rarray['csv_export'] == '1') ? true : false;
	
	$this->stat_searchcalleridnum = $request->getParameter('calleridnum');
	$this->stat_searchcallednum = $request->getParameter('callednum');
	$this->stat_searchtracknumber = $request->getParameter('tracknumber');;
	$this->stat_searchcalldirection = $request->getParameter('calldirection');
	$this->stat_searchfrominboundid = $request->getParameter('searchedfrominboundid');;
	$this->stat_searchfromoutboundid = $request->getParameter('searchedfromoutboundid');
	$this->stat_disposition = $request->getParameter('disposition');
	
	$this->stat_startdate = $request->getParameter('start_date');
	
	$this->stat_enddate = $request->getParameter('end_date');
			
	
	$this->stat_step = $request->getParameter('step');
	
	$this->stat_startdate_ext = $this->stat_startdate.((strlen($this->stat_startdate) < 18) ? ' 00:00:00' : '');
	$this->stat_enddate_ext   = $this->stat_enddate.((strlen($this->stat_enddate) < 18) ? ' 23:59:59' : ''); 
  }
  
  
  
  
  /* =================== */
  /* BLACK LISTS         */
  /* =================== */
  public function executeBlacklists(sfWebRequest $request)
  {
	$this->lists = Doctrine_Query::create()
						->from('ConfBlacklist c')
						->orderby('c.listname')
						->where('1');
						
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->lists = $this->lists->andWhere('c.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
						
	$this->lists = $this->lists->execute();
  }
  
  public function executeBlacklistaddrecord(sfWebRequest $request)
  {
	$this->forward404Unless($this->conf_black_list = Doctrine::getTable('ConfBlacklist')->find($request->getParameter('dbid')), sprintf('Object conf_blacklist does not exist (%s).', $request->getParameter('dbid')));
	$this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $this->conf_black_list->getTenantFk() == fonivaFilter::getCurrentUserTenantId()); 
	
	
	$this->number = $request->getParameter('number');
	
	$c = new ConfBlacklistData();
	$c->setListFk($this->conf_black_list->getDbid());
	$c->setPhonenumber($this->number);
	$c->replace();
  }
  
  public function executeBlacklistgetrecord(sfWebRequest $request)
  {
	$this->forward404Unless($this->conf_black_list = Doctrine::getTable('ConfBlacklist')->find($request->getParameter('dbid')), sprintf('Object conf_blacklist does not exist (%s).', $request->getParameter('dbid')));
	$this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $this->conf_black_list->getTenantFk() == fonivaFilter::getCurrentUserTenantId()); 
	
	$this->number = $request->getParameter('number');
	
	$this->rows = Doctrine_Query::create()
								->from('ConfBlacklistData c')
								->where('c.list_fk = ? AND c.phonenumber = ?', array($this->conf_black_list->dbid, $this->number))
								->limit(1)
								->execute();
  }
  
  public function executeBlacklistdelrecord(sfWebRequest $request)
  {
	$this->forward404Unless($this->conf_black_list = Doctrine::getTable('ConfBlacklist')->find($request->getParameter('dbid')), sprintf('Object conf_blacklist does not exist (%s).', $request->getParameter('dbid')));
	$this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $this->conf_black_list->getTenantFk() == fonivaFilter::getCurrentUserTenantId()); 
	
	$this->number = $request->getParameter('number');
	
	Doctrine_Query::create()
								->from('ConfBlacklistData c')
								->where('c.list_fk = ? AND c.phonenumber = ?', array($this->conf_black_list->dbid, $this->number))
								//->limit(1)
								->delete()
								->execute();
								
	$this->nbrowsaffected = 1; //sizeof($this->rows);
  }
  
  
  
  
  public function generateword($length)
  {
	list($usec, $sec) = explode(' ', microtime());
    srand((float) $sec + ((float) $usec * 100000));  
	
	$validchars = "0123456789QWERTYUIOPLKJHGFDSAZXCVBNMqwertyuioplkjhgfdsazxcvbnm";
	
	$word = '';
	$counter   = 0;
    while ($counter < $length) {
     	$actChar = substr($validchars, rand(0, strlen($validchars)-1), 1);

     	// All character must be different	     
    	$word .= $actChar;
        $counter++;
    }
	
	return $word;	  
  }
  	
  protected function dispatch_jabber_user_to_groups($jabber_user)
  {
	/** ok, we will try to create all the jb_user_group entries, to auto sign all users in their respective groups builtin */  
	/* so, if the group name contains the user type, the user belongs to that group */
	
	$stype = $jabber_user->type;
	$username = $jabber_user->username;
	
	$grps = Doctrine_Query::create()
					->select('jgr.name')
					->from('JbGroup jgr')
					->where('builtin = "yes"')
					->execute();
	foreach($grps as $g)
	{
		$grptypes = explode('-', $g->name);
		if(in_array($stype, $grptypes))
		{
			$jb_gp_user = new JbUserGroup();	
			$jb_gp_user->setUsernameFk($username);
			$jb_gp_user->setGroupnameFk($g->name);			
			$jb_gp_user->save();
		}
	}
	
	
  } 
  
  
}
