<?php
include_once("postget.php");
function processpipedticket ($to, $name, $email, $subject, $message, $attachment) {
	include_once("common.php");
	global $config;
	if (!is_in_utf8($subject)) {
		$subject = utf8_encode($subject);
	}
	if (!is_in_utf8($message)) {
		$message = utf8_encode($message);
	}
	$decodestring = $subject . '##||-SEPARATOR-||##' . $message;
	$decodestring = pipedecodestring ($decodestring);
	$decodestring = explode ('##||-SEPARATOR-||##', $decodestring);
	$subject = $decodestring[0];
	$message = $decodestring[1];
	$message = strip_tags ($message);
	$raw_message = $message;


	if ($to == $email)		{
		$errors = 'Blocked Potential Email Loop';
	}elseif (antispam('Email',$email)) {
		$errors = antispam('Email',$email);
	}elseif (antispam('Subject',$subject)) {
		$errors = antispam('Subject',$subject);
	}elseif (antispam('Body',$message)) {
		$errors = antispam('Body',$message);
	}elseif (is_array($email)) {
		$errors = "no email address";
	}elseif (is_array($to)) {
		$errors = "no email address";
	}else{
		$pos1 = strpos ($subject, '[');
		$pos2 = strpos ($subject, ']');
		if ($pos1 === false OR $pos2 === false)	{
		}else{
			$tid = substr ($subject, $pos1 + 1, $pos2 - 1);
			$query = "SELECT * FROM hd_tickets WHERE reference='".$tid."'";
			$result = mysql_query ($query);
			$data = mysql_fetch_array ($result);
			$tid = $data['ticketid'];
		}
		$to = trim ($to);
		$query = 'SELECT * FROM hd_tickets_dep';
		$result = mysql_query ($query);
		while ($data = mysql_fetch_array ($result))	{
			$did = $data['depid'];
			$deptemail = $data['email'];
			$clientsonly = $data['onlyclients'];
			$pos = strpos (strtolower ($to), strtolower ($deptemail));
			if ($pos === false)	{
				continue;
			}else{
				$deptid = $did;
				$deptclientsonly = $clientsonly;
				continue;
			}
		}
		if ($deptid == '')		{
			$errors = 'Department Not Found';
		}else{
			$separator = $config[4][1];
			$trozos = explode($separator, $message);
			$message = $trozos[0];
			$message = nl2br($trozos[0]);
			$query = "SELECT name, email FROM hd_tickets_dep WHERE email='".$email."'";
			$result = mysql_query ($query);
			$data = mysql_fetch_array ($result);
			$deptname = $data['name'];
			if ($deptname)	{
				if ($tid)	{
					addreply($tid,'0',$message,$attachment);
					$query="UPDATE hd_tickets SET status='3' WHERE ticketid='$tid'";
					mysql_query($query,$db_link);
					$now=time()+$config[31][1]*3600;
					$query="UPDATE hd_tickets SET lastreply='".$now."' WHERE ticketid='$tid'";
					mysql_query($query,$GLOBALS['db_link']);
					$query="UPDATE hd_tickets SET lastreplier='0' WHERE ticketid='$tid'";
					mysql_query($query,$GLOBALS['db_link']);
					$errors = 'Ticket Reply Imported Successfully';
				}else{
					$errors = 'Ticket ID Not Found';
				}
			}else{
				$query = "SELECT clientid FROM hd_clients WHERE email='".$email."'";
				$result = mysql_query ($query);
				$data = mysql_fetch_array ($result);
				$userid = $data['clientid'];
				if (($deptclientsonly == 'on' AND !$userid))	{
					///////////////////// no se encontr� el email en la tabla clients
				}else{
					if ($userid == '')	{
						$from['name'] = $name;
						$from['email'] = $email;
					}
					$quinceantes = time()-900;
					$query = "SELECT count(*) FROM hd_tickets WHERE date > ".$quinceantes." AND email='".$email."'";
					if ($userid)	{
						$query .= '' . ' OR clientid=\'' . $userid . '\'';
					}
					$query .= ' )';
					$result = mysql_query ($query);
					if (mysql_affected_rows() > 0) {
						$data = mysql_fetch_array ($result);
						$numtickets = $data[0];
					}else{
						$numtickets = 0;
					}
					if (10 < $numtickets)	{
						$errors = 'Exceeded Limit of 10 Tickets within 15 Minutes';
					}else{
						if ($tid)	{
							addreply($tid,'0',$message,$attachment);
							$query="UPDATE hd_tickets SET status='4' WHERE ticketid='$tid'";
							mysql_query($query,$GLOBALS['db_link']);
							$now=time()+$config[31][1]*3600;
							$query="UPDATE hd_tickets SET lastreply='".$now."' WHERE ticketid='$tid'";
							mysql_query($query,$GLOBALS['db_link']);
							$query="UPDATE hd_tickets SET lastreplier='0' WHERE ticketid='$tid'";
							mysql_query($query,$GLOBALS['db_link']);
							$errors = 'Ticket Reply Imported Successfully';
						}else{
							if ($subject<>'' AND $message<>'') {
								openticket($userid, $subject, $message, '1', 'medium', '', $deptid, $attachment, $userid, $from['name'], $from['email'] );
							}
							$errors = 'Ticket Imported Successfully';
						}
					}
				}
			}
		}
	}
}


