<?
/**
 * VoiceOne Webservices Methods
 * 
 * @package voiceone_webservices
 * @subpackage Contacts
 */
//******************************************************************************
//******************           PUBLIC FUNCTIONS            *********************
//******************************************************************************
function getContact($id,$id_user,$strict=0,$number=""){
  global $db;
  $ret=array();
  //set where string
  $where="";
  if((isset($id))&&($id!="")&&($id!=0)) $where="WHERE `id`='".$id."'";
  else if((isset($id_user))&&($id_user!="")&&($id_user!=0)){
    //retireve user type
    $userArr=getUser($id_user);
    if((is_array($userArr))&&($userArr[0]["type"]==USER_STANDARD)){
      $where="WHERE (`id_user`='".$id_user."' "; 
      if($strict==0) $where.="OR `read`='1' ";
      $where.=") ";
    }
  }else if(trim($number)!=""){
    $where="WHERE (`phonenumber`='".$number."' OR `mobile`='".$number."' OR `fax`='".$number."') ";
  }
  //get contacts
  $qry="SELECT * FROM `cw_contacts` ".$where." ORDER BY order_field ";
  $res=$db->Execute($qry);
  if($res===false) return 0;
  while($arr=$res->FetchRow()){
  	//get general settings
    $contact=array(
    	'id'            => $arr["id"],
      'id_user'       => $arr["id_user"],
      'name'          => $arr["name"],
      'surname'       => $arr["surname"],
      'company'       => $arr["company"],
      'email'         => $arr["email"],
      'read'          => $arr["read"],
      'write'         => $arr["write"],
      'phonenumber'   => $arr["phonenumber"],
      'mobile'        => $arr["mobile"],
      'fax'        => $arr["fax"],
      'phonenumber_on_cid' 	=> $arr["phonenumber_on_cid"],
      'mobile_on_cid'    		=> $arr["mobile_on_cid"],
      'fax_on_cid'    		  => $arr["fax_on_cid"],
      'order_by' 						=> $arr["order_by"],
      'cid_name' 						=> $arr["cid_name"],
      'key'						=> $arr["key"]
    );
    //get application settings
    if(($arr['app_phonenumber']!=0)&&(trim($arr['app_phonenumber'])!="")){
    	$app=getApplication($arr['app_phonenumber']);
      if((is_array($app))&&(is_array($app[0]))){
     		$contact['phonenumber_speed_id']=$app[0]["id"];
        $contact['phonenumber_speed_ext']=$app[0]["extension"];
      }else{
      	$contact['phonenumber_speed_id']=0;
        $contact['phonenumber_speed_ext']="";
      }
    }else{
    	$contact['phonenumber_speed_id']=0;
      $contact['phonenumber_speed_ext']="";
    }
	  if(($arr['app_mobile']!=0)&&(trim($arr['app_mobile'])!="")){
    	$app=getApplication($arr['app_mobile']);
      if((is_array($app))&&(is_array($app[0]))){
     		$contact['mobile_speed_id']=$app[0]["id"];
        $contact['mobile_speed_ext']=$app[0]["extension"];
      }else{
      	$contact['mobile_speed_id']=0;
        $contact['mobile_speed_ext']="";
      }
    }else{
    	$contact['mobile_speed_id']=0;
      $contact['mobile_speed_ext']="";
    }
    if(($arr['app_fax']!=0)&&(trim($arr['app_fax'])!="")){
    	$app=getApplication($arr['app_fax']);
      if((is_array($app))&&(is_array($app[0]))){
     		$contact['fax_speed_id']=$app[0]["id"];
        $contact['fax_speed_ext']=$app[0]["extension"];
      }else{
      	$contact['fax_speed_id']=0;
        $contact['fax_speed_ext']="";
      }
    }else{
    	$contact['fax_speed_id']=0;
      $contact['fax_speed_ext']="";
    }
    //get copntact's gropus
    $contact['groups']=getContactGroup(0,$id_user);
    //save in array
    $ret[]=$contact;
  }
  //return
  return $ret;
}
function putContact($contact,$id_user){
  global $db;
  //check speed dial limit
  $new_speed=0;
  if((trim($contact["phonenumber_speed_ext"])!='')&&($contact["phonenumber_speed_id"]<=0)) $new_speed++;
  if((trim($contact["mobile_speed_ext"])!='')&&($contact["mobile_speed_id"]<=0)) $new_speed++;
  if((trim($contact["fax_speed_ext"])!='')&&($contact["fax_speed_id"]<=0)) $new_speed++;
  if($new_speed>0){
    $speed_less=speedDialMaxExceed();
    if($speed_less<$new_speed){
      switch ($speed_less-$new_speed){
        case -1:
          if((trim($contact["fax_speed_ext"])!='')&&($contact["fax_speed_id"]<=0)){
            $contact["fax_speed_ext"]='';
          }else if((trim($contact["mobile_speed_ext"])!='')&&($contact["mobile_speed_id"]<=0)){
            $contact["mobile_speed_ext"]='';
          }else{
            $contact["phonenumber_speed_ext"]='';
          }
          break;
        case -2:
          $assigned=0;
          if((trim($contact["fax_speed_ext"])!='')&&($contact["fax_speed_id"]<=0)){
            $contact["fax_speed_ext"]='';
            $assigned++;
          }
          if((trim($contact["mobile_speed_ext"])!='')&&($contact["mobile_speed_id"]<=0)){
            $contact["mobile_speed_ext"]='';
            $assigned++;
          }
          if($assigned<2){
            $contact["phonenumber_speed_ext"]='';
          }
          break;
        case -3:
        default:
          $contact["fax_speed_ext"]='';
          $contact["mobile_speed_ext"]='';
          $contact["phonenumber_speed_ext"]='';
          break;
      }  
    }
  }
  //set update if contact already exists
  if((isset($contact["id"]))&&($contact["id"]!="")&&($contact["id"]!=0)){
    $id=$contact["id"];
    $ret=delContact($id,$id_user);
    if($ret=0) return 0;
  }else{
    $id="null";
  }
  //reset cid setting for phonenumber, mobile and fax number
  if(($contact["phonenumber_on_cid"]==1)&&(trim($contact["phonenumber"])!="")){
    $qry="UPDATE `cw_contacts` SET `phonenumber_on_cid`=0 WHERE `phonenumber` LIKE '".$contact["phonenumber"]."'";
    $res=$db->Execute($qry);
    $qry="UPDATE `cw_contacts` SET `mobile_on_cid`=0 WHERE `mobile` LIKE '".$contact["phonenumber"]."'";
    $res=$db->Execute($qry);
    $qry="UPDATE `cw_contacts` SET `fax_on_cid`=0 WHERE `fax` LIKE '".$contact["phonenumber"]."'";
  	$res=$db->Execute($qry);
  }
  if(($contact["mobile_on_cid"]==1)&&(trim($contact["mobile"])!="")){
  	$qry="UPDATE `cw_contacts` SET `mobile_on_cid`=0 WHERE `mobile` LIKE '".$contact["mobile"]."'";
  	$res=$db->Execute($qry);
    $qry="UPDATE `cw_contacts` SET `phonenumber_on_cid`=0 WHERE `phonenumber` LIKE '".$contact["mobile"]."'";
  	$res=$db->Execute($qry);
    $qry="UPDATE `cw_contacts` SET `fax_on_cid`=0 WHERE `fax` LIKE '".$contact["mobile"]."'";
  	$res=$db->Execute($qry);
  }
  if(($contact["fax_on_cid"]==1)&&(trim($contact["fax"])!="")){
  	$qry="UPDATE `cw_contacts` SET `fax_on_cid`=0 WHERE `fax` LIKE '".$contact["fax"]."'";
  	$res=$db->Execute($qry);
    $qry="UPDATE `cw_contacts` SET `phonenumber_on_cid`=0 WHERE `phonenumber` LIKE '".$contact["fax"]."'";
  	$res=$db->Execute($qry);
    $qry="UPDATE `cw_contacts` SET `mobile_on_cid`=0 WHERE `mobile` LIKE '".$contact["fax"]."'";
    $res=$db->Execute($qry);
  }
  //check if speeddial has been deleted
  if($id_user>0){
    $user=getUser($id_user);
    if((!is_array($user))||(!is_array($user[0]))) return 0;
    $user=$user[0];
    $user_type=$user["type"];
  }else{
    $user_type=USER_STANDARD;
  }
  /*
  if(trim($contact["phonenumber_speed_ext"])==''){
    $contact["phonenumber_speed_id"]=0;
  }else if($user_type==USER_STANDARD){
    $contact["phonenumber_speed_id"]=0;
    $contact["phonenumber_speed_ext"]='';
  }
  */
  if(($user_type!=USER_STANDARD)&&(trim($contact["phonenumber_speed_ext"])=='')){
    $contact["phonenumber_speed_id"]=0;
  }
  /*
  if(trim($contact["mobile_speed_ext"])==''){
    $contact["mobile_speed_id"]=0;
  }else if($user_type==USER_STANDARD){
    $contact["mobile_speed_id"]=0;
    $contact["mobile_speed_ext"]='';
  }
  */
  if(($user_type!=USER_STANDARD)&&(trim($contact["mobile_speed_ext"])=='')){
    $contact["mobile_speed_id"]=0;
  }
  /*
  if(trim($contact["fax_speed_ext"])==''){
    $contact["fax_speed_id"]=0;
  }else if($user_type==USER_STANDARD){
    $contact["fax_speed_id"]=0;
    $contact["fax_speed_ext"]='';
  }
  */
  if(($user_type!=USER_STANDARD)&&(trim($contact["fax_speed_ext"])=='')){
    $contact["fax_speed_id"]=0;
  }
  //create order field
  if(trim($contact["cid_name"])!="") $old_cid_name=$contact["cid_name"];
  $order_field="";
  if($contact["order_by"]=="name"){
  	$order_field=trim($contact["name"]).trim($contact["surname"]).trim($contact["company"]);
  	//if(trim($contact["cid_name"])==""){
    	if((trim($contact["company"])=="")&&(trim($contact["surname"])=="")){
      	$contact["cid_name"]=substr(trim($contact["name"]),0,254);
     	}else if(trim($contact["company"])==""){
     		$contact["cid_name"]=substr(trim($contact["name"])." ".trim($contact["surname"]),0,254);
      }else if(trim($contact["surname"])==""){
				$contact["cid_name"]=substr(trim($contact["name"])." (".trim($contact["company"]).")",0,254);
      }else{
     		$contact["cid_name"]=substr(trim($contact["name"])." ".trim($contact["surname"])." (".trim($contact["company"]).")",0,254);
      }
    //}  
  }else if($contact["order_by"]=="company"){
  	$order_field=trim($contact["company"]).trim($contact["surname"]).trim($contact["name"]);
  	//if(trim($contact["cid_name"])==""){
     	if((trim($contact["name"])=="")&&(trim($contact["surname"])=="")){
      	$contact["cid_name"]=substr(trim($contact["company"]),0,254);
     	}else if(trim($contact["name"])==""){
     		$contact["cid_name"]=substr(trim($contact["company"])." (".trim($contact["surname"]).")",0,254);
      }else if(trim($contact["surname"])==""){
     		$contact["cid_name"]=substr(trim($contact["company"])." (".trim($contact["name"]).")",0,254);
      }else{
     		$contact["cid_name"]=substr(trim($contact["company"])." (".trim($contact["surname"])." ".trim($contact["name"]).")",0,254);
      }
    //}
  }else{
  	$order_field=trim($contact["surname"]).trim($contact["name"]).trim($contact["company"]);
    //if(trim($contact["cid_name"])==""){
    	if((trim($contact["company"])=="")&&(trim($contact["name"])=="")){
      	$contact["cid_name"]=substr(trim($contact["surname"]),0,254);
     	}else if(trim($contact["company"])==""){
     		$contact["cid_name"]=substr(trim($contact["surname"])." ".trim($contact["name"]),0,254);
      }else if(trim($contact["name"])==""){
				$contact["cid_name"]=substr(trim($contact["surname"])." (".trim($contact["company"]).")",0,254);
      }else{
     		$contact["cid_name"]=substr(trim($contact["surname"])." ".trim($contact["name"])." (".trim($contact["company"]).")",0,254);
      }
    //}
  }
  //insert contacts
  $qry="INSERT INTO `cw_contacts`(`id`,`id_user`,`read`,`write`,`name`,`surname`,`company`,`phonenumber`,";
  $qry.="`mobile`,`fax`,`email`,`app_phonenumber`,`app_mobile`,`app_fax`,`phonenumber_on_cid`,`mobile_on_cid`,";
  $qry.="`fax_on_cid`,`order_by`,`order_field`,`cid_name`,`key`) ";
  $qry.="VALUES (".$id.",'".string2sql($contact["id_user"])."','".string2sql($contact["read"])."','".string2sql($contact["write"])."',";
  $qry.="'".string2sql($contact["name"])."','".string2sql($contact["surname"])."','".string2sql($contact["company"])."',";
  $qry.="'".string2sql($contact["phonenumber"])."','".string2sql($contact["mobile"])."','".string2sql($contact["fax"])."',";
  $qry.="'".string2sql($contact["email"])."','".string2sql($contact["phonenumber_speed_id"])."','".string2sql($contact["mobile_speed_id"])."',";
  $qry.="'".string2sql($contact["fax_speed_id"])."','".string2sql($contact["phonenumber_on_cid"])."','".string2sql($contact["mobile_on_cid"])."',";
  $qry.="'".string2sql($contact["fax_on_cid"])."','".string2sql($contact["order_by"])."','".string2sql(strtolower($order_field))."',";
  $qry.="'".string2sql($contact["cid_name"])."','".string2sql($contact["key"])."'); ";
  $res=$db->Execute($qry);
  if($res===false) return 0;
  if($id=="null") $id=$db->Insert_ID();
  //insert contact in groups
  delContactFromGroup($id,0);
  if(trim($contact["groups"])!=""){
    $groupArr=explode("|",$contact["groups"]);
    if(is_array($groupArr)){
      foreach($groupArr as $group){ 
        putContactInGroup($id,$group);
      }
    }
  }
  //create application for speeddials
  $ret=getMacroByName("reroute");
  if((is_array($ret))&&(is_array($ret[0]))){
  	$macro=$ret[0]["id"];
    //create application for phonenumber
    if((trim($contact["phonenumber_speed_ext"])!="")&&(trim($contact["phonenumber"])!="")){
    	//put application
    	if((trim($contact["phonenumber_speed_id"])!="")&&(trim($contact["phonenumber_speed_id"])!=0)){
      	$speed_id=trim($contact["phonenumber_speed_id"]);
      }else $speed_id="";
      
    	$speed_ext=trim($contact["phonenumber_speed_ext"]);
      $speed_num=$contact["phonenumber"];
      $speed_name="speed_".trim($id)."_phone";
      $entry=array(
          'id'          => $speed_id,
          'name'        => $speed_name,
          'label'       => "Speed_".trim($id)."_phone",
          'description' => "Speed dial for contact ".$contact["surname"]." ".$contact["name"]." (".$contact["company"].") on phonenumber ".$speed_num,
          'extension'   => $speed_ext,
          'code'        => "",
          'macro'       => $macro,
          'parameter'   => "destination=".$speed_num."|rule=",
          'groups'      => array()
      	);
      putApplication($entry);
      //get application id and update contact
      if($speed_id==""){
        $ret=getApplicationByName($speed_name);
        if((is_array($ret))&&(is_array($ret[0]))){
  			  $speed_id=trim($ret[0]["id"]);
        }
      }      
    	$qry="UPDATE `cw_contacts` SET `app_phonenumber`='".$speed_id."' WHERE id='".$id."' ";
      $res=$db->Execute($qry);
  		if($res===false) return 0;
    }
    //create application for mobile
    if((trim($contact["mobile_speed_ext"])!="")&&(trim($contact["mobile"])!="")){
    	//put application
    	if((trim($contact["mobile_speed_id"])!="")&&(trim($contact["mobile_speed_id"])!=0)){
      	$speed_id=trim($contact["mobile_speed_id"]);
      }else $speed_id="";
    	$speed_ext=trim($contact["mobile_speed_ext"]);
      $speed_num=$contact["mobile"];
      $speed_name="speed_".trim($id)."_mobile";
      $entry=array(
          'id'          => $speed_id,
          'name'        => $speed_name,
          'label'       => "Speed_".trim($id)."_mobile",
          'description' => "Speed dial for contact ".$contact["surname"]." ".$contact["name"]." (".$contact["company"].") on mobile ".$speed_num,
          'extension'   => $speed_ext,
          'code'        => "",
          'macro'       => $macro,
          'parameter'   => "destination=".$speed_num."|rule=",
          'groups'      => array()
      	);
      putApplication($entry);
      //get application id and update contact
      if($speed_id==""){
        $ret=getApplicationByName($speed_name);
        if((is_array($ret))&&(is_array($ret[0]))){
    			$speed_id=trim($ret[0]["id"]);
        }
      }
      $qry="UPDATE `cw_contacts` SET `app_mobile`='".$speed_id."' WHERE id='".$id."' ";
      $res=$db->Execute($qry);
  		if($res===false) return 0;
    }
    //create application for fax
    if((trim($contact["fax_speed_ext"])!="")&&(trim($contact["fax"])!="")){
    	//put application
    	if((trim($contact["fax_speed_id"])!="")&&(trim($contact["fax_speed_id"])!=0)){
      	$speed_id=trim($contact["fax_speed_id"]);
      }else $speed_id="";
    	$speed_ext=trim($contact["fax_speed_ext"]);
      $speed_num=$contact["fax"];
      $speed_name="speed_".trim($id)."_fax";
      $entry=array(
          'id'          => $speed_id,
          'name'        => $speed_name,
          'label'       => "Speed_".trim($id)."_fax",
          'description' => "Speed dial for contact ".$contact["surname"]." ".$contact["name"]." (".$contact["company"].") on fax ".$speed_num,
          'extension'   => $speed_ext,
          'code'        => "",
          'macro'       => $macro,
          'parameter'   => "destination=".$speed_num."|rule=",
          'groups'      => array()
      	);
      putApplication($entry);
      //get application id and update contact
      if($speed_id==""){
        $ret=getApplicationByName($speed_name);
        if((is_array($ret))&&(is_array($ret[0]))){
    			$speed_id=trim($ret[0]["id"]);
        }
      }      
    	$qry="UPDATE `cw_contacts` SET `app_fax`='".$speed_id."' WHERE id='".$id."' ";
      $res=$db->Execute($qry);
  		if($res===false) return 0;
    }
  }else return 0;
  //create LDAP entry
  if(function_exists("putLdapContact")){
    $ret=putLdapContact($contact);
    if($ret==0) return 0;
  }
  //create FAX entry
  if(function_exists("addFaxContact")){
    if((trim($contact["fax"])!='')&&(($contact["read"]==1)||($contact["write"]==1))){
      $ret=addFaxContact($id,substr($contact["cid_name"],0,254),$contact["fax"]);
      if($ret==0) return 0;
    }
  }
  //return
	return 1;
}
function delContact($id,$id_user=0){
  global $db;
  //Checks
  if((!isset($id))||($id=="")||($id==0)) return 0;
  //get contact info
  $app_phonenumber=0;
  $app_mobile=0;
  $app_fax=0;
  $contact=getContact($id,$id_user);
  if((is_array($contact))&&(is_array($contact[0]))){
    $contact=$contact[0];
  	$app_phonenumber=$contact['phonenumber_speed_id'];
    $app_mobile=$contact['mobile_speed_id'];
    $app_fax=$contact['fax_speed_id'];
  }
  //delete contact
  if($id_user>0){
    $userArr=getUser($id_user);
    if((is_array($userArr))&&($userArr[0]["type"]!=USER_STANDARD)){
      $where="WHERE `id`=".$id."";
    }else{
      $where="WHERE `id`=".$id." AND (`id_user`='".$id_user."' OR `write`='1')";
    }
  }else{
    $where="WHERE `id`=".$id."";
  }
  
  $qry="DELETE FROM `cw_contacts` ".$where." LIMIT 1";
  $res=$db->Execute($qry);
  if($res===false) return 0; 
  //delete applications
  $q=$db->Affected_Rows();
  if($q==1){
  	if($app_phonenumber!=0) delApplication($app_phonenumber);
  	if($app_mobile!=0) delApplication($app_mobile);
    if($app_fax!=0) delApplication($app_fax);
  }
  //delete LDAP contact
  if(function_exists("delLdapContact")){
    delLdapContact($contact);
  }
  //delete FAX entry
  if(function_exists("delFaxContact")){
    delFaxContact($id);
  }
  //return
  return 1;
}
function getContactIdFromCidName($cid_name,$id_user){
  global $db;
  if((!isset($id_user))||($id_user=="")||($id_user==0)) return 0;
  //retireve user type
  $userArr=getUser($id_user);
  if((is_array($userArr))&&($userArr[0]["type"]==USER_STANDARD)){
    $and="AND (`id_user`='".$id_user."' OR `read`='1' )";
  }
  //verify cid name
  $qry="SELECT id ";
  $qry.="FROM `cw_contacts` ";
  $qry.="WHERE `cid_name`='".addslashes($cid_name)."' ";
  $qry.=$and;
  $qry.="ORDER BY order_field ";
  $res=$db->Execute($qry);
  if($res===false) return 0;
  while($arr=$res->FetchRow()){
    $ret[]=$arr['id'];
  }
  //return
  return $ret;
}
function getContactIndex($id_user,$search){
  global $db;
	//retireve user type and set where string
  $where="";
  if((!isset($id_user))||($id_user=="")||($id_user==0)) return 0;
  $userArr=getUser($id_user);
  if((is_array($userArr))&&($userArr[0]["type"]==USER_STANDARD)){
    $where="WHERE (`id_user`='".$id_user."' OR `read`='1') ";
  }else $where="WHERE 1 ";
  //process filter
  $and_filter="";
  if(trim($search)!=""){
  	$searchArr=explode(" ",$search);
    if(is_array($searchArr)){
      foreach($searchArr as $s){
      	$s=string2sql($s);
      	$and_filter.="AND ( ";
        $and_filter.="LOWER(`name`) LIKE '%".strtolower($s)."%' OR ";
        $and_filter.="LOWER(`surname`) LIKE '%".strtolower($s)."%' OR ";
        $and_filter.="LOWER(`company`) LIKE '%".strtolower($s)."%' OR ";
        $and_filter.="LOWER(`phonenumber`) LIKE '%".strtolower($s)."%' OR ";
        $and_filter.="LOWER(`mobile`) LIKE '%".strtolower($s)."%' ";
       	$and_filter.=") ";
      }
    }
  }
  //get Contacts
  $qry="SELECT LOWER(SUBSTRING(`order_field`,1,1)) as `character`,COUNT(*) as `number` ";
  $qry.="FROM `cw_contacts` ";
  $qry.="".$where." ";
  $qry.="".$and_filter."";
  $qry.="GROUP BY LOWER(SUBSTRING(`order_field`,1,1)) ";
  $qry.="ORDER BY LOWER(SUBSTRING(`order_field`,1,1)) ASC"; 
  $res=$db->Execute($qry);
  if($res===false) return 0;
  while($arr=$res->FetchRow()){
  	$ret[]=array("key"=>$arr["character"],"value"=>$arr["number"]);
  }
  //return
  return $ret;
}
function getContactList($id_user,$starting,$search,$res_num,$page){
  global $db;
	//retireve user type and set where string
  $where="";
  if((!isset($id_user))||($id_user=="")||($id_user==0)) return 0;
  $userArr=getUser($id_user);
  if((is_array($userArr))&&($userArr[0]["type"]==USER_STANDARD)){
    $where="WHERE (`id_user`='".$id_user."' OR `read`='1') ";
  }else $where="WHERE 1 ";
  //process filter
  $and_filter="";
  if(trim($search)!=""){
  	$searchArr=explode(" ",$search);
    if(is_array($searchArr)){
      foreach($searchArr as $s){
      	$s=string2sql($s);
      	$and_filter.="AND ( ";
        $and_filter.="LOWER(`name`) LIKE '%".strtolower($s)."%' OR ";
        $and_filter.="LOWER(`surname`) LIKE '%".strtolower($s)."%' OR ";
        $and_filter.="LOWER(`company`) LIKE '%".strtolower($s)."%' OR ";
        $and_filter.="LOWER(`phonenumber`) LIKE '%".strtolower($s)."%' OR ";
        $and_filter.="LOWER(`mobile`) LIKE '%".strtolower($s)."%' ";
       	$and_filter.=") ";
      }
    }
  }
  //process limit
  if($res_num!=0){
  	if(($page==0)||($page==1)) $limit="LIMIT 0 , ".intval($res_num)." ";
    else $limit="LIMIT ".intval(($page-1)*$res_num)." , ".intval($res_num)." ";
  }
  //process char
  if(trim($starting)!="") $and_char="AND LOWER(SUBSTRING(`order_field`,1,1))='".string2sql(strtolower(substr($starting,0,1)))."' ";
  else $and_char="";
  //get contacts
  $qry="SELECT `id`,`name`,`surname`,`company`,`order_by`,`id_user`,`write`,`phonenumber`,`mobile`,`fax` ";
  $qry.="FROM `cw_contacts` ";
  $qry.="".$where."";
  $qry.="".$and_filter."";
  $qry.="".$and_char."";
  $qry.="ORDER BY `order_field` "; 
  $qry.="".$limit."";
  $res=$db->Execute($qry);
  if($res===false) return 0;
  while($arr=$res->FetchRow()){
    if($arr["order_by"]=="name"){
    	if(trim($arr["company"])!="") $name=$arr["name"]." ".$arr["surname"]." (".$arr["company"].")";
      else $name=$arr["name"]." ".$arr["surname"];
    }else if($arr["order_by"]=="company"){
    	if((trim($arr["surname"])!="")||(trim($arr["name"])!="")) $name=$arr["company"]." (".$arr["surname"]." ".$arr["name"].")";
      else $name=$arr["company"];
    }else{
    	if(trim($arr["company"])!="") $name=$arr["surname"]." ".$arr["name"]." (".$arr["company"].")";
      else $name=$arr["surname"]." ".$arr["name"];
    }
  	$ret[]=array(
    		"id"=>$arr["id"],
        "id_user"=>$arr["id_user"],
        "name"=>$name,
        "write"=>$arr["write"],
        "phonenumber"=>$arr["phonenumber"],
        "mobile"=>$arr["mobile"],
        "fax"=>$arr["fax"]
      );
  }
  //return
  return $ret;
}
function getContactFromPhonenumber($phonenumber){
  global $db;
  //set where string
  $where="";
  if((!isset($phonenumber))||(trim($phonenumber)=="")) return 0;
  //get contacts
  $qry="SELECT * FROM `cw_contacts` WHERE `phonenumber` LIKE '".$phonenumber."' ORDER BY `phonenumber_on_cid` DESC";
  $res=$db->Execute($qry);
  if($res===false) return 0;
  while($arr=$res->FetchRow()){
  	//get general settings
    $contact=array(
    	'id'            => $arr["id"],
      'id_user'       => $arr["id_user"],
      'name'          => $arr["name"],
      'surname'       => $arr["surname"],
      'company'       => $arr["company"],
      'email'         => $arr["email"],
      'read'          => $arr["read"],
      'write'         => $arr["write"],
      'phonenumber'   => $arr["phonenumber"],
      'mobile'        => $arr["mobile"],
      'fax'        => $arr["fax"],
      'phonenumber_on_cid' 	=> $arr["phonenumber_on_cid"],
      'mobile_on_cid'    		=> $arr["mobile_on_cid"],
      'fax_on_cid'    		  => $arr["fax_on_cid"],
      'order_by' 						=> $arr["order_by"],
      'cid_name' 						=> $arr["cid_name"]
    );
    //get application settings
    if(($arr['app_phonenumber']!=0)&&(trim($arr['app_phonenumber'])!="")){
    	$app=getApplication($arr['app_phonenumber']);
      if((is_array($app))&&(is_array($app[0]))){
     		$contact['phonenumber_speed_id']=$app[0]["id"];
        $contact['phonenumber_speed_ext']=$app[0]["extension"];
      }else{
      	$contact['phonenumber_speed_id']=id;
        $contact['phonenumber_speed_ext']="";
      }
    }else{
    	$contact['phonenumber_speed_id']=0;
      $contact['phonenumber_speed_ext']="";
    }
	  if(($arr['app_mobile']!=0)&&(trim($arr['app_mobile'])!="")){
    	$app=getApplication($arr['app_mobile']);
      if((is_array($app))&&(is_array($app[0]))){
     		$contact['mobile_speed_id']=$app[0]["id"];
        $contact['mobile_speed_ext']=$app[0]["extension"];
      }else{
      	$contact['mobile_speed_id']=0;
        $contact['mobile_speed_ext']="";
      }
    }else{
    	$contact['mobile_speed_id']=0;
      $contact['mobile_speed_ext']="";
    }
    if(($arr['app_fax']!=0)&&(trim($arr['app_fax'])!="")){
    	$app=getApplication($arr['app_fax']);
      if((is_array($app))&&(is_array($app[0]))){
     		$contact['fax_speed_id']=$app[0]["id"];
        $contact['fax_speed_ext']=$app[0]["extension"];
      }else{
      	$contact['fax_speed_id']=0;
        $contact['fax_speed_ext']="";
      }
    }else{
    	$contact['fax_speed_id']=0;
      $contact['fax_speed_ext']="";
    }
    //save in array
    $ret[]=$contact;
  }
  //return
  return $ret;
}
function getContactFromMobile($mobile){
  global $db;
  //set where string
  $where="";
  if((!isset($mobile))||(trim($mobile)=="")) return 0;
  //get contacts
  $qry="SELECT * FROM `cw_contacts` WHERE `mobile` LIKE '".$mobile."' ORDER BY `mobile_on_cid` DESC";
  $res=$db->Execute($qry);
  if($res===false) return 0;
  while($arr=$res->FetchRow()){
  	//get general settings
    $contact=array(
    	'id'            => $arr["id"],
      'id_user'       => $arr["id_user"],
      'name'          => $arr["name"],
      'surname'       => $arr["surname"],
      'company'       => $arr["company"],
      'email'         => $arr["email"],
      'read'          => $arr["read"],
      'write'         => $arr["write"],
      'phonenumber'   => $arr["phonenumber"],
      'mobile'        => $arr["mobile"],
      'fax'        => $arr["fax"],
      'phonenumber_on_cid' 	=> $arr["phonenumber_on_cid"],
      'mobile_on_cid'    		=> $arr["mobile_on_cid"],
      'fax_on_cid'    		  => $arr["fax_on_cid"],
      'order_by' 						=> $arr["order_by"],
      'cid_name' 						=> $arr["cid_name"]
    );
    //get application settings
    if(($arr['app_phonenumber']!=0)&&(trim($arr['app_phonenumber'])!="")){
    	$app=getApplication($arr['app_phonenumber']);
      if((is_array($app))&&(is_array($app[0]))){
     		$contact['phonenumber_speed_id']=$app[0]["id"];
        $contact['phonenumber_speed_ext']=$app[0]["extension"];
      }else{
      	$contact['phonenumber_speed_id']=id;
        $contact['phonenumber_speed_ext']="";
      }
    }else{
    	$contact['phonenumber_speed_id']=0;
      $contact['phonenumber_speed_ext']="";
    }
	  if(($arr['app_mobile']!=0)&&(trim($arr['app_mobile'])!="")){
    	$app=getApplication($arr['app_mobile']);
      if((is_array($app))&&(is_array($app[0]))){
     		$contact['mobile_speed_id']=$app[0]["id"];
        $contact['mobile_speed_ext']=$app[0]["extension"];
      }else{
      	$contact['mobile_speed_id']=0;
        $contact['mobile_speed_ext']="";
      }
    }else{
    	$contact['mobile_speed_id']=0;
      $contact['mobile_speed_ext']="";
    }
    if(($arr['app_fax']!=0)&&(trim($arr['app_fax'])!="")){
    	$app=getApplication($arr['app_fax']);
      if((is_array($app))&&(is_array($app[0]))){
     		$contact['fax_speed_id']=$app[0]["id"];
        $contact['fax_speed_ext']=$app[0]["extension"];
      }else{
      	$contact['fax_speed_id']=0;
        $contact['fax_speed_ext']="";
      }
    }else{
    	$contact['fax_speed_id']=0;
      $contact['fax_speed_ext']="";
    }
    //save in array
    $ret[]=$contact;
  }
  //return
  return $ret;
}
function getContactsFromNumber($number){
  $ret=array();
  if(trim($number)!=""){
    $ret=getContact(0,0,0,$number);
  }
  return $ret;
}
function speedDialMaxExceed(){
  global $db,$CONTACT_SPEEDDIAL_LIMIT;
  if($CONTACT_SPEEDDIAL_LIMIT==0) return 100;
  $count=0;
  $qry="( ";
  $qry.="SELECT 'app_phonenumber' AS 'type', COUNT(*) as number ";
  $qry.="FROM `cw_contacts` AS c ";
  $qry.="WHERE c.`app_phonenumber`>0 ";
  $qry.=")UNION( ";
  $qry.="SELECT 'app_mobile' AS 'type', COUNT(*) as number ";
  $qry.="FROM `cw_contacts` AS c ";
  $qry.="WHERE c.`app_mobile`>0 ";    
  $qry.=")UNION( ";
  $qry.="SELECT 'app_fax' AS 'type', COUNT(*) as number ";
  $qry.="FROM `cw_contacts` AS c ";
  $qry.="WHERE c.`app_fax`>0 ";
  $qry.=") ";
  $res=$db->Execute($qry);
  if($res===false) return 0;
  while($arr=$res->FetchRow()){
    $count+=$arr["number"];
  }
  $res=$CONTACT_SPEEDDIAL_LIMIT-$count;
  //return
  return $res; 
}
//******************           Groups of Contacts            *******************
function getContactGroup($id,$id_user){
  global $db;
  if((!isset($id_user))&&($id_user=="")&&($id_user==0)) return 0;
  //set where string
  $where="";
  if((isset($id))&&($id!="")&&($id!=0)) $where="WHERE `id`='".$id."'";
  //get groups of contacts
  $qry="SELECT * FROM `cw_contacts_group` ".$where." ORDER BY `name` ";
  $res=$db->Execute($qry);
  if($res===false) return 0;
  while($arr=$res->FetchRow()){
    $entity=array();
    //get entities
    $qry="SELECT id_contact ";
    $qry.="FROM `cw_contacts_group_entity` AS ge ";
    $qry.="JOIN `cw_contacts` AS c ON c.`id` = ge.`id_contact` ";
    $qry.="WHERE ge.`id_group`='".$arr["id"]."' ";
    $userArr=getUser($id_user);
    if((!is_array($userArr))||($userArr[0]["type"]==USER_STANDARD)){
      $qry.="AND (`id_user`='".$id_user."' OR `read`='1')";
    }
    $res2=$db->Execute($qry);
    if($res2===false) return 0;
    while($c=$res2->FetchRow()) $entity[]=$c["id_contact"];
    $arr["entity"]=$entity;
    $ret[]=$arr;
  }
  //return
  return $ret;
}
function putContactGroup($contactGroup,$id_user){
  global $db;
  if((!isset($id_user))||($id_user=="")||($id_user==0)) return 0;
  //set update if provisioning client already exists
  if((isset($contactGroup["id"]))&&($contactGroup["id"]!="")&&($contactGroup["id"]!=0)){
    $id=$contactGroup["id"];
    delContactGroup($id,$id_user,true);
  }else{
    $id="null";
  }
  //insert provisioning client
  $qry="INSERT INTO `cw_contacts_group`(`id`,`name`) ";
  $qry.="VALUES (".$id.",'".string2sql($contactGroup["name"])."'); ";
  $res=$db->Execute($qry);
  //link contact entities
  if($res===false) return 0;
  else{
    if($id=="null") $id=$db->Insert_ID();
    //insert entities
    if(is_array($contactGroup["entity"])){
      foreach($contactGroup["entity"] as $entity){
        $qry="INSERT INTO `cw_contacts_group_entity`(`id_group`,`id_contact`) ";
        $qry.="VALUES (".$id.",'".$entity."'); ";
        $res=$db->Execute($qry);
        if($res===false) return 0;
      }
    }
  }
  //return
  return 1;
}
function delContactGroup($id,$id_user,$modify=false){
  global $db;
  if((!isset($id_user))||($id_user=="")||($id_user==0)) return 0;
  if((!isset($id))||($id=="")||($id==0)) return 0;
  //Delete permanently
  if($modify===false){
    if(isContactGroupErasable($id,$id_user)!=1) return 0;
    else{
      $qry="DELETE FROM `cw_contacts_group` WHERE `id`=".$id." LIMIT 1";
      $res=$db->Execute($qry);
      if($res===false) return 0; 
      $qry="DELETE FROM `cw_contacts_group_entity` WHERE `id_group`='".$id."' ";
      $res=$db->Execute($qry);
      if($res===false) return 0;
    }
  }
  //Delete before reinsert
  else{
    $qry="DELETE FROM `cw_contacts_group` WHERE `id`=".$id." LIMIT 1";
    $res=$db->Execute($qry);
    if($res!==false){
      //delete group entities related to the user
      $qry="DELETE FROM `cw_contacts_group_entity` ";
      $qry.="WHERE `id_group`='".$id."' ";
      $userArr=getUser($id_user);
      if((!is_array($userArr))||($userArr[0]["type"]==USER_STANDARD)){
        $qry.="AND `id_contact` IN ( ";
        $qry.="SELECT `id` FROM `cw_contacts` "; 
        $qry.="WHERE ( `id_user`='".$id_user."' OR `write`='1' ) ";
        $qry.=")"; 
      }
      $res=$db->Execute($qry);
      if($res===false) return 0;
    }else return 0;
  }
  //return
  return 1;
}
function isContactGroupErasable($id,$id_user){
  global $db;
  $userArr=getUser($id_user);
  if((is_array($userArr))&&($userArr[0]["type"]!=USER_STANDARD)) return 1;
  else{
    $qry="SELECT id_contact ";
    $qry.="FROM `cw_contacts_group_entity` AS ge ";
    $qry.="JOIN `cw_contacts` AS c ON c.`id` = ge.`id_contact` ";
    $qry.="WHERE ge.`id_group`='".$id."' ";
    $qry.="AND (c.`id_user`<>'".$id_user."' AND c.`write`='0')";
    $res=$db->Execute($qry);
    $q=$res->RecordCount();
    if($q==0) return 1;
  }
  //return
  return 0;
}
//******************************************************************************
//*****************           PRIVATE FUNCTIONS            *********************
//******************************************************************************
function putContactInGroup($id_contact,$id_group){
  global $db;
  if((!isset($id_contact))||($id_contact=="")||($id_contact==0)) return 0;
  if((!isset($id_group))||($id_group=="")||($id_group==0)) return 0;
  //verify if contact is already in group
  $qry="SELECT * FROM `cw_contacts_group_entity` WHERE `id_contact`='".$id_contact."' AND `id_group`='".$id_group."' ";
  $res=$db->Execute($qry);
  if($res!==false){
    $q=$res->RecordCount();
    if($q==0){
      $qry="INSERT INTO `cw_contacts_group_entity`(`id_group`,`id_contact`) ";
      $qry.="VALUES ('".$id_group."','".$id_contact."') ";
      $res=$db->Execute($qry);
      if($res===false) return 0;
    }
  }
  //return
  return 1;
}
function delContactFromGroup($id_contact,$id_group){
  global $db;
  if((!isset($id_contact))||($id_contact=="")||($id_contact==0)) return 0;
  if((!isset($id_group))||($id_group=="")||($id_group==0)) $where_group="";
  else $where_group="AND `id_group`='".$id_group."'";
  //verify if contact is already in group
  $qry="DELETE FROM `cw_contacts_group_entity` WHERE `id_contact`='".$id_contact."' ".$where_group." ";
  $res=$db->Execute($qry);
  if($res!==false) return 0;
  return 1;
}
?>