<?php

/**
 * ressource actions.
 *
 * @package    foniva
 * @subpackage ressource
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 12479 2008-10-31 10:54:40Z fabien $
 */
class ressourceActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
    $this->forward('ressource', 'agents');
  }
  
  public function executeDids(sfWebRequest $request)
  {	
    $this->searchedDid = $this->getRequestParameter('searchedDid');
	$this->searchedDid = trim(strtolower($this->searchedDid));
  
	$this->pager = new sfDoctrinePager('ConfDid', sfConfig::get('app_display_nbrecordperpage'));
	$this->pager->getQuery()->from('ConfDid u')
					->orderBy('u.phonenumber');
	
	$defaultpage = $this->getcurrentmodule_defaultpage();
	$this->pager->getQuery()->where('1');
	if(!empty($this->searchedDid))
	{
		$this->pager->getQuery()->andwhere('lower(u.phonenumber) LIKE ? OR lower(u.description) LIKE ?', 
											array('%'.$this->searchedDid.'%', '%'.$this->searchedDid.'%'));	
		$defaultpage = 1;
	}
	
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->pager->getQuery()->andwhere('u.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
	
	$this->setcurrentmodule_defaultpage();
	$this->pager->setPage($defaultpage); //$this->getRequestParameter('page',1));
	$this->pager->init();
	$this->dids = $this->pager->getResults();

	/*
	$this->dids = Doctrine_Query::create()
					->from('ConfDid u')
					->orderBy('u.phonenumber')
					->execute();
	*/
  }
  
  public function executeDidnew(sfWebRequest $request)
  {
    $this->form = new ConfDidForm();
  }

  public function executeDidcreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));
    $this->form = new ConfDidForm();
    $this->processDidForm($request, $this->form);
    $this->setTemplate('didnew');
  }

  public function executeDidedit(sfWebRequest $request)
  {
    $this->forward404Unless($conf_did = Doctrine::getTable('ConfDid')->find($request->getParameter('dbid')), sprintf('Object conf_did does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_did->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$this->form = new ConfDidForm($conf_did);
  }

  public function executeDidupdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($conf_did = Doctrine::getTable('ConfDid')->find($request->getParameter('dbid')), sprintf('Object conf_did does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_did->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$this->form = new ConfDidForm($conf_did);
    $this->processDidForm($request, $this->form);
    $this->setTemplate('didedit');
  }

  public function executeDiddelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();
    $this->forward404Unless($conf_did = Doctrine::getTable('ConfDid')->find($request->getParameter('dbid')), sprintf('Object conf_did does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_did->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$conf_did->delete();
    $this->redirect('ressource/dids');
  }

  protected function processDidForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $conf_did = $form->getObject();
	  
	  if(fonivaFilter::isCurrentUserSuperTenant())
		  $conf_did->setTenantFk($form->getValue('tenant_fk'));
	  else
		  $conf_did->setTenantFk(fonivaFilter::getCurrentUserTenantId());
	  
	  $conf_did->setPhonenumber($form->getValue('phonenumber'));
	  //$conf_did->setCidmatch($form->getValue('cidmatch'));
	  $conf_did->setDescription($form->getValue('description'));
	  $conf_did->setLastmodifiedBy($this->getUser()->getUsername());
	  
	  $conf_did->save();
	  
	  
	  /* call properties */
	  $callpropertiesarr = $request->getParameter('resourcecallproperty');
	  if(is_array($callpropertiesarr) && sizeof($callpropertiesarr) > 0)
	  {
		  $f_addedarr = isset($callpropertiesarr['added']) ? $callpropertiesarr['added'] : array();
		  $f_modifiedarr = isset($callpropertiesarr['modified']) ? $callpropertiesarr['modified'] : array();
		  $f_deletedarr = isset($callpropertiesarr['deleted']) ? $callpropertiesarr['deleted'] : array();
		  
		  foreach($f_addedarr as $felt)
		  {
			$fdbid 			= $felt['dbid'];
			$fpropertyname	= $felt['propertyname'];
			$fpropertyvalue = $felt['propertyvalue'];
			
			$callproperty = new ConfDidCallproperty();
			$callproperty->setDidFk($conf_did->getDbid());
			$callproperty->setPropertyname($fpropertyname);
			$callproperty->setPropertyvalue($fpropertyvalue);
			$callproperty->save();
		  }
		  
		  foreach($f_modifiedarr as $felt)
		  {
			$fdbid 			= $felt['dbid'];
			$fpropertyname	= $felt['propertyname'];
			$fpropertyvalue = $felt['propertyvalue'];
			
			if($callproperty = Doctrine::getTable('ConfDidCallproperty')->find($fdbid))
			{
				$callproperty->setDidFk($conf_did->getDbid());
				$callproperty->setPropertyname($fpropertyname);
				$callproperty->setPropertyvalue($fpropertyvalue);
				$callproperty->save();
			}
		  }
		  
		  
		  foreach($f_deletedarr as $felt)
	  	  {
			 $fdbid 			= $felt['dbid'];
			 if($callproperty = Doctrine::getTable('ConfDidCallproperty')->find($fdbid))
			 {
				 $callproperty->delete();
			 } 
		  }
	  }
	  
	  
	  
	  $conf_inbound = $conf_did->getInboundAssignedTo();
	  if($conf_inbound != NULL)
	  {
	  	$isrunning  = ($conf_inbound->getLastStatus() == 'RUNNING');
	    $this->send_inbound_updates($conf_inbound, $isrunning, $isrunning);	 
	  }
	  
	  
      $this->redirect('ressource/dids');
    }
  }
  
  public function send_inbound_updates($conf_inbound, $wasrunning, $isrunning)
  {
	  /* *********************** */
	 /* send to foniva server */
	 /* *********************** */
	 if($wasrunning && $isrunning)
	 {
		 fonivaFilter::foniva_send_toserver("MSG_INBOUND_UPDATED", 
											 	"inboundid", $conf_inbound->getDbid());
	 }
	 else if(!$wasrunning && $isrunning)
	 {
		 fonivaFilter::foniva_send_toserver("MSG_INBOUND_ADDED", 
											 	"inboundid", $conf_inbound->getDbid());
	 }
	 else if($wasrunning && !$isrunning)
	 {
		fonivaFilter::foniva_send_toserver("MSG_INBOUND_DELETED", 
											 	"inboundid", $conf_inbound->getDbid());	 
	 }
  }
	
 
  /*********   ************/
  /***   TENANTS      *****/
  /*********   ************/	 
  
  public function executeTenants(sfWebRequest $request)
  {
	$this->searchedTenant = $this->getRequestParameter('searchedTenant');
	$this->searchedTenant = trim(strtolower($this->searchedTenant));
	
	$this->pager = new sfDoctrinePager('ConfTenant', sfConfig::get('app_display_nbrecordperpage'));
	$this->pager->getQuery()->from('ConfTenant ct')
							->orderBy('ct.fullname');
	
	$defaultpage = $this->getcurrentmodule_defaultpage();
	if(!empty($this->searchedTenant))
	{
		$this->pager->getQuery()->where('lower(ct.name) LIKE ? OR lower(ct.fullname) LIKE ? OR lower(ct.description) LIKE ?', array('%'.$this->searchedTenant.'%', '%'.$this->searchedTenant.'%', '%'.$this->searchedTenant.'%'));						
		$defaultpage = 1;
	}
									
	$this->setcurrentmodule_defaultpage();
	$this->pager->setPage($defaultpage); //$this->getRequestParameter('page',1));
	$this->pager->init();
	$this->tenants = $this->pager->getResults();
  }
  
  public function executeTenantnew(sfWebRequest $request)
  {
    $conf_tenant = new ConfTenant();
    $this->form = new ConfTenantForm($conf_tenant);
  }

  public function executeTenantcreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));
    $conf_tenant = new ConfTenant();
    $this->form = new ConfTenantForm($conf_tenant);
    $this->processTenantForm($request, $this->form);
    $this->setTemplate('tenantnew');
  }

  public function executeTenantedit(sfWebRequest $request)
  {
    $this->forward404Unless($conf_tenant = Doctrine::getTable('ConfTenant')->find($request->getParameter('dbid')), sprintf('Object conf_tenant does not exist (%s).', $request->getParameter('dbid')));
    $this->form = new ConfTenantForm($conf_tenant);
  }

  public function executeTenantupdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($conf_tenant = Doctrine::getTable('ConfTenant')->find($request->getParameter('dbid')), sprintf('Object conf_tenant does not exist (%s).', $request->getParameter('dbid')));
    $this->form = new ConfTenantForm($conf_tenant);
    $this->processTenantForm($request, $this->form);
    $this->setTemplate('tenantedit');
  }

  public function executeTenantdelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();
    $this->forward404Unless($conf_tenant = Doctrine::getTable('ConfTenant')->find($request->getParameter('dbid')), sprintf('Object conf_tenant does not exist (%s).', $request->getParameter('dbid')));
    $conf_tenant->delete();
	
	/* *********************** */
    /* send to foniva server */
    /* *********************** */
	fonivaFilter::foniva_send_toserver("MSG_TENANT_DELETED", 
											 	"tenantid", $conf_tenant->getDbid());
    $this->redirect('ressource/tenants');
  }

  protected function processTenantForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
	  $isnew = $form->getObject()->isNew();	
      $conf_tenant = $form->save();
	  
	  /* *********************** */
	  /*  send to foniva server  */
	  /* *********************** */
	  fonivaFilter::foniva_send_toserver(($isnew ? "MSG_TENANT_ADDED" : "MSG_TENANT_UPDATED"), 
											 	"tenantid", $conf_tenant->getDbid());
      $this->redirect('ressource/tenants');
    }
  }
  

  /*********   ************/
  /***   Sites *****/
  /*********   ************/	 
	
  public function executeSites(sfWebRequest $request)
  {
  
  	$this->searchedSite = $this->getRequestParameter('searchedSite');
	$this->searchedSite = trim(strtolower($this->searchedSite));
	
	
	$this->pager = new sfDoctrinePager('ConfSite', sfConfig::get('app_display_nbrecordperpage'));
  	$this->pager->getQuery()->select('st.dbid, st.name, count(at.dbid) as nbagents')
							->from('ConfSite st')
							->leftJoin('st.ConfAgent at')
							->orderBy('st.name')
							->groupBy('st.dbid')
							->where('1');
							
   if(!fonivaFilter::isCurrentUserSuperTenant())
   		$this->pager->getQuery()->andWhere('st.tenant_fk = ?', FonivaFilter::getCurrentUserTenantId());
	
	
	$defaultpage = $this->getcurrentmodule_defaultpage();
	if(!empty($this->searchedSite))
	{
		
		$this->pager->getQuery()->andWhere('lower(st.name) LIKE ?','%'.$this->searchedSite.'%');
		$defaultpage = 1;
	}
	
	//if(!fonivaFilter::canCurrentUserManageAllSites())
	//{
	//	$this->pager->getQuery()->leftJoin('cg.ConfUserAssignedsite a')
	//							->andWhere('a.user_fk = ?', fonivaFilter::getCurrentUser()->getDbid());
	//}
	
	$this->setcurrentmodule_defaultpage();
	$this->pager->setPage($defaultpage); //$this->getRequestParameter('page',1));
	$this->pager->init();
	$this->sites = $this->pager->getResults();
  }
  
  
  public function executeSitenew(sfWebRequest $request)
  {
	$conf_site = new ConfSite();
	$this->form = new ConfSiteForm($conf_site);
  }
  
  public function executeSitecreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));
    $conf_site = new ConfSite();
    $this->form = new ConfSiteForm($conf_site);
    $this->processSiteForm($request, $this->form);
    $this->setTemplate('sitenew');
  }
  
  public function executeSiteedit(sfWebRequest $request)
  {
	$this->forward404Unless($conf_site = Doctrine::getTable('ConfSite')->find($request->getParameter('dbid')), sprintf('Object conf_site does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_site->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$this->form = new ConfSiteForm($conf_site);
  }
  
  public function executeSiteupdate(sfWebRequest $request)
  {
	$this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($conf_site = Doctrine::getTable('ConfSite')->find($request->getParameter('dbid')), sprintf('Object conf_site does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_site->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$this->form = new ConfSiteForm($conf_site);
    $this->processSiteForm($request, $this->form);
	
    $this->setTemplate('siteedit');
  }

  public function executeSitedelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();
    $this->forward404Unless($conf_site = Doctrine::getTable('Confsite')->find($request->getParameter('dbid')), sprintf('Object conf_site does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_site->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$conf_site->delete();
	$this->redirect('ressource/sites');
  }
	  
  protected function processSiteForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $conf_site = $form->getObject();
	  $conf_site->setName($form->getValue('name'));	  
	  $conf_site->setLastmodifiedBy($this->getUser()->getUsername());
	  
	  if(fonivaFilter::isCurrentUserSuperTenant())
	    $conf_site->setTenantFk($form->getValue('tenant_fk'));
	  else
	    $conf_site->setTenantFk(fonivaFilter::getCurrentUserTenantId());
		
	  $conf_site->save();
	  
      $this->redirect('ressource/sites');
    }
  }

  
  /*********   ************/
  /***    A G E N T S *****/
  /*********   ************/  
  
  public function executeAgents(sfWebRequest $request)
  {
	  
	
	/* groups */
	/*
	$this->groups = Doctrine_Query::create()
					->select('g.dbid, g.name')
					->from('ConfGroup g')
					->orderBy('g.name');
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->groups->where('g.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
		*/
	$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->teams_list = array();
	$this->teamids_list = array('');
	foreach($this->teams as $t)
	{
		$this->teams_list[$t->getDbid()] = $t;
		array_push($this->teamids_list, $t->getDbid());
	}
	

	$this->searchedAgent = $this->getRequestParameter('searchedAgent');
	$this->searchedAgent = trim(strtolower($this->searchedAgent));

		
	$this->pager = new sfDoctrinePager('ConfAgent', sfConfig::get('app_display_nbrecordperpage'));
	$this->pager->getQuery()->select('a.dbid, a.shortusername, a.username, a.active, a.group_fk, a.created_at, a.updated_at,
							 	i.firstname as firstname, i.lastname as lastname, 
								SUM(IF(fa.user_fk = "'.fonivaFilter::getCurrentUser()->getDbid().'",1,0)) as isfollowedbyuser')
					->from('ConfAgent a')
					->leftJoin('a.ConfAgentInfo i ON i.dbid = a.info_fk')
					->leftJoin('a.ConfUserFollowedagent fa ON fa.agent_fk = a.dbid')
					->orderBy('a.username')
					->groupBy('a.dbid');
	
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->pager->getQuery()->where('a.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
		
	if(!fonivaFilter::canCurrentUserManageAllGroups())
		$this->pager->getQuery()->where('a.group_fk in ?', array($this->groupids_list));
	
	$this->searchFilter = $this->searchedAgent;
	$defaultpage = $this->getcurrentmodule_defaultpage();
	if(!empty($this->searchedAgent))
	{		
		$this->pager->getQuery()->where('lower(a.shortusername) = ? OR lower(i.firstname) LIKE ? OR lower(i.lastname) LIKE ?', array($this->searchedAgent, '%'.$this->searchedAgent.'%', '%'.$this->searchedAgent.'%'));
		//$defaultpage = 1;
	}
	
	$this->setcurrentmodule_defaultpage();
	$this->pager->setPage($defaultpage); //$this->getRequestParameter('page',1));
	$this->pager->init();
	$this->agents = $this->pager->getResults();
					
	
		
	
	/* skills */
	$this->skills = Doctrine_Query::create()
					->select('s.dbid, s.name, s.created_at, s.updated_at')
					->from('ConfSkill s')
					->orderBy('s.name');
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->skills->where('s.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
	$this->skills = $this->skills->execute();
					
	$this->skills_list = array();
	foreach($this->skills as $s)
		$this->skills_list[$s->getDbid()] = $s;
		
	/* sites  */
	$this->sites = Doctrine_Query::create()
					->select('s.dbid, s.name, s.created_at, s.updated_at')
					->from('ConfSite s')
					->orderBy('s.name');
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->sites->where('s.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
	$this->sites = $this->sites->execute();
					
	$this->sites_list = array();
	foreach($this->sites as $s)
		$this->sites_list[$s->getDbid()] = $s;	
		
		
		
  }
  
  public function executeAgentnew(sfWebRequest $request)
  {
	$conf_agent = new ConfAgent();  
    $this->form = new ConfAgentForm($conf_agent);
	$this->form->embedForm('infoform', (new ConfAgentInfoForm($conf_agent->getConfAgentInfo())));
	$this->form->embedForm('settingform', (new ConfAgentSettingForm($conf_agent->getConfAgentSetting())));
	$this->form->embedForm('securityloginform', (new SecurityloginForm()));
	
	$this->calldispositions = Doctrine_Query::create()
					->select('c.dbid, c.name')
					->from('ConfCallDisposition c')
					->orderBy('c.name');	
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->calldispositions = $this->calldispositions->andWhere('c.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
	$this->calldispositions = $this->calldispositions->execute();				
	
	$this->calldispositions_list = array();	
	foreach($this->calldispositions as $s)
		$this->calldispositions_list[$s->getDbid()] = $s;
		
	$assarr = $request->getParameter('assigned_calldisposition');
	$this->assigned_calldispositions = array();
	if($assarr != NULL)
	{
		foreach($assarr as $as)
			$this->assigned_calldispositions[$as] = 1;
	}
	
	$this->getResponse()->addJavascript('ui.multiselect.js', 'last');
	$this->getResponse()->addJavascript('plugins/scrollTo/jquery.scrollTo-min.js', 'last');
	$this->getResponse()->addJavascript('plugins/localisation/jquery.localisation-min.js', 'last');
	$this->getResponse()->addJavascript('jquery.tmpl.1.1.1.js', 'last');
	$this->getResponse()->addStylesheet('ui.multiselect.css', 'last');
  }

  public function executeAgentcreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));
	$conf_agent = new ConfAgent();
    $this->form = new ConfAgentForm($conf_agent);
	$this->form->embedForm('infoform', (new ConfAgentInfoForm($conf_agent->getConfAgentInfo())));
	$this->form->embedForm('settingform', (new ConfAgentSettingForm($conf_agent->getConfAgentSetting())));
	$this->form->embedForm('securityloginform', (new SecurityloginForm(array('origin_ips' => $conf_agent->getSecurityOriginIps()))));
    $this->processAgentForm($request, $this->form);
	
	
	$this->calldispositions = Doctrine_Query::create()
					->select('c.dbid, c.name')
					->from('ConfCallDisposition c')
					->orderBy('c.name');	
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->calldispositions = $this->calldispositions->andWhere('c.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
	$this->calldispositions = $this->calldispositions->execute();				
	
	$this->calldispositions_list = array();	
	foreach($this->calldispositions as $s)
		$this->calldispositions_list[$s->getDbid()] = $s;
		
	$assarr = $request->getParameter('assigned_calldisposition');
	$this->assigned_calldispositions = array();
	
	if($assarr != NULL)
	{
		foreach($assarr as $as)
			$this->assigned_calldispositions[$as] = 1;
	}
	
	$this->getResponse()->addJavascript('ui.multiselect.js', 'last');
	$this->getResponse()->addJavascript('plugins/scrollTo/jquery.scrollTo-min.js', 'last');
	$this->getResponse()->addJavascript('plugins/localisation/jquery.localisation-min.js', 'last');
	$this->getResponse()->addJavascript('jquery.tmpl.1.1.1.js', 'last');
	$this->getResponse()->addStylesheet('ui.multiselect.css', 'last');
	
    $this->setTemplate('agentnew');
  }

  public function executeAgentedit(sfWebRequest $request)
  {
    $this->forward404Unless($conf_agent = Doctrine::getTable('ConfAgent')->find($request->getParameter('dbid')), sprintf('Object conf_agent does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_agent->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$this->form = new ConfAgentForm($conf_agent);
	$this->form->embedForm('infoform', (new ConfAgentInfoForm($conf_agent->getConfAgentInfo())));
	$this->form->embedForm('settingform', (new ConfAgentSettingForm($conf_agent->getConfAgentSetting())));
	$this->form->embedForm('securityloginform', (new SecurityloginForm(array('origin_ips' => $conf_agent->getSecurityOriginIps()))));
	
	$this->calldispositions = Doctrine_Query::create()
					->select('c.dbid, c.name')
					->from('ConfCallDisposition c')
					->orderBy('c.name');	
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->calldispositions = $this->calldispositions->andWhere('c.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
	$this->calldispositions = $this->calldispositions->execute();				
	
	$this->calldispositions_list = array();	
	foreach($this->calldispositions as $s)
		$this->calldispositions_list[$s->getDbid()] = $s;
		
	$this->assigned_calldispositions = array();	
	if(($sfs = $conf_agent->ConfAgentSetting))
	{
		foreach($sfs->ConfAgentSettingCalldisposition as $as)
		{
			$this->assigned_calldispositions[$as->getDispositionFk()] = 1;
		}
	}
		
	$this->getResponse()->addJavascript('ui.multiselect.js', 'last');
	$this->getResponse()->addJavascript('plugins/scrollTo/jquery.scrollTo-min.js', 'last');
	$this->getResponse()->addJavascript('plugins/localisation/jquery.localisation-min.js', 'last');
	$this->getResponse()->addJavascript('jquery.tmpl.1.1.1.js', 'last');
	$this->getResponse()->addStylesheet('ui.multiselect.css', 'last');
  }

  public function executeAgentupdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($conf_agent = Doctrine::getTable('ConfAgent')->find($request->getParameter('dbid')), sprintf('Object conf_agent does not exist (%s).', $request->getParameter('dbid')));
	$this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_agent->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$this->form = new ConfAgentForm($conf_agent);	
	$this->form->embedForm('infoform', (new ConfAgentInfoForm($conf_agent->getConfAgentInfo())));
	$this->form->embedForm('settingform', (new ConfAgentSettingForm($conf_agent->getConfAgentSetting())));
	$this->form->embedForm('securityloginform', (new SecurityloginForm(array('origin_ips' => $conf_agent->getSecurityOriginIps()))));
    $this->processAgentForm($request, $this->form);
    $this->setTemplate('agentedit');
	
	
	$this->calldispositions = Doctrine_Query::create()
					->select('c.dbid, c.name')
					->from('ConfCallDisposition c')
					->orderBy('c.name');	
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->calldispositions = $this->calldispositions->andWhere('c.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
	$this->calldispositions = $this->calldispositions->execute();				
	
	$this->calldispositions_list = array();	
	foreach($this->calldispositions as $s)
		$this->calldispositions_list[$s->getDbid()] = $s;
		
	$assarr = $request->getParameter('assigned_calldisposition');
	$this->assigned_calldispositions = array();
	
	if($assarr != NULL)
	{
		foreach($assarr as $as)
			$this->assigned_calldispositions[$as] = 1;
	}
	
	$this->getResponse()->addJavascript('ui.multiselect.js', 'last');
	$this->getResponse()->addJavascript('plugins/scrollTo/jquery.scrollTo-min.js', 'last');
	$this->getResponse()->addJavascript('plugins/localisation/jquery.localisation-min.js', 'last');
	$this->getResponse()->addJavascript('jquery.tmpl.1.1.1.js', 'last');
	$this->getResponse()->addStylesheet('ui.multiselect.css', 'last');
  }

  public function executeAgentdelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();
    $this->forward404Unless($conf_agent = Doctrine::getTable('ConfAgent')->find($request->getParameter('dbid')), sprintf('Object conf_agent does not exist (%s).', $request->getParameter('dbid')));
	$this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_agent->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
		
    $conf_agent->delete();
	if(($sfu = $conf_agent->getsfGuardUser()))
		$sfu->delete();
	if(($sfgs = $sfu->getsfGuardUserGroup()))
		$sfgs->delete();
	if(($sfs = $conf_agent->getConfAgentSetting()))
		$sfs->delete();
	if(($jbu = $conf_agent->getJbUser()))
		$jbu->delete();
		
	/* *********************** */
	/* send to foniva server */
	/* *********************** */
	fonivaFilter::foniva_send_toserver("MSG_AGENT_PBXINFOS_DELETED", 
										"agentid", $conf_agent->getDbid(),
										"extension", $conf_agent->getExtension()	);	
	
    $this->redirect('ressource/agents');
  }

  protected function processAgentForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $ctenant = NULL;
	  if(fonivaFilter::isCurrentUserSuperTenant())
	  {
		if($form->getValue('tenant_fk') != '' && $form->getValue('tenant_fk') != NULL)
			$ctenant = Doctrine::getTable('ConfTenant')->find($form->getValue('tenant_fk'));	
	  }
	  else
	  {
		//if we are not a super tenant, set new user to current user
		$ctenant = fonivaFilter::getCurrentUserTenant();
	  }
	  $sf_username = $form->getValue('shortusername');
	  $jb_username = $form->getValue('shortusername'); //jabber cannot accept '@' in username
	  if($ctenant != NULL)
	  {
		$sf_username = $sf_username.'@'.$ctenant->getName();
	  	$jb_username = $jb_username.'_'.$ctenant->getName();
	  }
	  
	  
	  $strippedusername = preg_replace("/[^a-zA-Z0-9\s]/", "", $jb_username);
	  
	  $conf_agent = $form->getObject();
	  $conf_agent->setUsername($sf_username);
	  $conf_agent->setShortusername($form->getValue('shortusername'));
	  $conf_agent->setExtension(sfConfig::get('app_agent_extensionprefix').$strippedusername);
	  $conf_agent->setGroupFk($form->getValue('group_fk'));
	  $conf_agent->setTeamFk($form->getValue('team_fk'));
	  $conf_agent->setSiteFk($form->getValue('site_fk'));
	  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($form->getValue('password') != '')
		  $sfu->setPassword($form->getValue('password'));
	  $sfu->setIsActive($form->getValue('active') == 'yes' ? '1' : '0');
	  $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($agtinfos['firstname']);
	  $sfi->setLastname($agtinfos['lastname']);
	  $sfi->setEmail($agtinfos['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($form->getValue('password') != '')
		  $jbu->setPassword(md5($form->getValue('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->redirect('ressource/agents');
    }
  }
  
  public function executeAgentforcelogout(sfWebRequest $request)
  {
	$request->checkCSRFProtection();
    $this->forward404Unless($conf_agent = Doctrine::getTable('ConfAgent')->find($request->getParameter('dbid')), sprintf('Object conf_agent does not exist (%s).', $request->getParameter('dbid')));
	$this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_agent->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
		
	/* *********************** */
	/* send to foniva server */
	/* *********************** */
	fonivaFilter::foniva_send_toserver("MSG_AGT_FORCE_LOGOUT", 
										"agentid", $conf_agent->getDbid());	
	
    $this->redirect('ressource/agentedit?dbid='.$conf_agent->getDbid()); 
  }
  
  public function executeAgentforcecallterminate(sfWebRequest $request)
  {
	$request->checkCSRFProtection();
    $this->forward404Unless($conf_agent = Doctrine::getTable('ConfAgent')->find($request->getParameter('dbid')), sprintf('Object conf_agent does not exist (%s).', $request->getParameter('dbid')));
	$this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_agent->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
		
	/* *********************** */
	/* send to foniva server */
	/* *********************** */
	fonivaFilter::foniva_send_toserver("MSG_AGT_FORCED_ALLCALLTERMINATED", 
										"agentid", $conf_agent->getDbid());	
	
    $this->redirect('ressource/agentedit?dbid='.$conf_agent->getDbid()); 
  }
  
  public function executeDouserfollowagent(sfWebRequest $request)
  {
	$this->forward404Unless($this->conf_agent = Doctrine::getTable('ConfAgent')->find($request->getParameter('dbid')), sprintf('Object conf_agent does not exist (%s).', $request->getParameter('dbid')));
	$this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $this->conf_agent->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	
	$dofollow = $request->getParameter('dofollow');
	$dofollow = ($dofollow == 'true'); 
	
	Doctrine_Query::create()
		->from('ConfUserFollowedagent ca')
		->where('ca.user_fk = ? AND ca.agent_fk = ?', array(fonivaFilter::getCurrentUser()->getDbid(), $this->conf_agent->getDbid()))
		->delete()
		->execute();
	
	if($dofollow)
	{
		$cua = new ConfUserFollowedagent();
		$cua->setUserFk(fonivaFilter::getCurrentUser()->getDbid());
		$cua->setAgentFk($this->conf_agent->getDbid());
		$cua->replace();
	}
	
	$this->setLayout(false);
  }
  
  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;	  
  }
  
  /*********   ************/
  /***   AGENT SKILLS ASSIGNMENT *****/
  /*********   ************/	 
  
  public function executeAgentskillassignment(sfWebRequest $request)
  {
	$this->getResponse()->addStylesheet('chosen/chosen.css', 'last');
	$this->getResponse()->addJavascript('chosen/chosen.jquery.min.js', 'last');
	$this->getResponse()->addJavascript('jquery.fixedheadertable.min.js', 'last');
	
	//$this->getResponse()->addJavascript('mediaelement-and-player.min.js', 'last');
	//$this->getResponse()->addStylesheet('mediaelementplayer.min.css', 'last');
	$this->getResponse()->addStylesheet('fhtdefaultTheme.css', 'last');
	
	
	$this->getResponse()->addJavascript('jquery.toggleswitch.min.js', 'last');
	$this->getResponse()->addStylesheet('toggleswitch.css', 'last');	
	
	$this->agentid = $request->getParameter('agent_id');
	$this->siteid = $request->getParameter('site_id');
	$this->groupid = $request->getParameter('group_id');
	$this->connected_only = $request->getParameter('connected_only');
	
	$this->agentgroups = fonivaFilter::currentUserManagedGroups();
	$this->groupids_list = array('');
	foreach($this->agentgroups as $g)
	{
		array_push($this->groupids_list, $g->getDbid());
	}
	
	
	$this->sites = Doctrine_Query::create()
					->select('s.dbid, s.name, s.created_at, s.updated_at')
					->from('ConfSite s')
					->orderBy('s.name');
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->sites->where('s.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
	$this->sites = $this->sites->execute();
	
	/* agents list */
	$this->agents = Doctrine_Query::create()
						->select('ca.dbid, ca.username, ca.shortusername, ci.firstname as firstname, ci.lastname as lastname, cg.name as groupname, cs.name as sitename')
						->from('ConfAgent ca')						
						->leftJoin('ca.ConfAgentInfo ci ON ci.dbid = ca.info_fk')
						->leftJoin('ca.ConfGroup cg ON ca.group_fk = cg.dbid')
						->leftJoin('ca.ConfSite cs ON ca.site_fk = cs.dbid')
						->orderBy('cg.name, ca.username')
						->where('ca.active = "yes"');
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->agents->andWhere('ca.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
		
	if(!fonivaFilter::canCurrentUserManageAllGroups())
		$this->agents->andWhere('ca.group_fk in ?', array($this->groupids_list));
		
	if($this->agentid != NULL && $this->agentid != '')
		$this->agents->andWhere('ca.dbid = ?', $this->agentid);
	if($this->groupid != NULL && $this->groupid != '')
		$this->agents->andWhere('cg.dbid = ?', $this->groupid);
	if($this->siteid != NULL && $this->siteid != '')
		$this->agents->andWhere('ca.site_fk = ?', $this->siteid);
		
	if($this->connected_only == '1')
		$this->agents->andWhere('ca.isconnected = "yes"');
		
	$this->agents = $this->agents->execute();
	
	
	$this->skills = Doctrine_Query::create()
					->select('s.dbid, s.name, s.created_at, s.updated_at')
					->from('ConfSkill s')
					->orderBy('s.name')
					->execute();
	
  }
  
  public function executeAgentskillassignmentload(sfWebRequest $request)
  {
	$this->getResponse()->addStylesheet('chosen/chosen.css', 'last');
	$this->getResponse()->addJavascript('chosen/chosen.jquery.min.js', 'last');
	
	$this->getResponse()->addJavascript('mediaelement-and-player.min.js', 'last');
	$this->getResponse()->addStylesheet('mediaelementplayer.min.css', 'last');
	
	$this->agentid = $request->getParameter('agent_id');
	$this->siteid = $request->getParameter('site_id');
	$this->groupid = $request->getParameter('group_id');
	$this->skillslist = $request->getParameter('skillslist');
	$this->connected_only = $request->getParameter('connected_only');
	
	
	$this->agents = Doctrine_Query::create()
						->select('ca.dbid, ca.username, ca.shortusername, ci.firstname as firstname, ci.lastname as lastname, cg.name as groupname, cs.name as sitename')
						->from('ConfAgent ca')						
						->leftJoin('ca.ConfAgentInfo ci ON ci.dbid = ca.info_fk')
						->leftJoin('ca.ConfGroup cg ON ca.group_fk = cg.dbid')
						->leftJoin('ca.ConfSite cs ON ca.site_fk = cs.dbid')
						->orderBy('cg.name, ca.username')
						->where('ca.active = "yes"');
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->agents->andWhere('ca.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
		
	if(!fonivaFilter::canCurrentUserManageAllGroups())
		$this->agents->andWhere('ca.group_fk in ?', array($this->groupids_list));
		
	if($this->agentid != NULL && $this->agentid != '')
		$this->agents->andWhere('ca.dbid = ?', $this->agentid);
	if($this->groupid != NULL && $this->groupid != '')
		$this->agents->andWhere('cg.dbid = ?', $this->groupid);
	if($this->siteid != NULL && $this->siteid != '')
		$this->agents->andWhere('ca.site_fk = ?', $this->siteid);
		
	if($this->connected_only == '1')
		$this->agents->andWhere('ca.isconnected = "yes"');
		
	$this->agents = $this->agents->execute();
	
	
	$this->skills = Doctrine_Query::create()
					->select('s.dbid, s.name, s.created_at, s.updated_at')
					->from('ConfSkill s')
					->orderBy('s.name');
					
	if(sizeof($this->skillslist) > 0)
		$this->skills = $this->skills->whereIn('s.dbid', $this->skillslist);
	
	$this->skills = $this->skills->execute();
					
					
					
					
	$this->agentskills = Doctrine_Query::create()
							->select('cas.agent_fk, cas.skill_fk')
							->from('ConfAgentSkill cas')
							->leftJoin('cas.ConfAgent ca ON ca.dbid = cas.agent_fk')
							->orderby('cas.agent_fk, cas.skill_fk')
							->where('cas.active = "yes"');
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->agentskills->andWhere('ca.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
		
	if(!fonivaFilter::canCurrentUserManageAllGroups())
		$this->agentskills->andWhere('ca.group_fk in ?', array($this->groupids_list));
		
	if($this->agentid != NULL && $this->agentid != '')
		$this->agentskills->andWhere('ca.dbid = ?', $this->agentid);
	if($this->groupid != NULL && $this->groupid != '')
		$this->agentskills->andWhere('ca.group_fk = ?', $this->groupid);
	if($this->siteid != NULL && $this->siteid != '')
		$this->agentskills->andWhere('ca.site_fk = ?', $this->siteid);
		
	$this->agentskills = $this->agentskills->execute();
	
	
	$this->agentskills_arr = array();
	foreach($this->agentskills as $as)
	{
		if(!isset($this->agentskills_arr[$as->agent_fk]))
			$this->agentskills_arr[$as->agent_fk] = array();
			
		$this->agentskills_arr[$as->agent_fk][$as->skill_fk] = 1;
	}
	  
  }
  
  public function executeAgentsingleskillassignupdate(sfWebRequest $request)
  {
	sfConfig::set('sf_web_debug', false);  
	//$this->getResponse()->setContentType('text/json');
	$this->setLayout(false);
	
	$this->forward404Unless($conf_agent = Doctrine::getTable('ConfAgent')->find($request->getParameter('agentdbid')), sprintf('Object conf_agent does not exist (%s).', $request->getParameter('dbid')));	
	$this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_agent->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$this->forward404Unless($conf_skill = Doctrine::getTable('ConfSkill')->find($request->getParameter('skilldbid')), sprintf('Object conf_skill does not exist (%s).', $request->getParameter('dbid')));	
	$this->isactive = $request->getParameter('isactive');
	
	Doctrine_Query::create()
		->update('ConfAgentSkill cs')
		->set('cs.active', '?', 'no')
		->where('cs.agent_fk = ? AND cs.skill_fk = ?', array($conf_agent->dbid, $conf_skill->dbid))
		->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($conf_agent->dbid, $conf_skill->dbid))
					->execute();
	
	if(sizeof($asc) > 0)
	{
		$asc = $asc[0];
		$asc->setAgentFk($conf_agent->dbid);
		$asc->setSkillFk($conf_skill->dbid);
		$asc->setActive(($this->isactive == '1') ? 'yes' : 'no');
		$asc->save();
	}
	else
	{
		$asc = new ConfAgentSkill();
		$asc->setAgentFk($conf_agent->dbid);
		$asc->setSkillFk($conf_skill->dbid);
		$asc->setActive(($this->isactive == '1') ? 'yes' : 'no');
		$asc->save();
	}
		
		
	if($this->isactive == '1')
	{		
		$changelog_skillstr = 'Added '.$conf_skill->name;
	}
	else
	{
		$changelog_skillstr = 'Removed '.$conf_skill->name;
	}
	
	
	$changelog = new LogAgentskillsChangelog();
	$changelog->setOccuredDate(date('Y-m-d H:i:s'));
	$changelog->setModifiedby($this->getUser()->getUsername());
	$changelog->setAgentdbid($conf_agent->dbid);
	$changelog->setSkillsChangedto($changelog_skillstr);
	$changelog->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());
	}
  }
  
  /*********   ***********************/
  /***   OTHERS AJAX CALLS       *****/
  /*********   ***********************/
  public function executeGetagentsingroupandsite(sfWebRequest $request)
  {
	sfConfig::set('sf_web_debug', false);  
	$this->getResponse()->setContentType('text/json');
	$this->setLayout(false);
	
	//$this->forward404Unless($this->groupid = $request->getParameter('groupid'));
	$this->groupid = $request->getParameter('groupid');
	$this->siteid  = $request->getParameter('siteid');
	$this->agentid = $request->getParameter('agentid');

	$this->groups = fonivaFilter::currentUserManagedGroups();
	$this->groups_list = array();
	$this->groupids_list = array('');
	$allowed = false;
	foreach($this->groups as $g)
	{
		$this->groups_list[$g->getDbid()] = $g;
		array_push($this->groupids_list, $g->getDbid());
		
		if($this->groupid == $g->getDbid())
		{
			$allowed = true;
		}
	}
	
	if($this->groupid != NULL && $this->groupid != '' && !$allowed)
		$this->forward404();
		
	
	
	$this->sites = Doctrine_Query::create()
					->select('s.dbid, s.name, s.created_at, s.updated_at')
					->from('ConfSite s')
					->orderBy('s.name');
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->sites->where('s.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
	$this->sites = $this->sites->execute();
	
	$this->sites_list = array();
	$this->siteids_list = array('');
	$allowed = false;
	foreach($this->sites as $g)
	{
		$this->sites_list[$g->getDbid()] = $g;
		array_push($this->siteids_list, $g->getDbid());
		
		if($this->siteid == $g->getDbid())
		{
			$allowed = true;
		}
	}
	
	if($this->siteid != NULL && $this->siteid != '' && !$allowed)
		$this->forward404();
		
    
	$this->agents = Doctrine_Query::create()
						->select('ca.dbid, ca.username, ca.shortusername, ci.firstname as firstname, ci.lastname as lastname')
						->from('ConfAgent ca')						
						->leftJoin('ca.ConfAgentInfo ci ON ci.dbid = ca.info_fk')
						->orderBy('ca.username')
						->where('ca.active = "yes"');
	if($this->groupid != NULL && $this->groupid != '')
		$this->agents->andWhere('ca.group_fk = ?', $this->groupid);
	else
	{
		$this->agents->andWhere('ca.group_fk in ?', array($this->groupids_list));
	}
	
	if($this->siteid != NULL && $this->siteid != '')
		$this->agents->andWhere('ca.site_fk = ?', $this->siteid);
	//else
	//{
	//	$this->agents->andWhere('ca.site_fk in ?', array($this->siteids_list));
	//}
		
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->agents->andWhere('ca.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
	$this->agents = $this->agents->execute();
  }

 
  /*********   ************/
  /***   AGENT GROUPS *****/
  /*********   ************/	 
  
  public function executeAgentgroups(sfWebRequest $request)
  {
	  
	$this->searchedAgentGroup = $this->getRequestParameter('searchedAgentGroup');
	$this->searchedAgentGroup = trim(strtolower($this->searchedAgentGroup));

	
	$this->pager = new sfDoctrinePager('ConfGroup', sfConfig::get('app_display_nbrecordperpage'));
	$this->pager->getQuery()->select('cg.dbid, cg.name, count(ag.dbid) as nbagents')
							->from('ConfGroup cg')
							->leftJoin('cg.ConfAgent ag')
							->orderBy('cg.name')
							->groupBy('cg.dbid')
							->where('1');
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->pager->getQuery()->andWhere('cg.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
		
	$defaultpage = $this->getcurrentmodule_defaultpage();
	if(!empty($this->searchedAgentGroup))
	{
		$this->pager->getQuery()->andWhere('lower(cg.name) LIKE ?','%'.$this->searchedAgentGroup.'%');
		$defaultpage = 1;
	}
	
	if(!fonivaFilter::canCurrentUserManageAllGroups())
	{
		$this->pager->getQuery()->leftJoin('cg.ConfUserAssignedgroup a')
								->andWhere('a.user_fk = ?', fonivaFilter::getCurrentUser()->getDbid());
	}
	
	
	$this->setcurrentmodule_defaultpage();
	$this->pager->setPage($defaultpage); //$this->getRequestParameter('page',1));
	$this->pager->init();
	$this->agentgroups = $this->pager->getResults();
  }
  
  public function executeAgentgroupnew(sfWebRequest $request)
  {
    $conf_group = new ConfGroup();
    $this->form = new ConfGroupForm($conf_group);
	$this->form->embedForm('settingform', (new ConfAgentSettingForm($conf_group->getConfAgentSetting())));
	$this->form->embedForm('infovoicerecordingpolicy', (new ConfVoicerecordingPolicyForm($conf_group->getConfVoicerecordingPolicy())));
	
	$this->activities = Doctrine_Query::create()
						->select('a.dbid, a.name, a.colorcode')
						->from('ConfAgentActivity a')
						->where('a.active = "yes" and a.name != "WORKING"')
						->orderBy('a.name');
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->activities->andWhere('a.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
	$this->activities = $this->activities->execute();
	
	
	$this->calldispositions = Doctrine_Query::create()
					->select('c.dbid, c.name')
					->from('ConfCallDisposition c')
					->orderBy('c.name');	
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->calldispositions = $this->calldispositions->andWhere('c.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
	$this->calldispositions = $this->calldispositions->execute();				
	
	$this->calldispositions_list = array();	
	foreach($this->calldispositions as $s)
		$this->calldispositions_list[$s->getDbid()] = $s;
		
	$assarr = $request->getParameter('assigned_calldisposition');
	$this->assigned_calldispositions = array();
	
	if($assarr != NULL)
	{
		foreach($assarr as $as)
			$this->assigned_calldispositions[$as] = 1;
	}
	
	$this->notreadyreasons = array();
	
	$this->getResponse()->addJavascript('ui.multiselect.js', 'last');
	$this->getResponse()->addJavascript('plugins/scrollTo/jquery.scrollTo-min.js', 'last');
	$this->getResponse()->addJavascript('plugins/localisation/jquery.localisation-min.js', 'last');
	$this->getResponse()->addJavascript('jquery.tmpl.1.1.1.js', 'last');
	$this->getResponse()->addStylesheet('ui.multiselect.css', 'last');
  }

  public function executeAgentgroupcreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));
    $conf_group = new ConfGroup();
    $this->form = new ConfGroupForm($conf_group);
    $this->form->embedForm('settingform', (new ConfAgentSettingForm($conf_group->getConfAgentSetting())));
	$this->form->embedForm('infovoicerecordingpolicy', (new ConfVoicerecordingPolicyForm($conf_group->getConfVoicerecordingPolicy())));
    $this->processAgentgroupForm($request, $this->form);
	
	$this->activities = Doctrine_Query::create()
						->select('a.dbid, a.name, a.colorcode')
						->from('ConfAgentActivity a')
						->where('a.active = "yes" and a.name != "WORKING"')
						->orderBy('a.name');
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->activities->andWhere('a.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
	$this->activities = $this->activities->execute();
	
	$this->notreadyreasons = $request->getParameter('select_notreadyreasons');
	
	
	
	$this->calldispositions = Doctrine_Query::create()
					->select('c.dbid, c.name')
					->from('ConfCallDisposition c')
					->orderBy('c.name');	
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->calldispositions = $this->calldispositions->andWhere('c.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
	$this->calldispositions = $this->calldispositions->execute();				
	
	$this->calldispositions_list = array();	
	foreach($this->calldispositions as $s)
		$this->calldispositions_list[$s->getDbid()] = $s;
		
	$assarr = $request->getParameter('assigned_calldisposition');
	$this->assigned_calldispositions = array();
	if($assarr != NULL)
	{
		foreach($assarr as $as)
			$this->assigned_calldispositions[$as] = 1;
	}
	
	$this->getResponse()->addJavascript('ui.multiselect.js', 'last');
	$this->getResponse()->addJavascript('plugins/scrollTo/jquery.scrollTo-min.js', 'last');
	$this->getResponse()->addJavascript('plugins/localisation/jquery.localisation-min.js', 'last');
	$this->getResponse()->addJavascript('jquery.tmpl.1.1.1.js', 'last');
	$this->getResponse()->addStylesheet('ui.multiselect.css', 'last');
	 
    $this->setTemplate('agentgroupnew');
  }

  public function executeAgentgroupedit(sfWebRequest $request)
  {
    $this->forward404Unless($conf_group = Doctrine::getTable('ConfGroup')->find($request->getParameter('dbid')), sprintf('Object conf_group does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_group->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$this->form = new ConfGroupForm($conf_group);
	$this->form->embedForm('settingform', (new ConfAgentSettingForm($conf_group->getConfAgentSetting())));
	$this->form->embedForm('infovoicerecordingpolicy', (new ConfVoicerecordingPolicyForm($conf_group->getConfVoicerecordingPolicy())));
	
		
	$this->activities = Doctrine_Query::create()
						->select('a.dbid, a.name, a.colorcode')
						->from('ConfAgentActivity a')
						->where('a.active = "yes" and a.name != "WORKING"')
						->orderBy('a.name');
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->activities->andWhere('a.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
	$this->activities = $this->activities->execute();
	
	$groupnotreadyreasons = Doctrine_Query::create()
								->select('a.reason_fk')
								->from('ConfGroupNotreadyreason a')
								->where('a.group_fk = ?', $conf_group->dbid)
								->orderby('a.reason_fk')
								->execute();
	$this->notreadyreasons = array();
	foreach($groupnotreadyreasons as $gnr)
		$this->notreadyreasons[$gnr->reason_fk] = $gnr->reason_fk;
		
	
	
	$this->calldispositions = Doctrine_Query::create()
					->select('c.dbid, c.name')
					->from('ConfCallDisposition c')
					->orderBy('c.name');	
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->calldispositions = $this->calldispositions->andWhere('c.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
	$this->calldispositions = $this->calldispositions->execute();				
	
	$this->calldispositions_list = array();	
	foreach($this->calldispositions as $s)
		$this->calldispositions_list[$s->getDbid()] = $s;
		
	$this->assigned_calldispositions = array();	
	if(($sfs = $conf_group->ConfAgentSetting))
	{
		foreach($sfs->ConfAgentSettingCalldisposition as $as)
		{
			$this->assigned_calldispositions[$as->getDispositionFk()] = 1;
		}
	}
		
	$this->getResponse()->addJavascript('ui.multiselect.js', 'last');
	$this->getResponse()->addJavascript('plugins/scrollTo/jquery.scrollTo-min.js', 'last');
	$this->getResponse()->addJavascript('plugins/localisation/jquery.localisation-min.js', 'last');
	$this->getResponse()->addJavascript('jquery.tmpl.1.1.1.js', 'last');
	$this->getResponse()->addStylesheet('ui.multiselect.css', 'last');
	
  }

  public function executeAgentgroupupdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($conf_group = Doctrine::getTable('ConfGroup')->find($request->getParameter('dbid')), sprintf('Object conf_group does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_group->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$this->form = new ConfGroupForm($conf_group);
	$this->form->embedForm('settingform', (new ConfAgentSettingForm($conf_group->getConfAgentSetting())));
	$this->form->embedForm('infovoicerecordingpolicy', (new ConfVoicerecordingPolicyForm($conf_group->getConfVoicerecordingPolicy())));
    $this->processAgentgroupForm($request, $this->form);
	
	
		
	$this->activities = Doctrine_Query::create()
						->select('a.dbid, a.name, a.colorcode')
						->from('ConfAgentActivity a')
						->where('a.active = "yes" and a.name != "WORKING"')
						->orderBy('a.name');
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->activities->andWhere('a.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
	$this->activities = $this->activities->execute();
	
	$this->notreadyreasons = $request->getParameter('select_notreadyreasons');
	
	
	
	$this->calldispositions = Doctrine_Query::create()
					->select('c.dbid, c.name')
					->from('ConfCallDisposition c')
					->orderBy('c.name');	
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->calldispositions = $this->calldispositions->andWhere('c.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
	$this->calldispositions = $this->calldispositions->execute();				
	
	$this->calldispositions_list = array();	
	foreach($this->calldispositions as $s)
		$this->calldispositions_list[$s->getDbid()] = $s;
		
	$assarr = $request->getParameter('assigned_calldisposition');
	$this->assigned_calldispositions = array();
	foreach($assarr as $as)
		$this->assigned_calldispositions[$as] = 1;
	
	$this->getResponse()->addJavascript('ui.multiselect.js', 'last');
	$this->getResponse()->addJavascript('plugins/scrollTo/jquery.scrollTo-min.js', 'last');
	$this->getResponse()->addJavascript('plugins/localisation/jquery.localisation-min.js', 'last');
	$this->getResponse()->addJavascript('jquery.tmpl.1.1.1.js', 'last');
	$this->getResponse()->addStylesheet('ui.multiselect.css', 'last');
	
    $this->setTemplate('agentgroupedit');
  }

  public function executeAgentgroupdelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();
    $this->forward404Unless($conf_group = Doctrine::getTable('ConfGroup')->find($request->getParameter('dbid')), sprintf('Object conf_group does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_group->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$conf_group->delete();
	if(($sfs = $conf_group->getConfAgentSetting()))
		$sfs->delete();
	
	if(($srp = $conf_group->getConfVoicerecordingPolicy()))
		$srp->delete();
    $this->redirect('ressource/agentgroups');
  }

  protected function processAgentgroupForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $conf_group = $form->getObject();
	  $conf_group->setName($form->getValue('name'));	  
	  
	  if(fonivaFilter::isCurrentUserSuperTenant())
	    $conf_group->setTenantFk($form->getValue('tenant_fk'));
	  else
	    $conf_group->setTenantFk(fonivaFilter::getCurrentUserTenantId());
	  
	  $sfs = $conf_group->getConfAgentSetting();
	  if(!$sfs)
	  	$sfs = new ConfAgentSetting();
	  
	  $agtsettings = $form['settingform']->getValue();	  
	  $sfs->setAutoreadyatstart($agtsettings['autoreadyatstart']);
	  $sfs->setActivityatstartFk(($agtsettings['activityatstart_fk'] == '' ? NULL : $agtsettings['activityatstart_fk']));
	  $sfs->setWrapupmode($agtsettings['wrapupmode']);
	  $sfs->setWrapuptime($agtsettings['wrapuptime']);
	  $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();
	  
	  $conf_group->setSettingFk($sfs->getDbid());
	  $newadded = $conf_group->isNew();
	  
	  
	  $srp = $conf_group->getConfVoicerecordingPolicy();
	  if(!$srp)
		$srp = new ConfVoicerecordingPolicy();
	  $recpolicy = $form['infovoicerecordingpolicy']->getValue();
	  $srp->setNameformat($recpolicy['nameformat']);
	  $srp->setDorecord($recpolicy['dorecord']);
      //$srp->setOnduplicate($recpolicy['onduplicate']);
	  $srp->setCompression($recpolicy['compression']);
	  $srp->save();
	  
	  $conf_group->setManualoutboundVoicerecordingPolicyFk($srp->getDbid());
	  $conf_group->setLastmodifiedBy($this->getUser()->getUsername());
	  
	  $conf_group->save();
	  
	  
	  /* not ready reasons rules */
	  $notreadyreasonsarr = $request->getParameter('select_notreadyreasons');
	  Doctrine_Query::create()
	  		->from('ConfGroupNotreadyreason')
			->where('group_fk = ?', $conf_group->getDbid())
			->delete()
			->execute();
	  if(is_array($notreadyreasonsarr) && sizeof($notreadyreasonsarr) > 0)
	  {
		  foreach($notreadyreasonsarr as $felt)
		  {
			$freason 		= $felt;
			
			$conf_group_notreadyreason = new ConfGroupNotreadyreason();
			$conf_group_notreadyreason->setGroupFk($conf_group->getDbid());
			$conf_group_notreadyreason->setReasonFk($freason);
			$conf_group_notreadyreason->save();
		  }
	  }
	  
	  /* 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();
		  }
	  }
	  
	  
	  if($newadded)
	  {
		//auto assigned group to user
		$ag = new ConfUserAssignedGroup();
		$ag->setUserFk(fonivaFilter::getCurrentUser()->getDbid());  
		$ag->setAgentgroupFk($conf_group->getDbid());
		$ag->save();
	  }
	  
      $this->redirect('ressource/agentgroups');
    }
  }
  
  
 
  /*********   ************************/
  /***   AGENT GROUP SPEED DIALS  *****/
  /*********   ************************/
  public function executeAgentgroupspeeddials(sfWebRequest $request)
  {	  
	$this->searchedAgentGroupspeeddial = $this->getRequestParameter('searchedAgentGroupspeeddial');
	$this->searchedAgentGroupspeeddial = trim(strtolower($this->searchedAgentGroupspeeddial));
	
	$this->forward404Unless($this->conf_group = Doctrine::getTable('ConfGroup')->find($request->getParameter('agentgroupdbid')), sprintf('Object conf_group does not exist (%s).', $request->getParameter('dbid')));
    	
	$this->pager = new sfDoctrinePager('ConfAgentSpeeddial', sfConfig::get('app_display_nbrecordperpage'));
	$this->pager->getQuery()->select('sp.dbid as speeddialdbid, sp.name as speeddialname, sp.sendto as speedialsendto, sp.outboundnumber as speedialoutboundnumber, cgsp.group_fk as speedialgroupdbid,
										ci.dbid as inbound_dbid, ci.inbound_name as inbound_name')
							->from('ConfGroupSpeeddial cgsp')
							->leftJoin('cgsp.ConfAgentSpeeddial sp')
							->leftJoin('sp.ConfInbound ci ON ci.dbid = sp.inbound_fk')
							->orderBy('sp.name')
							->where('cgsp.group_fk = ?', $this->conf_group->dbid);
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->pager->getQuery()->andWhere('sp.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
		
	$defaultpage = $this->getcurrentmodule_defaultpage();
	if(!empty($this->searchedAgentGroupspeeddial))
	{
		$this->pager->getQuery()->andWhere('lower(sp.name) LIKE ?','%'.$this->searchedAgentGroupspeeddial.'%');
		$defaultpage = 1;
	}
	
	$this->setcurrentmodule_defaultpage();
	$this->pager->setPage($defaultpage); //$this->getRequestParameter('page',1));
	$this->pager->init();
	$this->speeddials = $this->pager->getResults();
  }
  
  public function executeAgentgroupspeeddialnew(sfWebRequest $request)
  {
	$this->forward404Unless($this->conf_group = Doctrine::getTable('ConfGroup')->find($request->getParameter('agentgroupdbid')), sprintf('Object conf_group does not exist (%s).', $request->getParameter('dbid')));
    $speeddial = new ConfAgentSpeeddial();
    $this->form = new ConfAgentSpeeddialForm($speeddial);
	$this->form->setDefault('agentgroupdbid', $this->conf_group->dbid);
  }

  public function executeAgentgroupspeeddialcreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));
    $speeddial = new ConfAgentSpeeddial();
    $this->form = new ConfAgentSpeeddialForm($speeddial);
    $this->processAgentgroupspeeddialForm($request, $this->form);
    $this->setTemplate('agentgroupspeeddialnew');
  }

  public function executeAgentgroupspeeddialedit(sfWebRequest $request)
  {
    $this->forward404Unless($speeddial = Doctrine::getTable('ConfAgentSpeeddial')->find($request->getParameter('dbid')), sprintf('Object conf_agent_speeddial does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $speeddial->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$conf_groupspeedial = $speeddial->ConfGroupSpeeddial;
	if($conf_groupspeedial)
		$conf_groupspeedial = $conf_groupspeedial[0];
	else
		$this->forward404();
	$this->forward404Unless($this->conf_group = Doctrine::getTable('ConfGroup')->find($conf_groupspeedial->group_fk), sprintf('Object conf_group does not exist (%s).', $request->getParameter('dbid')));
    $this->form = new ConfAgentSpeeddialForm($speeddial);
	$this->form->setDefault('agentgroupdbid', $this->conf_group->dbid);
  }

  public function executeAgentgroupspeeddialupdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($speeddial = Doctrine::getTable('ConfAgentSpeeddial')->find($request->getParameter('dbid')), sprintf('Object conf_agent_speeddial does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $speeddial->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$this->form = new ConfAgentSpeeddialForm($speeddial);
	$this->processAgentgroupspeeddialForm($request, $this->form);
    $this->setTemplate('agentgroupspeeddialedit');
  }

  public function executeAgentgroupspeeddialdelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();
    $this->forward404Unless($speeddial = Doctrine::getTable('ConfAgentSpeeddial')->find($request->getParameter('dbid')), sprintf('Object conf_agent_speeddial does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $speeddial->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$conf_groupspeedial = $speeddial->ConfGroupSpeeddial;
	if($conf_groupspeedial)
		$conf_groupspeedial = $conf_groupspeedial[0];
	else
		$this->forward404();
	$this->forward404Unless($this->conf_group = Doctrine::getTable('ConfGroup')->find($conf_groupspeedial->group_fk), sprintf('Object conf_group does not exist (%s).', $request->getParameter('dbid')));
    $speeddial->delete();
    $this->redirect('ressource/agentgroupspeeddials?agentgroupdbid='.$this->conf_group->dbid);
  }

  protected function processAgentgroupspeeddialForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
	  $speeddial = $form->getObject();
	  if(fonivaFilter::isCurrentUserSuperTenant())
		 $speeddial->setTenantFk($form->getValue('tenant_fk'));
	  else
		 $speeddial->setTenantFk(fonivaFilter::getCurrentUserTenantId());
	  $speeddial->setName($form->getValue('name'));
	  $speeddial->setSendto($form->getValue('sendto'));
	  $speeddial->setInboundFk($form->getValue('inbound_fk'));
	  $speeddial->setQueueFk($form->getValue('queue_fk'));
	  $speeddial->setOutboundnumber($form->getValue('outboundnumber'));
	  $speeddial->save();
	  
	  $agentgroupdbid = $form->getValue('agentgroupdbid');
	  Doctrine_Query::create()
	  		->from('ConfGroupSpeeddial')
			->where('group_fk = ? and speeddial_fk = ?', array($agentgroupdbid, $speeddial->dbid))
			->delete()
			->execute();
	  $nn = new ConfGroupSpeeddial();
	  $nn->setGroupFk($agentgroupdbid);
	  $nn->setSpeeddialFk($speeddial->dbid);
	  $nn->save();
	  
      $this->redirect('ressource/agentgroupspeeddials?agentgroupdbid='.$agentgroupdbid);
    }
  }
	
 
  /*********   ************/
  /***   AGENT SKILS  *****/
  /*********   ************/	 
  
  public function executeAgentskills(sfWebRequest $request)
  {
	$this->searchedAgentSkill = $this->getRequestParameter('searchedAgentSkill');
	$this->searchedAgentSkill = trim(strtolower($this->searchedAgentSkill));
	  
	$this->pager = new sfDoctrinePager('ConfSkill', sfConfig::get('app_display_nbrecordperpage'));
	$this->pager->getQuery()->from('ConfSkill cs')
							->orderBy('cs.name');
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->pager->getQuery()->where('cs.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
				
	$defaultpage = $this->getcurrentmodule_defaultpage();
	if(!empty($this->searchedAgentSkill))
	{
		$this->pager->getQuery()->where('lower(cs.name) LIKE ?','%'.$this->searchedAgentSkill.'%');	
		$defaultpage = 1;
	}
			
	$this->setcurrentmodule_defaultpage();
	$this->pager->setPage($defaultpage); //$this->getRequestParameter('page',1));
	$this->pager->init();
	$this->agentskills = $this->pager->getResults();
  }
  
  public function executeAgentskillnew(sfWebRequest $request)
  {
    $this->form = new ConfSkillForm();
  }

  public function executeAgentskillcreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));
    $this->form = new ConfSkillForm();
    $this->processAgentskillForm($request, $this->form);
    $this->setTemplate('agentskillnew');
  }

  public function executeAgentskilledit(sfWebRequest $request)
  {
    $this->forward404Unless($conf_skill = Doctrine::getTable('ConfSkill')->find($request->getParameter('dbid')), sprintf('Object conf_skill does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_skill->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$this->form = new ConfSkillForm($conf_skill);
  }

  public function executeAgentskillupdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($conf_skill = Doctrine::getTable('ConfSkill')->find($request->getParameter('dbid')), sprintf('Object conf_skill does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_skill->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$this->form = new ConfSkillForm($conf_skill);
    $this->processAgentskillForm($request, $this->form);
    $this->setTemplate('agentskilledit');
  }

  public function executeAgentskilldelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();
    $this->forward404Unless($conf_skill = Doctrine::getTable('ConfSkill')->find($request->getParameter('dbid')), sprintf('Object conf_skill does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_skill->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$conf_skill->delete();
    $this->redirect('ressource/agentskills');
  }

  protected function processAgentskillForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $conf_skill = $form->getObject();
	  $conf_skill->setName($form->getValue('name'));
	  if(fonivaFilter::isCurrentUserSuperTenant())
	     $conf_skill->setTenantFk($form->getValue('tenant_fk'));
	  else
	     $conf_skill->setTenantFk(fonivaFilter::getCurrentUserTenantId());
	  
	  $conf_skill->setLastmodifiedBy($this->getUser()->getUsername());
	  $conf_skill->save();
      $this->redirect('ressource/agentskills');
    }
  }
  
  public function executeAgentskillassign(sfWebRequest $request)
  {
	 $this->forward404Unless($conf_agent = Doctrine::getTable('ConfAgent')->find($request->getParameter('dbid')), sprintf('Object conf_agent does not exist (%s).', $request->getParameter('dbid')));
	 $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_agent->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	 $this->skills = Doctrine_Query::create()
					->select('s.dbid, s.name, s.created_at, s.updated_at')
					->from('ConfSkill s')
					->orderBy('s.name');
	 
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->skills->where('s.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
		
	$this->skills = $this->skills->execute();
	
	$this->conf_agent = $conf_agent;				
	
	$this->skills_list = array();	
	foreach($this->skills as $s)
		$this->skills_list[$s->getDbid()] = $s;
				
		
	$this->assigned_skills = array(); //$this->conf_agent->ConfAgentSkill;
	foreach($this->conf_agent->ConfAgentSkill as $as)
		$this->assigned_skills[$as->getSkillFk()] = $as;
	
	/* js headers */
	$this->getResponse()->addJavascript('ui.multiselect.js', 'last');
	$this->getResponse()->addJavascript('plugins/scrollTo/jquery.scrollTo-min.js', 'last');
	$this->getResponse()->addJavascript('plugins/localisation/jquery.localisation-min.js', 'last');
	$this->getResponse()->addJavascript('jquery.tmpl.1.1.1.js', 'last');
	$this->getResponse()->addStylesheet('ui.multiselect.css', 'last');
	$this->getResponse()->addStylesheet('agentselecteditor.css', 'last');
	
	$this->getResponse()->addJavascript('jquery.toggleswitch.min.js', 'last');
	$this->getResponse()->addStylesheet('toggleswitch.css', 'last');	
	 
  }
  
  public function executeAgentskillassignupdate(sfWebRequest $request)
  {
	$this->forward404Unless($conf_agent = Doctrine::getTable('ConfAgent')->find($request->getParameter('dbid')), sprintf('Object conf_agent does not exist (%s).', $request->getParameter('dbid')));	
	$this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_agent->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	
	
	Doctrine_Query::create()
		->update('ConfAgentSkill cs')
		->set('cs.active', '?', 'no')
		->where('cs.agent_fk = ?', $request->getParameter('dbid'))
		->execute();
	
	
	$this->skills = Doctrine_Query::create()
	
					->select('s.dbid, s.name, s.created_at, s.updated_at')
					->from('ConfSkill s')
					->orderBy('s.name');
	
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->skills->where('s.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
		
	$this->skills = $this->skills->execute();
	
	$this->skills_list = array();	
	foreach($this->skills as $s)
		$this->skills_list[$s->getDbid()] = $s;
	
	
	$changelog_skillstr = '';
	$assigned_skill = $request->getParameter('assigned_skill');
	$cntskill = 0;
	foreach($assigned_skill as $skillid => $skillarr)
	{
		$score = $skillarr['score'];
		$isactive = (isset($skillarr['active']) && ($skillarr['active'] == 'on' || $skillarr['active'] == 'true')) ? true : false;
		$asc = new ConfAgentSkill();
		$asc->setAgentFk($request->getParameter('dbid'));
		$asc->setSkillFk($skillid);
		$asc->setScore($score);
		$asc->setActive($isactive ? 'yes' : 'no');
		$asc->setAgentFk($request->getParameter('dbid'));
		$asc->replace();
	
		
		$changelog_skillstr .= isset($this->skills_list[$skillid]) ? $this->skills_list[$skillid]->name : 'unknown-skill#'.$skillid;
		$changelog_skillstr .= '('.$score.')';
		if($cntskill < sizeof($assigned_skill)-1)
			$changelog_skillstr .= ', ';
		$cntskill++;	
	}
	
	if($changelog_skillstr == '')
		$changelog_skillstr = 'No skill';
	
	//do change log
	$changelog = new LogAgentskillsChangelog();
	$changelog->setOccuredDate(date('Y-m-d H:i:s'));
	$changelog->setModifiedby($this->getUser()->getUsername());
	$changelog->setAgentdbid($conf_agent->dbid);
	$changelog->setSkillsChangedto($changelog_skillstr);
	$changelog->setComments($request->getParameter('comments'));
	$changelog->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());
	}
	
	$this->redirect('ressource/agents');
  }
  
  
  public function executeAgentskillschangelog(sfWebRequest $request)
  {
	$this->forward404Unless($conf_agent = Doctrine::getTable('ConfAgent')->find($request->getParameter('dbid')), sprintf('Object conf_agent does not exist (%s).', $request->getParameter('dbid')));	
	$this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_agent->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$this->changelogs = Doctrine_Query::create()
					->select('s.occured_date, s.modifiedby, s.skills_changedto, s.comments')
					->from('LogAgentSkillsChangelog s')
					->where('s.agentdbid = ?', $conf_agent->dbid)
					->orderBy('s.occured_date desc, s.dbid')
					->execute();
	$this->setlayout(false);
  }
  
  
   
  /*********   ************/
  /***   AGENT PROPERTIES  *****/
  /*********   ************/	 
  
  public function executeAgentproperties(sfWebRequest $request)
  {
	$this->searchedAgentProperty = $this->getRequestParameter('searchedAgentProperty');
	$this->searchedAgentProperty = trim(strtolower($this->searchedAgentProperty));
	  
	$this->pager = new sfDoctrinePager('ConfAgentProperty', sfConfig::get('app_display_nbrecordperpage'));
	$this->pager->getQuery()->from('ConfAgentProperty cap')
							->orderBy('cap.name');
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->pager->getQuery()->where('cap.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
				
	$defaultpage = $this->getcurrentmodule_defaultpage();
	if(!empty($this->searchedAgentProperty))
	{
		$this->pager->getQuery()->where('lower(cap.name) LIKE ?','%'.$this->searchedAgentProperty.'%');	
		$defaultpage = 1;
	}
			
	$this->setcurrentmodule_defaultpage();
	$this->pager->setPage($defaultpage); //$this->getRequestParameter('page',1));
	$this->pager->init();
	$this->agentproperties = $this->pager->getResults();
  }
  
  public function executeAgentpropertynew(sfWebRequest $request)
  {
    $this->form = new ConfAgentPropertyForm();
  }

  public function executeAgentpropertycreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));
    $this->form = new ConfAgentPropertyForm();
    $this->processAgentpropertyForm($request, $this->form);
    $this->setTemplate('agentpropertynew');
  }

  public function executeAgentpropertyedit(sfWebRequest $request)
  {
    $this->forward404Unless($conf_agent_property = Doctrine::getTable('ConfAgentProperty')->find($request->getParameter('dbid')), sprintf('Object conf_agent_property does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_agent_property->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$this->form = new ConfAgentPropertyForm($conf_agent_property);
  }

  public function executeAgentpropertyupdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($conf_agent_property = Doctrine::getTable('ConfAgentProperty')->find($request->getParameter('dbid')), sprintf('Object conf_agent_property does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_agent_property->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$this->form = new ConfAgentPropertyForm($conf_agent_property);
    $this->processAgentpropertyForm($request, $this->form);
    $this->setTemplate('agentpropertyedit');
  }

  public function executeAgentpropertydelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();
    $this->forward404Unless($conf_agent_property = Doctrine::getTable('ConfAgentProperty')->find($request->getParameter('dbid')), sprintf('Object conf_agent_property does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_agent_property->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$conf_agent_property->delete();
    $this->redirect('ressource/agentproperties');
  }

  protected function processAgentpropertyForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $conf_agent_property = $form->getObject();
	  $conf_agent_property->setName($form->getValue('name'));
	  if(fonivaFilter::isCurrentUserSuperTenant())
	     $conf_agent_property->setTenantFk($form->getValue('tenant_fk'));
	  else
	     $conf_agent_property->setTenantFk(fonivaFilter::getCurrentUserTenantId());
	  
	  //$conf_skill->setLastmodifiedBy($this->getUser()->getUsername());
	  $conf_agent_property->save();
      $this->redirect('ressource/agentproperties');
    }
  }
  
  /*********   ************/
  /***   MANAGERS     *****/
  /*********   ************/	 
  
  public function executeManagers(sfWebRequest $request)
  {
	$this->searchedManager = $this->getRequestParameter('searchedManager');
	$this->searchedManager = trim(strtolower($this->searchedManager));	  
	  
	$this->pager = new sfDoctrinePager('ConfUser', sfConfig::get('app_display_nbrecordperpage'));
	$this->pager->getQuery()->from('ConfUser cu')
							->orderBy('cu.lastname, cu.firstname');
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->pager->getQuery()->where('cu.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());



	$defaultpage = $this->getcurrentmodule_defaultpage();
	if(!empty($this->searchedManager))
	{
		$this->pager->getQuery()->where('lower(cu.username) LIKE ? OR lower(cu.firstname) LIKE ? OR lower(cu.lastname) LIKE ?', array($this->searchedManager, '%'.$this->searchedManager.'%', '%'.$this->searchedManager.'%'));
		$defaultpage = 1;
	}



	$this->setcurrentmodule_defaultpage();
	$this->pager->setPage($defaultpage); //$this->getRequestParameter('page',1));
	$this->pager->init();
	$this->managers = $this->pager->getResults();
  }
  
  public function executeManagernew(sfWebRequest $request)
  {
    $this->form = new ConfUserForm();
	$this->form->embedForm('securityloginform', (new SecurityloginForm()));
  }

  public function executeManagercreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));
    $this->form = new ConfUserForm();
	$this->form->embedForm('securityloginform', (new SecurityloginForm()));
    $this->processManagerForm($request, $this->form);
    $this->setTemplate('managersnew');
  }

  public function executeManageredit(sfWebRequest $request)
  {
    $this->forward404Unless($conf_user = Doctrine::getTable('ConfUser')->find($request->getParameter('dbid')), sprintf('Object conf_user does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_user->getTenantFk() == fonivaFilter::getCurrentUserTenantId()); 
	$this->form = new ConfUserForm($conf_user);
	$this->form->embedForm('securityloginform', (new SecurityloginForm(array('origin_ips' => $conf_user->getSecurityOriginIps()))));
  }

  public function executeManagerupdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($conf_user = Doctrine::getTable('ConfUser')->find($request->getParameter('dbid')), sprintf('Object conf_user does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_user->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$this->form = new ConfUserForm($conf_user);
    $this->form->embedForm('securityloginform', (new SecurityloginForm(array('origin_ips' => $conf_user->getSecurityOriginIps()))));
	$this->processManagerForm($request, $this->form);
    $this->setTemplate('manageredit');
  }

  public function executeManagerdelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();
    $this->forward404Unless($conf_user = Doctrine::getTable('ConfUser')->find($request->getParameter('dbid')), sprintf('Object conf_user does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_user->getTenantFk() == fonivaFilter::getCurrentUserTenantId()); 

	$sfu = $conf_user->getsfGuardUser();
	if($sfu)
		$sfu->delete();
		
	$conflivestatviewer = $conf_user->getConfLivestatviewer();
	if($conflivestatviewer)
	{
		$ljbu = $conflivestatviewer->getJbUser();
		if($ljbu)
			$ljbu->delete();
		$conflivestatviewer->delete();
	}
		
	$confqauser = $conf_user->getConfQauser();
	if($confqauser)
	{
		$confqauserdbid = $confqauser->getDbid();
		$ljbu = $confqauser->getJbUser();
		if($ljbu)
			$ljbu->delete();
		$confqauser->delete();
		
		/* *********************** */
		/* send to foniva server */
		/* *********************** */
		fonivaFilter::foniva_send_toserver("MSG_QAUSER_DELETED", 
											"qauserid", $confqauserdbid);
	}
	
	$conf_user->delete();
    $this->redirect('ressource/managers');
  }

  protected function processManagerForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
	  $cu = $form->getObject();
	  $cu->setFirstname($form->getValue('firstname'));
	  $cu->setLastname($form->getValue('lastname'));
	  $cu->setUsername($form->getValue('username'));
	  $cu->setProfileFk($form->getValue('profile_fk'));
	  $cu->setEmail($form->getValue('email'));
	  $cu->setLastmodifiedBy($this->getUser()->getUsername());
	  $newusertenant = NULL;
	  if(fonivaFilter::isUserSuperTenant($this->getUser()->getGuardUser()))
	  {
		//only this we are a super tenant, we can setup tenants 
		$cu->setIsSuperTenant($form->getValue('is_super_tenant'));
		$cu->setTenantFk($form->getValue('tenant_fk'));
		
		if($form->getValue('tenant_fk') != '' && $form->getValue('tenant_fk') != NULL)
			$newusertenant = Doctrine::getTable('ConfTenant')->find($form->getValue('tenant_fk'));
	  }
	  else
	  {
		//if we are not a super tenant, set new user to current user
		$newusertenant = fonivaFilter::getCurrentUserTenant();
		$cu->setIsSuperTenant('no');
		$cu->setTenantFk($newusertenant->getDbid());
	  }
	  
	  
	  $sf_username = $form->getValue('username');
	  if($newusertenant != NULL)
	  	$sf_username = $sf_username.'@'.$newusertenant->getName();
	  
	  
	  
	  $sfu = $cu->getsfGuardUser();
	  if(!$sfu)
	  	$sfu = new sfGuardUser($form->getPar);
		
		
	  $sfu->setUsername($sf_username);
	  if($form->getValue('password') != '')
	  	$sfu->setPassword($form->getValue('password'));
	  $sfu->save();
	  
	  $cu->setSfUserFk($sfu->getId());
	  
	  //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 livestatviewer
	  $lstatu = $cu->getConfLivestatviewer();
	  if(!$lstatu)
	  	$lstatu = new ConfLivestatviewer();
	  if($newusertenant != NULL)
		  $lstatu->setTenantFk($newusertenant->getDbid());
	  $liveviewer_username = 'livestatviewer_'.$form->getValue('username');
	  if($newusertenant != NULL)
	  	$liveviewer_username = $liveviewer_username . '_' . $newusertenant->getName();
	  $liveviewer_password = $this->generateword(10);
	  $lstatu->setUsername($liveviewer_username);
	  $lstatu->setPassword($liveviewer_password);
	  
	  $lstatu_jbuser = $lstatu->getJbUser();
	  if(!$lstatu_jbuser)
	  {
		$lstatu_jbuser = new JbUser();  
	  }
	  $lstatu_jbuser->setType('livestatviewer');
	  $lstatu_jbuser->setUsername($liveviewer_username);
	  $lstatu_jbuser->setPassword(md5($liveviewer_password));
	  $lstatu_jbuser->save();
	  
	  //add livestatviewer
	  $lstatu = $cu->getConfLivestatviewer();
	  if(!$lstatu)
	  	$lstatu = new ConfLivestatviewer();
	  if($newusertenant != NULL)
		  $lstatu->setTenantFk($newusertenant->getDbid());
	  $liveviewer_username = 'livestatviewer_'.$form->getValue('username');
	  if($newusertenant != NULL)
	  	$liveviewer_username = $liveviewer_username . '_' . $newusertenant->getName();
	  $liveviewer_password = $this->generateword(10);
	  $lstatu->setUsername($liveviewer_username);
	  $lstatu->setPassword($liveviewer_password);
	  
	  $lstatu_jbuser = $lstatu->getJbUser();
	  if(!$lstatu_jbuser)
	  {
		$lstatu_jbuser = new JbUser();  
	  }
	  $lstatu_jbuser->setType('livestatviewer');
	  $lstatu_jbuser->setUsername($liveviewer_username);
	  $lstatu_jbuser->setPassword(md5($liveviewer_password));
	  $lstatu_jbuser->save();
	  
	  /* auto assign group */
	  $this->dispatch_jabber_user_to_groups($lstatu_jbuser);
	  
	  
	  $lstatu->setJbuserFk($lstatu_jbuser->getDbid());
	  $lstatu->save();
	  
	  $cu->setConfLivestatviewerFk($lstatu->getDbid());
	  
	  
	  $qauserisnew = false;
	  //add qa user
	  $lsqau = $cu->ConfQauser;
	  if(sizeof($lsqau) > 0)
	  	$lsqau = $lsqau[0];
	  if(!$lsqau || sizeof($lsqau) <= 0)
	  {
	  	$lsqau = new ConfQauser();
		$qauserisnew = true;
	  }
	  
          $qa_username = 'qauser_'.$form->getValue('username');
	  if($newusertenant != NULL)
          {
		  $lsqau->setTenantFk($newusertenant->getDbid());
                  $qa_username .= '_' . $newusertenant->getName();
          }
	  $qa_password = $form->getValue('password');
	  
	  $strippedusername = preg_replace("/[^a-zA-Z0-9\s]/", "", $qa_username);
	  $qauser_sipusername = sfConfig::get('app_qauser_extensionprefix').$strippedusername;
	  $qauser_sippassword = $this->generateword(10);
	  
	  $lsqau->setSipusername($qauser_sipusername);
	  if(strlen($lsqau->getSippassword()) == 0)
	  	$lsqau->setSippassword($qauser_sippassword);
	  
	  $qau_jbuser = $lsqau->getJbUser();
	  if(!$qau_jbuser)
	  {
		$qau_jbuser = new JbUser();  
	  }
	  $qau_jbuser->setType('qauser');
	  $qau_jbuser->setUsername($qa_username);
	  if($qa_password != '')
	  	$qau_jbuser->setPassword(md5($qa_password));
	  $qau_jbuser->save();
	  
	  /* auto assign group */
	  $this->dispatch_jabber_user_to_groups($qau_jbuser);
	  
	  
	  $lsqau->setJbuserFk($qau_jbuser->getDbid());
	  $lsqau->save();
	  
	  $cu->setConfLivestatviewerFk($lstatu->getDbid());
	  $cu->setConfQauserFk($lsqau->getDbid());
	  
	  $cu->save();
	  
	  $lsqau->setUserFk($cu->getDbid());
	  $lsqau->save();
	  
	  //fix profile related groups 
	  //delete all previous group
	  Doctrine_Query::create()
		->delete('sfGuardUserGroup sfgug')
		->where('sfgug.user_id = ?', $sfu->getId())
		->execute();
			  
	  $sfgroupname = '';
	  $cfp = $cu->getConfUserProfile();
	  if($cfp)
	  {
		$cfpg = $cfp->getsfGuardGroup();
		if($cfpg)
			$sfgroupname = $cfpg->getName();
	  }
	  
	  
	  if($sfgroupname != '')
	  {
		  if(!$sfu->hasGroup($sfgroupname))
		  {
			  $sfu->addGroupByName($sfgroupname);
		  }
	  }
	  
	  //add this user also in the specific USERTYPE_GROUP_ADMINPANELUSER
	  if(!$sfu->hasGroup('USERTYPE_GROUP_ADMINPANELUSER'))
	  {
		  $sfu->addGroupByName('USERTYPE_GROUP_ADMINPANELUSER');
	  }
	  
	  
      if($qauserisnew)
	  {
		/* *********************** */
		/* send to foniva server */
		/* *********************** */
		fonivaFilter::foniva_send_toserver("MSG_QAUSER_ADDED", 
											"qauserid", $lsqau->getDbid());
	  }
	  
      $this->redirect('ressource/managers');
    }
  }
  
  public function executeManagerassignresource(sfWebRequest $request)
  {
	$this->forward404Unless($conf_user = Doctrine::getTable('ConfUser')->find($request->getParameter('dbid')), sprintf('Object conf_user does not exist (%s).', $request->getParameter('dbid')));
	$this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_user->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	
	$this->conf_user = $conf_user;
	
	/* -- -- 			*/
	/* assigned groups 	*/
	$this->agentgroups = Doctrine_Query::create()
					->select('g.dbid, g.name')
					->from('ConfGroup g');
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->agentgroups = $this->agentgroups->where('g.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
	$this->agentgroups = $this->agentgroups->orderBy('g.name')->execute();
	
	
	$this->groups_list = array();	
	foreach($this->agentgroups as $s)
		$this->groups_list[$s->getDbid()] = $s;
				
		
	$this->assigned_groups = array();
	foreach($this->conf_user->getConfUserAssignedgroup() as $as)
		$this->assigned_groups[$as->getAgentgroupFk()] = 1;
	
	/* -- -- 			*/
	/* assigned inbounds 	*/
	$this->inbounds = Doctrine_Query::create()
					->select('i.dbid, i.inbound_name')
					->from('ConfInbound i');
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->inbounds = $this->inbounds->where('i.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
	$this->inbounds = $this->inbounds->orderBy('i.inbound_name')->execute();
	
	
	$this->inbounds_list = array();	
	foreach($this->inbounds as $i)
		$this->inbounds_list[$i->getDbid()] = $i;
				
		
	$this->assigned_inbounds = array();
	foreach($this->conf_user->getConfUserAssignedinbound() as $ai)
		$this->assigned_inbounds[$ai->getInboundFk()] = 1;
	
	/* -- -- 			*/
	/* assigned outbounds 	*/
	$this->outbounds = Doctrine_Query::create()
					->select('c.dbid, c.campaign_name')
					->from('ConfCampaign c');
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->outbounds = $this->outbounds->where('c.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
	$this->outbounds = $this->outbounds->orderBy('c.campaign_name')->execute();
	
	
	$this->outbounds_list = array();	
	foreach($this->outbounds as $o)
		$this->outbounds_list[$o->getDbid()] = $o;
				
		
	$this->assigned_outbounds = array();
	foreach($this->conf_user->getConfUserAssignedoutbound() as $ao)
		$this->assigned_outbounds[$ao->getOutboundFk()] = 1;
	
	/* -- -- 			*/
	/* assigned queues 	*/
	$this->queues = Doctrine_Query::create()
					->select('q.dbid, q.name')
					->from('ConfQueue q');
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->queues = $this->queues->where('q.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
	$this->queues = $this->queues->orderBy('q.name')->execute();
	
	
	$this->queues_list = array();	
	foreach($this->queues as $q)
		$this->queues_list[$q->getDbid()] = $q;
				
		
	$this->assigned_queues = array();
	foreach($this->conf_user->getConfUserAssignedqueue() as $aq)
		$this->assigned_queues[$aq->getQueueFk()] = 1;
	
	
	
	/* js headers */
	$this->getResponse()->addJavascript('ui.multiselect.js', 'last');
	$this->getResponse()->addJavascript('plugins/scrollTo/jquery.scrollTo-min.js', 'last');
	$this->getResponse()->addJavascript('plugins/localisation/jquery.localisation-min.js', 'last');
	$this->getResponse()->addJavascript('jquery.tmpl.1.1.1.js', 'last');
	$this->getResponse()->addStylesheet('ui.multiselect.css', 'last');
	$this->getResponse()->addStylesheet('agentselecteditor.css', 'last');
  }
  
  
  public function executeManagerassignresourceupdate(sfWebRequest $request)
  {
 	$this->forward404Unless($conf_user = Doctrine::getTable('ConfUser')->find($request->getParameter('dbid')), sprintf('Object conf_user does not exist (%s).', $request->getParameter('dbid')));	
	$this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_user->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	
	Doctrine_Query::create()
		->delete('ConfUserAssignedGroup cs')
		->where('cs.user_fk = ?', $request->getParameter('dbid'))
		->execute();
		
	Doctrine_Query::create()
		->delete('ConfUserAssignedInbound cq')
		->where('cq.user_fk = ?', $request->getParameter('dbid'))
		->execute();
		
	Doctrine_Query::create()
		->delete('ConfUserAssignedOutbound cq')
		->where('cq.user_fk = ?', $request->getParameter('dbid'))
		->execute();
		
	Doctrine_Query::create()
		->delete('ConfUserAssignedQueue cq')
		->where('cq.user_fk = ?', $request->getParameter('dbid'))
		->execute();
	
	/* assigned groups */
	$assigned_groups = $request->getParameter('assigned_groups');
	for($i = 0; $i < sizeof($assigned_groups); $i++)
	{
		$as = $assigned_groups[$i];
		
		$asc = new ConfUserAssignedGroup();
		$asc->setAgentgroupFk($as);
		$asc->setUserFk($request->getParameter('dbid'));
		$asc->replace();
	}
	
	/* assigned inbounds */
	$assigned_inbounds = $request->getParameter('assigned_inbounds');
	for($i = 0; $i < sizeof($assigned_inbounds); $i++)
	{
		$as = $assigned_inbounds[$i];
		
		$asc = new ConfUserAssignedInbound();
		$asc->setInboundFk($as);
		$asc->setUserFk($request->getParameter('dbid'));
		$asc->replace();
	}
	
	/* assigned outbounds */
	$assigned_outbounds = $request->getParameter('assigned_outbounds');
	for($i = 0; $i < sizeof($assigned_outbounds); $i++)
	{
		$as = $assigned_outbounds[$i];
		
		$asc = new ConfUserAssignedOutbound();
		$asc->setOutboundFk($as);
		$asc->setUserFk($request->getParameter('dbid'));
		$asc->replace();
	}
	
	/* assigned queues */
	$assigned_queues = $request->getParameter('assigned_queues');
	for($i = 0; $i < sizeof($assigned_queues); $i++)
	{
		$as = $assigned_queues[$i];
		
		$asc = new ConfUserAssignedQueue();
		$asc->setQueueFk($as);
		$asc->setUserFk($request->getParameter('dbid'));
		$asc->replace();
	}
	
	$conf_user->setManageAllGroups($request->getParameter('manage_all_groups'));
	$conf_user->setManageAllInbounds($request->getParameter('manage_all_inbounds'));
	$conf_user->setManageAllOutbounds($request->getParameter('manage_all_outbounds'));
	$conf_user->setManageAllQueues($request->getParameter('manage_all_queues'));
	$conf_user->save();
	//todo: send message to server so livestats viewer can be updated 
	//maybe this agent is connected ... send foniva message
	//if(....... if-$conf_user...is..livestatviewer...conncted == 'yes')
	//{
		/* *********************** */
	   /* send to foniva server */
	   /* *********************** */
	//	fonivaFilter::foniva_send_toserver("MSG_USER_UPDATED", 
	//										 	"userid", $conf_user->getDbid());
	//}	
	
	$this->redirect('ressource/managers');
  }
  
   

  
  /*******************
  MANAGER PROFILE
  ********************/  
  public function executeManagerprofiles(sfWebRequest $request)
  {	
	$this->pager = new sfDoctrinePager('ConfUserProfile', sfConfig::get('app_display_nbrecordperpage'));
	$this->pager->getQuery()->from('ConfUserProfile u')
					->orderBy('u.name');
	if(!fonivaFilter::isCurrentUserSuperTenant())
	{
		$this->pager->getQuery()->where('u.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
		$this->pager->getQuery()->orWhere('(u.builtin = "yes" and u.dbid != "1") ');
	}
	
	$this->setcurrentmodule_defaultpage();
	$this->pager->setPage($this->getcurrentmodule_defaultpage()); //$this->getRequestParameter('page',1));
	$this->pager->init();
	$this->managerprofiles = $this->pager->getResults();

  }
  
  public function executeManagerprofilenew(sfWebRequest $request)
  {
    $this->form = new ConfUserProfileForm();
	$this->form->embedForm('securityloginform', (new SecurityloginForm()));
  }

  public function executeManagerprofilecreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));
    $this->form = new ConfUserProfileForm();
	$this->form->embedForm('securityloginform', (new SecurityloginForm()));
    $this->processManagerprofileForm($request, $this->form);
    $this->setTemplate('managerprofilenew');
  }

  public function executeManagerprofileedit(sfWebRequest $request)
  {
    $this->forward404Unless($conf_profile = Doctrine::getTable('ConfUserProfile')->find($request->getParameter('dbid')), sprintf('Object conf_user_profile does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || ($conf_profile->getBuiltin() == 'yes') || ($conf_profile->getTenantFk() == fonivaFilter::getCurrentUserTenantId())); 
	$this->form = new ConfUserProfileForm($conf_profile);
	$this->form->embedForm('securityloginform', (new SecurityloginForm(array('origin_ips' => $conf_profile->getSecurityOriginIps()))));
  }

  public function executeManagerprofileupdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($conf_profile = Doctrine::getTable('ConfUserProfile')->find($request->getParameter('dbid')), sprintf('Object conf_user_profile does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_profile->getTenantFk() == fonivaFilter::getCurrentUserTenantId()); 
	$this->form = new ConfUserProfileForm($conf_profile);
	$this->form->embedForm('securityloginform', (new SecurityloginForm(array('origin_ips' => $conf_profile->getSecurityOriginIps()))));
    $this->processManagerprofileForm($request, $this->form);
    $this->setTemplate('managerprofileedit');
  }

  public function executeManagerprofiledelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();
    $this->forward404Unless($conf_profile = Doctrine::getTable('ConfUserProfile')->find($request->getParameter('dbid')), sprintf('Object conf_user_profile does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_profile->getTenantFk() == fonivaFilter::getCurrentUserTenantId()); 
	$profilename = $conf_profile->getName();
	$conf_profile->delete();
	
	Doctrine_Query::create()
	  ->delete()
	  ->from('sfGuardGroup g')
	  ->where('g.name = ?', $profilename)
	  ->execute();
		  
    $this->redirect('ressource/managerprofiles');
  }

  
  
  protected function reset_group_permission($sfgroup, $form_arr, $permission)
  {
	  
	if(!$sfgroup)
		return;
		
	$sfpermision = Doctrine::getTable('sfGuardPermission')->findOneByName($permission);
	if(!$sfpermision)
		return;
	
	//$grpperms = $sfgroup->getPermissions();
	
	$doset = isset($form_arr[$permission]);
	if($doset)
	{
		$grpperm = new sfGuardGroupPermission();
		$grpperm->setGroupId($sfgroup->getId());
		$grpperm->setPermissionId($sfpermision->getId());
		$grpperm->replace();	
	}
	else
	{
		$grpperm = Doctrine::getTable('sfGuardGroupPermission')->find(array($sfgroup->getId(), $sfpermision->getId()));
		if($grpperm)
			$grpperm->delete();
	}
	  
  }
  
  protected function processManagerprofileForm(sfWebRequest $request, sfForm $form)
  {
	$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $conf_profile = $form->getObject();
	  
	  $conf_profile->setName($form->getValue('name'));
	  $conf_profile->setLastmodifiedBy($this->getUser()->getUsername());

	  if($conf_profile->isNew())
	  {
		  $grp = new sfGuardGroup();
		  $grp->setName('CONFPROFILE_GROUP_'.$conf_profile->getName());
		  $grp->save();
		  
		  $conf_profile->setSfGroupFk($grp->getId());
	  }
	  
	  
	  if(fonivaFilter::isCurrentUserSuperTenant())
	    $conf_profile->setTenantFk($form->getValue('tenant_fk'));
	  else
	    $conf_profile->setTenantFk(fonivaFilter::getCurrentUserTenantId());
		
	  $conf_profile->save();
	  
	  $grp = $conf_profile->getsfGuardGroup();
	  $permissionsform = $request->getParameter('permission');
	  
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_AGENTS");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_AGENTS_ADD");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_AGENTS_UPDATE");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_AGENTS_DELETE");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_AGENTGROUPS");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_AGENTGROUPS_ADD");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_AGENTGROUPS_UPDATE");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_AGENTGROUPS_DELETE");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_DIDS");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_DIDS_ADD");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_DIDS_UPDATE");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_DIDS_DELETE");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_QUEUES");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_QUEUES_ADD");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_QUEUES_UPDATE");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_QUEUES_DELETE");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_PBXS");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_PBXS_ADD");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_PBXS_UPDATE");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_PBXS_DELETE");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_STORAGESERVERS");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_STORAGESERVERS_ADD");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_STORAGESERVERS_UPDATE");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_STORAGESERVERS_DELETE");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_AGENTSKILLS");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_AGENTSKILLS_ADD");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_AGENTSKILLS_UPDATE");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_AGENTSKILLS_DELETE");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_USERS");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_USERS_ADD");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_USERS_UPDATE");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_USERS_DELETE");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_LOGDBS");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_LOGDBS_ADD");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_LOGDBS_UPDATE");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_LOGDBS_DELETE");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_CUSTOMAPPS");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_CUSTOMAPPS_ADD");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_CUSTOMAPPS_UPDATE");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_CUSTOMAPPS_DELETE");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_CALLDISPOSITIONS");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_CALLDISPOSITIONS_ADD");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_CALLDISPOSITIONS_UPDATE");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_CALLDISPOSITIONS_DELETE");
	  $this->reset_group_permission($grp, $permissionsform, "CAMPAIGNS");
	  $this->reset_group_permission($grp, $permissionsform, "CAMPAIGNS_INBOUNDS");
	  $this->reset_group_permission($grp, $permissionsform, "CAMPAIGNS_INBOUNDS_ADD");
	  $this->reset_group_permission($grp, $permissionsform, "CAMPAIGNS_INBOUNDS_UPDATE");
	  $this->reset_group_permission($grp, $permissionsform, "CAMPAIGNS_INBOUNDS_DELETE");
	  $this->reset_group_permission($grp, $permissionsform, "CAMPAIGNS_OUTBOUNDS");
	  $this->reset_group_permission($grp, $permissionsform, "CAMPAIGNS_OUTBOUNDS_ADD");
	  $this->reset_group_permission($grp, $permissionsform, "CAMPAIGNS_OUTBOUNDS_UPDATE");
	  $this->reset_group_permission($grp, $permissionsform, "CAMPAIGNS_OUTBOUNDS_DELETE");
	  $this->reset_group_permission($grp, $permissionsform, "CAMPAIGNS_CALLFLOWS");
	  $this->reset_group_permission($grp, $permissionsform, "CAMPAIGNS_CALLFLOWS_ADD");
	  $this->reset_group_permission($grp, $permissionsform, "CAMPAIGNS_CALLFLOWS_UPDATE");
	  $this->reset_group_permission($grp, $permissionsform, "CAMPAIGNS_CALLFLOWS_DELETE");
	  $this->reset_group_permission($grp, $permissionsform, "LIVESTATS");
	  $this->reset_group_permission($grp, $permissionsform, "LIVESTATS_AGENTS");
	  $this->reset_group_permission($grp, $permissionsform, "LIVESTATS_INBOUNDS");
	  $this->reset_group_permission($grp, $permissionsform, "LIVESTATS_OUTBOUNDS");
	  $this->reset_group_permission($grp, $permissionsform, "LIVESTATS_QUEUES");
	  $this->reset_group_permission($grp, $permissionsform, "LIVESTATS_CALLS");
	  $this->reset_group_permission($grp, $permissionsform, "REPORTS");
	  $this->reset_group_permission($grp, $permissionsform, "REPORTS_AGENTS");
	  $this->reset_group_permission($grp, $permissionsform, "REPORTS_INBOUNDS");
	  $this->reset_group_permission($grp, $permissionsform, "REPORTS_OUTBOUNDS");
	  $this->reset_group_permission($grp, $permissionsform, "REPORTS_QUEUES");
	  $this->reset_group_permission($grp, $permissionsform, "REPORTS_VIEW_CUSTOMERINFO");
	  $this->reset_group_permission($grp, $permissionsform, "SETTINGS");
	  $this->reset_group_permission($grp, $permissionsform, "SETTINGS_AGENTS");
	  $this->reset_group_permission($grp, $permissionsform, "SETTINGS_SERVER");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_PROFILES");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_PROFILES_ADD");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_PROFILES_UPDATE");
	  $this->reset_group_permission($grp, $permissionsform, "RESOURCES_PROFILES_DELETE");
	  $this->reset_group_permission($grp, $permissionsform, "FINANCE_AGENTWAGE");
	  $this->reset_group_permission($grp, $permissionsform, "FINANCE_ACTIVITYCOST");
	  $this->reset_group_permission($grp, $permissionsform, "FINANCE_COSTREPORTS");
	  
	  
	  $this->reset_group_permission($grp, $permissionsform, "WFM");
	  $this->reset_group_permission($grp, $permissionsform, "WFM_ACTIVITIES");
	  $this->reset_group_permission($grp, $permissionsform, "WFM_ACTIVITIES_ADD");
	  $this->reset_group_permission($grp, $permissionsform, "WFM_ACTIVITIES_UPDATE");
	  $this->reset_group_permission($grp, $permissionsform, "WFM_ACTIVITIES_DELETE");
	  $this->reset_group_permission($grp, $permissionsform, "WFM_SHIFTS");
	  $this->reset_group_permission($grp, $permissionsform, "WFM_SHIFTS_ADD");
	  $this->reset_group_permission($grp, $permissionsform, "WFM_SHIFTS_UPDATE");
	  $this->reset_group_permission($grp, $permissionsform, "WFM_SHIFTS_DELETE");
	  $this->reset_group_permission($grp, $permissionsform, "WFM_EVALUATIONFORMS");
	  $this->reset_group_permission($grp, $permissionsform, "WFM_EVALUATIONFORMS_ADD");
	  $this->reset_group_permission($grp, $permissionsform, "WFM_EVALUATIONFORMS_UPDATE");
	  $this->reset_group_permission($grp, $permissionsform, "WFM_EVALUATIONFORMS_DELETE");
	  $this->reset_group_permission($grp, $permissionsform, "WFM_AGENTSCHEDULING");
	  $this->reset_group_permission($grp, $permissionsform, "WFM_FORECASTING");
	  
	  $this->reset_group_permission($grp, $permissionsform, "API_CLIENT");
	  
	  //security ips
	  $agtsecurity = $form['securityloginform']->getValue();	  
	  $ssip = $grp->getSfGuardGroupAllowedoriginips();
	  if(sizeof($ssip) <= 0)
	  	$ssip = new SfGuardGroupAllowedoriginips();
	  else
	  	$ssip = $ssip[0];
	  $ssip->setGroupId($grp->id);
	  $ssip->setOriginIps($agtsecurity['origin_ips']); 
	  $ssip->save();
      
	  $this->redirect('ressource/managerprofiles');
    }
  }
  
  
  
  /*******************
  CUSTOM APPS
  ********************/  
  public function executeCustomapplications(sfWebRequest $request)
  {	
	$this->pager = new sfDoctrinePager('ConfCustomApplication', sfConfig::get('app_display_nbrecordperpage'));
	$this->pager->getQuery()->from('ConfCustomApplication u')
							->orderBy('u.name');
	if(!fonivaFilter::isCurrentUserSuperTenant())
	{
		$this->pager->getQuery()->where('u.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
	}
	
	$this->searchedCustomapplication = $this->getRequestParameter('searchedCustomapplication');
	$this->searchedCustomapplication = trim(strtolower($this->searchedCustomapplication));	

	if(!empty($this->searchedCustomapplication))
	{
		$this->pager->getQuery()->where('lower(u.name) LIKE ? OR lower(u.name) LIKE ? OR lower(u.name) LIKE ?', array($this->searchedCustomapplication, '%'.$this->searchedCustomapplication.'%', '%'.$this->searchedCustomapplication.'%'));
		$defaultpage = 1;
	}
	
	$this->setcurrentmodule_defaultpage();
	$this->pager->setPage($this->getcurrentmodule_defaultpage()); //$this->getRequestParameter('page',1));
	$this->pager->init();
	$this->customapplications = $this->pager->getResults();

  }
  
  public function executeCustomapplicationnew(sfWebRequest $request)
  {
    $this->form = new ConfCustomApplicationForm();
  }

  public function executeCustomapplicationcreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));
    $this->form = new ConfCustomApplicationForm();
    $this->processCustomapplicationForm($request, $this->form);
    $this->setTemplate('customapplicationnew');
  }

  public function executeCustomapplicationedit(sfWebRequest $request)
  {
    $this->forward404Unless($conf_custom_application = Doctrine::getTable('ConfCustomApplication')->find($request->getParameter('dbid')), sprintf('Object conf_custom_application does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_custom_application->getTenantFk() == fonivaFilter::getCurrentUserTenantId()); 
	$this->form = new ConfCustomApplicationForm($conf_custom_application);
  }

  public function executeCustomapplicationshow(sfWebRequest $request)
  {
    $this->forward404Unless($this->custom_application = Doctrine::getTable('ConfCustomApplication')->find($request->getParameter('dbid')), sprintf('Object conf_custom_application does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $this->custom_application->getTenantFk() == fonivaFilter::getCurrentUserTenantId()); 
	
  }
  
  

  public function executeCustomapplicationupdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($conf_custom_application = Doctrine::getTable('ConfCustomapplication')->find($request->getParameter('dbid')), sprintf('Object conf_custom_application does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_custom_application->getTenantFk() == fonivaFilter::getCurrentUserTenantId()); 
	$this->form = new ConfCustomApplicationForm($conf_custom_application);
    $this->processCustomapplicationForm($request, $this->form);
    $this->setTemplate('customapplicationedit');
  }

  public function executeCustomapplicationdelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();
    $this->forward404Unless($conf_custom_application = Doctrine::getTable('ConfCustomApplication')->find($request->getParameter('dbid')), sprintf('Object conf_custom_application does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_custom_application->getTenantFk() == fonivaFilter::getCurrentUserTenantId()); 
	$conf_custom_application->delete();
		  
    $this->redirect('ressource/customapplications');
  }
  
  protected function processCustomapplicationForm(sfWebRequest $request, sfForm $form)
  {
	$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $conf_custom_application = $form->getObject();
	  
	  if(fonivaFilter::isCurrentUserSuperTenant())
	    $conf_custom_application->setTenantFk($form->getValue('tenant_fk'));
	  else
	    $conf_custom_application->setTenantFk(fonivaFilter::getCurrentUserTenantId());
	  $conf_custom_application->setName($form->getValue('name'));
	  $conf_custom_application->setDescription($form->getValue('description'));
	  $conf_custom_application->setUrl($form->getValue('url'));
	  $conf_custom_application->save();  
      
	  $this->redirect('ressource/customapplications');
    }
  }
  
  
  
  /*******************
  CALL DISPOSITION
  ********************/  
  public function executeCalldispositions(sfWebRequest $request)
  {	
	$this->pager = new sfDoctrinePager('ConfCallDisposition', sfConfig::get('app_display_nbrecordperpage'));
	$this->pager->getQuery()->from('ConfCallDisposition u')
							->orderBy('u.name');
	if(!fonivaFilter::isCurrentUserSuperTenant())
	{
		$this->pager->getQuery()->where('u.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
	}
	
	$this->searchedCalldisposition = $this->getRequestParameter('searchedCalldisposition');
	$this->searchedCalldisposition = trim(strtolower($this->searchedCalldisposition));	

	if(!empty($this->searchedCalldisposition))
	{
		$this->pager->getQuery()->where('lower(u.name) LIKE ? OR lower(u.name) LIKE ? OR lower(u.name) LIKE ?', array($this->searchedCalldisposition, '%'.$this->searchedCalldisposition.'%', '%'.$this->searchedCalldisposition.'%'));
		$defaultpage = 1;
	}
	
	$this->setcurrentmodule_defaultpage();
	$this->pager->setPage($this->getcurrentmodule_defaultpage()); //$this->getRequestParameter('page',1));
	$this->pager->init();
	$this->calldispositions = $this->pager->getResults();

  }
  
  public function executeCalldispositionnew(sfWebRequest $request)
  {
    $this->form = new ConfCallDispositionForm();
  }

  public function executeCalldispositioncreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));
    $this->form = new ConfCallDispositionForm();
    $this->processCalldispositionForm($request, $this->form);
    $this->setTemplate('calldispositionnew');
  }

  public function executeCalldispositionedit(sfWebRequest $request)
  {
    $this->forward404Unless($conf_call_disposition = Doctrine::getTable('ConfCallDisposition')->find($request->getParameter('dbid')), sprintf('Object conf_call_disposition does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_call_disposition->getTenantFk() == fonivaFilter::getCurrentUserTenantId()); 
	$this->form = new ConfCallDispositionForm($conf_call_disposition);
  }

  public function executeCalldispositionupdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($conf_call_disposition = Doctrine::getTable('ConfCallDisposition')->find($request->getParameter('dbid')), sprintf('Object conf_call_disposition does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_call_disposition->getTenantFk() == fonivaFilter::getCurrentUserTenantId()); 
	$this->form = new ConfCallDispositionForm($conf_call_disposition);
    $this->processCalldispositionForm($request, $this->form);
    $this->setTemplate('calldispositionedit');
  }

  public function executeCalldispositiondelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();
    $this->forward404Unless($conf_call_disposition = Doctrine::getTable('ConfCallDisposition')->find($request->getParameter('dbid')), sprintf('Object conf_call_disposition does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_custom_application->getTenantFk() == fonivaFilter::getCurrentUserTenantId()); 
	$conf_call_disposition->delete();
		  
    $this->redirect('ressource/calldispositions');
  }
  
  protected function processCalldispositionForm(sfWebRequest $request, sfForm $form)
  {
	$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $conf_call_disposition = $form->getObject();
	  
	  if(fonivaFilter::isCurrentUserSuperTenant())
	    $conf_call_disposition->setTenantFk($form->getValue('tenant_fk'));
	  else
	    $conf_call_disposition->setTenantFk(fonivaFilter::getCurrentUserTenantId());
	  $conf_call_disposition->setName($form->getValue('name'));
	  $conf_call_disposition->setDescription($form->getValue('description'));
	  $conf_call_disposition->save();
	  
	  
	  //if call disposition is used in a queue, reload it
	  
	  foreach($conf_call_disposition->getConfQueueCalldisposition() as $cqcd)
	  {
		fonivaFilter::foniva_send_toserver("MSG_QUEUE_UPDATED",
											 	"queueid", $cqcd->getQueueFk());  
	  }
	  
      
	  $this->redirect('ressource/calldispositions');
    }
  }
  
  
  
  
  
  /********* ***********/
  /****  QUEUES ********/
  /********* ***********/
  
  
  public function executeQueues(sfWebRequest $request)
  {					  
  	$this->searchedQueue = $this->getRequestParameter('searchedQueue');
	$this->searchedQueue = trim(strtolower($this->searchedQueue));
  	
    $this->pager = new sfDoctrinePager('ConfQueue', sfConfig::get('app_display_nbrecordperpage'));
	$this->pager->getQuery()->from('ConfQueue q')
							->orderBy('q.name');
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->pager->getQuery()->andWhere('q.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());

	$defaultpage = $this->getcurrentmodule_defaultpage();
	if(!empty($this->searchedQueue))
	{
		$this->pager->getQuery()->where('lower(q.name) LIKE ? OR lower(q.strategy) LIKE ?', array('%'.$this->searchedQueue.'%', '%'.$this->searchedQueue.'%'));	
		$defaultpage = 1;
	}
		
	if(!fonivaFilter::canCurrentUserManageAllQueues())
	{
		$this->pager->getQuery()->leftJoin('q.ConfUserAssignedqueue a')
								->andWhere('a.user_fk = ?', fonivaFilter::getCurrentUser()->getDbid());
	}
		
	$this->setcurrentmodule_defaultpage();
	$this->pager->setPage($defaultpage); //$this->getRequestParameter('page',1));
	$this->pager->init();
	$this->queues = $this->pager->getResults();
  }
  
  public function executeQueuenew(sfWebRequest $request)
  {
	$conf_queue = new ConfQueue();
    $this->form = new ConfQueueForm($conf_queue);
	$this->form->embedForm('infovoicerecordingpolicy', (new ConfVoicerecordingPolicyForm($conf_queue->getConfVoicerecordingPolicy())));
	
	$this->calldispositions = Doctrine_Query::create()
					->select('c.dbid, c.name')
					->from('ConfCallDisposition c')
					->orderBy('c.name');	
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->calldispositions = $this->calldispositions->andWhere('c.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
	$this->calldispositions = $this->calldispositions->execute();				
	
	$this->calldispositions_list = array();	
	foreach($this->calldispositions as $s)
		$this->calldispositions_list[$s->getDbid()] = $s;
		
	$this->assigned_calldispositions = array();
	foreach($conf_queue->ConfQueueCalldisposition as $as)
		$this->assigned_calldispositions[$as->getDispositionFk()] = 1;
		
	/* js headers */
	$this->getResponse()->addJavascript('dropdownchecklist/ui.dropdownchecklist.js', 'last');
	$this->getResponse()->addStylesheet('dropdownchecklist/ui.dropdownchecklist.themeroller.css', 'last');
	
	$this->getResponse()->addJavascript('editagentselect_expression.js', 'last');
	
	
	$this->getResponse()->addJavascript('ui.multiselect.js', 'last');
	$this->getResponse()->addJavascript('plugins/scrollTo/jquery.scrollTo-min.js', 'last');
	$this->getResponse()->addJavascript('plugins/localisation/jquery.localisation-min.js', 'last');
	$this->getResponse()->addJavascript('jquery.tmpl.1.1.1.js', 'last');
	$this->getResponse()->addStylesheet('ui.multiselect.css', 'last');
  }

  public function executeQueuecreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));
	$conf_queue = new ConfQueue();
    $this->form = new ConfQueueForm($conf_queue);
	$this->form->embedForm('infovoicerecordingpolicy', (new ConfVoicerecordingPolicyForm($conf_queue->getConfVoicerecordingPolicy())));
    $this->processQueueForm($request, $this->form);
    $this->setTemplate('queuenew');
	
	
	$this->calldispositions = Doctrine_Query::create()
					->select('c.dbid, c.name')
					->from('ConfCallDisposition c')
					->orderBy('c.name');	
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->calldispositions = $this->calldispositions->andWhere('c.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
	$this->calldispositions = $this->calldispositions->execute();				
	
	$this->calldispositions_list = array();	
	foreach($this->calldispositions as $s)
		$this->calldispositions_list[$s->getDbid()] = $s;
		
	$assarr = $request->getParameter('assigned_calldisposition');
	$this->assigned_calldispositions = array();
	if($assarr != NULL)
	{
		foreach($assarr as $as)
			$this->assigned_calldispositions[$as] = 1;
	}
	
	/* js headers */
	
	$this->getResponse()->addJavascript('dropdownchecklist/ui.dropdownchecklist.js', 'last');
	$this->getResponse()->addStylesheet('dropdownchecklist/ui.dropdownchecklist.themeroller.css', 'last');
	
	$this->getResponse()->addJavascript('editagentselect_expression.js', 'last');
	
	$this->getResponse()->addJavascript('ui.multiselect.js', 'last');
	$this->getResponse()->addJavascript('plugins/scrollTo/jquery.scrollTo-min.js', 'last');
	$this->getResponse()->addJavascript('plugins/localisation/jquery.localisation-min.js', 'last');	
	$this->getResponse()->addJavascript('jquery.tmpl.1.1.1.js', 'last');
	$this->getResponse()->addStylesheet('ui.multiselect.css', 'last');
	$this->getResponse()->addJavascript('inlinemultiselect/jquery.inlinemultiselect-1.2.min.js', 'last');
  }

  public function executeQueueedit(sfWebRequest $request)
  {
    $this->forward404Unless($conf_queue = Doctrine::getTable('ConfQueue')->find($request->getParameter('dbid')), sprintf('Object conf_queue does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_queue->getTenantFk() == fonivaFilter::getCurrentUserTenantId()); 
	$this->form = new ConfQueueForm($conf_queue);
	$this->form->embedForm('infovoicerecordingpolicy', (new ConfVoicerecordingPolicyForm($conf_queue->getConfVoicerecordingPolicy())));
	
	
	$this->calldispositions = Doctrine_Query::create()
					->select('c.dbid, c.name')
					->from('ConfCallDisposition c')
					->orderBy('c.name');	
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->calldispositions = $this->calldispositions->andWhere('c.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
	$this->calldispositions = $this->calldispositions->execute();				
	
	$this->calldispositions_list = array();	
	foreach($this->calldispositions as $s)
		$this->calldispositions_list[$s->getDbid()] = $s;
		
	$this->assigned_calldispositions = array();
	foreach($conf_queue->ConfQueueCalldisposition as $as)
		$this->assigned_calldispositions[$as->getDispositionFk()] = 1;
	
	/* js headers */
	
	$this->getResponse()->addJavascript('editagentselect_expression.js', 'last');
	
	$this->getResponse()->addJavascript('ui.multiselect.js', 'last');
	$this->getResponse()->addJavascript('plugins/scrollTo/jquery.scrollTo-min.js', 'last');
	$this->getResponse()->addJavascript('plugins/localisation/jquery.localisation-min.js', 'last');
	$this->getResponse()->addJavascript('jquery.tmpl.1.1.1.js', 'last');
	$this->getResponse()->addStylesheet('ui.multiselect.css', 'last');
	$this->getResponse()->addJavascript('dropdownchecklist/ui.dropdownchecklist.js', 'last');
	$this->getResponse()->addStylesheet('dropdownchecklist/ui.dropdownchecklist.themeroller.css', 'last');
  }

  public function executeQueueupdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($conf_queue = Doctrine::getTable('ConfQueue')->find($request->getParameter('dbid')), sprintf('Object conf_queue does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_queue->getTenantFk() == fonivaFilter::getCurrentUserTenantId()); 
	$this->form = new ConfQueueForm($conf_queue);
	$this->form->embedForm('infovoicerecordingpolicy', (new ConfVoicerecordingPolicyForm($conf_queue->getConfVoicerecordingPolicy())));
    $this->processQueueForm($request, $this->form);
    $this->setTemplate('queueedit');
	
	$this->calldispositions = Doctrine_Query::create()
					->select('c.dbid, c.name')
					->from('ConfCallDisposition c')
					->orderBy('c.name');	
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->calldispositions = $this->calldispositions->andWhere('c.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
	$this->calldispositions = $this->calldispositions->execute();				
	
	$this->calldispositions_list = array();	
	foreach($this->calldispositions as $s)
		$this->calldispositions_list[$s->getDbid()] = $s;
		
	$assarr = $request->getParameter('assigned_calldisposition');
	$this->assigned_calldispositions = array();
	
	if($assarr != NULL)
	{
		foreach($assarr as $as)
			$this->assigned_calldispositions[$as] = 1;
	}
		
		
	/* js headers */
	$this->getResponse()->addJavascript('ui.multiselect.js', 'last');
	$this->getResponse()->addJavascript('plugins/scrollTo/jquery.scrollTo-min.js', 'last');
	$this->getResponse()->addJavascript('plugins/localisation/jquery.localisation-min.js', 'last');
	$this->getResponse()->addJavascript('jquery.tmpl.1.1.1.js', 'last');
	$this->getResponse()->addStylesheet('ui.multiselect.css', 'last');
	$this->getResponse()->addJavascript('inlinemultiselect/jquery.inlinemultiselect-1.2.min.js', 'last');
	
	$this->getResponse()->addJavascript('dropdownchecklist/ui.dropdownchecklist.js', 'last');
	$this->getResponse()->addStylesheet('dropdownchecklist/ui.dropdownchecklist.themeroller.css', 'last');
	
	$this->getResponse()->addJavascript('editagentselect_expression.js', 'last');
  }

  public function executeQueuedelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();
    $this->forward404Unless($conf_queue = Doctrine::getTable('ConfQueue')->find($request->getParameter('dbid')), sprintf('Object conf_queue does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_queue->getTenantFk() == fonivaFilter::getCurrentUserTenantId()); 
	$conf_queue->delete();

	if(($srp = $conf_queue->getConfVoicerecordingPolicy()))
		$srp->delete();

	 /* *********************** */
	   /* send to foniva server */
	   /* *********************** */
	fonivaFilter::foniva_send_toserver("MSG_QUEUE_DELETED", 
											 	"queueid", $conf_queue->getDbid());
    $this->redirect('ressource/queues');
  }

  protected function processQueueForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
	  $conf_queue = $form->getObject();
	  if(fonivaFilter::isCurrentUserSuperTenant())
	    $conf_queue->setTenantFk($form->getValue('tenant_fk'));
	  else
	    $conf_queue->setTenantFk(fonivaFilter::getCurrentUserTenantId());
	  $conf_queue->setName($form->getValue('name'));
	  $conf_queue->setLastmodifiedBy($this->getUser()->getUsername());
	  $conf_queue->setMoh($form->getValue('moh'));
	  $conf_queue->setAgentAnnounce($form->getValue('agent_announce'));
	  $conf_queue->setStrategy($form->getValue('strategy'));
	  $conf_queue->setCustomstrategyFk($form->getValue('customstrategy_fk') == '' ? NULL :  $form->getValue('customstrategy_fk'));
	  $conf_queue->setAgentautoanswer($form->getValue('agentautoanswer'));
	  $conf_queue->setServicelevel($form->getValue('servicelevel'));
	  $conf_queue->setRingtimeout($form->getValue('ringtimeout'));
	  $conf_queue->setTotalwaittime($form->getValue('totalwaittime'));
	  $conf_queue->setPriority($form->getValue('priority'));
	  $conf_queue->setWrapupmode($form->getValue('wrapupmode'));
	  $conf_queue->setWrapuptime($form->getValue('wrapuptime'));
	  $conf_queue->setAutoreadyAftercall($form->getValue('autoready_aftercall'));
	  $conf_queue->setActivityAftercallFk($form->getValue('activity_aftercall_fk') == '' ? NULL : $form->getValue('activity_aftercall_fk'));
	  $conf_queue->setMaxwaitingpeople($form->getValue('maxwaitingpeople'));
	  $conf_queue->setEnterifempty($form->getValue('enterifempty'));
	  $conf_queue->setUrl($form->getValue('url'));
	  $conf_queue->setOpenurlInnewtab($form->getValue('openurl_innewtab'));
	  $conf_queue->setDtmfToleave($form->getValue('dtmf_toleave'));
	  $conf_queue->setAgentselectExpression($form->getValue('agentselect_expression'));
	  $conf_queue->setCallbasedFilterExpression($form->getValue('callbased_filter_expression'));
	  $conf_queue->setMandatoryCalldispositions($form->getValue('mandatory_calldispositions'));
	  
	  $isnew = $conf_queue->isNew();

	  $srp = $conf_queue->getConfVoicerecordingPolicy();
	  if(!$srp)
		$srp = new ConfVoicerecordingPolicy();
	  $recpolicy = $form['infovoicerecordingpolicy']->getValue();
	  $srp->setNameformat($recpolicy['nameformat']);
	  $srp->setDorecord($recpolicy['dorecord']);
      //$srp->setOnduplicate($recpolicy['onduplicate']);
	  $srp->setCompression($recpolicy['compression']);
	  $srp->save();

      $conf_queue->setVoicerecordingpolicyFk($srp->getDbid());
	  
	  
	  /* announcement rules */
	  $announcementsarr = $request->getParameter('queueannouncement');
	  if(is_array($announcementsarr) && sizeof($announcementsarr) > 0)
	  {
		  $f_addedarr = isset($announcementsarr['added']) ? $announcementsarr['added'] : array();
		  $f_modifiedarr = isset($announcementsarr['modified']) ? $announcementsarr['modified'] : array();
		  $f_deletedarr = isset($announcementsarr['deleted']) ? $announcementsarr['deleted'] : array();
		  
		  foreach($f_addedarr as $felt)
		  {
			$fdbid 			= $felt['dbid'];
			$fannouncetype	= $felt['announcetype'];
			$fstart_after 		= $felt['start_after'];
			$fdorepeat 			= $felt['dorepeat'];
			$frepeat_frequency 	= $felt['repeat_frequency'];
			$fmax_repeat 		= $felt['max_repeat'];
			$fmessage_file 		= $felt['message_file'];
			$fqueue_position_limit 	= $felt['queue_position_limit'];
			$fhold_time_limit 		= $felt['hold_time_limit'];
			$factive 			= $felt['active'];
			
			$conf_announcement = new ConfQueueAnnouncement();
			$conf_announcement->setQueueFk($conf_queue->getDbid());
			$conf_announcement->setAnnouncetype($fannouncetype);
			$conf_announcement->setStartAfter($fstart_after);
			$conf_announcement->setDorepeat($fdorepeat);
			$conf_announcement->setRepeatFrequency($frepeat_frequency);
			$conf_announcement->setMaxRepeat($fmax_repeat);
			$conf_announcement->setMessageFile($fmessage_file);
			$conf_announcement->setQueuePositionLimit($fqueue_position_limit);
			$conf_announcement->setHoldTimeLimit($fhold_time_limit);
			$conf_announcement->setActive($factive);
			$conf_announcement->save();
		
		  }
		  
		  foreach($f_modifiedarr as $felt)
		  {
			$fdbid 			= $felt['dbid'];
			$fannouncetype	= $felt['announcetype'];
			$fstart_after 		= $felt['start_after'];
			$fdorepeat 			= $felt['dorepeat'];
			$frepeat_frequency 	= $felt['repeat_frequency'];
			$fmax_repeat 		= $felt['max_repeat'];
			$fmessage_file 		= $felt['message_file'];
			$fqueue_position_limit 	= $felt['queue_position_limit'];
			$fhold_time_limit 		= $felt['hold_time_limit'];
			$factive 			= $felt['active'];
			
			if($conf_announcement = Doctrine::getTable('ConfQueueAnnouncement')->find($fdbid))
			{
				$conf_announcement->setQueueFk($conf_queue->getDbid());
				$conf_announcement->setAnnouncetype($fannouncetype);
				$conf_announcement->setStartAfter($fstart_after);
				$conf_announcement->setDorepeat($fdorepeat);
				$conf_announcement->setRepeatFrequency($frepeat_frequency);
				$conf_announcement->setMaxRepeat($fmax_repeat);
				$conf_announcement->setMessageFile($fmessage_file);
				$conf_announcement->setQueuePositionLimit($fqueue_position_limit);
				$conf_announcement->setHoldTimeLimit($fhold_time_limit);
				$conf_announcement->setActive($factive);
				$conf_announcement->save();
			}
		  }
		  
		  
		  foreach($f_deletedarr as $felt)
	  	  {
			 $fdbid 			= $felt['dbid'];
			 if($conf_announcement = Doctrine::getTable('ConfQueueAnnouncement')->find($fdbid))
			 {
				 $conf_announcement->delete();
			 } 
		  }
	  }
	  
	  
	  $conf_queue->save();
	  
	  
	  
	  
	  /* call properties */
	  $callpropertiesarr = $request->getParameter('resourcecallproperty');
	  if(is_array($callpropertiesarr) && sizeof($callpropertiesarr) > 0)
	  {
		  $f_addedarr = isset($callpropertiesarr['added']) ? $callpropertiesarr['added'] : array();
		  $f_modifiedarr = isset($callpropertiesarr['modified']) ? $callpropertiesarr['modified'] : array();
		  $f_deletedarr = isset($callpropertiesarr['deleted']) ? $callpropertiesarr['deleted'] : array();
		  
		  foreach($f_addedarr as $felt)
		  {
			$fdbid 			= $felt['dbid'];
			$fpropertyname	= $felt['propertyname'];
			$fpropertyvalue = $felt['propertyvalue'];
			
			$callproperty = new ConfQueueCallproperty();
			$callproperty->setQueueFk($conf_queue->getDbid());
			$callproperty->setPropertyname($fpropertyname);
			$callproperty->setPropertyvalue($fpropertyvalue);
			$callproperty->save();
		  }
		  
		  foreach($f_modifiedarr as $felt)
		  {
			$fdbid 			= $felt['dbid'];
			$fpropertyname	= $felt['propertyname'];
			$fpropertyvalue = $felt['propertyvalue'];
			
			if($callproperty = Doctrine::getTable('ConfQueueCallproperty')->find($fdbid))
			{
				$callproperty->setQueueFk($conf_queue->getDbid());
				$callproperty->setPropertyname($fpropertyname);
				$callproperty->setPropertyvalue($fpropertyvalue);
				$callproperty->save();
			}
		  }
		  
		  
		  foreach($f_deletedarr as $felt)
	  	  {
			 $fdbid 			= $felt['dbid'];
			 if($callproperty = Doctrine::getTable('ConfQueueCallproperty')->find($fdbid))
			 {
				 $callproperty->delete();
			 } 
		  }
	  }
	  
	  
	  $assigned_calldispositionarr = $request->getParameter('assigned_calldisposition');
	  Doctrine_Query::create()
	  		->from('ConfQueueCalldisposition')
			->where('queue_fk = ?', $conf_queue->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 ConfQueueCalldisposition();
		  	$asscalldisp->setQueueFk($conf_queue->getDbid());
		  	$asscalldisp->setDispositionFk($dispositionid);
		  	$asscalldisp->save();
		  }
	  }
	  
	  
	  if($isnew)
	  {
		//auto assigned group to user
		$ag = new ConfUserAssignedQueue();
		$ag->setUserFk(fonivaFilter::getCurrentUser()->getDbid());  
		$ag->setQueueFk($conf_queue->getDbid());
		$ag->save();
	  }
	  
	 /* *********************** */
	   /* send to foniva server */
	   /* *********************** */
	  fonivaFilter::foniva_send_toserver(($isnew ? "MSG_QUEUE_ADDED" : "MSG_QUEUE_UPDATED"), 
											 	"queueid", $conf_queue->getDbid());
      $this->redirect('ressource/queues');
    }
  }
  
  
 
  /*********   ************************/
  /** QUEUE TRANSFER SPEED DIALS  *****/
  /*********   ************************/
  public function executeQueuetransferspeeddials(sfWebRequest $request)
  {	  
	$this->searchedQueuetransferspeeddial = $this->getRequestParameter('searchedQueuetransferspeeddial');
	$this->searchedQueuetransferspeeddial = trim(strtolower($this->searchedQueuetransferspeeddial));
	
	$this->forward404Unless($this->conf_queue = Doctrine::getTable('ConfQueue')->find($request->getParameter('queuedbid')), sprintf('Object conf_queue does not exist (%s).', $request->getParameter('dbid')));
    	
	$this->pager = new sfDoctrinePager('ConfAgentSpeeddial', sfConfig::get('app_display_nbrecordperpage'));
	$this->pager->getQuery()->select('sp.dbid as speeddialdbid, sp.name as speeddialname, sp.sendto as speedialsendto, sp.outboundnumber as speedialoutboundnumber, cqsp.queue_fk as speedialqueuedbid,
										ci.dbid as inbound_dbid, ci.inbound_name as inbound_name')
							->from('ConfQueueTransferSpeeddial cqsp')
							->leftJoin('cqsp.ConfAgentSpeeddial sp')
							->leftJoin('sp.ConfInbound ci ON ci.dbid = sp.inbound_fk')
							->orderBy('sp.name')
							->where('cqsp.queue_fk = ?', $this->conf_queue->dbid);
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->pager->getQuery()->andWhere('sp.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
		
	$defaultpage = $this->getcurrentmodule_defaultpage();
	if(!empty($this->searchedAgentGroupspeeddial))
	{
		$this->pager->getQuery()->andWhere('lower(sp.name) LIKE ?','%'.$this->searchedQueuetransferspeeddial.'%');
		$defaultpage = 1;
	}
	
	$this->setcurrentmodule_defaultpage();
	$this->pager->setPage($defaultpage); //$this->getRequestParameter('page',1));
	$this->pager->init();
	$this->speeddials = $this->pager->getResults();
  }
  
  public function executeQueuetransferspeeddialnew(sfWebRequest $request)
  {
	$this->forward404Unless($this->conf_queue = Doctrine::getTable('ConfQueue')->find($request->getParameter('queuedbid')), sprintf('Object conf_queue does not exist (%s).', $request->getParameter('dbid')));
    $speeddial = new ConfAgentSpeeddial();
    $this->form = new ConfAgentSpeeddialForm($speeddial);
	$this->form->setDefault('queuedbid', $this->conf_queue->dbid);
  }

  public function executeQueuetransferspeeddialcreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));
    $speeddial = new ConfAgentSpeeddial();
    $this->form = new ConfAgentSpeeddialForm($speeddial);
    $this->processQueuetransferspeeddialForm($request, $this->form);
	$this->form->setDefault('queuedbid', $this->conf_queue->dbid);
    $this->setTemplate('queuetransferspeeddialnew');
  }

  public function executeQueuetransferspeeddialedit(sfWebRequest $request)
  {
    $this->forward404Unless($speeddial = Doctrine::getTable('ConfAgentSpeeddial')->find($request->getParameter('dbid')), sprintf('Object conf_agent_speeddial does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $speeddial->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$conf_queuespeedial = $speeddial->ConfQueueTransferSpeeddial;
	if($conf_queuespeedial)
		$conf_queuespeedial = $conf_queuespeedial[0];
	else
		$this->forward404();
	$this->forward404Unless($this->conf_queue = Doctrine::getTable('ConfQueue')->find($conf_queuespeedial->queue_fk), sprintf('Object conf_queue does not exist (%s).', $conf_queuespeedial->queue_fk));
    $this->form = new ConfAgentSpeeddialForm($speeddial);
	$this->form->setDefault('queuedbid', $this->conf_queue->dbid);
  }

  public function executeQueuetransferspeeddialupdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($speeddial = Doctrine::getTable('ConfAgentSpeeddial')->find($request->getParameter('dbid')), sprintf('Object conf_agent_speeddial does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $speeddial->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$this->form = new ConfAgentSpeeddialForm($speeddial);
	$this->processQueuetransferspeeddialForm($request, $this->form);
    $this->setTemplate('queuetransferspeeddialedit');
  }

  public function executeQueuetransferspeeddialdelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();
    $this->forward404Unless($speeddial = Doctrine::getTable('ConfAgentSpeeddial')->find($request->getParameter('dbid')), sprintf('Object conf_agent_speeddial does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $speeddial->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$conf_queuespeedial = $speeddial->ConfQueueTransferSpeeddial;
	if($conf_queuespeedial)
		$conf_queuespeedial = $conf_queuespeedial[0];
	else
		$this->forward404();
	$this->forward404Unless($this->conf_queue = Doctrine::getTable('ConfQueue')->find($conf_queuespeedial->queue_fk), sprintf('Object conf_queue does not exist (%s).', $conf_queuespeedial->queue_fk));
    $speeddial->delete();
	
	
  
    /* *********************** */
    /* send to foniva server */
    /* *********************** */
    fonivaFilter::foniva_send_toserver("MSG_QUEUE_UPDATED", 
											"queueid", $this->conf_queue->getDbid());
											
    $this->redirect('ressource/queuetransferspeeddials?queuedbid='.$this->conf_queue->dbid);
  }

  protected function processQueuetransferspeeddialForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
	$this->forward404Unless($this->conf_queue = Doctrine::getTable('ConfQueue')->find($form->getValue('queuedbid')), sprintf('Object conf_queue does not exist (%s).', $form->getValue('queuedbid')));
	
	if ($form->isValid())
    {
	  $speeddial = $form->save();
	  
	  $queuedbid = $form->getValue('queuedbid');
	  Doctrine_Query::create()
	  		->from('ConfQueueTransferSpeeddial')
			->where('queue_fk = ? and speeddial_fk = ?', array($queuedbid, $speeddial->dbid))
			->delete()
			->execute();
	  $nn = new ConfQueueTransferSpeeddial();
	  $nn->setQueueFk($queuedbid);
	  $nn->setSpeeddialFk($speeddial->dbid);
	  $nn->save();
	  
      /* *********************** */
	   /* send to foniva server */
	   /* *********************** */
	  fonivaFilter::foniva_send_toserver("MSG_QUEUE_UPDATED", 
											 	"queueid", $this->conf_queue->getDbid());
      
	  $this->redirect('ressource/queuetransferspeeddials?queuedbid='.$queuedbid);
    }
  }
	
 
  
  /********* *******************/
  /****  QUEUE CUSTOM STRATEGY */
  /********* *******************/  
  public function executeQueuecustomstrategies(sfWebRequest $request)
  {
	$this->searchedQueueCustomstrategy = $this->getRequestParameter('searchedQueueCustomstrategy');
	$this->searchedQueueCustomstrategy = trim(strtolower($this->searchedQueueCustomstrategy));
	  
	$this->pager = new sfDoctrinePager('ConfQueueCustomstrategy', sfConfig::get('app_display_nbrecordperpage'));
	$this->pager->getQuery()->from('ConfQueueCustomstrategy cap')
							->orderBy('cap.name');
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->pager->getQuery()->where('cap.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
				
	$defaultpage = $this->getcurrentmodule_defaultpage();
	if(!empty($this->searchedQueueCustomstrategy))
	{
		$this->pager->getQuery()->where('lower(cap.name) LIKE ?','%'.$this->searchedQueueCustomstrategy.'%');	
		$defaultpage = 1;
	}
			
	$this->setcurrentmodule_defaultpage();
	$this->pager->setPage($defaultpage); //$this->getRequestParameter('page',1));
	$this->pager->init();
	$this->queuecustomstrategies = $this->pager->getResults();
  }
  
  public function executeQueuecustomstrategynew(sfWebRequest $request)
  {
    $this->form = new ConfQueueCustomstrategyForm();
	
	$this->skills = Doctrine_Query::create()
								->select('s.dbid, s.name')
								->from('ConfSkill s');								
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->skills->where('s.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());		
	$this->skills->orderBy('s.name');
	$this->skills = $this->skills->execute();
	
	$this->strategierules = array();
  }

  public function executeQueuecustomstrategycreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));
    $this->form = new ConfQueueCustomstrategyForm();
    $this->processQueueCustomstrategyForm($request, $this->form);
    $this->setTemplate('queuecustomstrategynew');
  }

  public function executeQueuecustomstrategyedit(sfWebRequest $request)
  {
    $this->forward404Unless($queue_custom_strategy = Doctrine::getTable('ConfQueueCustomstrategy')->find($request->getParameter('dbid')), sprintf('Object conf_queue_customstrategy does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $queue_custom_strategy->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$this->form = new ConfQueueCustomstrategyForm($queue_custom_strategy);
	
	$this->skills = Doctrine_Query::create()
								->select('s.dbid, s.name')
								->from('ConfSkill s');
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->skills->where('s.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());		
	$this->skills->orderBy('s.name');
	$this->skills = $this->skills->execute();
	
	$this->strategierules = array();
	foreach($queue_custom_strategy->getConfQueueCustomstrategyRule() as $r)
		$this->strategierules[$r->skill_fk] = $r;
  }

  public function executeQueuecustomstrategyupdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($queue_custom_strategy = Doctrine::getTable('ConfQueueCustomstrategy')->find($request->getParameter('dbid')), sprintf('Object conf_queue_customstrategy does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $queue_custom_strategy->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$this->form = new ConfQueueCustomstrategyForm($queue_custom_strategy);
    $this->processQueueCustomstrategyForm($request, $this->form);
    $this->setTemplate('queuecustomstrategyedit');
  }

  public function executeQueuecustomstrategydelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();
    $this->forward404Unless($queue_custom_strategy = Doctrine::getTable('ConfQueueCustomstrategy')->find($request->getParameter('dbid')), sprintf('Object conf_queue_customstrategy does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $queue_custom_strategy->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	
	$dbid = $queue_custom_strategy->getDbid();
	$queue_custom_strategy->delete();
	
	fonivaFilter::foniva_send_toserver("MSG_QUEUESTRATEGY_DELETED", 
											 	"strategyid", $dbid);
												
    $this->redirect('ressource/queuecustomstrategies');
  }

  protected function processQueuecustomstrategyForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $queue_custom_strategy = $form->getObject();
	  $queue_custom_strategy->setName($form->getValue('name'));
	  if(fonivaFilter::isCurrentUserSuperTenant())
	     $queue_custom_strategy->setTenantFk($form->getValue('tenant_fk'));
	  else
	     $queue_custom_strategy->setTenantFk(fonivaFilter::getCurrentUserTenantId());
	  
	  //$conf_skill->setLastmodifiedBy($this->getUser()->getUsername());
	  $isnew = $queue_custom_strategy->isNew();
	  $queue_custom_strategy->save();
	  
	  //save rules
	  Doctrine_Query::create()
		->from('ConfQueueCustomstrategyRule p')
		->where('p.strategy_fk = ?', $queue_custom_strategy->getDbid())
		->delete()
		->execute();
	  
	  
	  
	  foreach($request->getParameter('agentskills_selected') as $skillid => $skilldata)
	  {
		$skillselected = isset($skilldata['checked']) ? $skilldata['checked'] : 'false';
		$skillposition = $skilldata['priority'];
		$skilldirection = $skilldata['direction'];
		
		if($skillselected == 'true' || $skillselected == 'on')
		{			
			$pv = new ConfQueueCustomstrategyRule();
			$pv->setStrategyFk($queue_custom_strategy->getDbid());
			$pv->setSkillFk($skillid);
			$pv->setPosition($skillposition);
			$pv->setRuleorderdirection($skilldirection);
			$pv->save();
		}
	  }
	  
	  
	  
      /* *********************** */
	   /* send to foniva server */
	   /* *********************** */
	  fonivaFilter::foniva_send_toserver($isnew ? "MSG_QUEUESTRATEGY_ADDED" : "MSG_QUEUESTRATEGY_UPDATED", 
											 	"strategyid", $queue_custom_strategy->getDbid());
	  
      $this->redirect('ressource/queuecustomstrategies');
    }
  }
  
  /********* ***********/
  /****  AGENT SETTING */
  /********* ***********/
  public function executeAgentsetting(sfWebRequest $request)
  {
	//$this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($conf_agent = Doctrine::getTable('ConfAgent')->find($request->getParameter('dbid')), sprintf('Object conf_agent does not exist (%s).', $request->getParameter('dbid')));
	$this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_agent->getTenantFk() == fonivaFilter::getCurrentUserTenantId()); 

	$this->conf_agent = $conf_agent;
	$this->conf_agent_setting = $conf_agent->getConfAgentSetting();
	
	if(!$this->conf_agent_setting)
	{
		$this->conf_agent_setting = new ConfAgentSetting();
	}
	
	$this->form = new ConfAgentSettingForm($this->conf_agent_setting);
    
  }  
  
  public function executeAgentsettingcreate(sfWebRequest $request)
  {
	$this->forward404Unless($request->isMethod(sfRequest::POST));
    $this->form = new ConfAgentSettingForm();
	$this->forward404Unless($this->conf_agent = Doctrine::getTable('ConfAgent')->find($request->getParameter('agentdbid')), sprintf('Object conf_agent does not exist (%s).', $request->getParameter('agentdbid')));	    
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $this->conf_agent->getTenantFk() == fonivaFilter::getCurrentUserTenantId()); 
	$this->processAgentSettingForm($request, $this->form, $this->conf_agent);	
    $this->setTemplate('agentsetting');
  }
  
  public function executeAgentsettingupdate(sfWebRequest $request)
  {
	$this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));	
    $this->forward404Unless($this->conf_agent_setting = Doctrine::getTable('ConfAgentSetting')->find($request->getParameter('dbid')), sprintf('Object conf_agent_setting does not exist (%s).', $request->getParameter('dbid')));	
    $this->forward404Unless($this->conf_agent = Doctrine::getTable('ConfAgent')->find($request->getParameter('agentdbid')), sprintf('Object conf_agent does not exist (%s).', $request->getParameter('agentdbid')));	
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $this->conf_agent->getTenantFk() == fonivaFilter::getCurrentUserTenantId()); 
	$this->form = new ConfAgentSettingForm($this->conf_agent_setting);
    $this->processAgentSettingForm($request, $this->form, $this->conf_agent);
    $this->setTemplate('agentsetting');
  }  

  protected function processAgentSettingForm(sfWebRequest $request, sfForm $form, $conf_agent)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
	  $isnew = $form->getObject()->isNew();
      $conf_agent_setting = $form->save();	
	  
	  if($isnew)
	  {
		$conf_agent->setSettingFk($conf_agent_setting->getDbid());  
		$conf_agent->save();
	  }
	  
	  if($conf_agent->getIsconnected() == 'yes')
	  {
	  
		  /* *********************** */
		  /* send to foniva server */
		  /* *********************** */
		  fonivaFilter::foniva_send_toserver("MSG_AGENT_UPDATED", "agentid", $conf_agent->getDbid());
	  }
      $this->redirect('ressource/agents');
    }
  }
  
  /*********   ************/
  /***    P B X *****/
  /*********   ************/  
  public function executePbxs(sfWebRequest $request)
  {
    $this->searchedPbx = $this->getRequestParameter('searchedPbx');
	$this->searchedPbx = trim(strtolower($this->searchedPbx));
	  
	$this->pager = new sfDoctrinePager('ConfPbx', sfConfig::get('app_display_nbrecordperpage'));
	$this->pager->getQuery()->select('dbid, pbx_name, can_outbound, 
										outbounds_loadbalance_weight, can_register_agent, 
										 agents_loadbalance_weight, can_register_agent_from_anysite, 
										 registration_host, registration_port, isconnected,
										 count(a.agent_fk) as nbconnectedagents')
							->from('ConfPbx p')
							->leftJoin('p.LivelogPbxAgent a')
							->orderBy('p.pbx_name')
							->groupBy('p.dbid');
	
	$defaultpage = $this->getcurrentmodule_defaultpage();
	if(!empty($this->searchedPbx))
	{
		$this->pager->getQuery()->where('lower(p.pbx_name) LIKE ?', '%'.$this->searchedPbx.'%');	
		$defaultpage = 1;
	}
							
							
							
	$this->setcurrentmodule_defaultpage();
	$this->pager->setPage($defaultpage); //$this->getRequestParameter('page',1));
	$this->pager->init();
	$this->pbxs = $this->pager->getResults();
  }
  
  public function executePbxnew(sfWebRequest $request)
  {	
	$conf_pbx = new ConfPbx();
	$this->form = new ConfPbxForm($conf_pbx);
	$this->sites = Doctrine_Query::create()
					->select('s.dbid, s.name')
					->from('ConfSite s')
					->orderBy('s.name');
	$this->sites = $this->sites->execute();				
	
	$this->sites_list = array();	
	foreach($this->sites as $s)
		$this->sites_list[$s->getDbid()] = $s;
		
	$assarr = $request->getParameter('assigned_site');
	$this->assigned_sites = array();
	if($assarr != NULL)
	{
		foreach($assarr as $as)
			$this->assigned_sites[$as] = 1;
	}	
	
	$this->tenants = Doctrine_Query::create()
					->select('t.dbid, t.name')
					->from('ConfTenant t')
					->orderBy('t.name');
	$this->tenants = $this->tenants->execute();
	
	$this->tenants_list = array();	
	foreach($this->tenants as $s)
		$this->tenants_list[$s->getDbid()] = $s;
		
	$this->assigned_tenants = array();
	
	foreach($conf_pbx->ConfPbxRestrictedOutboundTenant as $as)
	{
		$this->assigned_tenants[$as->getTenantFk()] = 1;
		
	}
	
	$this->getResponse()->addJavascript('ui.multiselect.js', 'last');
	$this->getResponse()->addJavascript('plugins/scrollTo/jquery.scrollTo-min.js', 'last');
	$this->getResponse()->addJavascript('plugins/localisation/jquery.localisation-min.js', 'last');
	$this->getResponse()->addJavascript('jquery.tmpl.1.1.1.js', 'last');
	$this->getResponse()->addStylesheet('ui.multiselect.css', 'last');
  }

  public function executePbxcreate(sfWebRequest $request) 
  {
	$this->forward404Unless($request->isMethod(sfRequest::POST));
	$conf_pbx = new ConfPbx();
	$this->form = new ConfPbxForm($conf_pbx);
	$this->processPbxForm($request, $this->form);
	
	$this->sites = Doctrine_Query::create()
					->select('s.dbid, s.name')
					->from('ConfSite s')
					->orderBy('s.name');
	$this->sites = $this->sites->execute();				
	
	$this->sites_list = array();	
	foreach($this->sites as $s)
		$this->sites_list[$s->getDbid()] = $s;
		
	$assarr = $request->getParameter('assigned_site');
	$this->assigned_sites = array();
	if($assarr != NULL)
	{
		foreach($assarr as $as)
			$this->assigned_sites[$as] = 1;
	}
	
	
	$this->tenants = Doctrine_Query::create()
					->select('t.dbid, t.name')
					->from('ConfTenant t')
					->orderBy('t.name');
	$this->tenants = $this->tenants->execute();				
	
	$this->tenants_list = array();	
	foreach($this->tenants as $s)
		$this->tenants_list[$s->getDbid()] = $s;
		
	$this->assigned_tenants = array();
	foreach($conf_pbx->ConfPbxRestrictedOutboundTenant as $as)
	{
		$this->assigned_tenants[$as->getTenantFk()] = 1;
		
	}
	
	$this->getResponse()->addJavascript('ui.multiselect.js', 'last');
	$this->getResponse()->addJavascript('plugins/scrollTo/jquery.scrollTo-min.js', 'last');
	$this->getResponse()->addJavascript('plugins/localisation/jquery.localisation-min.js', 'last');
	$this->getResponse()->addJavascript('jquery.tmpl.1.1.1.js', 'last');
	$this->getResponse()->addStylesheet('ui.multiselect.css', 'last');
	
	$this->setTemplate('pbxnew');
  }

  public function executePbxedit(sfWebRequest $request)
  {
	$this->forward404Unless($conf_pbx = Doctrine::getTable('ConfPbx')->find($request->getParameter('dbid')), sprintf('Object conf_pbx does not exist (%s).', $request->getParameter('dbid')));
    $this->form = new ConfPbxForm($conf_pbx);
	
	
	$this->sites = Doctrine_Query::create()
					->select('s.dbid, s.name')
					->from('ConfSite s')
					->orderBy('s.name');
	$this->sites = $this->sites->execute();				
	
	$this->sites_list = array();	
	foreach($this->sites as $s)
		$this->sites_list[$s->getDbid()] = $s;
		
	$this->assigned_sites = array();
	foreach($conf_pbx->ConfPbxRestrictedSite as $as)
	{
		$this->assigned_sites[$as->getSiteFk()] = 1;
		
	}
	
	
	$this->tenants = Doctrine_Query::create()
					->select('t.dbid, t.name')
					->from('ConfTenant t')
					->orderBy('t.name');
	$this->tenants = $this->tenants->execute();				
	
	$this->tenants_list = array();	
	foreach($this->tenants as $s)
		$this->tenants_list[$s->getDbid()] = $s;
		
	$this->assigned_tenants = array();
	foreach($conf_pbx->ConfPbxRestrictedOutboundTenant as $as)
	{
		$this->assigned_tenants[$as->getTenantFk()] = 1;
		
	}
	
	$this->getResponse()->addJavascript('ui.multiselect.js', 'last');
	$this->getResponse()->addJavascript('plugins/scrollTo/jquery.scrollTo-min.js', 'last');
	$this->getResponse()->addJavascript('plugins/localisation/jquery.localisation-min.js', 'last');
	$this->getResponse()->addJavascript('jquery.tmpl.1.1.1.js', 'last');
	$this->getResponse()->addStylesheet('ui.multiselect.css', 'last');
  }
  
  public function executePbxupdate(sfWebRequest $request)
  {
	$this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($conf_pbx = Doctrine::getTable('ConfPbx')->find($request->getParameter('dbid')), sprintf('Object conf_pbx does not exist (%s).', $request->getParameter('dbid')));
	$this->form = new ConfPbxForm($conf_pbx);	
    $this->processPbxForm($request, $this->form);
	
	
	
	$this->sites = Doctrine_Query::create()
					->select('s.dbid, s.name')
					->from('ConfSite s')
					->orderBy('s.name');
	$this->sites = $this->sites->execute();				
	
	$this->sites_list = array();	
	foreach($this->sites as $s)
		$this->sites_list[$s->getDbid()] = $s;
		
	$assarr = $request->getParameter('assigned_site');
	$this->assigned_sites = array();
	
	if($assarr != NULL)
	{
		foreach($assarr as $as)
			$this->assigned_sites[$as] = 1;
	}
	
	
	$this->tenants = Doctrine_Query::create()
					->select('t.dbid, t.name')
					->from('ConfTenant t')
					->orderBy('t.name');
	$this->tenants = $this->tenants->execute();				
	
	$this->tenants_list = array();	
	foreach($this->tenants as $s)
		$this->tenants_list[$s->getDbid()] = $s;
		
	$this->assigned_tenants = array();
	foreach($conf_pbx->ConfPbxRestrictedOutboundTenant as $as)
	{
		$this->assigned_tenants[$as->getTenantFk()] = 1;
		
	}
	
	$this->getResponse()->addJavascript('ui.multiselect.js', 'last');
	$this->getResponse()->addJavascript('plugins/scrollTo/jquery.scrollTo-min.js', 'last');
	$this->getResponse()->addJavascript('plugins/localisation/jquery.localisation-min.js', 'last');
	$this->getResponse()->addJavascript('jquery.tmpl.1.1.1.js', 'last');
	$this->getResponse()->addStylesheet('ui.multiselect.css', 'last');
	
    $this->setTemplate('pbxedit');
  }

  public function executePbxdelete(sfWebRequest $request)
  {
	$request->checkCSRFProtection();
    $this->forward404Unless($conf_pbx = Doctrine::getTable('ConfPbx')->find($request->getParameter('dbid')), sprintf('Object conf_pbx does not exist (%s).', $request->getParameter('dbid')));
		
	$dbid = $conf_pbx->getDbid();
	$pbxname = $conf_pbx->getInterpbxUser();
    $conf_pbx->delete();	
	if(($jbu = $conf_pbx->getJbUser()))
		$jbu->delete();
	
	/* *********************** */
	/* send to foniva server */
	/* *********************** */
	fonivaFilter::foniva_send_toserver("MSG_PBX_PBXINFOS_DELETED", 
										"pbxid", $dbid,
										"pbxname", $pbxname	);
										
	$this->redirect('ressource/pbxs');
  }

  protected function processPbxForm(sfWebRequest $request, sfForm $form)
  {
	$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
	if ($form->isValid())
	{
	  $conf_pbx = $form->getObject();
	  $conf_pbx->setPbxName($form->getValue('pbx_name'));
	  $conf_pbx->setPassword($form->getValue('password'));
 	  $conf_pbx->setCanOutbound($form->getValue('can_outbound'));
 	  $conf_pbx->setOutboundsLoadbalanceWeight($form->getValue('outbounds_loadbalance_weight'));
	  $conf_pbx->setCanRegisterAgent($form->getValue('can_register_agent'));
	  $conf_pbx->setAgentsLoadbalanceWeight($form->getValue('agents_loadbalance_weight'));
	  $conf_pbx->setCanRegisterAgentFromAnysite($form->getValue('can_register_agent_from_anysite'));
	  $conf_pbx->setCanOutboundForAnytenant($form->getValue('can_outbound_for_anytenant'));
	  $conf_pbx->setRegistrationHost($form->getValue('registration_host'));
 	  $conf_pbx->setRegistrationPort($form->getValue('registration_port'));
 	  $conf_pbx->setInterpbxHost($form->getValue('interpbx_host'));
 	  $conf_pbx->setInterpbxPort($form->getValue('interpbx_port'));
	  $conf_pbx->setLastmodifiedBy($this->getUser()->getUsername());
	  
	  $newpbx = $conf_pbx->isNew();
	  if($newpbx) /* for new pbx, generate */
	  {
		$strippedusername = preg_replace("/[^a-zA-Z0-9\s]/", "", $form->getValue('pbx_name'));
 	  	$conf_pbx->setInterpbxUser($strippedusername);
 	  	$conf_pbx->setInterpbxPass($this->generateword(sfConfig::get('app_generator_pbxusernamelength')));
	  }
	  

	  $jbu = $conf_pbx->getJbUser();
	  if(!$jbu)
	  {
		$jbu = new JbUser();  
	  }
	  $jbu->setType('pbx');
	  $jbu->setUsername($form->getValue('pbx_name'));
	  $jbu->setPassword(md5($form->getValue('password')));
	  $jbu->save();
	  
	  /* auto assign group */
	  $this->dispatch_jabber_user_to_groups($jbu);
	  
	  $conf_pbx->setJbuserFk($jbu->getDbid());
	  $conf_pbx->save();
	  
	  
	  
	  
	  /* save sites */
	  $assigned_sitearr = $request->getParameter('assigned_site');
	  Doctrine_Query::create()
			->from('ConfPbxRestrictedSite')
			->where('pbx_fk = ?', $conf_pbx->getDbid())
			->delete()
			->execute();	  
	  if(is_array($assigned_sitearr) && sizeof($assigned_sitearr) > 0)
	  {
		  for($i = 0; $i < sizeof($assigned_sitearr); $i++)
		  {
			$siteid = $assigned_sitearr[$i];
			$asspbxsite = new ConfPbxRestrictedSite();
			$asspbxsite->setPbxFk($conf_pbx->getDbid());
			$asspbxsite->setSiteFk($siteid);
			$asspbxsite->save();
		  }
	  }
	  
	  /* save sites */
	  $assigned_tenantarr = $request->getParameter('assigned_tenant');
	  Doctrine_Query::create()
			->from('ConfPbxRestrictedOutboundTenant')
			->where('pbx_fk = ?', $conf_pbx->getDbid())
			->delete()
			->execute();	  
	  if(is_array($assigned_tenantarr) && sizeof($assigned_tenantarr) > 0)
	  {
		  for($i = 0; $i < sizeof($assigned_tenantarr); $i++)
		  {
			$tenantid = $assigned_tenantarr[$i];
			$asstenantsite = new ConfPbxRestrictedOutboundTenant();
			$asstenantsite->setPbxFk($conf_pbx->getDbid());
			$asstenantsite->setTenantFk($tenantid);
			$asstenantsite->save();
		  }
	  }
	  
	  
	  /* *********************** */
	  /* send to foniva server */
	  /* *********************** */
	  fonivaFilter::foniva_send_toserver("MSG_PBX_PBXINFOS_UPDATED", 
										"pbxid", $conf_pbx->getDbid()	);	

	  $this->redirect('ressource/pbxs');
    }
  }
  
  /*********   ************/
  /*** STORAGE SERVER *****/
  /*********   ************/  
  public function executeStorageservers(sfWebRequest $request)
  {
	$this->searchedStorageServer = $this->getRequestParameter('searchedStorageServer');
	$this->searchedStorageServer = trim(strtolower($this->searchedStorageServer));

	$this->pager = new sfDoctrinePager('ConfStorageserver', sfConfig::get('app_display_nbrecordperpage'));
	$this->pager->getQuery()->from('ConfStorageserver s')
							->orderBy('s.storagename');
	
	
	$defaultpage = $this->getcurrentmodule_defaultpage();
	if(!empty($this->searchedStorageServer))
	{
		$this->pager->getQuery()->where('lower(s.storagename) LIKE ? OR lower(s.directory) LIKE ? OR lower(s.pathformat) LIKE ?', array('%'.$this->searchedStorageServer.'%','%'.$this->searchedStorageServer.'%', '%'.$this->searchedStorageServer.'%'));							
		$defaultpage = 1;	
	}
	
	$this->setcurrentmodule_defaultpage();
	$this->pager->setPage($defaultpage); //$this->getRequestParameter('page',1));
	$this->pager->init();
	$this->storageservers = $this->pager->getResults();
  }
  
  public function executeStorageservernew(sfWebRequest $request)
  {
	$this->form = new ConfStorageserverForm();  
  }

  public function executeStorageservercreate(sfWebRequest $request) 
  {
	$this->forward404Unless($request->isMethod(sfRequest::POST));
	$conf_storageserver = new ConfStorageserver();
	$this->form = new ConfStorageserverForm($conf_storageserver);
	$this->processStorageserverForm($request, $this->form);
	$this->setTemplate('storageservernew');
  }

  public function executeStorageserveredit(sfWebRequest $request)
  {
	$this->forward404Unless($conf_storageserver = Doctrine::getTable('ConfStorageserver')->find($request->getParameter('dbid')), sprintf('Object conf_storageserver does not exist (%s).', $request->getParameter('dbid')));
    $this->form = new ConfStorageserverForm($conf_storageserver);
  }
  
  public function executeStorageserverupdate(sfWebRequest $request)
  {
	$this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($conf_storageserver = Doctrine::getTable('ConfStorageserver')->find($request->getParameter('dbid')), sprintf('Object conf_storageserver does not exist (%s).', $request->getParameter('dbid')));
	$this->form = new ConfStorageserverForm($conf_storageserver);
    $this->processStorageserverForm($request, $this->form);
    $this->setTemplate('storageserveredit');
  }

  public function executeStorageserverdelete(sfWebRequest $request)
  {
	$request->checkCSRFProtection();
    $this->forward404Unless($conf_storageserver = Doctrine::getTable('ConfStorageserver')->find($request->getParameter('dbid')), sprintf('Object conf_storageserver does not exist (%s).', $request->getParameter('dbid')));
		
    $conf_storageserver->delete();	
	if(($jbu = $conf_storageserver->getJbUser()))
		$jbu->delete();
	$this->redirect('ressource/storageservers');
  }

  protected function processStorageserverForm(sfWebRequest $request, sfForm $form)
  {
	$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
	if ($form->isValid())
	{
	  $conf_storageserver = $form->getObject();
	  $isnew = $conf_storageserver->isNew();
	  $conf_storageserver->setStoragename($form->getValue('storagename'));
	  $conf_storageserver->setPassword($form->getValue('password'));
	  $conf_storageserver->setDirectory($form->getValue('directory'));
	  $conf_storageserver->setPathformat($form->getValue('pathformat'));
	  $conf_storageserver->setFtpHost($form->getValue('ftp_host'));
	  $conf_storageserver->setFtpPort($form->getValue('ftp_port'));
	  $conf_storageserver->setRecordingsLoadbalanceWeight($form->getValue('recordings_loadbalance_weight'));
	  $conf_storageserver->setLastmodifiedBy($this->getUser()->getUsername());
	  
	  if($conf_storageserver->getFtpUsername() == '')
	  {
		  $randusername = $this->generateword(5);
	  	  $conf_storageserver->setFtpUsername($randusername);
	  }
	  
	  if($conf_storageserver->getFtpPassword() == '')
	  {
		  $randpassword = $this->generateword(5);
	  	  $conf_storageserver->setFtpPassword($randpassword);
	  }
	  
	  if($conf_storageserver->getFtpUsernameRead() == '')
	  {
		  $randusername = $this->generateword(5);
	  	  $conf_storageserver->setFtpUsernameRead($randusername);
	  }
	  
	  if($conf_storageserver->getFtpPasswordRead() == '')
	  {
		  $randpassword = $this->generateword(5);
	  	  $conf_storageserver->setFtpPasswordRead($randpassword);
	  }

	  $jbu = $conf_storageserver->getJbUser();
	  if(!$jbu)
	  {
		$jbu = new JbUser();  
	  }
	  $jbu->setType('storageserver');
	  $jbu->setUsername($form->getValue('storagename'));
	  $jbu->setPassword(md5($form->getValue('password')));
	  $jbu->save();
	  
	  /* auto assign group */
	  $this->dispatch_jabber_user_to_groups($jbu);
	  
	  $conf_storageserver->setJbuserFk($jbu->getDbid());
	  
	  $ismod = $conf_storageserver->isModified();
	  $conf_storageserver->save();

	  if(!$isnew && $ismod)
	  { /* send modifications to server */
		  fonivaFilter::foniva_send_toserver("MSG_SRG_UPDATED", "storageid", $conf_storageserver->getDbid());
	  }
	  
	  $this->redirect('ressource/storageservers');
    }
  }
  

  /******************************************************/
  /*                                                    */
  /*                 LOG DBS                          */
  /*                                                    */
  /******************************************************/
  public function executeLogdatabases(sfWebRequest $request)
  {
	$this->searchedLogdatabase = $this->getRequestParameter('searchedLogdatabase');
	$this->searchedLogdatabase = trim(strtolower($this->searchedLogdatabase));
	
	$this->pager = new sfDoctrinePager('ConfExternLogdb', sfConfig::get('app_display_nbrecordperpage'));
	$this->pager->getQuery()
							->from('ConfExternLogdb d')
							-> OrderBy('d.name');
							
							
	$defaultpage = $this->getcurrentmodule_defaultpage();				
	if(!empty($this->searchedLogdatabase))
	{
		$this->pager->getQuery()->where('lower(d.name) LIKE ? OR lower(d.dsn) LIKE ?', array('%'.$this->searchedLogdatabase.'%', '%'.$this->searchedLogdatabase.'%'));	
		$defaultpage = 1;
	}
		
		
  	
	$this->setcurrentmodule_defaultpage();
	$this->pager->setPage($defaultpage); //$this->getRequestParameter('page',1));
	$this->pager->init();
	
	$this->logdatabases = $this->pager->getResults();
  }
  
  public function executeLogdatabasenew(sfWebRequest $request)
  {
    $conf_extern_logdb = new ConfExternLogdb();
	$this->form = new ConfExternLogdbForm($conf_extern_logdb);
  }

  public function executeLogdatabasecreate(sfWebRequest $request)
  {
	$this->forward404Unless($request->isMethod(sfRequest::POST));
	$logdb = new ConfExternLogdb();
	$this->form = new ConfExternLogdbForm($logdb);
	$this->processLogdatabaseForm($request, $this->form);
	$this->setTemplate('logdatabasenew');
  }

  public function executeLogdatabaseedit(sfWebRequest $request)
  {
    $this->forward404Unless($logdb = Doctrine::getTable('ConfExternLogdb')->find($request->getParameter('dbid')), sprintf('Object conf_exten_logdb does not exist (%s).', $request->getParameter('dbid')));
    $this->form = new ConfExternLogdbForm($logdb);
  }

  public function executeLogdatabaseupdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($logdb = Doctrine::getTable('ConfExternLogdb')->find($request->getParameter('dbid')), sprintf('Object conf_extern_logdb does not exist (%s).', $request->getParameter('dbid')));
    $this->form = new ConfExternLogdbForm($logdb);
    $this->processLogdatabaseForm($request, $this->form);
    $this->setTemplate('logdatabaseedit');
  }

  public function executeLogdatabasedelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();
	
    $this->forward404Unless($logdb = Doctrine::getTable('ConfExternLogdb')->find($request->getParameter('dbid')), sprintf('Object conf_extern_logdb does not exist (%s).', $request->getParameter('dbid')));
	$wasconnected = $logdb->connected;
	$logdb->delete();
	
	if($wasconnected == 'yes')
	{
		fonivaFilter::foniva_send_toserver("MSG_LOGDATABASE_DELETED", 
											 	"logdbid", $logdb->getDbid());	
	}
	
    $this->redirect('ressource/logdatabases');
  }
  
  public function executeEditagentselect_expression(sfWebRequest $request)
  {
	
	$this->agents = Doctrine_Query::create()
					->select('a.dbid, a.shortusername, a.username, a.active,
							 	i.firstname as firstname, i.lastname as lastname')
					->from('ConfAgent a')
					->leftJoin('a.ConfAgentInfo i ON i.dbid = a.info_fk')
					->orderBy('a.username');
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->agents->where('a.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
	$this->agents->andWhere('a.active = ?', 'yes');
	$this->agents = $this->agents->execute();
	
	$this->agentgroups = Doctrine_Query::create()
							->select('cg.dbid, cg.name')
	 						->from('ConfGroup cg')
							->orderBy('cg.name');
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->agentgroups->where('cg.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
	$this->agentgroups = $this->agentgroups->execute();
	
	$this->skills = Doctrine_Query::create()
					->select('s.dbid, s.name')
					->from('ConfSkill s')
					->orderBy('s.name');
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->skills->where('s.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
	$this->skills = $this->skills->execute();
	
	$this->agentselect_expression = ''; 
	$queueid = $request->getParameter('queueid');
	if($queueid != NULL && $queueid != '')
	{
		$queue = Doctrine::getTable('ConfQueue')->find($queueid);
		if($queue)
			$this->agentselect_expression = $queue->getAgentselectExpression();
	}
	
  }
  
  protected function processLogdatabaseForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
	  $logdb = $form->getObject();
	  
	  $isnew = $logdb->isNew();
	  $wasactive = $logdb->getActive();
	  $logdb->setName($form->getValue('name'));
	  $logdb->setDsn($form->getValue('dsn'));
	  $logdb->setUsername($form->getValue('username'));
	  $logdb->setPassword($form->getValue('password'));
	  $logdb->setInsertLogAgentCall($form->getValue('insert_log_agent_call'));
	  $logdb->setInsertLogAgentEvent($form->getValue('insert_log_agent_event'));
	  $logdb->setInsertLogCallRecord($form->getValue('insert_log_call_record'));
	  $logdb->setInsertLogCampaignActivity($form->getValue('insert_log_campaign_activity'));
	  $logdb->setInsertLogCampaignDialing($form->getValue('insert_log_campaign_dialing'));
	  $logdb->setLastmodifiedBy($this->getUser()->getUsername());
	  $logdb->setActive($form->getValue('active'));
	  $isactive = $logdb->getActive();
	  
	  $ismodified = $logdb->isModified();
	  
	  $logdb->save();
	  
	  if($isnew && $logdb->getActive() == 'yes')
	  {
		  fonivaFilter::foniva_send_toserver("MSG_LOGDATABASE_ADDED", 
											 	"logdbid", $logdb->getDbid());
	  } else if($ismodified)
	  {
		  if($wasactive == 'yes' && $isactive == 'no')
		  		fonivaFilter::foniva_send_toserver("MSG_LOGDATABASE_DELETED", 
													"logdbid", $logdb->getDbid());
		  else if($wasactive == 'no' && $isactive == 'yes')
		  		fonivaFilter::foniva_send_toserver("MSG_LOGDATABASE_ADDED", 
													"logdbid", $logdb->getDbid());
		  else  if($wasactive == 'yes' && $isactive == 'yes')
			 	fonivaFilter::foniva_send_toserver("MSG_LOGDATABASE_UPDATED", 
													"logdbid", $logdb->getDbid());
	  }
	  
      $this->redirect('ressource/logdatabases');
    }
  }
  
  
  
  /*********   ************/
  /***   AGENT GROUPS *****/
  /*********   ************/	 
  
  public function executeAgentteams(sfWebRequest $request)
  {
	  
	$this->searchedAgentTeam = $this->getRequestParameter('searchedAgentTeam');
	$this->searchedAgentTeam = trim(strtolower($this->searchedAgentTeam));

	
	$this->pager = new sfDoctrinePager('ConfTeam', sfConfig::get('app_display_nbrecordperpage'));
	$this->pager->getQuery()->select('cg.dbid, cg.name, count(ag.dbid) as nbagents, u.firstname as supervisor_firstname, u.lastname as supervisor_lastname')
							->from('ConfTeam cg')
							->leftJoin('cg.ConfUser u')
							->leftJoin('cg.ConfAgent ag')
							->orderBy('cg.name')
							->groupBy('cg.dbid')
							->where('1');
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->pager->getQuery()->andWhere('cg.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
		
	$defaultpage = $this->getcurrentmodule_defaultpage();
	if(!empty($this->searchedAgentTeam))
	{
		$this->pager->getQuery()->andWhere('lower(cg.name) LIKE ?','%'.$this->searchedAgentTeam.'%');
		$defaultpage = 1;
	}
	
	
	$this->setcurrentmodule_defaultpage();
	$this->pager->setPage($defaultpage); //$this->getRequestParameter('page',1));
	$this->pager->init();
	$this->agentteams = $this->pager->getResults();
  }
  
  public function executeAgentteamnew(sfWebRequest $request)
  {
    $conf_team = new ConfTeam();
    $this->form = new ConfTeamForm($conf_team);	
	
	$this->getResponse()->addJavascript('ui.multiselect.js', 'last');
	$this->getResponse()->addJavascript('plugins/scrollTo/jquery.scrollTo-min.js', 'last');
	$this->getResponse()->addJavascript('plugins/localisation/jquery.localisation-min.js', 'last');
	$this->getResponse()->addJavascript('jquery.tmpl.1.1.1.js', 'last');
	$this->getResponse()->addStylesheet('ui.multiselect.css', 'last');
  }

  public function executeAgentteamcreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));
    $conf_team = new ConfTeam();
    $this->form = new ConfTeamForm($conf_team);
    $this->processAgentteamForm($request, $this->form);
		
	$this->getResponse()->addJavascript('ui.multiselect.js', 'last');
	$this->getResponse()->addJavascript('plugins/scrollTo/jquery.scrollTo-min.js', 'last');
	$this->getResponse()->addJavascript('plugins/localisation/jquery.localisation-min.js', 'last');
	$this->getResponse()->addJavascript('jquery.tmpl.1.1.1.js', 'last');
	$this->getResponse()->addStylesheet('ui.multiselect.css', 'last');
	 
    $this->setTemplate('agentteamnew');
  }

  public function executeAgentteamedit(sfWebRequest $request)
  {
    $this->forward404Unless($conf_team = Doctrine::getTable('ConfTeam')->find($request->getParameter('dbid')), sprintf('Object conf_team does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_team->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$this->form = new ConfTeamForm($conf_team);
		
	$this->getResponse()->addJavascript('ui.multiselect.js', 'last');
	$this->getResponse()->addJavascript('plugins/scrollTo/jquery.scrollTo-min.js', 'last');
	$this->getResponse()->addJavascript('plugins/localisation/jquery.localisation-min.js', 'last');
	$this->getResponse()->addJavascript('jquery.tmpl.1.1.1.js', 'last');
	$this->getResponse()->addStylesheet('ui.multiselect.css', 'last');	
  }

  public function executeAgentteamupdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($conf_team = Doctrine::getTable('ConfTeam')->find($request->getParameter('dbid')), sprintf('Object conf_team does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_team->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$this->form = new ConfTeamForm($conf_team);
	$this->processAgentteamForm($request, $this->form);
	
	$this->getResponse()->addJavascript('ui.multiselect.js', 'last');
	$this->getResponse()->addJavascript('plugins/scrollTo/jquery.scrollTo-min.js', 'last');
	$this->getResponse()->addJavascript('plugins/localisation/jquery.localisation-min.js', 'last');
	$this->getResponse()->addJavascript('jquery.tmpl.1.1.1.js', 'last');
	$this->getResponse()->addStylesheet('ui.multiselect.css', 'last');
	
    $this->setTemplate('agentteamedit');
  }

  public function executeAgentteamdelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();
    $this->forward404Unless($conf_team = Doctrine::getTable('ConfTeam')->find($request->getParameter('dbid')), sprintf('Object conf_team does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_team->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$dbid = $conf_team->getDbid();
	$conf_team->delete();
	
	fonivaFilter::foniva_send_toserver("MSG_AGENTTEAM_DELETED", 
											 	"teamid", $dbid);
												
    $this->redirect('ressource/agentteams');
  }

  protected function processAgentteamForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $conf_team = $form->getObject();
	  $conf_team->setName($form->getValue('name'));
	  $conf_team->setSupervisorFk($form->getValue('supervisor_fk'));
	  
	  if(fonivaFilter::isCurrentUserSuperTenant())
	    $conf_team->setTenantFk($form->getValue('tenant_fk'));
	  else
	    $conf_team->setTenantFk(fonivaFilter::getCurrentUserTenantId());
		
	  $isnew = $conf_team->isNew();
	  
	  $conf_team->save();
	  
	  fonivaFilter::foniva_send_toserver(($isnew ? "MSG_AGENTTEAM_ADDED" : "MSG_AGENTTEAM_UPDATED"), 
											 	"teamid", $conf_team->getDbid());
												
      $this->redirect('ressource/agentteams');
    }
  }
  
  
  
  
  public function executeAudioprompts(sfWebRequest $request)
  {	
    $this->searchedAudioprompt = $this->getRequestParameter('searchedAudioprompt');
	$this->searchedAudioprompt = trim(strtolower($this->searchedAudioprompt));
  
	$this->pager = new sfDoctrinePager('ConfAudioPrompt', sfConfig::get('app_display_nbrecordperpage'));
	$this->pager->getQuery()->from('ConfAudioPrompt u')
					->orderBy('u.name');
	
	$defaultpage = $this->getcurrentmodule_defaultpage();
	if(!empty($this->searchedAudioprompt))
	{
		$this->pager->getQuery()->where('lower(u.name) LIKE ? OR lower(u.description) LIKE ?', 
											array('%'.$this->searchedAudioprompt.'%', '%'.$this->searchedAudioprompt.'%'));	
		$defaultpage = 1;
	}
	
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->pager->getQuery()->where('u.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
	
	$this->setcurrentmodule_defaultpage();
	$this->pager->setPage($defaultpage);
	$this->pager->init();
	$this->audioprompts = $this->pager->getResults();
  }
  
  public function executeAudiopromptnew(sfWebRequest $request)
  {
    $this->form = new ConfAudiopromptForm();
  }

  public function executeAudiopromptcreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));
    $this->form = new ConfAudiopromptForm();
    $this->processAudiopromptForm($request, $this->form);
    $this->setTemplate('audiopromptnew');
  }

  public function executeAudiopromptedit(sfWebRequest $request)
  {
    $this->forward404Unless($conf_audio_prompt = Doctrine::getTable('ConfAudioprompt')->find($request->getParameter('dbid')), sprintf('Object conf_audio_prompt does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_audio_prompt->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$this->form = new ConfAudiopromptForm($conf_audio_prompt);
  }

  public function executeAudiopromptupdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($conf_audio_prompt = Doctrine::getTable('ConfAudioprompt')->find($request->getParameter('dbid')), sprintf('Object conf_audioprompt does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_audio_prompt->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$this->form = new ConfAudiopromptForm($conf_audio_prompt);
    $this->processAudiopromptForm($request, $this->form);
    $this->setTemplate('audiopromptedit');
  }

  public function executeAudiopromptdelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();
    $this->forward404Unless($conf_audio_prompt = Doctrine::getTable('ConfAudioprompt')->find($request->getParameter('dbid')), sprintf('Object conf_audioprompt does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_audio_prompt->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$conf_audio_prompt->delete();
    $this->redirect('ressource/audioprompts');
  }

  protected function processAudiopromptForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $conf_audio_prompt = $form->getObject();
	  
	  if(fonivaFilter::isCurrentUserSuperTenant())
		  $conf_audio_prompt->setTenantFk($form->getValue('tenant_fk'));
	  else
		  $conf_audio_prompt->setTenantFk(fonivaFilter::getCurrentUserTenantId());
	  
	  $conf_audio_prompt->setName($form->getValue('name'));
	  //$conf_did->setCidmatch($form->getValue('cidmatch'));
	  $conf_audio_prompt->setDescription($form->getValue('description'));
	  $conf_audio_prompt->setLang($form->getValue('lang'));
	  
	  $conf_audio_prompt->save();
	  
      $this->redirect('ressource/audioprompts');
    }
  }
  
  
  
  
  
  public function executeAudiomusiconholds(sfWebRequest $request)
  {	
    $this->searchedAudiomusiconhold = $this->getRequestParameter('searchedAudiomusiconhold');
	$this->searchedAudiomusiconhold = trim(strtolower($this->searchedAudiomusiconhold));
  
	$this->pager = new sfDoctrinePager('ConfAudioMusiconhold', sfConfig::get('app_display_nbrecordperpage'));
	$this->pager->getQuery()->from('ConfAudioMusiconhold u')
					->orderBy('u.name');
	
	$defaultpage = $this->getcurrentmodule_defaultpage();
	if(!empty($this->searchedAudiomusiconhold))
	{
		$this->pager->getQuery()->where('lower(u.name) LIKE ? OR lower(u.description) LIKE ?', 
											array('%'.$this->searchedAudiomusiconhold.'%', '%'.$this->searchedAudiomusiconhold.'%'));	
		$defaultpage = 1;
	}
	
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->pager->getQuery()->where('u.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());
	
	$this->setcurrentmodule_defaultpage();
	$this->pager->setPage($defaultpage);
	$this->pager->init();
	$this->audiomusiconholds = $this->pager->getResults();
  }
  
  public function executeAudiomusiconholdnew(sfWebRequest $request)
  {
    $this->form = new ConfAudiomusiconholdForm();
  }

  public function executeAudiomusiconholdcreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));
    $this->form = new ConfAudiomusiconholdForm();
    $this->processAudiomusiconholdForm($request, $this->form);
    $this->setTemplate('audiomusiconholdnew');
  }

  public function executeAudiomusiconholdedit(sfWebRequest $request)
  {
    $this->forward404Unless($conf_audio_musiconhold = Doctrine::getTable('ConfAudiomusiconhold')->find($request->getParameter('dbid')), sprintf('Object conf_audio_musiconhold does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_audio_musiconhold->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$this->form = new ConfAudiomusiconholdForm($conf_audio_musiconhold);
  }

  public function executeAudiomusiconholdupdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($conf_audio_musiconhold = Doctrine::getTable('ConfAudiomusiconhold')->find($request->getParameter('dbid')), sprintf('Object conf_audiomusiconhold does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_audio_musiconhold->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$this->form = new ConfAudiomusiconholdForm($conf_audio_musiconhold);
    $this->processAudiomusiconholdForm($request, $this->form);
    $this->setTemplate('audiomusiconholdedit');
  }

  public function executeAudiomusiconholddelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();
    $this->forward404Unless($conf_audio_musiconhold = Doctrine::getTable('ConfAudiomusiconhold')->find($request->getParameter('dbid')), sprintf('Object conf_audiomusiconhold does not exist (%s).', $request->getParameter('dbid')));
    $this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $conf_audio_musiconhold->getTenantFk() == fonivaFilter::getCurrentUserTenantId());
	$conf_audio_musiconhold->delete();
    $this->redirect('ressource/audiomusiconholds');
  }

  protected function processAudiomusiconholdForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $conf_audio_musiconhold = $form->getObject();
	  
	  if(fonivaFilter::isCurrentUserSuperTenant())
		  $conf_audio_musiconhold->setTenantFk($form->getValue('tenant_fk'));
	  else
		  $conf_audio_musiconhold->setTenantFk(fonivaFilter::getCurrentUserTenantId());
	  
	  $conf_audio_musiconhold->setName($form->getValue('name'));
	  //$conf_did->setCidmatch($form->getValue('cidmatch'));
	  $conf_audio_musiconhold->setDescription($form->getValue('description'));
	  
	  $conf_audio_musiconhold->save();
	  
      $this->redirect('ressource/audiomusiconholds');
    }
  }
  
  
  
  
  /******************************************************/
  /*                                                    */
  /*                 BLACK LISTS                      */
  /*                                                    */
  /******************************************************/  
  public function executeBlacklists(sfWebRequest $request)
  {
	$this->searchedBlacklist = $request->getParameter('searchedBlacklist');
	$this->searchedBlacklist = trim(strtolower($this->searchedBlacklist));

	$this->pager = new sfDoctrinePager('ConfBlacklist', sfConfig::get('app_display_nbrecordperpage'));
	
	$this->pager->getQuery()->select('i.dbid, i.listname, i.description,
											i.created_at, i.updated_at')
								->from('ConfBlacklist i')
								->OrderBy('i.listname');
	if(!fonivaFilter::isCurrentUserSuperTenant())
		$this->pager->getQuery()->where('i.tenant_fk = ?', fonivaFilter::getCurrentUserTenantId());

	if(!empty($this->searchedInbound))
		$this->pager->getQuery()->where('lower(i.listname) LIKE ?', '%'.$this->searchedBlacklist.'%');
	
	$this->pager->setPage($this->getRequestParameter('page',1));
	$this->pager->init();	
	
	$this->blacklists = $this->pager->getResults();
  }

  public function executeBlacklistnew(sfWebRequest $request)
  {
	 $conf_black_list = new ConfBlackList();
	 $this->form = new ConfBlackListForm($conf_black_list);
  }

  public function executeBlacklistcreate(sfWebRequest $request)
  {
	$this->forward404Unless($request->isMethod(sfRequest::POST));
	$this->form = new ConfBlackListForm();
	$this->processBlackListForm($request, $this->form);
	$this->setTemplate('blacklistnew');
  }

  public function executeBlacklistedit(sfWebRequest $request)
  {
    $this->forward404Unless($conf_black_list = Doctrine::getTable('ConfBlackList')->find($request->getParameter('dbid')), sprintf('Object conf_black_list does not exist (%s).', $request->getParameter('dbid')));
    $this->form = new ConfBlackListForm($conf_black_list);
  }

  public function executeBlacklistupdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($conf_black_list = Doctrine::getTable('ConfBlackList')->find($request->getParameter('dbid')), sprintf('Object conf_black_list does not exist (%s).', $request->getParameter('dbid')));
    $this->form = new ConfBlackListForm($conf_black_list);
    $this->processBlacklistForm($request, $this->form);
  
    $this->setTemplate('blacklistedit');
  }
  
  public function executeBlacklistupload(sfWebRequest $request)
  {
	$this->forward404Unless($this->conf_black_list = Doctrine::getTable('ConfBlackList')->find($request->getParameter('dbid')), sprintf('Object conf_black_list does not exist (%s).', $request->getParameter('dbid')));
	
  }
  
  public function executeBlacklistdata(sfWebRequest $request) 
  {
	$this->forward404Unless($this->conf_black_list = Doctrine::getTable('ConfBlackList')->find($request->getParameter('dbid')), sprintf('Object conf_black_list does not exist (%s).', $request->getParameter('dbid')));
	$this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $this->conf_black_list->getTenantFk() == fonivaFilter::getCurrentUserTenantId()); 
	
	sfConfig::set('sf_web_debug', false);
	$this->setLayout(false);
	$this->getResponse()->setContentType('text/json');
	
	$this->draw = $request->getParameter('draw');
	$this->start = $request->getParameter('start');
	$this->length = $request->getParameter('length');
	$this->filters = $request->getParameter('search');
	$this->orders = $request->getParameter('order');
	$this->columns = $request->getParameter('columns');
	$this->search = $request->getParameter('search');
	  
	$manager = Doctrine_manager::getInstance();
	$clist_conn = $manager->getCurrentConnection();
	
	$sql = 'SELECT COUNT(*) as total FROM conf_blacklist_data WHERE list_fk = "'.$this->conf_black_list->dbid.'" ';
	$pstatement = $clist_conn->execute($sql);
	$this->totalrows = $pstatement->fetchAll();
	if(is_array($this->totalrows))
		$this->totalrows = $this->totalrows[0];
	
	$sql = 'SELECT phonenumber FROM conf_blacklist_data ';
	$sql .= ' WHERE list_fk = "'.$this->conf_black_list->dbid.'" ';
	
	$this->filtered = false;
	if($this->search['value'] != "")
	{
		$sql .= ' AND phonenumber like "%'.$this->search['value'].'%"';	
		$this->filtered = true;
	}
	
	/*
	if(sizeof($this->orders) > 0)
	{
		$sql .= ' ORDER BY ';
		$cnt = 0;
		foreach($this->orders as $o)
		{
			if($cnt != 0)
				$sql .= ',';
				
			$colname = $this->columns[$o['column']]["data"];
			$sql .= ' '.$colname. ' ' . $o['dir'];
			$cnt++;
		}
	}
	*/
	
	//$sql .= ' LIMIT 20';//.$this->length.','.$this->start;
	if($this->length >= 0)
		$sql .= ' LIMIT '.$this->start.','.$this->length;
	
	
	$pstatement = $clist_conn->execute($sql);
	$this->rows = $pstatement->fetchAll(PDO::FETCH_ASSOC);
  }
  
  public function executeBlacklistaddrow(sfWebRequest $request)
  {
	  sfConfig::set('sf_web_debug', false);
	  $this->setLayout(false);
	  $this->forward404Unless($this->conf_black_list = Doctrine::getTable('ConfBlackList')->find($request->getParameter('dbid')), sprintf('Object conf_black_list does not exist (%s).', $request->getParameter('dbid')));
	   
	  $this->tablecolumns = array('phonenumber');
  }
  
  public function executeBlacklistaddrowdoinsert(sfWebRequest $request)
  {
	  sfConfig::set('sf_web_debug', false);
	  $this->setLayout(false);
	  $this->forward404Unless($this->conf_black_list = Doctrine::getTable('ConfBlackList')->find($request->getParameter('dbid')), sprintf('Object conf_black_list does not exist (%s).', $request->getParameter('dbid')));
	  
	  $rowdata = $request->getParameter('row');
	  $columns = array_keys($rowdata);
	  $values  = array_values($rowdata);
	  
	  $colsqlstr =  implode(',', $columns);
	  $pvalsqlstr = implode(',', array_fill(0, sizeof($columns), '?'));
	  $psql = 'INSERT INTO conf_blacklist_data (list_fk, phonenumber) VALUES ('.$this->conf_black_list->dbid.', '.$pvalsqlstr.')';
	  
	  $manager = Doctrine_manager::getInstance();
	  $clist_conn = $manager->openConnection();
	  
	  $pstatement = $clist_conn->execute($psql, $values);
  }
  
  public function executeBlacklistdeleterow(sfWebRequest $request)
  {
	  sfConfig::set('sf_web_debug', false);
	  $this->setLayout(false);
	  $this->forward404Unless($this->conf_black_list = Doctrine::getTable('ConfBlackList')->find($request->getParameter('dbid')), sprintf('Object conf_black_list does not exist (%s).', $request->getParameter('dbid')));
	  
	  $rowsrr = $request->getParameter('rowids');
	  if(is_array($rowsrr))
	  	$rowsrr = implode(',', $rowsrr);
	  
	  $manager = Doctrine_manager::getInstance();
	  $clist_conn = $manager->openConnection();
	  $sql = 'DELETE FROM conf_blacklist_data WHERE list_fk = '.$this->conf_black_list->dbid.' AND dbid IN ('.$rowsrr.')';
	  $pstatement = $clist_conn->execute($sql);
  }
  
  
  public function executeBlacklistdeleteallrows(sfWebRequest $request)
  {
	  sfConfig::set('sf_web_debug', false);
	  $this->setLayout(false);
	  $this->forward404Unless($this->conf_black_list = Doctrine::getTable('ConfBlackList')->find($request->getParameter('dbid')), sprintf('Object conf_black_list does not exist (%s).', $request->getParameter('dbid')));
	  
	  $manager = Doctrine_manager::getInstance();
	  $clist_conn = $manager->openConnection();
	  $sql = 'DELETE FROM xonf_blacklist_data WHERE list_fk = "'.$this->conf_black_list->dbid.'"';
	  $pstatement = $clist_conn->execute($sql);
  }
  
  public function executeBlacklistdoupload(sfWebRequest $request)
  {
	$this->forward404Unless($this->conf_black_list = Doctrine::getTable('ConfBlackList')->find($request->getParameter('dbid')), sprintf('Object conf_black_list does not exist (%s).', $request->getParameter('dbid')));
	
	set_time_limit(0);
	$this->setLayout(false);
  	sfConfig::set('sf_web_debug', false);
	 
	$table_name = $this->table_name;
	$field_delimiter = $request->getParameter('delimiter');
	$field_quote = $request->getParameter('quote');
	$ignore_lines = $request->getParameter('ignoredline');
	
	switch($field_delimiter)
	{
		case 'SEMI_COLON':
			$field_delimiter = ';';
		break;
		case 'COMMA':
			$field_delimiter = ',';
		break;
		case 'TAB':
			$field_delimiter = '\\t';
		break;
		case 'SPACE':
			$field_delimiter = ' ';
		break;
	}
	
	switch($field_quote)
	{
		case 'DOUBLE_QUOTE':
			$field_quote = '"';
		break;
		case 'SINGLE_QUOTE':
			$field_quote = '\\\'';
		break;	
	}
	
	if(!isset($_FILES))
		$this->forward404();
	if(!isset($_FILES['listfile']))
		$this->forward404();
		
	//$file_name = $this->getRequest()->getFileName('listfile');
	$file_name = $_FILES['listfile']['name'];
	$tmp_name = $_FILES['listfile']['tmp_name'];
	$filesize = $_FILES['listfile']['size'];
	
	if(!file_exists($tmp_name))
		$this->forward404();
	
	$ntmp_name = sfConfig::get('sf_upload_dir').'/'.$file_name;
	rename($tmp_name, $ntmp_name);
	$tmp_name = $ntmp_name;
	$this->file_name = $file_name;
	
	$manager = Doctrine_manager::getInstance();
	$clist_conn = $manager->openConnection();
	
	$sql = 'SHOW COLUMNS FROM '.$this->table_name;
	$pstatement = $clist_conn->execute($sql);
	$this->tablecolumns = $pstatement->fetchAll(PDO::FETCH_ASSOC);
	$columns = array('phonenumber');
	
	$columnslist = implode(',', $columns);
	$pvalsqlstr = implode(',', array_fill(0, sizeof($columns), '?'));
	$psql = 'INSERT INTO conf_blacklist_data (list_fk, '.$columnslist.') VALUES ('.$this->conf_black_list->dbid.', '.$pvalsqlstr.')';
	$nbcols = sizeof($columns);
	
	$this->countinserted = 0;
	if (($handle = fopen($tmp_name, "r")) !== FALSE) {
		while (($values = fgetcsv($handle, 0, $field_delimiter, $field_quote)) !== FALSE) {
			
			if(sizeof($values) < $nbcols) /* if we dont have enougth, fill it */
				$values = array_merge($values, array_fill(0,$nbcols-sizeof($values),''));
			else if(sizeof($values) > $nbcols)	/* if we have too much trunk it */
				$values = array_splice($values, 0, $nbcols);
			
			
			$pstatement = $clist_conn->execute($psql, $values);
			$this->countinserted ++;
		}
		fclose($handle);
	}
	
	$this->redirect('ressource/blacklistedit?dbid='.$this->conf_black_list->getDbid());
  }

  
  public function executeBlacklistdosingleupload(sfWebRequest $request)
  {
	$this->forward404Unless($this->conf_black_list = Doctrine::getTable('ConfBlackList')->find($request->getParameter('dbid')), sprintf('Object conf_black_list does not exist (%s).', $request->getParameter('dbid')));
	$this->forward404Unless(fonivaFilter::isCurrentUserSuperTenant() || $this->conf_black_list->getTenantFk() == fonivaFilter::getCurrentUserTenantId()); 
	
	
	set_time_limit(0);
	$this->setLayout(false);
  	sfConfig::set('sf_web_debug', false);
	$this->getResponse()->setContentType('text/json');
	 
	$table_name = $this->table_name;
	$field_delimiter = $request->getParameter('delimiter');
	$field_quote = $request->getParameter('quote');
	$ignore_lines = $request->getParameter('ignoredline');
	
	switch($field_delimiter)
	{
		case 'SEMI_COLON':
			$field_delimiter = ';';
		break;
		case 'COMMA':
			$field_delimiter = ',';
		break;
		case 'TAB':
			$field_delimiter = '\\t';
		break;
		case 'SPACE':
			$field_delimiter = ' ';
		break;
	}
	
	switch($field_quote)
	{
		case 'DOUBLE_QUOTE':
			$field_quote = '"';
		break;
		case 'SINGLE_QUOTE':
			$field_quote = '\\\'';
		break;	
	}
	
	if(!isset($_FILES))
		$this->forward404();
	if(!isset($_FILES['fileupload']))
		$this->forward404();
		
	
	$file_name = $_FILES['fileupload']['name'][0];
	$tmp_name = $_FILES['fileupload']['tmp_name'][0];
	$filesize = $_FILES['fileupload']['size'][0];
	
	
	$this->file_name = $file_name;
	$this->file_size = $filesize;
	
	if(!file_exists($tmp_name))
	{
		echo $tmp_name;
		$this->file_error = 'File upload error';
		exit;
	}
	
	$ntmp_name = sfConfig::get('sf_upload_dir').'/'.$file_name;
	rename($tmp_name, $ntmp_name);
	$tmp_name = $ntmp_name;
	
	$manager = Doctrine_manager::getInstance();
	$clist_conn = $manager->getCurrentConnection();
	
	$columns = array('phonenumber');
	
	$columnslist = implode(',', $columns);
	$pvalsqlstr = implode(',', array_fill(0, sizeof($columns), '?'));
	$psql = 'INSERT INTO conf_blacklist_data (list_fk, '.$columnslist.') VALUES ("'.$this->conf_black_list->dbid.'", '.$pvalsqlstr.')';
	$nbcols = sizeof($columns);
	
	$this->countinserted = 0;
	if (($handle = fopen($tmp_name, "r")) !== FALSE) {
		while (($values = @fgetcsv($handle, 0, $field_delimiter, $field_quote)) !== FALSE) {
			
			if($ignore_lines > 0)
			{
				$ignore_lines--;
				continue;	
			}
			
			if(sizeof($values) < $nbcols) /* if we dont have enougth, fill it */
				$values = array_merge($values, array_fill(0,$nbcols-sizeof($values),''));
			else if(sizeof($values) > $nbcols)	/* if we have too much trunk it */
				$values = array_splice($values, 0, $nbcols);
			
			
			//echo $psql; echo "<br />";
			//echo $values; echo "<br />";
			//exit();
			try
			{
				$pstatement = @$clist_conn->execute($psql, $values);
				$this->countinserted ++;
			}
			catch(Exception $e) {
				//echo 'Caught exception: ',  $e->getMessage(), "\n";
			}
		}
		fclose($handle);
	}
  }
  
  
  public function executeBlacklistdelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();
    $this->forward404Unless($conf_black_list = Doctrine::getTable('ConfBlackList')->find($request->getParameter('dbid')), sprintf('Object conf_black_list does not exist (%s).', $request->getParameter('dbid')));
	
	$conf_black_list->delete();
	
	
    $this->redirect('ressource/blacklists');
  }
  
  public function executeBlacklistimport(sfWebRequest $request)
  {
	 $this->forward404Unless($this->conf_black_list = Doctrine::getTable('ConfBlackList')->find($request->getParameter('dbid')), sprintf('Object conf_black_list does not exist (%s).', $request->getParameter('dbid')));
  }
  
  public function executeBlacklistexport(sfWebRequest $request)
  {
	 $this->forward404Unless($this->conf_black_list = Doctrine::getTable('ConfBlackList')->find($request->getParameter('dbid')), sprintf('Object conf_black_list does not exist (%s).', $request->getParameter('dbid')));
	 
	 set_time_limit(0);
	 $this->setLayout(false);
  	 sfConfig::set('sf_web_debug', false);
	 	
	 $localfilesdir = '/tmp/';
	 /* 
	 if(!is_dir($localfilesdir))
	 {
		 mkdir($localfilesdir, 0777, true);  
	 }
	 */
	 
	 $clean_list_name = preg_replace("/[^A-Za-z0-9]/", "_", $this->conf_black_list->listname);
	 $filename = 'foniva_'.$clean_list_name.'_'.date('YmdHis').'.csv';
	 $localfile = $localfilesdir.''.$filename;
	 $tmpfile = '/tmp/'.$filename;	 
	 
	 $manager = Doctrine_manager::getInstance();
	 $clist_conn = $manager->openConnection();
	 
	 $columns = array('phonenumber');
	 
	 $collist = implode(',', $columns);
	 $colifnulllist = implode(',', $columns_ifnull);
	  
	 $sql = "SET NAMES utf8;
			SELECT $collist
	 		UNION
	 		SELECT $colifnulllist INTO OUTFILE '$tmpfile'
				FIELDS TERMINATED BY ',' ENCLOSED BY '\"'
				LINES TERMINATED BY '\\n'
				FROM ".$this->table_name; 
	 $pstatement = $clist_conn->execute($sql);
	 
	 
	 //rename($tmpfile, $localfile);
	 
	 // Adding the file to the Response object
	 $this->getResponse()->clearHttpHeaders();
	 $this->getResponse()->setContentType('text/csv');
	 $this->getResponse()->setHttpHeader('Content-Disposition', 'attachment; filename="'.$filename.'"');
	 $this->getResponse()->sendHttpHeaders();
	 readfile($tmpfile);
	 return sfView::NONE;
  }

  protected function processBlacklistForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
	  $conf_black_list = $form->getObject();
	  
	  if(fonivaFilter::isCurrentUserSuperTenant())
		  $conf_black_list->setTenantFk($form->getValue('tenant_fk'));
	  else
		  $conf_black_list->setTenantFk(fonivaFilter::getCurrentUserTenantId());
	  $conf_black_list->setListname($form->getValue('listname'));
	  $conf_black_list->setDescription($form->getValue('description'));
		  
      $conf_black_list->save();
	  
      $this->redirect('ressource/blacklists');
    }
  }
  
   
  	
  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();
		}
	}
	
	
  } 
  
  private function getcurrentmodule_defaultpage()
  {
	  $searchstring = '';
	  if(isset($this->searchFilter) && $this->searchFilter != NULL && $this->searchFilter != '')
	  	$searchstring = preg_replace('/[^A-Za-z0-9\-]/', '', str_replace(' ', '-', $this->searchFilter));
		
	  $sessionvarname = $this->getModuleName().'_'.$this->getActionName().'_currentpage';
	  $currentpage = $this->getRequestParameter('page', $this->getUser()->getAttribute($sessionvarname, '1'));
	  return $currentpage;
  }
  
  private function setcurrentmodule_defaultpage()
  {
	  $searchstring = '';
	  if(isset($this->searchFilter) && $this->searchFilter != NULL && $this->searchFilter != '')
	  	$searchstring = preg_replace('/[^A-Za-z0-9\-]/', '', str_replace(' ', '-', $this->searchFilter));
		
	  $sessionvarname = $this->getModuleName().'_'.$this->getActionName().'_'.$searchstring.'_currentpage';
	  if($this->getRequestParameter('page') != NULL)
	  	$this->getUser()->setAttribute($sessionvarname, $this->getRequestParameter('page'));  
  }
  

 
}