function pipedecodestring ($string) {
	if ($pos = strpos ($string, '=?') === false)	{
		return $string;
	}
	$newresult = NULL;
	while (!($pos === false))	{
		$newresult .= substr ($string, 0, $pos);
		$string = substr ($string, $pos + 2, strlen ($string));
		$intpos = strpos ($string, '?');
		$charset = substr ($string, 0, $intpos);
		$enctype = strtolower (substr ($string, $intpos + 1, 1));
		$string = substr ($string, $intpos + 3, strlen ($string));
		$endpos = strpos ($string, '?=');
		$mystring = substr ($string, 0, $endpos);
		$string = substr ($string, $endpos + 2, strlen ($string));
		if ($enctype == 'q')	{
			$mystring = quoted_printable_decode (preg_replace ('/_/', ' ', $mystring));
		}else{
			if ($enctype == 'b')	{
				$mystring = base64_decode ($mystring);
			}
		}
		$newresult .= $mystring;
		$pos = strpos ($string, '=?');
	}
	$result = $newresult . $string;
	return $result;
}




function split_boundary ($data, $boundary) {
	while (preg_match ('' . '#([-]+|)' . $boundary . '(.+?)([-]+)' . $boundary . '#is', $data, $strip)) 	{
		$strips[] = $strip[2];
		$data = str_replace ($strip[0], $boundary, $data);
	}
	return $strips;
}





function strip_headers ($data, $rev = 0) {
	$data = explode ('', $data);
	while (list ($num, $line) = each ($data)) {
		++$x;
		if ($rev == 1) {
			$collect .= $line . '';
		}

		$line = trim ($line);
		if (($line == '' AND $x != 1)) {
			break;
		}

		if ($rev != 1) {
			unset ($data[$num]);
			continue;
		}
	}
	if ($rev == 1) {
		$data = $collect;
	}else{
		$data = implode ('', $data);
	}
	return $data;
}





