<?
########## Confixx(R) 3.0 Professional ############
####### Copyright SWsoft, Inc. 2004-2005 ##########
#### http://www.sw-soft.com - info@sw-soft.com ####

function dateFormat($timeStamp,$format) {
  if($format == "datetime") {
    return date("d.m.Y H:i", $timeStamp);
  }
  if($format == "date") {
    return date("d.m.Y", $timeStamp);
  }
  if($format == "time") {
    return date("H:i", $timeStamp);
  }
  if($format == "sortdate") {
    return date("YmdHi", $timeStamp);
  }
}

function sizeFormat($size) {
  if($size < 99999) {
    $size = round(($size/1024),2)."k";
  } else {
    $size = round(($size/1024)/1024,2)."M";
  }
  return $size;
}

function getLine() {
  global $fp;
  //return fgets($fp, 1024);
  return substr(fgets($fp, 1024), 0, -2);
}
 
function getLine2() {
  global $fp;
  while (!feof($fp)) {
    $buffer = fgets($fp, 4096);
  }
}

function removeLineBreaks($string) {
  return strtr($string, "\r\n", "  ");
}

function get_options()
{
	$id = db_query('SELECT imap_options FROM admin');	
	$res = db_fetch_array($id);
	return $res['imap_options'];
}

function set_options($options)
{
	safe_query2( 'UPDATE admin SET imap_options=?', new SQLString($options) );
}

function server_connect($options = '')
{
	global $cnf_user;//, $cnf_pass;
	global $mail_pop3Server;
	if (!isset($mail_pop3Server)){
		$mail_pop3Server='localhost';
	}
	//$mbox = false;
	$strConn='{'.$mail_pop3Server.':110/pop3'.$options.'}INBOX';
	if($mbox = @imap_open ($strConn, $cnf_user, getUserParam($cnf_user, 'password')))
	{
		delUserParam($cnf_user, 'old_password');
	}
	elseif ($pass = getUserParam($cnf_user, 'old_password'))
	{
		$mbox = @imap_open ($strConn, $cnf_user, $pass);
	}
	
	return $mbox;
}

function e_connect()
{
	global $mbox, $cnf_server, $cnf_port, $cnf_user, $cnf_pass;
	$ret = false;
	
	if($mbox = server_connect(get_options()))
	{
		$ret = true;	
	}
	
	if(!$ret)
	{
		$opts = array('', '/notls/novalidate-cert', '/notls', '/novalidate-cert');
		
		foreach ($opts as $op)
		{
			if($mbox = server_connect($op))	
			{
				$ret = true;
				set_options($op);
				break;	
			}
		}
	}
	return $ret;
}


function getHeaders($headerArray) {
  for ($i = 0; $i < sizeof($headerArray); $i++) {
    $parts = explode(": ", $headerArray[$i], 2);
    $headers[strtolower($parts[0])] = $parts[1];
  }
  return $headers;
}

/*
function mimeHeaderDecode($string) {
  if (strstr($string, "=?")) {
    $explode = explode("=?", $string);
    $newString = $explode[0];
    for ($i = 1; $i < sizeof($explode); $i++) {
      $explode2 = explode("?", $explode[$i]);
      $newString .= (strtolower($explode2[1]) == "q") ? quoted_printable_decode($explode2[2]) : base64_decode($explode2[2]);
      $newString .= substr($explode2[3], 1);
    }
  }
  else return $string;
  return $newString;
}
*/
function mimeHeaderDecode($string)
{
	return decode_subject($string);
}

function showBody($body) {
  $body = htmlspecialchars($body);
  //$body = str_replace("  ", "&nbsp;&nbsp;", $body);
  //$body = str_replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;", $body);
  
  # Making bold text out of *text*:
  $body = eregi_replace(" \*([a-z0-9]+[^*]*[a-z0-9]+)\*", " <b>\\1</b>", $body);
  # Making italic text out of /text/:
  $body = eregi_replace(" /([a-z0-9]+[^/]*[a-z0-9]+)/", " <i>\\1</i>", $body);
  # Making underlined text out of _text_:
  $body = eregi_replace(" _([a-z0-9]+[^_]*[a-z0-9]+)_", " <u>\\1</u>", $body);

  $body = eregi_replace("([a-z0-9._-]+@[a-z0-9.-]+\.[a-z]{2,6})", "<a href='email_neu.php?writeTo=\\1'>\\1</a>", $body);
  $body = eregi_replace("((f|ht)tps?://[^ \r]*[^ \r,.:!?)])", "<a href='\\1' target='_blank'>\\1</a>", $body);
  
  $body = nl2br($body);
  return $body;
}

