<?php
/* $Id: vcard.php,v 1.8 2003/09/27 17:01:13 k-fish Exp $ */

$myEnv["module"] = "contact";

include_once("../../config.inc.php");
include_once(INCLUDEPATH . "container.inc.php");

include(INCLUDEPATH . "vcard/vcard_email.php");
include(INCLUDEPATH . "vcard/vcard_adr.php");
include(INCLUDEPATH . "vcard/vcard_tel.php");

define ("TAG_START"        , "BEGIN:VCARD");
define ("TAG_END"          , "END:VCARD");
define ("TAG_VERSION"      , "VERSION:");
define ("TAG_BIRTHDATE"    , "BDAY:");

class VCard{
    var $elements;
    var $teleNr;
    var $Card_header = "BEGIN:VCARD";
    var $Card_footer = "END:VCARD";
    var $versionNr = "2.1";

    /*
 This property specifies the date of birth of the individual associated with the vCard. 
 The value for this property is a calendar date in a complete representation consistent 
 with ISO 8601.
 This property is identified by the property name BDAY. The property value is a string 
 conforming to the ISO 8601 calendar date, complete representation, in either basic or 
 extended format. The following example is in the basic format of ISO 8601:
  BDAY:19950415
 The following example is in the extended format of ISO 8601:
  BDAY:1995-04-15
 Support for this property is OPTIONAL for vCard Writers conforming to this specification.
    */
    var $birthDate;

    var $familyName;
    var $givenName;
    var $addName;
    var $namePrefix;
    var $nameSuffix;
    var $title;
 
    /* This property specifies the formatted name string associated with the vCard object. 
 This is the way that the name is to be displayed. It can contain desired honorific prefixes, 
 suffixes, titles, etc. For example, "Mr. John Q. Public, Jr.", Dr. Ann Tyler, or Hon. Judge Blackwell. 
 This property is based on the semantics of the X.520 Common Name attribute.
 This property is identified by the property name FN. The following is an example of the Formatted Name property:
  FN:Mr. John Q. Public, Esq.
 Support for this property is OPTIONAL for vCard Writers conforming to this specification.
    */
    var $formattedName;
 
    /* This property is identified by the property name N. 
 This property is defined to encapsulate the individual components of an object's name. 
 The property value consists of the components of the name specified as positional fields 
 separated by the Field Delimiter character (ASCII decimal 59). 
 The property value is a concatenation of the Family Name (first field), Given Name (second field), 
 Additional Names (third field), Name Prefix (fourth field), and Name Suffix (fifth field) strings. 
 The following is an example of the Name property for a person:
  N:Public;John;Quinlan;Mr.;Esq.
 The following is an example of the Name property for a resource or place:
  N:Veni, Vidi, Vici;The Restaurant.
    */
    var $name;

    /*
 Last Revision
 This property specifies the combination of the calendar date and time of day of the last 
 update to the vCard object. The property value is a character string conforming to the basic 
 or extended format of ISO 8601. The value can either be in terms of local time or UTC.
 This property is identified by the property name REV. Valid values for this property are 
 a character string representing a combination of the calendar date and time of day conforming 
 to the basic or extended format of ISO 8601. The time of day can be either local time or UTC. 
 The following example is in the basic format and local time of ISO 8601:
  REV:19951031T222710
 The following example is in the extended format and UTC time of ISO 8601:
  REV:1995-10-31T22:27:10Z
 Support for this property is OPTIONAL for vCard Writers conforming to this specification.
 */
    var $revision;

    function setVersionNr($m_versionNr) {
	$this->versionNr = $m_versionNr;
    }// end setVersion

    function getVersion() {
	$result = TAG_VERSION.($this->versionNr);
	return $result;
    }// end getVersion 
 
    function getVersionNr() {
	return $this->versionNr;
    }// end getVersionNr  

    function getBirthDate() {
	// BDAY:YYYYMMDD
	return $this->elements["BDAY:"];
    }// end getBirthDate  

    function setBirthDate($m_birthDate) {
	// BDAY:YYYYMMDD
	if ($m_birthDate != "0000-00-00"){
	    $this->elements["BDAY:"] = str_replace("-","",$m_birthDate);
	} 
    }// end setBirthDate 

