<?php
/* $Id: contact.class.php,v 1.76 2004/07/16 11:17:06 k-fish Exp $ */

class Contact{
	var $templatesAreIn="";

    function opMassUpdate($data){
	global $conn;
	if(is_array($data['cids'])){
	  foreach($data['cids'] as $cid)
	    $cids[] = (int)$cid;

	  // mass update groups
	  if($data['group']!==0){
	    $sql="SELECT id,owner FROM mgw_contacts WHERE id IN(".implode(',',$cids).")";
	    if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	    while($row = $res->FetchRow()){
	      if((($row['owner'] == $_SESSION["MGW"]->userid) &&
		  queryRights2_bool('root_modules_contact_contact_modify'))
		 || queryRights2_bool('root_modules_contact_contact_modifyothers')){
		$sql = 'UPDATE mgw_contacts SET groupid='.(int)$data['group'].' WHERE id='.$row['id'];
		if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	      }
	    }
	  }

	  // mass update action
	  if($data['action']!==0){
	    $sql="SELECT id,owner FROM mgw_contacts WHERE id IN(".implode(',',$cids).")";
	    if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

	    switch($data['action']){
	    case 'delete':
	      while($row = $res->FetchRow()){
		if((($row['owner'] == $_SESSION["MGW"]->userid) &&
		    queryRights2_bool('root_modules_contact_contact_delete'))
		   || queryRights2_bool('root_modules_contact_contact_deleteothers')){
		  $sql = 'DELETE FROM mgw_contacts WHERE id='.$row['id'];
		  if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
		}
	      }
	      break;
	    case 'private':
	      while($row = $res->FetchRow()){
		if((($row['owner'] == $_SESSION["MGW"]->userid) &&
		    queryRights2_bool('root_modules_contact_contact_modify'))
		   || queryRights2_bool('root_modules_contact_contact_modifyothers')){
		  $sql = 'UPDATE mgw_contacts SET ispublic=0 WHERE id='.$row['id'];
		  if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
		}
	      }
	      break;
	    case 'public':
	      while($row = $res->FetchRow()){
		if((($row['owner'] == $_SESSION["MGW"]->userid) &&
		    queryRights2_bool('root_modules_contact_contact_modify'))
		   || queryRights2_bool('root_modules_contact_contact_modifyothers')){
		  $sql = 'UPDATE mgw_contacts SET ispublic=1 WHERE id='.$row['id'];
		  if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
		}
	      }
	    }
	  }
	  return true;
	}
	return false;
    }

    // =================================================
    // create item
    // =================================================
    function opCreate(){
	global $conn;

	queryRights2('root_modules_contact_contact_create');

	$id = mgw_genID('mgw__seq_contacts');

	$title = $conn->QMagic(isset($_POST["title"])?$_POST["title"]:"");
	$honpref = $conn->QMagic(isset($_POST["honpref"])?$_POST["honpref"]:"");
	$firstname = $conn->QMagic(isset($_POST["firstname"])?$_POST["firstname"]:"");
	$name_add = $conn->QMagic(isset($_POST["addname"])?$_POST["addname"]:"");
	$nickname = $conn->QMagic(isset($_POST["nickname"])?$_POST["nickname"]:"");
	$lastname = $conn->QMagic(isset($_POST["lastname"])?$_POST["lastname"]:"");
	$name_suffix = $conn->QMagic(isset($_POST["namesuffix"])?$_POST["namesuffix"]:"");

	$street = $conn->QMagic(isset($_POST["priv_strasse"])?$_POST["priv_strasse"]:"");
	$add = $conn->QMagic(isset($_POST["priv_zusatz"])?$_POST["priv_zusatz"]:"");
	$zip = $conn->QMagic(isset($_POST["priv_plz"])?$_POST["priv_plz"]:"");
	$city = $conn->QMagic(isset($_POST["priv_ort"])?$_POST["priv_ort"]:"");
	$state = $conn->QMagic(isset($_POST["priv_state"])?$_POST["priv_state"]:"");
	$country = $conn->QMagic(isset($_POST["priv_country"])?$_POST["priv_country"]:"");
	$region = $conn->QMagic(isset($_POST["priv_region"])?$_POST["priv_region"]:"");

	$priv_phone = $conn->QMagic(isset($_POST["telefon_privat"])?$_POST["telefon_privat"]:"");
	$fax = $conn->QMagic(isset($_POST["telefax"])?$_POST["telefax"]:"");
	$email = $conn->QMagic(isset($_POST["email"])?$_POST["email"]:"");
	$email2 = $conn->QMagic(isset($_POST["email2"])?$_POST["email2"]:"");
	$email3 = $conn->QMagic(isset($_POST["email3"])?$_POST["email3"]:"");
	$comp_phone = $conn->QMagic(isset($_POST["telefon_firma"])?$_POST["telefon_firma"]:"");
	$mobile = $conn->QMagic(isset($_POST["telefon_mobil"])?$_POST["telefon_mobil"]:"");
	$url = $conn->QMagic(isset($_POST["url"])?$_POST["url"]:"");

	$function = $conn->QMagic(isset($_POST["function"])?$_POST["function"]:"");
	if(isset($_POST['setbirthday']) and (int) $_POST['setbirthday'] == 1){
	    $bday = isset($_POST["birthdayDay"])?(int) $_POST["birthdayDay"]:0;
	    $bmonth = isset($_POST["birthdayMonth"])?(int) $_POST["birthdayMonth"]:0;
	    $byear = isset($_POST["birthdayYear"])?(int) $_POST["birthdayYear"]:0;
	    $bday = $conn->DBDate(sprintf("%04d-%02d-%02d",$byear,$bmonth,$bday));
	}
	else{
	    $bday = 'null';
	}
	$note = $conn->QMagic(isset($_POST["bemerkung"])?$_POST["bemerkung"]:"");
	$pubkey = $conn->QMagic(isset($_POST["pubkey"])?$_POST["pubkey"]:"");
	$group = isset($_POST["_group"])?(int) $_POST["_group"]:0;
	$public = isset($_POST["public"])?(int) $_POST["public"]:0;

	$company = isset($_POST["_company"])?(int) $_POST["_company"]:0;
	$newcomp = isset($_POST["newcomp"])?$_POST["newcomp"]:"";
	if($company==0 && $newcomp!=''){
	    $company = Company::opCreate(array('name1' => $newcomp));
	}

	$sql="INSERT INTO mgw_contacts (id, title, honorific_prefix, firstname, name_add, nickname, lastname, name_suffix, priv_street, priv_additional, priv_zip, priv_city, priv_state, priv_countrycode, priv_region, priv_telefon, priv_fax, email, email2, email3, tel_company, tel_mobile, url, function, birthday, note, publicKey, companyid, groupid, ispublic, owner, lu_user, lu_date) VALUES ($id, $title, $honpref, $firstname, $name_add, $nickname, $lastname, $name_suffix, $street, $add, $zip, $city, $state, $country, $region, $priv_phone, $fax, $email, $email2, $email3, $comp_phone, $mobile, $url, $function, $bday, $note, $pubkey, $company, $group, $public, ".$_SESSION["MGW"]->userid.", ".$_SESSION["MGW"]->userid.", ".$conn->DBTimeStamp(time()).")";

	if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

	if($_POST['_company'] != $company){
	    Company::viewEditForm($company);
	    Company::display('contact_comp_edit.tpl');
	    exit();
	}
	else return true;
    }

