<?php 
/*
* Copyright (c) 2009-2010 ATMAIL. All rights reserved
* See http://atmail.com/license.php for license agreement
*/

class Vcard {

	/** @var string */
	public $xfile		= null;
	/** @var string */
	public $filepath	= null;
	/** @var string */
	public $filename	= null;
	/** @var string */
	public $vcard		= null;
	/** @var string */
	public $contents	= null;
	/** @var string */
	public $error		= null;
	
	public function __constructor($filepath = '',$filename = '') {
		if(is_string($filepath) && strlen($filepath) > 0) {
			$this->filepath = mysql_escape_string($filepath);
		}
		else {
			$this->filepath	= '';
		}
		if(is_string($filename) && strlen($filename) > 0) {
			$this->filename	= mysql_escape_string($filename);
		}
		else {
			$this->filename = '';
		}
		$this->xfile		= ''; # No, this name there's nothing to do with the XFiles movie or series. The "file" is a protected word of PHP.		
		$this->vcard		= array();
		$this->error		= '';
	} # Constructor

	public function build($filename, $vcard_array = null)
	{
		if($vcard_array != null)
		{
			// wrap lines
			foreach ($vcard_array as $k => $v)
			{
				// remove end of line encoding
				$vcard_array[$k] = trim($v, "\n\r");
				
				// wrap fields that are not encoded
				if(strlen($v) > 75 && strstr($v, "ENCODING") == NULL)
				{
					$vcard_array[$k] = wordwrap($v, 75, "\n  ", 0);	
				}	
			}

			// remove any duplicate entries
			$vcard_array = array_unique($vcard_array);
			
			// add version 3.0 newline
			$this->vcardRows = implode("\n", $vcard_array);
		}
		else
		{
			// file writer
			$this->vcardRaw = '';
	
			if(file_exists($filename))
			{
				$handle	= fopen($filename,'r+');
				while(!feof($handle))
				{
					$lineContents = fgets($handle,4096);
					$this->vcardRaw .= $lineContents;
				}
	
				$this->vcardRows = preg_split('/END:VCARD/', $this->vcardRaw);	
				fclose($handle);
			}
			else 
			{
				return 0;
			}
		}
		
		return $this->vcardRows;
	
	} # builder
	
	public function countOccurences($vcard, $search_fields)
	{
		$occurences = 0;
		
		foreach($vcard as &$vcardline)
		{
			list($field, $value) = explode(":", $vcardline, 2);
			$original_field = $field;
			$junk = $junk2 = '';
			if(strstr($field, ".") != NULL)
			{
				list($junk, $field) = explode(".", $field, 2);	
			}
			
			if(strstr($field, ";") != NULL)
			{
				list($field, $junk) = explode(";", $field, 2);
			}
			if(strstr($junk, ";") != NULL)
			{
				list($junk, $junk2) = explode(";", $junk, 2);				
			}
			else if(strstr($junk, ",") != NULL)
			{
				list($junk, $junk2) = explode(",", $junk, 2);
			}
						
			if(	(count($search_fields) == 1 && $field == $search_fields[0])
			||	(count($search_fields) == 2 && strstr($field, $search_fields[0]) != NULL && strstr($junk, $search_fields[1]) && $junk2 == '')
			||	(count($search_fields) == 3 && strstr($field, $search_fields[0]) != NULL && strstr($junk, $search_fields[1]) && strstr($junk2, $search_fields[2]))
			)
			{
				$occurences++;
			}	
		}
		
		return $occurences;		
	}
	