    function setOrg($str) {
	$this->elements["ORG:"] = $str;
    }

    function setURL($str) {
	$this->elements["URL:"] = $str;
    }

    function setLastName($str) {
	$this->familyName = $str;
    }// end setLastName 

    function getLastName() {
	return $this->familyName;
    }

    function setGivenName($str) {
	$this->givenName = $str;
    }

    function getGivenName($givenName) {
	return $this->givenName;
    }

    function setAddName($str) {
	$this->addName = $str;
    }

    function setNamePrefix($str) {
	$this->NamePrefix = $str;
    }

    function setNameSuffix($str) {
	$this->NameSuffix = $str;
    }

    function getHeader() {
	return $this->Card_header;
    }

    function getFooter() {
	return $this->Card_footer;
    }

    function setWorkVoiceNr($teleNr) {
	$workVoiceNr = new VCard_WorkTel($teleNr);
	$this->elements[$workVoiceNr->getKey()]= $workVoiceNr->getTeleNr();
    }

    function setHomeVoiceNr($teleNr) {
	$homeVoiceNr = new VCard_HomeTel($teleNr);
	$this->elements[$homeVoiceNr->getKey()]= $homeVoiceNr->getTeleNr();
    }

    function setMobileVoiceNr($teleNr) {
	$mobileVoiceNr = new VCard_MobileTel($teleNr);
	$this->elements[$mobileVoiceNr->getKey()]= $mobileVoiceNr->getTeleNr();
    }

    function setWorkFaxNr($teleNr) {
	$workFaxNr = new VCard_WorkFax($teleNr);
	$this->elements[$workFaxNr->getKey()]= $workFaxNr->getTeleNr();
    }

    function setHomeFaxNr($teleNr) {
	$homeFaxNr = new VCard_HomeFax($teleNr);
	$this->elements[$homeFaxNr->getKey()]= $homeFaxNr->getTeleNr();
    }

    function setEmailAddress($address) {
	$emailAddress = new VCard_EMAIL($address);
	$key = $emailAddress->getKey();
	$this->elements[$key]= $address;
    }
 
    function getEmailAddress() {
	return $this->elements["EMAIL;INTERNET;PREF:"];
    }
 
    function setHomeAddress($street,$city,$region,$code,$countrycode,$pobox="",$extadr="") {
	global $conn;
	$sql = "SELECT name AS country FROM mgw_countries WHERE code=".$conn->QMagic($countrycode);
        if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
        $row = $res->FetchRow();
        $country = $row["country"];

	$homeAddress = new VCard_HomeAddress($street,$city,$region,$code,$country,$pobox,$extadr);
	$this->elements[$homeAddress->getKey()]= $homeAddress->getAddress();
    }

    function setWorkAddress($street,$city,$region,$code,$countrycode,$pobox="",$extadr="") {
	global $conn;
	$sql = "SELECT name AS country FROM mgw_countries WHERE code=".$conn->QMagic($countrycode);
        if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
        $row = $res->FetchRow();
        $country = $row["country"];

	$workAddress = new VCard_WorkAddress($street,$city,$region,$code,$country,$pobox,$extadr);
	$this->elements[$workAddress->getKey()]= $workAddress->getAddress();
    }

    function setFormattedName ($m_namePrefix, $m_firstName, $m_addName, $m_lastName, $m_honorPrefix  ) {
	// FN:Mr. John Q. Public, Dr.
   	
	$tmpFName = ucfirst($m_namePrefix)." ".$m_firstName;
	if ($m_addName!= ""){
	    $tmpFName .= " ".$m_addName;
	}
	$tmpFName .= " ".$m_lastName;
	if ($m_honorPrefix!= ""){
	    $tmpFName = $tmpFName.", ".$m_honorPrefix;
	}
	$this->elements["FN:"] = $tmpFName;

	// N:Public;John;Quinlan;Mr.;Esq.
	$tmpName = $m_lastName.";".$m_firstName.";".$m_addName.";".ucfirst($m_namePrefix);
	if ($m_honorPrefix!= ""){
	    $tmpName = $tmpName.";".$m_honorPrefix;
	}
	$this->elements["N:"] = $tmpName;
    }// end setLastName