    // =================================================
    // update item
    // =================================================
    function opUpdate(){
	global $conn;

	if(isset($_POST["id"]))
	    $id = (int) $_POST["id"];
	else
	    return false;

	$sql="SELECT owner FROM mgw_contacts WHERE id=$id";
	if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	$row = $res->FetchRow();
	
	if($row['owner'] == $_SESSION["MGW"]->userid)
	    queryRights2('root_modules_contact_contact_modify');
	else
	    queryRights2('root_modules_contact_contact_modifyothers');

	$title = $conn->QMagic(isset($_POST["title"])?$_POST["title"]:"");
	$honpref = $conn->QMagic(isset($_POST["honpref"])?$_POST["honpref"]:"");
	$firstname = $conn->QMagic(isset($_POST["firstname"])?$_POST["firstname"]:"");
	$name_add = $conn->QMagic(isset($_POST["addname"])?$_POST["addname"]:"");
	$nickname = $conn->QMagic(isset($_POST["nickname"])?$_POST["nickname"]:"");
	$lastname = $conn->QMagic(isset($_POST["lastname"])?$_POST["lastname"]:"");
	$name_suffix = $conn->QMagic(isset($_POST["namesuffix"])?$_POST["namesuffix"]:"");

	$street = $conn->QMagic(isset($_POST["priv_strasse"])?$_POST["priv_strasse"]:"");
	$add = $conn->QMagic(isset($_POST["priv_zusatz"])?$_POST["priv_zusatz"]:"");
	$zip = $conn->QMagic(isset($_POST["priv_plz"])?$_POST["priv_plz"]:"");
	$city = $conn->QMagic(isset($_POST["priv_ort"])?$_POST["priv_ort"]:"");
	$state = $conn->QMagic(isset($_POST["priv_state"])?$_POST["priv_state"]:"");
	$country = $conn->QMagic(isset($_POST["priv_country"])?$_POST["priv_country"]:"");
	$region = $conn->QMagic(isset($_POST["priv_region"])?$_POST["priv_region"]:"");

	$priv_phone = $conn->QMagic(isset($_POST["telefon_privat"])?$_POST["telefon_privat"]:"");
	$fax = $conn->QMagic(isset($_POST["telefax"])?$_POST["telefax"]:"");
	$email = $conn->QMagic(isset($_POST["email"])?$_POST["email"]:"");
	$email2 = $conn->QMagic(isset($_POST["email2"])?$_POST["email2"]:"");
	$email3 = $conn->QMagic(isset($_POST["email3"])?$_POST["email3"]:"");
	$comp_phone = $conn->QMagic(isset($_POST["telefon_firma"])?$_POST["telefon_firma"]:"");
	$mobile = $conn->QMagic(isset($_POST["telefon_mobil"])?$_POST["telefon_mobil"]:"");
	$url = $conn->QMagic(isset($_POST["url"])?$_POST["url"]:"");

	$function = $conn->QMagic(isset($_POST["function"])?$_POST["function"]:"");
	if(isset($_POST['setbirthday']) and (int) $_POST['setbirthday'] == 1){
	    $bday = (int) $_POST["birthdayDay"];
	    $bmonth = (int) $_POST["birthdayMonth"];
	    $byear = (int) $_POST["birthdayYear"];
	    $bday = $conn->DBDate(sprintf("%04d-%02d-%02d",$byear,$bmonth,$bday));
	}
	else{
	    $bday = 'null';
	}
	$note = $conn->QMagic(isset($_POST["bemerkung"])?$_POST["bemerkung"]:"");
	$pubkey = $conn->QMagic(isset($_POST["pubkey"])?$_POST["pubkey"]:"");
	$group = isset($_POST["_group"])?(int) $_POST["_group"]:0;

	$public = isset($_POST["public"])?(int) $_POST["public"]:0;

	$company = isset($_POST["_company"])?(int) $_POST["_company"]:0;
	$newcomp = isset($_POST["newcomp"])?$_POST["newcomp"]:"";
	if($company==0 && $newcomp!=''){
	    $company = Company::opCreate(array('name1' => $newcomp));
	}

	$sql="UPDATE mgw_contacts SET title=$title, honorific_prefix=$honpref, firstname=$firstname, name_add=$name_add, nickname=$nickname, lastname=$lastname, name_suffix=$name_suffix, priv_street=$street, priv_additional=$add, priv_zip=$zip, priv_city=$city, priv_state=$state, priv_countrycode=$country, priv_region=$region, priv_telefon=$priv_phone, priv_fax=$fax, email=$email, email2=$email2, email3=$email3, tel_company=$comp_phone, tel_mobile=$mobile, url=$url, function=$function, birthday=$bday, note=$note, publicKey=$pubkey, companyid=$company, groupid=$group, ispublic=$public, lu_user=".$_SESSION["MGW"]->userid.", lu_date=".$conn->DBTimeStamp(time())." WHERE (ispublic=1 or owner=".$_SESSION["MGW"]->userid.") and id=$id";

	if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

	if($_POST['_company'] != $company){
	    Company::viewEditForm($company);
	    exit();
	}
	else return true;
    }