function handle_split ($data, $bound) {
	global $BODY;
	global $attachment;
	global $filedata;
	global $base64;
	global $plain_only;
	$strips = split_boundary ($data, $bound);
	foreach ($strips as $content) 	{
		if (preg_match ('#boundary="(.+)"#i', $content, $boundary))	{
			if (stristr ($content, 'multipart/alternative;')) {
				$plain_only = 1;
			}

			$boundary = $boundary[1];
			handle_split ($content, $boundary);
			continue;
		}

		if (stristr ($content, 'quoted-printable')) {
			$content = quoted_printable_decode ($content);
		}

		if (preg_match ('#content-disposition(.+?)attachment#i', $content)) {
			$filedata = strip_headers ($content);
			$headers = strip_headers ($content, 1);
			if (stristr ($headers, 'Content-transfer-encoding: base64')) {
				$return['filedata'] = base64_decode ($filedata);
			}

			if (preg_match ('#(name|filename)="(.+?)"#', $headers, $file)) {
				$return['attachment'] = $file[2];
				continue;
			}

			continue;
		}else{
			if (preg_match ('#Content-Type(.+?)text/(plain|html)#i', $content, $type))	{
				if (($plain_only == 1 AND $type[2] == 'html'))	{
					continue;
				}

				$headers = strip_headers ($content, 1);
				$body = strip_headers ($content);
				if (stristr ($headers, 'Content-transfer-encoding: base64')) {
					$body = base64_decode ($body);
				}

				$return['body'] = $body;
				$BODY .= $body;
				continue;
			}
			continue;
		}
	}
	return $return;
}






function get_mime_type (&$structure) {
	$primary_mime_type = array ('TEXT', 'MULTIPART', 'MESSAGE', 'APPLICATION', 'AUDIO', 'IMAGE', 'VIDEO', 'OTHER');
	if ($structure->subtype){
		return $primary_mime_type[(int)$structure->type] . '/' . $structure->subtype;
	}
	return 'TEXT/PLAIN';
}



function get_part ($stream, $msg_number, $mime_type, $structure = false, $part_number = false){
	if (!$structure){
		$structure = @imap_fetchstructure ($stream, $msg_number);
	}

	if ($structure)	{
		if ($mime_type == get_mime_type ($structure))		{
			if (!$part_number)			{
				$part_number = '1';
			}

			$text = @imap_fetchbody ($stream, $msg_number, $part_number);
			if ($structure->encoding == 3)			{
				return imap_base64 ($text);
			}

			if ($structure->encoding == 4)			{
				return imap_qprint ($text);
			}
			return $text;
		}

		if ($structure->type == 1)		{
			while (list ($index, $sub_structure) = each ($structure->parts))			{
				if ($part_number)				{
					$prefix = $part_number . '.';
				}

				$data = get_part ($stream, $msg_number, $mime_type, $sub_structure, $prefix . ($index + 1));
				if ($data)		{
					return $data;
				}
			}
		}
	}
	return false;
}






function parse ($structure) {
	global $type;
	global $encoding;
	$ret = array ();
	$parts = $structure->parts;
	$x = 0;
	while ($x < sizeof ($parts))	{
		$ret[$x]['pid'] = $x + 1;
		$thisPart = $parts[$x];
		if ($thisPart->type == '')		{
			$thisPart->type = 0;
		}

		$ret[$x]['type'] = $type[$thisPart->type] . '/' . strtolower ($thisPart->subtype);
		if ($thisPart->encoding == '')		{
			$thisPart->encoding = 0;
		}

		$ret[$x]['encoding'] = $encoding[$thisPart->encoding];
		$ret[$x]['size'] = strtolower ($thisPart->bytes);
		$ret[$x]['disposition'] = strtolower ($thisPart->disposition);
		if ((strtolower ($thisPart->disposition) == 'attachment' OR strtolower ($thisPart->disposition) == 'inline'))		{
			if ($params = $thisPart->dparameters)		{
				foreach ($params as $p)		{
					if ($p->attribute == 'FILENAME')	{
						$ret[$x]['name'] = $p->value;
						break;
					}
				}
			}
		}
		++$x;
	}
	return $ret;
}






function get_attachments ($arr){
	unset ($ret);
	$x = 0;
	while ($x < sizeof ($arr))	{
		if (($arr[$x]['disposition'] == 'attachment' OR $arr[$x]['disposition'] == 'inline'))		{
			$ret[] = $arr[$x];
		}
		++$x;
	}
	return $ret;
}




function char_replace ($bad_char, $good_char, $str){
	if (is_array ($bad_char))	{
		$i = 0;
		while ($i < sizeof ($bad_char))		{
			$str = preg_replace ('/'.$bad_char[$i].'/', $good_char, $str);
			++$i;
		}
	}else{
		$str = preg_replace ('/'.$bad_char.'/', $good_char, $str);
	}
	return $str;
}