    function getObjectByID($id){
	global $conn;
	$sql = "SELECT a.*, b.name1, b.telephone, b.street AS comp_street, b.city AS comp_city, b.zip AS comp_zip, b.countrycode AS comp_countrycode, b.additional AS comp_additional, b.fax AS comp_fax FROM mgw_contacts a LEFT JOIN mgw_companies b ON a.companyid = b.id WHERE a.id=".(int)$id;

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

	if($row["birthday"]!="") $this->setBirthDate($row["birthday"] ); 
	$this->setFormattedName($row["title"],$row["firstname"],$row["name_add"],$row["lastname"],$row["honorific_prefix"]);
	$this->setLastName($row["lastname"]);
	if($row["priv_telefon"]!="") $this->setHomeVoiceNr($row["priv_telefon"]);
	if($row["tel_company"]!="") $this->setWorkVoiceNr($row["tel_company"]);
	elseif($row["telephone"]!="") $this->setWorkVoiceNr($row["telephone"]);
	if($row["tel_mobile"]!="") $this->setMobileVoiceNr($row["tel_mobile"]);
	if($row["priv_fax"]!="") $this->setHomeFaxNr($row["priv_fax"]);
	if($row["email"]!="") $this->setEmailAddress($row["email"]);
// 	if($row["email2"]!="") $this->setEmailAddress($row["email2"],false);
// 	if($row["email3"]!="") $this->setEmailAddress($row["email3"],false);
	if($row["url"]!="") $this->setURL($row["url"]);
	$this->setHomeAddress($row["priv_street"],$row["priv_city"],$row["priv_region"],$row["priv_zip"],$row["priv_countrycode"],"",$row["priv_additional"]);

	// get company address if possible
	if($row["companyid"] != ""){
	    $this->setWorkAddress($row["comp_street"],$row["comp_city"],"",$row["comp_zip"],$row["comp_countrycode"],"",$row["comp_additional"]);
	    if($row["comp_fax"]!="") $this->setWorkFaxNr($row["comp_fax"]);
	    if($row["name1"]!="") $this->setOrg($row["name1"]);
	}
    }

    function getString(){
	$vcstr = $this->getHeader()."\n";
	$vcstr .= $this->getVersion()."\n";
	while (list ($key, $val) = each ($this->elements)) {
	    $vcstr .= "$key$val\n";
	}
	$vcstr .= $this->getFooter()."\n";

	return $vcstr;
    }
 
    function insertObject($id, $elements){
	$this->setBirthDate($elements["birthday"] ); 
	$this->setFormattedName($elements["title"],$elements["firstname"],$elements["name_add"],$elements["lastname"],$elements["honorific_prefix"]);
	$this->setHomeVoiceNr($elements["priv_telefon"]);
	$this->setWorkVoiceNr($elements["tel_company"]);
	$this->setMobileVoiceNr($elements["tel_mobile"]);
	$this->setHomeFaxNr($elements["priv_fax"]);
	$this->setEmailAddress($elements["email"]);
	// $street,$city,$region,$code,$country,pobox,extadr
	$this->setHomeAddress($elements["priv_street"],$elements["priv_city"],$row["priv_region"],$elements["priv_zip"],$elements["priv_country"],$elements["pobox"],$elements["extadr"]);
    }