// Parses an address string such as "Testname <test@example.com>" and
// returns the name as well as the email address.
function getSender($sender) {
  $senderParts["name"] = $sender;

  if (($pos = strrpos($sender, "<")) && substr($sender, -1) == ">") {
    $senderParts["name"] = substr($sender, 0, $pos - 1);
    $senderParts["email"] = substr($sender, $pos);
  }

  $firstChar = substr($senderParts["name"], 0, 1);
  $lastChar = substr($senderParts["name"], -1);
  if ($firstChar == "\"" || $firstChar == "'") $senderParts["name"] = substr($senderParts["name"], 0);
  if ($lastChar == "\"" || $lastChar == "'") $senderParts["name"] = substr($senderParts["name"], 0, -1);

  return $senderParts;
}

function headerInfo($string) {
//    echo "<br>---<br>".nl2br($string)."<br>---<br>";
 $string = str_replace("filename = ", "filename=", $string);
 $lookingFor = array("contentType" => "Content-Type: ", "boundary" => "boundary=", "charSet" => "charset=", "name" => "name=", "contentTransferEncoding" => "Content-Transfer-Encoding: ", "contentDisposition" => "Content-Disposition: ", "fileName" => "filename=");
  $getValue = "[\"']?([^\"';\r]+)";
  reset($lookingFor);
  while (list($key, $value) = each($lookingFor)) {
    ereg("$value$getValue", $string, $matches);
    $info[$key] = $matches[1];
    unset($matches);
  }
  return $info;
}

function showInLine($contentType, $showImagesInLine = true) {
  $returnValue = false;
  $category = substr($contentType, 0, strpos($contentType, "/"));
  if ($category == "text" || $category == "message") $returnValue = true;
  if ($showImagesInLine) {
    $inLineImages = array("image/png", "image/jpeg", "image/gif");
    if (in_array($contentType, $inLineImages)) $returnValue = true;
  }
  return $returnValue;
}

function headerArray($header)
{
	$types = array(TYPETEXT => 'text', TYPEMULTIPART => 'multipart', TYPEMESSAGE => 'message',
			TYPEAPPLICATION => 'application', TYPEAUDIO => 'audio',TYPEIMAGE => 'image',
			TYPEVIDEO => 'video', TYPEOTHER => 'other',
			);
	$encodings = array(ENC7BIT => '7bit', ENC8BIT => '8bit', ENCBINARY => 'binary', ENCBASE64 => 'base64', 
			ENCQUOTEDPRINTABLE => 'quoted-printable', ENCOTHER => 'other',
			);
			
	$params = array('parameters', 'dparameters');
	$out = false;
	
	if(is_object($header))
	{
		$out = array();
		$out['type'] = $types[$header->type];
		if($header->ifsubtype)
		{
			$out['type'] .= '/' . strtolower($header->subtype);
		}
		$out['encoding'] = $encodings[$header->encoding];
		if($header->ifdisposition)
		{
			$out['disposition'] = strtolower($header->disposition);
		}
		$out['lines'] = $header->lines;
		$out['bytes'] = $header->bytes;
		
		foreach($params as $par)
		{
			$ifpar = "if" . $par;	
			if($header->$ifpar)
			{
				if( is_array($header->$par) )
				{
					$out[$par] = array();
					foreach($header->$par as $p)
					{
						$out[$par][strtolower($p->attribute)] = $p->value;
					}
				}
			}
		}
	}
	
	return $out;
}

function decode_subject($subject)
{
	if( preg_match_all('/=\?.*\?(.)\?(.*)\?=/U', $subject, $f) )
	{
		foreach($f[0] as $k => $v)
		{
			$strrep = "";
			if( strtolower($f[1][$k]) == "b" )
			{
				$strrep = base64_decode($f[2][$k]);
			}
			if( strtolower($f[1][$k]) == "q" )
			{
				$strrep = quoted_printable_decode($f[2][$k]);
			}
			if($strrep)
			{
				$subject = str_replace($v, $strrep, $subject)	;
			}
		}
	}
	
	return $subject;
}