	public function updateVcard($vcard, $search_fields, $input_field, $input_value, $occurence = 1)
	{
		$found = false;
		$occurences = $this->countOccurences($vcard, $search_fields);
		
		$total_occurences = 1;
		foreach($vcard as &$vcardline)
		{
			list($field, $value) = explode(":", $vcardline, 2);
			$original_field = $field;
			$junk = $junk2 = '';
			if(strstr($field, ".") != NULL)
			{
				list($junk, $field) = explode(".", $field, 2);	
			}
			
			if(strstr($field, ";") != NULL)
			{
				list($field, $junk) = explode(";", $field, 2);
			}
			if(strstr($junk, ";") != NULL)
			{
				list($junk, $junk2) = explode(";", $junk, 2);				
			}
			else if(strstr($junk, ",") != NULL)
			{
				list($junk, $junk2) = explode(",", $junk, 2);
			}
						
			if(	(count($search_fields) == 1 && $field == $search_fields[0])
			||	(count($search_fields) == 2 && strstr($field, $search_fields[0]) != NULL && strstr($junk, $search_fields[1]) && $junk2 == '')
			||	(count($search_fields) == 3 && strstr($field, $search_fields[0]) != NULL && strstr($junk, $search_fields[1]) && strstr($junk2, $search_fields[2]))
			)
			{
				if($occurence == 1 || $occurences <= 1)
				{
					$vcardline = $original_field . ':' . $input_value;
					$found = true;
					break;
				}
				else
				{
					if($total_occurences == $occurence)
					{
						$vcardline = $original_field . ':' . $input_value;
						$found = true;
						break;
					}
					else
					{
						$total_occurences++;
					}
				}
			}	
		}
		
		if(!$found)
		{
			$vcard[] = $input_field . ':' . $input_value;	
		}
		return $vcard;
	}
	
	public function massageVcard($input)
	{
		$lines = array();
		$lines_to_merge = preg_split("/\n/", $input);
		
		// massage the input data
		// to remove newlines
		// and multiline data to a single line
		// the vcard RFC requires no line to be longer then 80 chars
		
		//first strip empty lines (some clients (especially syncml) violate RFC with additional \r and or \n)
		foreach($lines_to_merge as $k => $line)
		{
			
			if( $line == '' || $line == ' ' || $line == "\n" || $line == "\r" || $line == "\r\n" || $line == "\n\r" || trim($line) == '' )
				unset($lines_to_merge[$k]);
			
		}
		foreach($lines_to_merge as $line)
		{
			// multilines require the first character to be a space
			if(isset($line[0]) && $line[0] == ' ')
			{
				// we are continuing a multiline section
				$lines[count($lines)-1] = trim($lines[count($lines)-1], "\r\n");
				$lines[count($lines)-1] .= trim($line, ' ');
			}
			else
			{
				if($line != '')
				{
					$lines[] = $line;
				}
			}
		}
		return $lines;

	}
	