    function opDelete($id){
	global $conn;

	$sql="SELECT owner FROM mgw_contacts WHERE id=$id";
	if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	$row = $res->FetchRow();
	if($row['owner'] == $_SESSION["MGW"]->userid)
	    queryRights2('root_modules_contact_contact_delete');
	else
	    queryRights2('root_modules_contact_contact_deleteothers');

	$sql = "DELETE FROM mgw_contacts WHERE (ispublic=1 or owner=".$_SESSION["MGW"]->userid.") and id=".(int)$id;
	if(!$conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	return true;
    }

    function viewDelete($id){
	global $smarty, $conn, $appconf;

	$sql = "SELECT * FROM mgw_contacts WHERE (ispublic=1 or owner=".$_SESSION["MGW"]->userid.") and id=".(int)$id;
	if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	$row = $res->FetchRow();

	if($row['owner'] == $_SESSION["MGW"]->userid)
	    queryRights2('root_modules_contact_contact_delete');
	else
	    queryRights2('root_modules_contact_contact_deleteothers');
		
	$smarty->assign("menuid", "1");
	$smarty->assign("itemid", $id);
	$smarty->assign("parms", str_replace("delete","list",$_SERVER["QUERY_STRING"]));
	$smarty->assign("reallydeleteitem", Lang::getLanguageString("reallydelcontact"));
	$smarty->assign("deleteheader", Lang::getLanguageString("deletecontacth"));
	$smarty->assign("deletedetail1", $row["lastname"].", " .$row["firstname"]);
	$smarty->assign("deletedetail2", $row["priv_street"]);
	$smarty->assign("deletedetail3", $row["priv_city"]);
	$smarty->assign("suclass", "submit");		
	return true;
    }

    // =================================================
    // new item form
    // =================================================
    function viewNewForm(){
	global $conn, $smarty;
	queryRights2('root_modules_contact_contact_create');

	include(INCLUDEPATH . "mSelectBox.class.php");

	$sb = new mSelectBox("bday");
	$smarty->assign("bday", $sb->getSB_Day(0, true));

	$sb2 = new mSelectBox("bmonth");
	$smarty->assign("bmonth", $sb2->getSB_Month(0, true));

	$sb3 = new mSelectBox("byear");
	$smarty->assign("byear", $sb3->getSB_Year(1920, date("Y"), 0, true));

	$sb4 = new mSelectBox("title");
	$smarty->assign("title", $sb4->getSB_Title());

	$sb5 = new mSelectBox("_company");
	$sb5->setContentType("sql");
	$sb5->setSQLvalue("id");
	$sb5->setSQLcontent("name1");
	$sb5->addContent("SELECT * FROM mgw_companies WHERE (ispublic=1 or owner=".$_SESSION["MGW"]->userid.") ORDER BY name1");
	$sb5->addOption("0", Lang::getLanguageString("chosecompanytext"), "pre");
	$smarty->assign("companysb", $sb5->draw());

	$sb6 = new mSelectBox("_group");
	$sb6->setContentType("sql");
	$sb6->setSQLvalue("id");
	$sb6->setSQLcontent("name_key");
	$sb6->addContent("SELECT id, name_key FROM mgw_contacts_groups ORDER BY name_key");
	$sb6->addOption("0", Lang::getLanguageString("chosegrouptext"), "pre");
	$smarty->assign("groupsb", $sb6->draw());

	$smarty->assign("countrysb", createCountrySB("priv_country"));
	$smarty->assign("npage",isset($_GET["npage"])?$_GET["npage"]:"");
	$smarty->assign("pubcheckedyes"," checked");
	$smarty->assign("mode","new");
	$smarty->assign("suname","create");
	$smarty->assign("suclass","submit");
	
	if (isset($_GET["wm2_contact"]) and $_GET["wm2_contact"]) {
	  $wm2_td = array();

	  $data = trim(str_replace(array("&lt;","&gt;"),array("<",">"),$_GET["wm2_contact"]));
	  if (eregi("<(.*)>",$data,$my_array) and is_array($my_array) and count($my_array)>0) {
	    $wm2_td["email"] = $my_array[1];

  	    $wm2_name = trim(str_replace(array("\"","'"),"",strip_tags($data)));
	    $wm2_td["lastname"] = $wm2_name;
	  
	    if (strlen($wm2_name)>2 and strpos($wm2_name,",")>0) {
	      $wm2_td["firstname"] = trim(substr($wm2_name,strpos($wm2_name,",")+1));
		  $wm2_td["lastname"] = trim(substr($wm2_name,0,strpos($wm2_name,",")));
	    } elseif (strlen($wm2_name)>2 and strpos($wm2_name," ")>0) {
		  $wm2_td["firstname"] = trim(substr($wm2_name,0,strrpos($wm2_name," ")));
	      $wm2_td["lastname"] = trim(substr($wm2_name,strrpos($wm2_name," ")+1));
	    }
	  } elseif (eregi("\"(.*) (.*)\" (.*)",$data,$my_array) and is_array($my_array) and count($my_array)>2) {
	    if ($my_array[1][0]=="'") {
		  $wm2_td["lastname"] = substr($my_array[1],1);
		  $wm2_td["firstname"] = substr($my_array[2],0,-1);
		} else {
		  $wm2_td["firstname"] = $my_array[1];
		  $wm2_td["lastname"] = $my_array[2];
		}
		$wm2_td["email"] = $my_array[3];
	  } elseif (eregi("(.*) \\((.*) (.*)\\)",$data,$my_array) and is_array($my_array) and count($my_array)>2) {
		$wm2_td["lastname"] = $my_array[3];
		$wm2_td["firstname"] = $my_array[2];
		$wm2_td["email"] = $my_array[1];
	  } else {
	    if (!strpos($data,"@")) {
	      $wm2_td["lastname"] = $data;
		} else {
	      $wm2_td["email"] = $data;
		}
	  }
	  $smarty->assign("td", $wm2_td);
	}

	return true;
    }

    // =================================================
    // edit item form
    // =================================================
    function viewEditForm($id){
	global $conn, $smarty;

	$sql="SELECT owner FROM mgw_contacts WHERE id=$id";
	if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	$row = $res->FetchRow();

	if($row['owner'] == $_SESSION["MGW"]->userid)
	    queryRights2('root_modules_contact_contact_modify');
	else
	    queryRights2('root_modules_contact_contact_modifyothers');

	include(INCLUDEPATH . "mSelectBox.class.php");
	$sql = "SELECT * FROM mgw_contacts WHERE (ispublic=1 or owner=".$_SESSION["MGW"]->userid.") and id=".(int)$id;
	
	if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	$row = $res->FetchRow();

	$row['birthday'] = $conn->UnixDate($row['birthday']);
	$smarty->assign('setbirthday', (!$row['birthday']) ? '' : 'checked');

	$sb4 = new mSelectBox("title");
	$smarty->assign("title", $sb4->getSB_Title($row["title"]));

	$sb5 = new mSelectBox("_company");
	$sb5->setContentType("sql");
	$sb5->setSQLvalue("id");
	$sb5->setSQLcontent("name1");
	$sb5->addContent("SELECT * FROM mgw_companies WHERE (ispublic=1 or owner=".$_SESSION["MGW"]->userid.") ORDER BY name1");
	$sb5->addOption("0", Lang::getLanguageString("nocompany"), "pre");
	$smarty->assign("companysb", $sb5->draw($row["companyid"]));

	$sb6 = new mSelectBox("_group");
	$sb6->setContentType("sql");
	$sb6->setSQLvalue("id");
	$sb6->setSQLcontent("name_key");
	$sb6->addContent("SELECT id, name_key FROM mgw_contacts_groups ORDER BY name_key");
	$sb6->addOption("0", Lang::getLanguageString("chosegrouptext"), "pre");
	$smarty->assign("groupsb", $sb6->draw($row["groupid"]));

	$smarty->assign("countrysb", createCountrySB("priv_country", $row["priv_countrycode"]));

	$smarty->assign("list", isset($_GET["list"])?$_GET["list"]:"");
	$smarty->assign("npage",isset($_GET["npage"])?$_GET["npage"]:0);
	$smarty->assign("searchterm", isset($_GET["searchterm"])?$_GET["searchterm"]:"");
	$smarty->assign("itemid", $id);
	
	$smarty->assign("td", $row);
	$smarty->assign("myurl", $row["url"]);
	$smarty->assign("suname","edit");
	$smarty->assign("suclass","submit");
	$smarty->assign("mode","edit");

	if($row["ispublic"]=="1") {
	    $pcy = " checked";
	    $pcn = "";
	} 
	else {
	    $pcy = "";
	    $pcn = " checked";
	}
	$smarty->assign("pubcheckedyes",$pcy);
	$smarty->assign("pubcheckedno",$pcn);

	$smarty->assign("editcontact", Lang::getParmLang(Lang::getLanguageString("editcontact"), array($row["lastname"] . ", " . $row["firstname"])));

	return true;
    }

    // =================================================
    // detail view
    // =================================================
    function viewDetails($id){
	global $conn, $appconf, $smarty;
	include(INCLUDEPATH . "mSelectBox.class.php");

	$sql = "SELECT a.*, b.id, b.name_key AS groupname FROM mgw_contacts a LEFT JOIN mgw_contacts_groups b ON a.groupid = b.id WHERE (a.ispublic=1 or a.owner=".$_SESSION["MGW"]->userid.") and a.id=".(int)$id;
	if(($row = $conn->GetRow($sql)) === false) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

	// modify only for user with appropriate rights
	if((queryRights2_bool('root_modules_contact_contact_modify') && $row["owner"] == $_SESSION["MGW"]->userid) ||
	   (queryRights2_bool('root_modules_contact_contact_modifyothers') && $row["owner"] != $_SESSION["MGW"]->userid))
	    $smarty->assign("maymod","yes");
	else
	    $smarty->assign("maymod","no");

	// delete only for user with appropriate rights
	if((queryRights2_bool('root_modules_contact_contact_delete') && $row["owner"] == $_SESSION["MGW"]->userid) ||
	   (queryRights2_bool('root_modules_contact_contact_deleteothers') && $row["owner"] != $_SESSION["MGW"]->userid))
		$smarty->assign("maydel","yes");
	else
		$smarty->assign("maydel","no");

	$sql2 = "SELECT name AS country FROM mgw_countries WHERE code='".$row['priv_countrycode']."'";
	if(($row2 = $conn->GetRow($sql2)) === false) exit(showSQLerror($sql2, $conn->ErrorMsg(), __LINE__, __FILE__));
	$row["priv_country"] = $row2['country'];

	$sql3 = "SELECT name1, telephone, email AS email_company FROM mgw_companies WHERE 
(ispublic=1 or owner=".$_SESSION["MGW"]->userid.") and id=".(int)$row['companyid'];
	if(($row3 = $conn->GetRow($sql3)) === false) exit(showSQLerror($sql3, $conn->ErrorMsg(), __LINE__, __FILE__));
	$row = array_merge($row, $row3);

	$row['title'] = Lang::getLanguageString($row['title']);

	$row["birthday"] = $conn->UnixDate($row["birthday"]);

	$row["note"] = nl2br($row["note"]);
	$row["publicKey"] = nl2br($row["publicKey"]);

	$row["email"] = linkEmail($row["email"]);
	$row["email2"] = linkEmail($row["email2"]);
	$row["email3"] = linkEmail($row["email3"]);

	if ($row["tel_company"] == "") $row["tel_company"] = $row["telephone"];
	if ($row["email"] == "") $row["email"] = $row["email_company"];

	$smarty->assign("usedialer", $_SESSION['MGW']->settings['use_dialer']);
	$smarty->assign("sort", isset($_GET["sort"])?$_GET["sort"]:"");
	$smarty->assign("list", isset($_GET["list"])?$_GET["list"]:"");
	$smarty->assign("searchterm", isset($_GET["searchterm"])?$_GET["searchterm"]:"");
	$smarty->assign("npage", isset($_GET["npage"])?$_GET["npage"]:"");
	$smarty->assign("id", $id);
	$smarty->assign("td", $row);
	$smarty->assign("suname","edit");
	$smarty->assign("suvalue","Speichern");
	$smarty->assign("suclass","submit");
	$smarty->assign("contentheader", Lang::getLanguageString("details"));
	return true;
    }

    // =================================================
    // vCard import
    // =================================================
    function viewCardImport(){
	global $smarty;
	include(INCLUDEPATH . "mSelectBox.class.php");
	queryRights2('root_modules_contact_contact_create');

	$smarty->assign("suvalue",Lang::getLanguageString("import"));
	$smarty->assign("suname","import");
	$smarty->assign("suclass","submit");
	
	return true;
    }

    function opCardImport($userfile){
	global $conn;
	include_once(INCLUDEPATH . "vcard/mgw_Contact_Vcard_Parse.php");
	queryRights2('root_modules_contact_contact_create');

	if (is_uploaded_file($userfile["tmp_name"])) {
	    $tmpfile = CACHE_FOLDER.basename($userfile["tmp_name"]);
	    move_uploaded_file($userfile["tmp_name"], $tmpfile);

	    $vcard = new mgw_Contact_Vcard_Parse();
	    $cards = $vcard->fromFile($tmpfile);
	    unlink($tmpfile);
	    // now loop through the data
	    $counter = 0;
	    for($vccount=0; $vccount<count($cards); $vccount++){
		$card = $cards[$vccount];

		if($vcard->getOrg($card) != ''){
		    // check if we have a matching company
		    $sql = "SELECT id FROM mgw_companies WHERE (ispublic=1 or owner=".$_SESSION["MGW"]->userid.") and name1=".$conn->quote($vcard->getOrg($card))." AND name2=".$conn->quote($vcard->getSubOrg($card));
		    $row = $conn->GetRow($sql);
		    if(is_array($row) && (count($row) > 0)){
			$companyid = $row['id'];
		    }
		    else{

			$sql="INSERT INTO mgw_companies (id, name1, name2, street, additional, zip, city, state, ispublic, owner,  lu_user, lu_date) VALUES (";

			$companyid = mgw_genID('mgw__seq_companies');
			$sql .= $companyid.','.
			    $conn->quote($vcard->getOrg($card)).','.
			    $conn->quote($vcard->getSubOrg($card)).',';

			$cadr = $vcard->getAddress($card, 'WORK');
			if(is_array($cadr[0])){
			    $sql .=
				$conn->quote($vcard->getStreet($cadr[0])).",".
				$conn->quote($vcard->getExtAdr($cadr[0])).",".
				$conn->quote($vcard->getZIP($cadr[0])).",".
				$conn->quote($vcard->getLocality($cadr[0])).",".
				$conn->quote($vcard->getRegion($cadr[0])).",\n";
			}
			else{
			    $sql .= "'','','','','',\n";
			}

			$sql .= (int)$_POST['ispublic'].", ".$_SESSION["MGW"]->userid.", ".$_SESSION["MGW"]->userid.", ". $conn->DBTimeStamp(time()). ")";

			if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
		    }
		}
		else $companyid = 'NULL';

		//insert data into db
		$id = mgw_genID('mgw__seq_contacts');

		//title,honorific_prefix,companyid?!?
		$sql = "INSERT INTO mgw_contacts (id,
                            name_prefix,firstname,name_add,lastname,name_suffix,nickname,
                            priv_street,priv_additional,priv_zip,priv_city,priv_region,
                            priv_telefon,priv_fax,email,email2,email3,tel_company,tel_mobile,
                            url,birthday,function,note,companyid,
                            owner,ispublic,lu_user,lu_date)";
		$sql .= " VALUES ($id,".
		    $conn->quote($vcard->getNamePrefixes($card)).",".
		    $conn->quote($vcard->getGivenNames($card)).",".
		    $conn->quote($vcard->getAddNames($card)).",".
		    $conn->quote($vcard->getLastNames($card)).",".
		    $conn->quote($vcard->getNameSuffixes($card)).",".
		    $conn->quote($vcard->getNicknames($card)).",\n";
		$adr = $vcard->getAddress($card, 'HOME');
		if(is_array($adr[0])){
		    $sql .=
			$conn->quote($vcard->getStreet($adr[0])).",".
			$conn->quote($vcard->getExtAdr($adr[0])).",".
			$conn->quote($vcard->getZIP($adr[0])).",".
			$conn->quote($vcard->getLocality($adr[0])).",".
			$conn->quote($vcard->getRegion($adr[0])).",\n";
		}
		else{
		    $sql .= "'','','','','',\n";
		}
		$hp = $vcard->getPhone($card, 'HOME,VOICE');
		$wp = $vcard->getPhone($card, 'WORK,VOICE');
		$hf = $vcard->getPhone($card,'HOME,FAX');
		$emails = $vcard->getEmail($card);
		$sql .=
		    $conn->quote($hp[0]).",".
		    $conn->quote($hf[0]).",".
		    $conn->quote($emails[0]).",".
		    $conn->quote($emails[1]).",".
		    $conn->quote($emails[2]).",".
		    $conn->quote($wp[0]).",\n";
		$mobiles = $vcard->getPhone($card,'CELL');
		$sql .=
		    $conn->quote($mobiles[0]).",";
		$urls = $vcard->getURL($card);
		$sql .=
		    $conn->quote($urls[0]).",".
		    $conn->DBDate($vcard->getBirthday($card)).",".
		    $conn->quote($vcard->getTitle($card)).",".
		    $conn->quote($vcard->getNote($card)).",$companyid,";
		$sql .=
		    $_SESSION['MGW']->userid.",".(int)$_POST['ispublic'].",".$_SESSION['MGW']->userid.",".$conn->DBTimeStamp(time()).")";
		
		if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
		$counter++;
	    }
	}

	$GLOBALS['notify']->message(Lang::getLanguageString('importedvcards').': '.$counter, NOTIFY_SCREEN);
    }