    function parse($content) {
        global $conn;
	$counter = 0;
	reset($content);

	$GLOBALS['log']->message(MGW_INFO, "About to parse vCard.", __LINE__, __FILE__);
	while (list ($k, $line) = each($content)){
	    $line = explode(":",$line);
	    $key = trim(strtoupper($line[0]));
	    array_shift($line);
	    $value = trim(implode(":",$line));

	    if($key=="BEGIN") $counter++;
	    $cards[$counter][$key]=$value;
	}

	$counter = 0;
	while (list ($n, $card) = each($cards)){
	    $vcard = new VCard();
	    while (list ($k, $v) = each($card)){
		$k = explode(";",$k);
		switch($k[0]){
		case "BDAY":
		    $bday=$v;
		    if(!strstr($bday,"-")) $bday = substr($bday,0,4)."-".substr($bday,4,2)."-".substr($bday,-2);
		    break;
		case "N":
		    $v = explode(";",$v);
		    $lastname=$v[0];
		    $firstname=$v[1];
		    $addname=$v[2];
		    $nameprefix=$v[3];
		    $namesuffix=$v[4];
		    break;
		case "ADR":
		    $v = explode(";",$v);
 		    if(in_array("WORK",$k)){
			$workstreet=$v[2];
			$workcity=$v[3];
			$workregion=$v[4];
			$workcode=$v[5];
			$workcountry=$v[6];
			$workpobox=$v[0];
			$workextadr=$v[1];
		    }

 		    if(in_array("HOME",$k)){
			$homestreet=$v[2];
			$homecity=$v[3];
			$homeregion=$v[4];
			$homecode=$v[5];
			$homecountry=$v[6];
			$homepobox=$v[0];
			$homeextadr=$v[1];
		    }
		    break;
		case "TEL":
 		    if(in_array("WORK",$k) && !in_array("FAX",$k)) $worktel=$v;
 		    if(in_array("FAX",$k) && !in_array("WORK",$k)) $privfax=$v;
 		    if(in_array("HOME",$k) && !in_array("FAX",$k)) $hometel=$v;
 		    if(in_array("CELL",$k)) $mobile=$v;
		    break;
		case "EMAIL":
		    $email=$v;
		    break;
		case "URL":
		    $url=$v;
		    break;

                // makes no sense
		case "FN":
		    break;

                // not yet supported
		case "ORG":
		    break;
		case "REVISION":
		    break;

                // fallback
		default:
		    break;
		}
	    }
	    $sql = "SELECT lastname FROM mgw_contacts WHERE lastname=".$conn->QMagic($lastname)." AND firstname=".$conn->QMagic($firstname)." AND priv_street=".$conn->QMagic($street);
	    if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	    if($res->rowCount()==0){
		//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,priv_street,priv_additional,priv_zip,priv_city,priv_region,priv_telefon,priv_fax,email,tel_company,tel_mobile,url,birthday,owner,ispublic,lu_user,lu_date)";
		$sql .= " VALUES ($id,".$conn->QMagic($nameprefix).",".$conn->QMagic($firstname).",".$conn->QMagic($addname).",".$conn->QMagic($lastname).",".$conn->QMagic($namesuffix).",".$conn->QMagic($homestreet).",".$conn->QMagic($homeextadr).",".$conn->QMagic($homecode).",".$conn->QMagic($homecity).",".$conn->QMagic($homeregion).",".$conn->QMagic($hometel).",".$conn->QMagic($privfax).",".$conn->QMagic($email).",".$conn->QMagic($worktel).",".$conn->QMagic($mobile).",".$conn->QMagic($url).",".$conn->DBDate($bday).",".$_SESSION['MGW']->userid.",1,".$_SESSION['MGW']->userid.",".$conn->DBTimeStamp(time()).")";

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

	    // reset vars
	    $nameprefix="";
	    $firstname="";
	    $addname="";
	    $lastname="";
	    $namesuffix="";
	    //$workstreet="";
	    //$workcity="";
	    //$workregion="";
	    //$workcode="";
	    //$workcountry="";
	    //$workpobox="";
	    //$workextadr="";
	    $homestreet="";
	    $homecity="";
	    $homeregion="";
	    $homecode="";
	    $homecountry="";
	    $homepobox="";
	    $homeextadr="";
	    $hometel="";
	    $privfax="";
	    $email="";
	    $worktel="";
	    $mobile="";
	    $url="";
	    $bday="";
	}

	return $counter;
    }

    function VCard(){
	$numargs = func_num_args();
	$arg_list = func_get_args();

	$GLOBALS['log']->message(MGW_INFO, "Initializing vCard.", __LINE__, __FILE__);
	switch ($numargs) {
    	case 1:
	    $this->getObjectByID($arg_list[0]);
	    break;
    	default:
	    break;
	}
    }

}//end class

?>