	public function exportPart($contact, $original = NULL)
	{
		$this->vcardExport = array();
	
		// if there is an original vcard that we wish to modify, lets explode it
		if($original != NULL)
		{
			$this->vcardExport = array();
			$this->vcardExport[] = "BEGIN:VCARD";
			
			$vcardExport_temp = $this->massageVcard($original);
			
			foreach($vcardExport_temp as $line)
			{
				$line = trim($line, "\n\r");
				if($line != "BEGIN:VCARD" && $line != "END:VCARD")
				{
						$this->vcardExport[] = $line;
				} 
			}
		}
		else
		{
			$this->vcardExport[] = "BEGIN:VCARD";
			$this->vcardExport[] = "VERSION:3.0";
		}
	
		// First, clean the array, no \n|\r
		foreach(array_keys($contact) as $field)
		{
			$contact[$field] = str_replace("\n", '', $contact[$field]);
			$contact[$field] = str_replace("\r", '', $contact[$field]);
		}
	
		// N:Duncan;Benjamin;Robert;Mr;
		$fn = array();
		foreach(array('UserTitle', 'UserFirstName', 'UserMiddleName', 'UserLastName') as $field)
		{
			if(empty($contact[$field]))
			{
				continue;
			}
			
			$fn[] = $contact[$field];
		}
	
		if(is_array($fn))
		{
			$this->vcardExport = $this->updateVcard($this->vcardExport, array("FN"), "FN", implode(" ", $fn));
		}
	
		// N:Duncan;Benjamin;Robert;Mr;[?]
		$n = array();
		foreach(array('UserLastName', 'UserFirstName', 'UserMiddleName', 'UserTitle', '') as $field)
		{
			if(!empty($contact[$field]))
			{
				$n[] = $contact[$field];
			}
			else
			{
				$n[] = "";
			}
		}
	
		if(is_array($n))
		{
			$this->vcardExport = $this->updateVcard($this->vcardExport, array("N"), "N", implode(";", $n));
			//			$this->vcardExport[] = "N:" . implode(";", $n);
		}
	
		// ORG:Atmail;R&D
		$org = array();
		foreach(array('UserWorkCompany', 'UserWorkDept') as $field)
		{
			if(!empty($contact[$field]))
			{
				$org[] = $contact[$field];
			}
			else
			{
				$org[] = "";
			}
		}
	
		if(is_array($org))
		{
			$this->vcardExport = $this->updateVcard($this->vcardExport, array("ORG"), "ORG", implode(";", $org));
			//			$this->vcardExport[] = "ORG:" . implode(";", $org);
		}
		// Translate UserEmail from Atmail syntax > Vcard
	
		// Primary email
		if(!empty($contact['UserEmail']))
		{
			$this->vcardExport = $this->updateVcard($this->vcardExport, array("EMAIL", "INTERNET", "HOME"), "EMAIL;type=INTERNET;type=HOME;type=pref", $contact['UserEmail']);
			//			$this->vcardExport[] = "EMAIL;type=INTERNET;type=HOME;type=pref:" . $contact['UserEmail'];
		}
	
		if(!empty($contact['UserEmail2']))
		{
			$this->vcardExport = $this->updateVcard($this->vcardExport, array("EMAIL", "INTERNET", "WORK"), "EMAIL;type=INTERNET;type=WORK", $contact['UserEmail2']);
			//			$this->vcardExport[] = "EMAIL;type=INTERNET;type=WORK:" . $contact['UserEmail2'];
		}
	
		if(!empty($contact['UserEmail3']))
		{
		//	$this->vcardExport[] = "EMAIL;type=INTERNET:" . $contact['UserEmail3'];
			$this->vcardExport = $this->updateVcard($this->vcardExport, array("EMAIL", "INTERNET"), "EMAIL;type=INTERNET", $contact['UserEmail3'], 1);
		}
		
		if(!empty($contact['UserEmail4']))
		{
		//	$this->vcardExport[] = "EMAIL;type=INTERNET:" . $contact['UserEmail4'];
			$this->vcardExport = $this->updateVcard($this->vcardExport, array("EMAIL", "INTERNET"), "EMAIL;type=INTERNET", $contact['UserEmail4'], 2);
		}
		
		if(!empty($contact['UserEmail5']))
		{
		//	$this->vcardExport[] = "EMAIL;type=INTERNET:" . $contact['UserEmail5'];
			$this->vcardExport = $this->updateVcard($this->vcardExport, array("EMAIL", "INTERNET"), "EMAIL;type=INTERNET", $contact['UserEmail5'], 3);
		}
		
		// Work address
		// ADR;type=WORK;type=pref:;;666 hells rd;Hell;Underground;6666;Australia
		$workAddr = array();
		$writeAddress = false;
		foreach( array('', '', 'UserWorkAddress', 'UserWorkCity', 'UserWorkState', 'UserWorkZip', 'UserWorkCountry') as $field)
		{
			if(!empty($contact[$field]))
			{
				$workAddr[] = $contact[$field];
				$writeAddress = true;
			}
			else
			{
				$workAddr[] = "";
			}
		}
	
		if(is_array($workAddr) && $writeAddress)
		{
			if($this->countOccurences($this->vcardExport, array("ADR", "WORK")))
			{
				$this->vcardExport = $this->updateVcard($this->vcardExport, array("ADR", "WORK"), "ADR;type=WORK", implode(";", $workAddr));
			}
			else
			{
				$this->vcardExport = $this->updateVcard($this->vcardExport, array("ADR", "WORK", "pref"), "ADR;type=WORK;type=pref", implode(";", $workAddr));				
			}
//			$this->vcardExport[] = "ADR;type=WORK;type=pref:" . implode(";", $workAddr);
		}
		
		// Home address
		// ADR;type=HOME:;;120 somewhere rd;Somewhere Beach;QLD;9012;Australia
		$homeAddr = array();
		$writeAddress = false;
		
		foreach( array('', '', 'UserHomeAddress', 'UserHomeCity', 'UserHomeState', 'UserHomeZip', 'UserHomeCountry') as $field)
		{
			if(!empty($contact[$field]))
			{
				$homeAddr[] = $contact[$field];
				$writeAddress = true;
			}
			else
			{
				$homeAddr[] = "";
			}
		}
	
		if(is_array($homeAddr) && $writeAddress)
		{
			if($this->countOccurences($this->vcardExport, array("ADR", "HOME")))
			{
				$this->vcardExport = $this->updateVcard($this->vcardExport, array("ADR", "HOME"), "ADR;type=HOME", implode(";", $homeAddr));
			}
			else
			{
				$this->vcardExport = $this->updateVcard($this->vcardExport, array("ADR", "HOME", "pref"), "ADR;type=HOME;type=pref", implode(";", $homeAddr));
			}
//			$this->vcardExport[] = "ADR;type=HOME;type=pref:" . implode(";", $homeAddr);
		}
		
		// First, loop thro all the fields that have a single value
		foreach(array_keys($contact) as $field)
		{
			if(empty($field) || empty($contact[$field]))
			{
				continue;
			}
			
			switch($field)
			{
				
				case 'UID':
				{
					$this->vcardExport = $this->updateVcard($this->vcardExport, array("UID"), "UID", $contact[$field]);
				}
				break;
				
				case 'UserWorkMobile':
				{
					$this->vcardExport = $this->updateVcard($this->vcardExport, array("TEL", "WORK", "CELL"), "TEL;type=WORK;type=CELL", $contact[$field]);
				}
				break;

				case 'UserPhoto':
				{
					$contact['UserPhoto'] = wordwrap($contact['UserPhoto'], 80, "\n ", true);
					$this->vcardExport = $this->updateVcard($this->vcardExport, array("PHOTO", "ENCODING"), "PHOTO;ENCODING=B", $contact[$field]);
//					PHOTO;ENCODING=B
				}
				break;
				
				case 'UserWorkTitle':
				{
					$this->vcardExport = $this->updateVcard($this->vcardExport, array("TITLE"), "TITLE", $contact[$field]);
//					$this->vcardExport[] = "TITLE:" . $contact[$field];
				}
				break;

				case 'UserWorkPhone':
				{
					$this->vcardExport = $this->updateVcard($this->vcardExport, array("TEL", "WORK"), "TEL;type=WORK", $contact[$field]);
//					$this->vcardExport[] = "TEL;type=WORK:" . $contact[$field];
				}
				break;

				case 'UserWorkFax':
				{
					$this->vcardExport = $this->updateVcard($this->vcardExport, array("TEL", "WORK", "FAX"), "TEL;type=WORK;type=FAX", $contact[$field]);
//					$this->vcardExport[] = "TEL;type=WORK;type=FAX:" . $contact[$field];
				}
				break;

				case 'UserHomeMobile':
				{
					$this->vcardExport = $this->updateVcard($this->vcardExport, array("TEL", "CELL"), "TEL;type=CELL", $contact[$field]);					
//					$this->vcardExport[] = "TEL;type=CELL:" . $contact[$field];
				}
				break;
				
				case 'UserHomePhone':
				{
					$this->vcardExport = $this->updateVcard($this->vcardExport, array("TEL", "HOME"), "TEL;type=HOME", $contact[$field]);					
//					$this->vcardExport[] = "TEL;type=HOME:" . $contact[$field];
				}
				break;
				
				case 'UserHomeFax':
				{
					$this->vcardExport = $this->updateVcard($this->vcardExport, array("TEL", "HOME", "FAX"), "TEL;type=HOME;type=FAX", $contact[$field]);
//					$this->vcardExport[] = "TEL;type=HOME;type=FAX:" . $contact[$field];
				}
				break;
	
				// Misc
				case 'UserURL':
				{
					// Escape : from the URL
					$value = str_replace(":", "\:", $contact[$field]);
					$this->vcardExport = $this->updateVcard($this->vcardExport, array("URL"), "URL", $value);
//					$this->vcardExport[] = "URL:" . $value;
				}
				break;
				
				case 'UserDOB':
				{
					// Remove the MySQL time for the DOB
					$value = str_replace(" 00:00:00", "", $contact[$field]);
					$this->vcardExport = $this->updateVcard($this->vcardExport, array("BDAY"), "BDAY;value=date", $value);
//					$this->vcardExport[] = "BDAY;value=date:" . $value;
				}
				break;
				
				case 'UserInfo':
				{
					$this->vcardExport = $this->updateVcard($this->vcardExport, array("NOTE"), "NOTE", $contact[$field]);
				}
				break;
				
				default:
				{
					continue;
				}
				break;
			}
		}
		
		$this->vcardExport[] = "END:VCARD";

		return $this->vcardExport;
	}
	