function show_mail($body, $type, $encoding)
{
	global $lang_text, $showHtml, $PHP_SELF, $id;
	global $linkToHtml;
	
	echo "<tr><td>";
	if ($encoding == "quoted-printable")
	{
		$body = quoted_printable_decode($body);
	}
	if($encoding == "base64")
	{
		$body = base64_decode($body);
	}
	//$body = $partInfo[$i]["body"];
	if($type == "text/html") 
	{
		if(!$showHtml)
		{
			if ( !$linkToHtml ) { // show link only one time
				
				$linkToHtml = 1;
				
				echo "<hr noshade size=1>";
				echo $lang_text["wbm_msg_htmlalert"]."<br>";
				echo "<a class=data href=$PHP_SELF?id=$id&showHtml=1><b>&raquo; ".$lang_text["wbm_msg_htmlshow"]."</b></a><hr noshade size=1><br>";
				
			}	
		}
		else 
		{
			$body_html = str_replace("\n","",$body);
			echo $body_html;
		}
	}
	else
	{
		if(!$showHtml)
		{
			$body = showBody($body);
			$body_text = str_replace("<br />","<br>",$body);
			echo "$body_text\n";
		}
	}
	//$body = str_replace("charset=&quot;iso-8859-1&quot;", "<meta http-equiv=\"content-type\" content=\"charset=iso-8859-1\">", $body);
	echo "</td></tr>";	
}

function correctType ( &$ha, &$body ) {
	if ( ( !$ha['type'] || ( $ha['type'] == "text/plain" ) ) 
		&& eregi( "<html>.*</html>", $body) )	{
		$ha['type'] = "text/html";
	}	
	if ( $ha['type'] == "text/html" ) {
			if ( preg_match('/^.+?</i',$body) ) { // check if there is chars befor the first tag
				$body = preg_replace('/^.+?</i','<',$body); // clean all chars befor the first tag
			}
	}
}

function &parseMultipart ( &$body, $boundary ) {
	
	global $DEBUG;
	
	if ( $DEBUG ){
		echo "boundary: $boundary<br>\n";	
		echo "body:<hr><pre>$body</pre><hr>\n";
	}
	
	$boundary = '--'.$boundary;
	$len = strlen($boundary);
	$state = 0;
	$arRes = array();
	$iPart = 0;


	$tok = strtok($body,"\n");
	while ( $tok ){
		
		if ($DEBUG) {
			echo "$state: $tok<br>\n";	
		}
		
		$tok = rtrim( $tok );
		if ( strncmp($boundary,$tok,$len) ) { 

			if ( !$tok ){ ## empty line
				if ( $state == 1 ){
					$state = 2; ## end of head
					$contentName='';
				}
			}
			if ( $state == 1 ) { ## in head
				if ( preg_match( '/^([-\w]+):\s+(.*)/', $tok, $matches) ) {
					$contentName = $matches[1];
					$contentValue = $matches[2];
					$arRes[$iPart]['content'][$contentName] = $contentValue;
				} else {
					$contentValue = ltrim($tok);
					$arRes[$iPart]['content'][$contentName] .= $contentValue;
				}
			} else {

				if ( $state == 2 ) {
					$state++; ## skip first blank line
				} else if( $state == 3 ) {
					$arRes[$iPart]['body'] .= $tok."\r\n";
				}
			}
		} else {

			if ( strlen( $tok ) > $len ){
				break; ## end of body
			} else {
				
				if ( $state ) {
					$iPart++;  ## new part
				}
				$arRes[$iPart] = array('content'=>array(),'body'=>'');
				$state = 1;
			}
		}

		$tok = strtok("\n"); ## get next line
	}

//
// add 'type','encoding'-keys to the array of content parameters
//
	for ( $i=0; $i<$iPart; $i++ ) {
		$arContent =& $arRes[$iPart]['content'];
		foreach ( $arRes[$i]['content'] as $key => $value )  {
			
			if ( preg_match('/type/i', $key) ) {
				foreach ( explode(';',$value)	as $contentValue ) {
				
					if ( preg_match('/\w+\/\w+/', $contentValue) ) {
						$arRes[$i]['content']['type'] = $contentValue;
					} elseif ( preg_match('/boundary\s*=\s*"(.*)"/i',$contentValue,$matches ) ) {
						$arRes[$i]['content']['boundary'] = $matches[1];
					}		
				}
			} elseif ( preg_match( '/encoding/i', $key ) ) {
				$arRes[$i]['content']['encoding'] = $value;
			}				
		}
	} 
	
	return $arRes;
}

?>