    // =================================================
    // vCard export
    // =================================================
    function viewCardExport($id){
	global $conn;
	include_once(INCLUDEPATH . "vcard/vcard.php");
	queryRights2('root_modules_contact_contact_export');

	if($id == -1){
	    $sql = "SELECT id FROM mgw_contacts WHERE owner=".$_SESSION["MGW"]->userid." OR ispublic=1 ORDER BY lastname";
	    if(!$res = $conn->Execute($sql)) exit(showSQLError($sql, $conn->ErrorString(), __LINE__, __FILE__));
	    while($row = $res->FetchRow()){
		$vcard = new VCard($row["id"]);
		$vcstr .= $vcard->getString()."\n";
		unset($vcard);
	    }
	    $fname = "mgw-contacts";
	}
	else{
	    $vcard = new VCard($id);
	    $vcstr = $vcard->getString();
	    $fname = $vcard->getLastName();
	}

	header("Content-Type: text/x-vcard");
	header("Content-Length: ".strlen($vcstr));
	header("Content-Disposition: attachment; filename=".$fname.".vcf");
	header("Content-Transfer-Encoding: 7bit");
	header("Content-Description: vcard-export");
	echo $vcstr;

	return true;
    }

    // =================================================
    // email list view
    // =================================================
    function viewEmailList(){
	global $smarty, $conn;

	$concat = $conn->Concat("a.firstname","' '","a.name_add");
	$sql = "SELECT a.lastname, $concat AS firstname, b.name1 FROM mgw_contacts a LEFT JOIN mgw_companies b ON a.companyid=b.id WHERE (a.ispublic=1 or a.owner=".$_SESSION["MGW"]->userid.") and a.email<>'' ORDER BY lastname";
	if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

	while($row = $res->FetchRow()) {
	    $smarty->append("td",$row);

	    // build action urls
	    $detlink = "<a href=\"javascript:setOpenerValue('" . $row[$toShowValue] . "','" . $row[$toSelectValue] . "')\" class=\"edit\">".Lang::getLanguageString("Auswahl")."</a>";
	    $urls[] = $detlink;
	    $smarty->assign('urls', $urls);
	}

	$smarty->assign("fieldname", $fieldName);
	$smarty->assign('at', alphabet_table(session_id()));

	return true;
    }