	public function viewPart($row)
	{
		
		$contents = array();
		$this->emails = array();
	
		// massage the input data
		$lines = $this->massageVcard($row);
	    //Zend_Registry::get('log')->debug( "\n" . print_r($lines, true) . "\n" . __METHOD__ . ' #' . __LINE__ . ": \$lines \n");
	    
		// go through each line and see what we can extract
		if( !is_array($lines) ) 
			return $contents;
		$prevItem = '';
		foreach($lines as $line)
		{
	
			// Build an array of name:value
			// Escape :
			$line = str_replace('\\:', '###', $line);
	
			// explode the input line into [field]:[value]
			$lineKeyValue = explode(':',$line);
			//Zend_Registry::get('log')->debug( "\n" . print_r($lineKeyValue, true) . "\n" . __METHOD__ . ' #' . __LINE__ . ": \$lineKeyValue \n");
	        
			$item  = trim($lineKeyValue[0]);
			if( isset($lineKeyValue[1]) )
			{

				// trim away return carriage and newline
				$value = str_replace("\r",'',$lineKeyValue[1]);
				$value = str_replace("\n",'',$value);

			}
			else
				$value = '';
            

			//try match up empty value with next line for certain fields (next line part count = 1)
			if( count($lineKeyValue) == 1 )
			{
				
				if( $prevItem == 'PHOTO;ENCODING=BASE64;TYPE=JPEG')
				{
				
					$value = $lineKeyValue[0];
					$item = $prevItem;
				
				}
				
			}
			$prevItem = $item;
			
			if( empty($item) || empty($value) )
				continue;

			$item = preg_replace('/^item\d+\./', '', $item);

			// Replace ### with : for escaped fields
			$value = str_replace('###', ':', $value);
			
			// Replace escaped :'s
			$value = str_replace('\\:' , ':', $value);
			$item = strtoupper(trim($item));
			//Zend_Registry::get('log')->debug( "\n" . print_r($item, true) . "\n" . __METHOD__ . ' #' . __LINE__ . ": \$item \n");
			
			switch( $item )
			{
				case 'N;LANGUAGE=EN-US':
				case 'N':
				{
					if(is_string($value) && strlen($value) > 0)
					{
						$name = explode(';',$value);
						if(isset($name[0]) && is_string($name[0]) && strlen($name[0]) > 0)
							$contents['UserLastName']   = $name[0];
						if(isset($name[1]) && is_string($name[1]) && strlen($name[1]) > 0)
							$contents['UserFirstName']   = $name[1];
						if(isset($name[2]) && is_string($name[2]) && strlen($name[2]) > 0)
							$contents['UserMiddleName']   = $name[2];
						if(isset($name[3]) && is_string($name[3]) && strlen($name[3]) > 0)
							$contents['UserTitle']   = $name[3];
					}
					//$contents['name'] = $names;
				}
				break;
									
				case 'PHOTO;ENCODING=B':
				case 'PHOTO;BASE64':
				case 'PHOTO;ENCODING=B;TYPE=IMAGE/PNG':
				case 'PHOTO;ENCODING=B;TYPE=IMAGE/JPEG':
				case 'PHOTO;ENCODING=B;TYPE=JPEG':
				case 'PHOTO;ENCODING=BASE64;TYPE=JPEG':
				{						
					$contents['UserPhoto'] = $value;
				}
				break;
				case 'FN':
				{
					if(is_string($value) && strlen($value) > 0)
						$contents['fullname'] = $value;
				}
				break;
				case 'TITLE':
				{
					if(is_string($value) && strlen($value) > 0)
						$contents['UserWorkTitle'] = $value;
				}
				break;
				case 'BDAY;VALUE=DATE':
				{
					if(is_string($value) && strlen($value) > 0)
						$contents['UserDOB'] = $value;
				}
				break;
				case 'ORG':
				{
					if(is_string($value) && strlen($value) > 0)
					{
						$name = explode(';',$value);
						if(isset($name[0]) && is_string($name[0]) && strlen($name[0]) > 0)
							$contents['UserWorkCompany']   = $name[0];
						if(isset($name[1]) && is_string($name[1]) && strlen($name[1]) > 0)
							$contents['UserWorkDept']   = $name[1];
					}
				}
				break;
				/*case 'TITLE':
				{
					if(is_string($value) && strlen($value) > 0)
						$contents['UserTitle'] = $value;
				}
				break;*/
				case 'NOTE':
					if(is_string($value) && strlen($value) > 0)
						$contents['UserInfo'] = $value;
				break;
				case 'NOTE;ENCODING=QUOTED-PRINTABLE':
				case 'NOTE;ENCODING=QUOTED-PRINTABLE;CHARSET=UTF-8':
				{
					if(is_string($value) && strlen($value) > 0)
						$contents['UserInfo'] = quoted_printable_decode($value);
				}
				break;
				case 'TEL;TYPE=WORK;TYPE=PREF':
				case 'TEL;TYPE=WORK,PREF':
				case 'TEL;TYPE=WORK':
				case 'TEL;WORK':
				case 'TEL;WORK;VOICE':
				{
					if(is_string($value) && strlen($value) > 0)
						$contents['UserWorkPhone'] = trim($value);
				}
				break;
				case 'TEL;TYPE=HOME;TYPE=PREF':
				case 'TEL;TYPE=HOME,PREF':
				case 'TEL;TYPE=HOME':
				case 'TEL;HOME':
				case 'TEL;HOME;VOICE':
				case 'TEL':
				{
					if(is_string($value) && strlen($value) > 0)
						$contents['UserHomePhone'] = trim($value);
				}
				break;
				case 'TEL;TYPE=CELL;TYPE=PREF':
				case 'TEL;TYPE=CELL,PREF':
				case 'TEL;TYPE=CELL':
				case 'TEL;CELL':
				case 'TEL;CELL;VOICE':
				case 'TEL;CELL\,VOICE':
					{
					if(is_string($value) && strlen($value) > 0)
						$contents['UserHomeMobile'] = trim($value);
				}
				break;
				case 'TEL;TYPE=HOME,FAX':
				case 'TEL;TYPE=HOME;TYPE=FAX':
				{
					if(is_string($value) && strlen($value) > 0)
						$contents['UserHomeFax'] = trim($value);
				}
				break;
				case 'TEL;TYPE=FAX;TYPE=PREF':
				case 'TEL;TYPE=FAX,PREF':
				case 'TEL;TYPE=WORK,FAX':
				case 'TEL;TYPE=WORK;TYPE=FAX':
				case 'TEL;TYPE=FAX':
				case 'TEL;FAX':
				case 'TEL;WORK;FAX':
				{
					if(is_string($value) && strlen($value) > 0)
						$contents['UserWorkFax'] = trim($value);
				}
				break;
				
				case 'TEL;TYPE=WORK;TYPE=CELL':
				case 'TEL;TYPE=WORK,CELL':
				case 'TEL;WORK;CELL':
				{
					if(is_string($value) && strlen($value) > 0)
						$contents['UserWorkMobile'] = trim($value);
				}
				
				case 'ADR;TYPE=WORK;TYPE=PREF':
				case 'ADR;TYPE=WORK,PREF':
				case 'ADR;TYPE=WORK':
				case 'ADR;WORK':
				{
					if(is_string($value) && strlen($value) > 0)
					{
						$addr = explode(';',$value);
						$address = array();
						foreach($addr as $string)
							$address[] = $string;

						if(isset($address[2]))$contents["UserWorkAddress"] = $address[2];
						if(isset($address[3]))$contents["UserWorkCity"] = $address[3];
						if(isset($address[4]))$contents['UserWorkState'] = $address[4];
						if(isset($address[5]))$contents["UserWorkZip"] = $address[5];
						if(isset($address[6]))$contents["UserWorkCountry"] = $address[6];
					}
				}
				break;

				case 'ADR;TYPE=HOME;TYPE=PREF':
				case 'ADR;TYPE=HOME,PREF':
				case 'ADR;TYPE=HOME':
				case 'ADR;HOME':
				{
					if(is_string($value) && strlen($value) > 0)
					{
						$addr = explode(';',$value);
						$address = array();
						foreach($addr as $string)
							$address[] = $string;

						if(isset($address[2]))$contents["UserHomeAddress"] = $address[2];
						if(isset($address[3]))$contents["UserHomeCity"] = $address[3];
						if(isset($address[4]))$contents['UserHomeState'] = $address[4];
						if(isset($address[5]))$contents["UserHomeZip"] = $address[5];
						if(isset($address[6]))$contents["UserHomeCountry"] = $address[6];
					}
				}
				break;
				case 'UID':
				{
					if(is_string($value) && strlen($value) > 0)
					{
						$contents['UID'] = str_replace("\r",'',$value);
						$contents['UID'] = str_replace("\n",'', $contents['UID']);
					}
				}
				break;

				case 'URL':
				case 'URL;TYPE':
				case 'URL;TYPE=PREF':
				case 'URL;WORK':
				{
					if(is_string($value) && strlen($value) > 0)
					{
						$contents['UserURL'] = str_replace("\r",'',$value);
						$contents['UserURL'] = str_replace("\n",'',$contents['UserURL']);
					}
				}
				break;
				
				case 'EMAIL;TYPE=INTERNET,HOME':
				case 'EMAIL;TYPE=INTERNET,HOME,PREF':
				case 'EMAIL;TYPE=INTERNET;TYPE=HOME':
				case 'EMAIL;TYPE=INTERNET;TYPE=HOME;TYPE=PREF':
				{
					if(is_string($value) && strlen($value) > 0)
					{
						$value = str_replace("\r",'',$value);
						$value = str_replace("\n",'',$value);
						if(!isset($this->emails[0]) || (isset($this->emails[0]) && $this->emails[0] == ''))
							$this->emails[0] = $value;
						else
						{							
							if(!isset($this->emails[1]))
								$this->emails[1] = '';
							$this->emails[] = $value;
						}
					}
				}
				break;
				
				case 'EMAIL;TYPE=INTERNET,WORK':
				case 'EMAIL;TYPE=INTERNET,WORK,PREF':
				case 'EMAIL;TYPE=INTERNET;TYPE=WORK':
				case 'EMAIL;TYPE=INTERNET;TYPE=WORK;TYPE=PREF':
				{
					if(is_string($value) && strlen($value) > 0)
					{
						$value = str_replace("\r",'',$value);
						$value = str_replace("\n",'',$value);
						if(!isset($this->emails[1]) || (isset($this->emails[1]) && $this->emails[1] == ''))
							$this->emails[1] = $value;
						else
						{
							if(!isset($this->emails[0]))
								$this->emails[0] = '';
							$this->emails[] = $value;
						}
					}
				}
				break;

				case 'EMAIL':
				case 'EMAIL;TYPE=INTERNET':
				case 'EMAIL;PREF;INTERNET':
				{

					if(is_string($value) && strlen($value) > 0)
					{

						$value = str_replace("\r",'',$value);
						$value = str_replace("\n",'',$value);
						if(!isset($this->emails[0]))
							$this->emails[0] = '';
						if(!isset($this->emails[1]))
							$this->emails[1] = '';	
						$this->emails[] = $value;

					}

				}
				break;
				default:
					continue;
				break;
			}
		}

	
		if(isset($this->emails[0]))
			$contents['UserEmail'] = $this->emails[0];
		
		// Create the user emails in the Atmail syntax
		for($i = 1; $i<6; $i++)
		{
			$atmaili = $i + 1;
			if(isset($this->emails[$i]))
				$contents['UserEmail' . $atmaili] = $this->emails[$i];
		}

		return $contents;

	}

}