function getheaders ($mbox, $msgno){
	if ($headers = @imap_headerinfo ($mbox, $msgno))	{
		$header_info['msgID'] = $headers->message_id;
		if ($headersFrom = $headers->from)		{
			$header_info['fromAddr'] = $headersFrom[0]->mailbox . '@' . $headersFrom[0]->host;
			if ($headersFrom[0]->personal)	{
				$fromName = $headersFrom[0]->personal;
			}else{
				$fromName = $headersFrom[0]->mailbox . '@' . $headersFrom[0]->host;
			}

			$fromName = char_replace (array ('<', '>', '"', '\''), '', $fromName);
			if (stristr ($fromName, '?iso-8859-1?'))		{
				$fromName = imap_utf8 ($fromName);
				$fromName = utf8_decode ($fromName);
			}else{
				if (stristr ($fromName, '?utf-8?'))		{
					$fromName = imap_utf8 ($fromName);
				}
			}
			$header_info['fromName'] = $fromName;
		}

		unset ($to);
		if ($headersTo = $headers->to)	{
			if (1 < sizeof ($headersTo))	{
				$toMailbox = $headersTo[0]->mailbox . '@' . $headersTo[0]->host;
				if (!strstr ($toMailbox, 'UNEXPECTED_DATA'))	{
					$to .= $toMailbox;
				}

				$i = 1;
				while ($i < sizeof ($headersTo) - 1) {
					$toMailbox = $headersTo[$i]->mailbox . '@' . $headersTo[$i]->host;
					if (!strstr ($toMailbox, 'UNEXPECTED_DATA'))	{
						$to .= ', ' . $toMailbox;
					}
					++$i;
				}
				$header_info['to'] = $to;
			}else{
				$header_info['to'] = $headersTo[0]->mailbox . '@' . $headersTo[0]->host;
			}
		}else{
			$header_info['to'] = '&nbsp;';
		}

		unset ($cc);
		if ($headersCc = $headers->cc)		{
			if (1 < sizeof ($headersCc))	{
				$i = 0;
				while ($i < sizeof ($headersCc) - 1)	{
					$ccMailbox = $headersCc[$i]->mailbox . '@' . $headersCc[$i]->host;
					$cc .= $ccMailbox . ', ';
					++$i;
				}

				$ccMailbox = $headersCc[sizeof ($headersCc) - 1]->mailbox . '@' . $headersCc[sizeof ($headersCc) - 1]->host;
				$cc .= $ccMailbox;
				$header_info['cc'] = $cc;
			}else{
				$header_info['cc'] = $headersCc[0]->mailbox . '@' . $headersCc[0]->host;
			}
		}

		if ($headers->Date)	{
			$header_info['date'] = htmlspecialchars ($headers->Date);
		}else{
			$header_info['date'] = '&nbsp;';
		}

		if ($headers->subject)	{
			$subject = htmlspecialchars ($headers->subject);
			if (stristr ($subject, '?iso-8859-1?'))		{
				$subject = imap_utf8 ($subject);
				$subject = utf8_decode ($subject);
			}else{
				if (stristr ($subject, '?utf-8?'))	{
					$subject = imap_utf8 ($subject);
				}
			}
			$header_info['subject'] = $subject;
		}else{
			$header_info['subject'] = '{none}';
		}
	}else{
		$header_info = false;
	}
	return $header_info;
}



function addlink ($str){
	$link = preg_replace ('¬((http|https|ftp):\\/\\/)(([-_a-zA-Z1-9]+)\\.)+([-_a-zA-Z1-9]{2,3})((/([-_a-zA-Z0-9\\.\\/\\?\\=\\%\\&\\;]+)?)?)¬', '<a href="\\0">\\0</a>', $str);
	return $link;
}


$type = array ('text', 'multipart', 'message', 'application', 'audio', 'image', 'video', 'other');
$encoding = array ('7bit', '8bit', 'binary', 'base64', 'quoted-printable', 'other');
?>