    // =================================================
    // PDF export
    // =================================================
    function viewPDFExport(){
	global $smarty;
	include(INCLUDEPATH . "mSelectBox.class.php");
	queryRights2('root_modules_contact_contact_export');

	$sb1 = new mSelectBox("_company");
	$sb1->setMultiple(true);
	$sb1->setContentType("sql");
	$sb1->setSQLvalue("id");
	$sb1->setSQLcontent("name1");
	$sb1->addContent("SELECT * FROM mgw_companies WHERE (ispublic=1 or owner=".$_SESSION["MGW"]->userid.") ORDER BY name1");
	$sb1->setHeight(8);
	$smarty->assign("companysb", $sb1->draw());

	$sb2 = new mSelectBox("_lang");
	$sb2->setContentType("sql");        
	$sb2->setSQLvalue("langcode");     
	$sb2->setSQLcontent("description");        
	$sb2->addContent("SELECT * FROM mgw_languages ORDER BY lu_date");        
	$smarty->assign("langsb",$sb2->draw($_SESSION["MGW"]->spkz));

	$smarty->assign("suname","print");
	$smarty->assign("suclass","submit");
	$smarty->assign("cmpallcheck", "checked");
	$smarty->assign("cmpsavcheck", "checked");

	return true;
    }

    function opPDFExport(){
	global $conn, $appconf;
	define("FPDF_FONTPATH", INCLUDEPATH . "fpdf/font/");
	include_once(INCLUDEPATH . "fpdf/fpdf.php");
	include_once(ROOTPATH . "/modules/contact/inc/pdf.class.php");
	queryRights2('root_modules_contact_contact_export');

	$pdf=new PDF("L");
	$pdf->hashmaploc = Lang::setLocaledText(isset($_POST["_lang"])?str_replace(array("\\","/"),"",$_POST["_lang"]):"", "contact");
	$pdf->Open();
	$pdf->SetAuthor($_SESSION["MGW"]->fullusername);
	$pdf->SetTitle(Lang::getLanguageString("pdftitle"));
	$pdf->SetCreator("moregroupware");
	$pdf->AliasNbPages();

	if(isset($_POST["chosecmp"]) and $_POST["chosecmp"] == "multiple"){
	    $pdf->SetSubject(Lang::getLanguageString("multiplecompanies"));
	    $_company = $_POST["_company"];
	    if(count($_company) > 0){
		for($i=0;$i<count($_company);$i++) { //parse all the companies selected
		    $sql = "SELECT a.*, b.name1, b.telephone, b.url AS company_url FROM mgw_contacts a, mgw_companies b WHERE (a.ispublic=1 OR a.owner=".$_SESSION["MGW"]->userid.") AND (b.ispublic=1 OR b.owner=".$_SESSION["MGW"]->userid.") AND a.companyid=b.id AND a.companyid=".(int)$_company[$i]." ORDER BY a.lastname";
		    if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
		    $pdf->Body($res);
		}
	    }
	    else redirect("index.php?view=pdfexport&".SID);
	}
	elseif(isset($_POST["chosecmp"]) and $_POST["chosecmp"] == "all"){
	    $pdf->SetSubject(Lang::getLanguageString("chosecompanyalltext"));
	    //select all companies
	    $sql = "SELECT DISTINCT b.id FROM mgw_companies b WHERE (b.ispublic=1 OR b.owner=".$_SESSION["MGW"]->userid.")";

	    if(!$res2 = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	    while($row = $res2->FetchRow()) {
		$sql = "SELECT DISTINCT a.*, b.name1, b.telephone, b.url AS company_url FROM mgw_contacts a, mgw_companies b WHERE (a.ispublic=1 OR a.owner=".$_SESSION["MGW"]->userid.") AND (b.ispublic=1 OR b.owner=".$_SESSION["MGW"]->userid.") AND a.companyid=b.id AND a.companyid=".$row["id"]." ORDER BY a.lastname";

		if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
		$pdf->Body($res);
	    }
	}
	elseif(isset($_POST["chosecmp"]) and $_POST["chosecmp"] == "nocompany"){
	    $pdf->SetSubject(Lang::getLanguageString("chosenocompanytext"));

	    $sql = "SELECT DISTINCT * FROM mgw_contacts WHERE (ispublic=1 OR owner=".$_SESSION["MGW"]->userid.") and (companyid=0 OR companyid IS NULL) ORDER BY lastname";
	    if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	    $pdf->Body($res);
	}
	else{
	    $pdf->SetSubject(Lang::getLanguageString("choseallcontactstext"));

	    $sql = "SELECT DISTINCT * FROM mgw_contacts WHERE (ispublic=1 OR owner=".$_SESSION["MGW"]->userid.") ORDER BY lastname";
	    if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	    $pdf->Body($res);
	}

	$pdf->Close();
	if(isset($_POST["chosesav"]) and $_POST["chosesav"] == "saveas") $pdf->output($_SESSION["MGW"]->username .".pdf",true);
	else $pdf->output();

	return true;
    }

    // =================================================
    // list view
    // =================================================
    function viewList(){
	global $conn, $smarty;
	include(INCLUDEPATH."mSelectBox.class.php");

	if(isset($_GET["sort"])){
	    if($_GET["sort"] == $_SESSION["contact"]["person"]["prevorderby"]){
		$_SESSION["contact"]["person"]["sort_order"] = ($_SESSION["contact"]["person"]["sort_order"] == "DESC") ? "ASC" : "DESC";
	    }
	    else{
		$_SESSION["contact"]["person"]["sort_order"] = 'ASC';
	    }
	    $_SESSION["contact"]["person"]["prevorderby"] = $_GET["sort"];
		if ($_GET["sort"] == "name1") { $prefixDB = 'b.'; } else { $prefixDB = 'a.'; }
	    $_SESSION["contact"]["person"]["sort_by"] = $prefixDB.$_GET["sort"];
	}
	elseif(!isset($_SESSION["contact"]["person"]["sort_by"])){
	    $_SESSION["contact"]["person"]["sort_by"] = ($_SESSION['MGW']->settings['name_display'][0] == 'lastfirst') ? 'a.lastname' : 'a.firstname';
	    $_SESSION["contact"]["person"]["sort_order"] = 'ASC';
	}

	$searchterm = (isset($_POST["searchterm"])) ? $_POST["searchterm"] : (isset($_GET["searchterm"])?$_GET["searchterm"]:"");
	$qsearchterm = $conn->QMagic('%'.$searchterm.'%');
	$list = (isset($_GET["list"])) ? $_GET["list"] : "";
	$compid = isset($_GET["compid"])?(int)$_GET["compid"]:0;

//	if(isset($_POST['groupsearch'])){
	if(isset($_POST['search'])){
		if($_POST['_group']!='*'){
	    	$_SESSION['contact']['groupsql'] = "AND (b.groupid=".(int)$_POST["_group"]." OR a.groupid=".(int)$_POST["_group"].")";
	    	$_SESSION['contact']['actgroup'] = (int)$_POST["_group"];
		}
		else{
	    	$_SESSION['contact']['groupsql'] = '';
	    	$_SESSION['contact']['actgroup'] = '';
		}
	}
	elseif(!isset($_SESSION['contact']['groupsql'])){
		$_SESSION['contact']['groupsql'] = '';
    	$_SESSION['contact']['actgroup'] = '';
	}

	$groupsql = $_SESSION['contact']['groupsql'];

	$icons = getIconStrings();
	$smarty->assign("prevsym", $icons["prev"]);
	$smarty->assign("nextsym", $icons["next"]);
	
	// default contentheader
	$cheader = Lang::getLanguageString("overview_contacts");
	if(
			( isset($_POST["op"]) and $_POST["op"] == "qsearch" and ( isset($_POST["search"]) or !empty($_POST["searchterm"])) ) 
			|| ( isset($_GET["searchterm"]) and $_GET["searchterm"] != "" )
			) 

		{
	    $sql = "SELECT DISTINCT a.*, a.owner as c_owner, b.owner, b.name1, b.telephone, b.email AS email_company FROM mgw_contacts a LEFT JOIN mgw_companies b ON a.companyid=b.id WHERE (";
		$sql .=  "(a.ispublic=1 ".$groupsql.") OR (a.ispublic=0 ".$groupsql." AND a.owner=".$_SESSION["MGW"]->userid . "))";

		if (!empty($searchterm)) {
		 	$sql .= " AND (";
	   	    $qsearchterm = $conn->QMagic('%'.$searchterm.'%');
			for($i=0;$i<count($_SESSION["MGW"]->settings["quicksearchmethod"]);$i++) {
			$sql .= "(UPPER(".$_SESSION["MGW"]->settings["quicksearchmethod"][$i] . ") LIKE UPPER($qsearchterm) AND a.ispublic = 1) OR ".
					"(UPPER(".$_SESSION["MGW"]->settings["quicksearchmethod"][$i] . ") LIKE UPPER($qsearchterm) AND a.ispublic = 0 AND a.owner=".$_SESSION["MGW"]->userid.")";
			
			if(count($_SESSION["MGW"]->settings["quicksearchmethod"])-1 != $i)
			    $sql .= " OR ";
	    		}
			$sql .= ")";
			}

	    $sql .= " ORDER BY ".$_SESSION["contact"]["person"]["sort_by"].' '.$_SESSION["contact"]["person"]["sort_order"];
		$sql = str_replace("mgw_contacts.","a.",$sql);
		$sql = str_replace("mgw_companies.","b.",$sql);
		
	    $cheader = Lang::getParmLang(Lang::getLanguageString("overview_contacts_by_qsearch"), array($searchterm));
	}
	elseif(isset($_GET["list"]) and $_GET["list"] != "") {
	    $qsearchterm = $conn->QMagic($list."%");
	    $sql = "SELECT a.*, b.name1, b.telephone, a.owner as c_owner, b.owner, b.email AS email_company 
					FROM mgw_contacts a LEFT JOIN mgw_companies b ON a.companyid=b.id 
					WHERE ((UPPER(a.lastname) LIKE UPPER(".$qsearchterm.") 
						AND a.ispublic=1) OR (UPPER(a.lastname) LIKE UPPER(".$qsearchterm.") 
						AND a.ispublic=0 AND a.owner=".$_SESSION["MGW"]->userid.")) $groupsql 
					ORDER BY ".$_SESSION["contact"]["person"]["sort_by"].' '.$_SESSION["contact"]["person"]["sort_order"];
	    $cheader = Lang::getParmLang(Lang::getLanguageString("overview_contacts_by_a"), array($list));
	}
	elseif($compid != 0) {
	    $sql = "SELECT a.*, b.name1, b.telephone, a.owner as c_owner, b.owner, b.email AS email_company FROM mgw_contacts a LEFT JOIN mgw_companies b ON a.companyid=b.id WHERE (a.ispublic=1 AND b.id = $compid $groupsql) OR (a.ispublic=0 AND a.owner=".$_SESSION["MGW"]->userid." AND b.id = $compid $groupsql) ORDER BY ".$_SESSION["contact"]["person"]["sort_by"].' '.$_SESSION["contact"]["person"]["sort_order"];
	}
	elseif(isset($_GET["sort"]) and $_GET["sort"] == "bycompany") {
	    $sql = "SELECT a.*, b.name1, b.telephone, a.owner as c_owner,b.owner, b.email AS email_company FROM mgw_contacts a LEFT JOIN mgw_companies b ON a.companyid=b.id WHERE (a.ispublic=1 $groupsql) OR (a.ispublic=0 $groupsql AND a.owner=".$_SESSION["MGW"]->userid.") ORDER BY ".$_SESSION["contact"]["person"]["sort_by"].' '.$_SESSION["contact"]["person"]["sort_order"];
	}
	else{
	    $sql = "SELECT a.*, b.name1, b.telephone, a.owner as c_owner,b.owner, b.email AS email_company FROM mgw_contacts a LEFT JOIN mgw_companies b ON a.companyid=b.id WHERE (a.ispublic=1 $groupsql) OR (a.ispublic=0 $groupsql AND a.owner=".$_SESSION["MGW"]->userid.") ORDER BY ".$_SESSION["contact"]["person"]["sort_by"].' '.$_SESSION["contact"]["person"]["sort_order"];
	}

	// ========== PAGING STUFF 1 ================
	session_register('curr_page');
	if (isset($_GET['npage']) || isset($_POST['npage'])){
	    $curr_page = isset($_POST['npage']) ? $_POST['npage'] : $_GET['npage'];
	} else {
	    $curr_page = 1; // at first page
	}
	// ============================================
	if(!$res = $conn->PageExecute($sql, $_SESSION["MGW"]->settings["list_items_number"], $curr_page)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

	if(isset($_GET["sort"]) and $_GET["sort"] == "bycompany") $cheader = Lang::getParmLang(Lang::getLanguageString("overview_contacts_by_comp"), array($res->Fields("name1")));
	
	// ========== PAGING STUFF 2 ================
	// if NOT on first page
	if(!$res->AtFirstPage()) {
	    $smarty->assign("_prev", true); 
	    $smarty->assign("ppage", $res->AbsolutePage() - 1);
	}
	
	// if NOT on last page
	if(!$res->AtLastPage()) {
	    $smarty->assign("_next", true); 
	    $smarty->assign("npage", $res->AbsolutePage() + 1);
	}
	// ============================================

	$counter = 0;

	while($row = $res->FetchRow()) {
	    $counter++;
	    $myid = $row["id"];
	    $rowcompid = $row["companyid"];
	    if ($row["tel_company"] == "") $row["tel_company"] = $row["telephone"];
	    if ($row["email"] == "") $row["email"] = $row["email_company"];
	    $row["firstname"] = $row["firstname"]." ".$row["name_add"];

	    $row['company'] = $row["name1"];
		if ($row["owner"]=="") $row["owner"] = $row["c_owner"];

	    // create Action URLs
	    $aqlink = "";
	    if (queryRights2_bool("root_modules_contact_crm_create")) {
		$aqlink = "<a href=\"index.php?mod=contact&amp;obj=crm&amp;view=directnewform&amp;compid="
		.$rowcompid."&amp;personid=".$myid
		."&amp;".SID."\">".Lang::getLanguageString('call')."</a>";
	    }
	    $detlink = "<a href=\"index.php?mod=contact&amp;obj=person&amp;view=details&amp;id=".$row['id']."&amp;list=$list&amp;searchterm=$searchterm&amp;npage=$curr_page&amp;".SID."\">".$icons["details"]."</a>";

	    // modify only for user with appropriate rights
	    if((queryRights2_bool("root_modules_contact_contact_modify") && $row["owner"] == $_SESSION["MGW"]->userid) ||
	       (queryRights2_bool("root_modules_contact_contact_modifyothers") && $row["owner"] != $_SESSION["MGW"]->userid)) {
		if (!isset($action)) $action="";
		$editlink = "<a href=\"index.php?mod=contact&amp;obj=person&amp;view=editform&amp;id=".$row['id']."&amp;act=$action&amp;searchterm=$searchterm&amp;list=$list&amp;npage=$curr_page&amp;".SID."\">".$icons["edit"]."</a>";
	    }
	    else {
		$editlink = "";
	    }

	    // delete only for user with appropriate rights
	    if((queryRights2_bool("root_modules_contact_contact_delete") && $row["owner"] == $_SESSION["MGW"]->userid)
	       OR (queryRights2_bool("root_modules_contact_contact_deleteothers") && $row["owner"] <> $_SESSION["MGW"]->userid)) {
		$dellink = "<a href=\"index.php?mod=contact&amp;obj=person&amp;view=delete&amp;id=$myid&amp;act=$action&amp;searchterm=$searchterm&amp;list=$list&amp;npage=$curr_page&amp;".SID."\" class=\"delete\">".$icons["delete"]."</a>";
	    }
	    else {
		$dellink = "";
	    }

	    $row['action'] = $detlink . "<br />" . $editlink . "<br />" . $dellink . "<br />".$aqlink."<br />"
		.'<a href="index.php?mod=contact&amp;view=vcardexport&amp;id='.$row['id'].'&amp;'.SID.'">'
		.Lang::getLanguageString('vcf_export')."</a><br />"
		."<hr />". linkEmail2($row["email"])."<hr />"
		. "<a href=\"index.php?mod=contact&amp;obj=company&amp;view=details&amp;id=$rowcompid&amp;".SID."\">". 'Company details' ."</a><br />"
		. "<a href=\"index.php?mod=contact&amp;obj=person&amp;view=list&amp;compid=$rowcompid&amp;".SID."\">". 'Company contacts' ."</a>";

	    if($row["ispublic"]==1)
		$row['pimg'] = "&nbsp;";
	    else
		$row['pimg'] = $icons['private'];
	
	    $smarty->append("td",$row);
	}

	// ========== PAGING STUFF 3 ==================
	// display next link when more records available
	if($counter<>$_SESSION["MGW"]->settings["list_items_number"]) $smarty->assign("next", false); else $smarty->assign("next", true);
	// =============================================
	
	if($_SESSION["MGW"]->settings["quicksearchmethod"]=="") $qsbool = false; else $qsbool = true;

	$smarty->assign('groups', $conn->GetAssoc("SELECT id, name_key FROM mgw_contacts_groups ORDER by name_key"));
	$smarty->assign("actgroup", $_SESSION['contact']['actgroup']);

	$columns[]['url'] = "index.php?mod=contact&amp;obj=person&amp;view=list&amp;compid=$compid&amp;sort=ispublic";
	$columns[]['url'] = "index.php?mod=contact&amp;obj=person&amp;view=list&amp;compid=$compid&amp;sort=lastname";
	$columns[]['url'] = "index.php?mod=contact&amp;obj=person&amp;view=list&amp;compid=$compid&amp;sort=firstname";
	$columns[]['url'] = "index.php?mod=contact&amp;obj=person&amp;view=list&amp;compid=$compid&amp;sort=tel_company";
	$columns[]['url'] = "index.php?mod=contact&amp;obj=person&amp;view=list&amp;compid=$compid&amp;sort=email";
	$columns[]['url'] = "index.php?mod=contact&amp;obj=person&amp;view=list&amp;compid=$compid&amp;sort=name1";
	$smarty->assign("columns", $columns);

	$smarty->assign("contentheader", $cheader);
	$smarty->assign("qsearchon", $qsbool);
	$smarty->assign("hascreaterights", queryRights2_bool("root_modules_contact_contact_create"));
	$smarty->assign('compid', $compid);
	$smarty->assign('at', alphabet_table("mod=contact&amp;obj=person&amp;view=list"));
	$smarty->assign('searchterm', $searchterm);
	$smarty->assign('list', $list);
	$smarty->assign('namedisplay', $_SESSION['MGW']->settings['name_display']);

	return true;
    }

	function display($template) {
		global $smarty,$appconf,$myEnv;
		if (strstr($template,$appconf["gentemplates"])) {
		} elseif (!empty($this->templatesAreIn)) {
		    $smarty->template_dir=ROOTPATH ."/modules/" . $this->templatesAreIn . "/templates/" .$appconf["theme"] ."/" . $myEnv["output"];
		}
		$smarty->display($template);
	}

}
?>
