<?php
/*
This file is part of Thomas Bley's moregroupware webmail2/calendar2/admin2 module. (tb-mgw)

More information:
-----------------

Simple Groupware Solutions Thomas Bley
Fichtenstr. 23
Germany, 85640 Putzbrunn

Contact:
--------

info@simple-groupware.de

http://www.simple-groupware.de


Copyright 2002-2003 Thomas Bley
tb-mgw is distributed under the terms of the GNU General Public License 

tb-mgw is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

tb-mgw is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with tb-mgw; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

// webmail2_func
// Moregroupware.org

$MGW = $_SESSION["MGW"];

define('WM2_INC_DIR', ROOTPATH."/modules/webmail2/inc/");
define('WM2_DIR', ROOTPATH."/modules/webmail2/");

include WM2_INC_DIR."mime_types.php";

if (get_magic_quotes_gpc() == 1){
  if (is_array($_POST) and count($_POST)>0)
  while (list ($key, $val) = each ($_POST)){
    $_POST[$key] = stripslashes_array($val);
  }
  if (is_array($_GET) and count($_GET)>0)
  while (list ($key, $val) = each ($_GET)){
    $_GET[$key] = stripslashes_array($val);
  }
  if (is_array($_COOKIE) and count($_COOKIE)>0)
  while (list ($key, $val) = each ($_COOKIE)){
    $_COOKIE[$key] = stripslashes_array($val);
  }
}


function store_webmail_maillist($mbox_id,$account,$msg_begin) {
  $_POST["option"] = "";
  require_once("../settings/inc/settings_func.inc.php");
  store_flag ("wm2_default_mbox_id","webmail2","str");
  updateSettingsInDB("wm2_default_mbox_id", $mbox_id);
  store_flag ("wm2_default_account2","webmail2","str");
  updateSettingsInDB("wm2_default_account2", $account);
  store_flag ("wm2_default_msg_begin","webmail2","str");
  updateSettingsInDB("wm2_default_msg_begin", $msg_begin);
}

function store_webmail_readmessage($markmessage) {
  $_POST["option"] = "";
  require_once("../settings/inc/settings_func.inc.php");
  store_flag ("wm2_default_markmessage","webmail2","str");
  updateSettingsInDB("wm2_default_markmessage", $markmessage);
}

function clean_html($text) {
    $text = preg_replace(array(
	  		"'<script[^>]*?>.*?</script[^>]*?>'si",
	  		"'<applet[^>]*?>.*?</applet[^>]*?>'si",
			"'<object[^>]*?>.*?</object[^>]*?>'si",
			"'<iframe[^>]*?>.*?</iframe[^>]*?>'si",
	  		"'<frameset[^>]*?>.*?</frameset[^>]*?>'si",
	  		"'<style[^>]*?>.*?</style[^>]*?>'si",
	  		"'<marquee[^>]*?>.*?</marquee[^>]*?>'si",
			"'<script[^>]*?>'si",
	  		"'<meta[^>]*?>'si",
			"'<base[^>]*?>'si",
			"'<applet[^>]*?>'si",
			"'<object[^>]*?>'si",
			"'<link[^>]*?>'si",
			"'<iframe[^>]*?>'si",
			"'<frame[^>]*?>'si",
			"'<frameset[^>]*?>'si",
			"'<input[^>]*?>'si",
			"'<form[^>]*?>'si",
			"'<embed[^>]*?>'si",
			"'background-image:url'si",
			"'<\w+ .*?(javascript:|onabort|onbeforeunload|onblur|onchange|onclick|ondblclick|ondragdrop|onerror|onfilterchange|onfocus|onhelp|onkeydown|onkeypress|onkeyup|onload|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|onmove|onreadystatechange|onreset|onresize|onscroll|onselect|onselectstart|onsubmit|onunload).*?>'si",
			), '', $text);
return $text;
}

function clean_html_signature($text) {
    $text = preg_replace(array(
	  		"'<script[^>]*?>.*?</script[^>]*?>'si",
	  		"'<applet[^>]*?>.*?</applet[^>]*?>'si",
			"'<object[^>]*?>.*?</object[^>]*?>'si",
			"'<iframe[^>]*?>.*?</iframe[^>]*?>'si",
	  		"'<frameset[^>]*?>.*?</frameset[^>]*?>'si",
	  		"'<style[^>]*?>.*?</style[^>]*?>'si",
	  		"'<marquee[^>]*?>.*?</marquee[^>]*?>'si",
			"'<script[^>]*?>'si",
	  		"'<meta[^>]*?>'si",
			"'<base[^>]*?>'si",
			"'<applet[^>]*?>'si",
			"'<object[^>]*?>'si",
			"'<link[^>]*?>'si",
			"'<iframe[^>]*?>'si",
			"'<frame[^>]*?>'si",
			"'<frameset[^>]*?>'si",
			"'<input[^>]*?>'si",
			"'<form[^>]*?>'si",
			"'<embed[^>]*?>'si",
			"'<img[^>]*?>'si",
			"'background-image:url'si",
			"'<\w+ .*?(onabort|onbeforeunload|onblur|onchange|onclick|ondblclick|ondragdrop|onerror|onfilterchange|onfocus|onhelp|onkeydown|onkeypress|onkeyup|onload|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|onmove|onreadystatechange|onreset|onresize|onscroll|onselect|onselectstart|onsubmit|onunload).*?>'si",
			), '', $text);
return $text;
}

function return_flags($email,$msg_no) {
  $myarr = sqimap_get_flags($email,$msg_no);
  
  $flags["deleted"] = 0;
  $flags["forward"] = 0;
  $flags["flagged"] = 0;
  $flags["seen"] = 1;
  $flags["reply"] = 0;

  $flags["important"] = 0;
  $flags["todo"] = 0;
  $flags["personal"] = 0;
  $flags["work"] = 0;
  $flags["later"] = 0;
  
  foreach ($myarr as $my) {
    if ($my == "Seen") { $flags["seen"] = 0; }
      else if ($my == "Answered") { $flags["reply"] = 1; }
      else if ($my == "\$Label1") { $flags["important"] = 1; }
      else if ($my == "\$Label2") { $flags["work"] = 1; }
      else if ($my == "\$Label3") { $flags["personal"] = 1; }
      else if ($my == "\$Label4") { $flags["todo"] = 1; }
      else if ($my == "\$Label5") { $flags["later"] = 1; }
      else if ($my == "Flagged") { $flags["flagged"] = 1; }
      else if ($my == "Deleted") { $flags["deleted"] = 1; }
      else if ($my == "\$Forwarded") { $flags["forward"] = 1; }
  }
  
  return $flags;
}
          
function my_decodeHTML($string) {
   $string = strtr($string, array_flip(get_html_translation_table(HTML_ENTITIES)));
   $string = preg_replace("/&#([0-9]+);/me", "chr('\\1')", $string);
   return $string;
}

function make_contact_links($to) {
  $to = str_replace(array("&quot;"),array("\""),$to);

  $in = false;
  for ($i=0;$i<strlen($to);$i++) {
    if ($to[$i]=="\"") {
	  $in = !$in;
	}
	if ($to[$i]=="," and $in) {
	  $to[$i] = "§";
	}
  }
  $to_arr = explode(",",$to);
  if (is_array($to_arr) and count($to_arr)>0) {
    $to = "";
    foreach ($to_arr as $to_key=>$to_key2) {
      $to_key2 = str_replace("§",",",$to_key2);
	  if ($to!="") { $to .= ", ";}
      $to .= "<a style='text-decoration: none' href='../contact/index.php?mod=contact&obj=person&view=newform&wm2_contact=".urlencode($to_key2)."&".SID."' target='_blank'>".str_replace(array("\"","'"),"",$to_key2)."</a>";
    }
  }
  return $to;
}

function get_all_email_addresses($to) {
  $to = str_replace(array("&quot;"),array("\""),$to);

  $in = false;
  for ($i=0;$i<strlen($to);$i++) {
    if ($to[$i]=="\"") {
	  $in = !$in;
	}
	if ($to[$i]=="," and $in) {
	  $to[$i] = "§";
	}
  }
  $to_arr = explode(",",$to);
  if (is_array($to_arr) and count($to_arr)>0) {
    $to = "";
    foreach ($to_arr as $to_key=>$to_key2) {
      $to_key2 = str_replace("§",",",$to_key2);
	  $to_key2 = preg_replace("/(.*)<(.*)>/","\\2",$to_key2);
	  $to_key2 = trim(str_replace(array("<",">"),"",preg_replace(array("/\"(.*)\"/","/'(.*)'/"),"",$to_key2)));
	  if ($to!="") { $to .= ", ";}
      $to .= $to_key2;
    }
  }
  return $to;
}

function connect_my_imap($account,$mbox_id,$error) {

  global $conn,$user_id,$imap_conn_error,$username,$trash_name,$trash_name_id,$mbox_id_name,$mboxname,$delimiter;
  $mboxname = "";
  $trash_name = "";
  $mbox_id_name = "";
  $delimiter = ".";
  
  include CACHE_FOLDER."imap/tree/".$account.".php";
  foreach ($folders as $folder) {
    if ($folder[1] == $mbox_id) {
      $mboxname = $folder[2];
      $mbox_id_name = $folder[7];
    }
  }

  $sql = "select * from mgw_webmail2_accounts where mailboxname!='' and activated='checked' and servertype='wm2_servertype_imap_only' and id=".(int)$account." and user_id=".(int)$user_id;
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));

  $email = false;
  if ($res->RecordCount() != 0 and $mbox_id!="") {
    $account_row = $res->FetchRow();

    require_once(WM2_INC_DIR.'imap/imap.php');
    require_once(INCLUDEPATH . "crypt.inc.php");

    if ($account_row["enable_ssl"]=="checked") {
      $default_port = "993";
    } else {
      $default_port = "143";
	}

    $myC = new Crypto();
    $email = my_imap_connect("int",$default_port,"imap",$account_row,$myC->decrypt($username, $account_row["password"]),$mbox_id_name);
    $imap_conn = $email;

    $delimiter = sqimap_get_delimiter($email);
	
    if (isset($imap_conn_error) and $imap_conn_error!="") {
      if ($error) echo "<script>alert('Error: ".addslashes($imap_conn_error)."');</script>";
      $email = false;
    }
  }

  include CACHE_FOLDER."imap/tree/".$account.".php";
  foreach ($folders as $folder) {
    if (strtolower($folder[7]) == "inbox".$delimiter."trash" or strtolower($folder[7]) == "trash") {
      $trash_name = $folder[7];
      $trash_name_id = $folder[1];
    }
  }

  return $email;
}

function getmessage_id($header) {
  if (strlen($header->message_id) < 10) {
    if (!isset($header->subject)) {$header->subject="";}
    if (!isset($header->toaddress)) {$header->toaddress="";}
    if (!isset($header->fromaddress)) {$header->fromaddress="";}
    if (!isset($header->date)) {$header->date="";}
	return crc32(decode_mime_string(trim($header->subject)).decode_mime_string(trim($header->toaddress)).decode_mime_string(trim($header->fromaddress)).$header->date);
  } else {
    return $header->message_id;
  }
}

function mboxname_replace_imap($mboxname) {
  global $hashmap;
  
  $mboxname2 = strtolower($mboxname);
  switch ($mboxname2) {
    case "inbox": $mboxname = $hashmap["webmail2_func_inbox"]; break;
    case "drafts": $mboxname = $hashmap["webmail2_func_drafts"]; break;
    case "sent": $mboxname = $hashmap["webmail2_func_sent"]; break;
    case "trash": $mboxname = $hashmap["webmail2_func_trash"]; break;
    case "spam": $mboxname = $hashmap["webmail2_func_spam"]; break;
  }    
  return $mboxname;
}

function draw_array($the_array,$second) {
  if (is_array($the_array)) {
  	$return_string = "array(";
    foreach ($the_array as $the_arrayer) {
      if (is_array($the_arrayer)) {
		$return_string .= draw_array($the_arrayer,false);
	  } else {
	    $return_string .= "\"".addcslashes(addslashes($the_arrayer),"\$")."\",";
	  }
	}
  	$return_string .= ")";
	if (!$second) {$return_string .= ",\n";} else {$return_string .= ";\n";}
  } else {
    $return_string .= "\"".addcslashes(addslashes($the_array),"\$")."\"";
	if (!$second) {$return_string .= ",\n";} else {$return_string .= ";\n";}
  }
  return $return_string;
}

function shorten_sub_string($str,$len) {
  if (strlen($str) > $len) {
	$str = substr($str,0,$len)." ...";
  }
  return $str;
}

function htmlspecial_mime($subject) {
  return trim(htmlspecialchars(decode_mime_string(str_replace(array("\n","\r"),array("",""),trim($subject)))));
}

function format_filesize($full_size) {
  if (is_numeric($full_size)) {
    if ($full_size > 1024*1024*1024*1024) {
      $full_size = number_format(($full_size / (1024*1024*1024*1024)),2)." TB";
    } else if ($full_size > 1024*1024*1024) {
      $full_size = number_format(($full_size / (1024*1024*1024)),2)." GB";
    } else if ($full_size > 1024*1024) {
      $full_size = number_format(($full_size / (1024*1024)),1)." MB";
    } else if ($full_size > 1024) {
      $full_size = number_format(($full_size / 1024),1)."K";
    } else {
      $full_size = number_format(($full_size),1)." byte";
    }
  }
  return $full_size;
}

function getmailadr($str) {
  if (!strpos($str,"(")) {
    $arr = Mail_RFC822::parseAddressList(strtolower($str)." (abc)", '', TRUE);
  } else {
    $arr = Mail_RFC822::parseAddressList(strtolower($str), '', TRUE);
  }
  $str2 = trim($arr[0]->mailbox."@".$arr[0]->host);
  if ($str2 != "" and $str2 != "@") { return $str2; } else { return $str; }
}

function quote2($str) {
  return stripslashes(myquote($str));
}

function user_exists($temp) {
  global $conn;
  $sql = "select id from mgw_users where username=".$conn->Quote($temp);
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
  $row = $res->FetchRow();
  if (isset($row["id"]) and is_numeric($row["id"])) return true;
    else return false;
}

function getallusers2() {
  global $conn;
  $sql = "select username,id from mgw_users";
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
  $users = array();
  while ($row = $res->FetchRow()) {
    $users[$row["id"]] = strtolower($row["username"]);
  }
  return $users;
}

function treesort($tree) {
  global $folders,$folders2;
  foreach ($tree as $key=>$key2) {
    $folders2[] = $folders[$key];
    if (is_array($key2) and count($key2)!=0) {
      treesort($key2);
    }
  }
}

function getchildren($tree,$boxid) {
  foreach ($tree as $key=>$key2) {
    if ($boxid==$key) {
      if (is_array($key2) and count($key2)!=0) {
        arrtolist($key2);
      }
    } else {
      if (is_array($key2) and count($key2)!=0) {
        getchildren($key2,$boxid);
      }
    }
  }
}

function arrtolist($tree) {
  global $children;
  foreach ($tree as $key=>$key2) {
    $children[] = $key;
    if (is_array($key2) and count($key2)!=0) {
      arrtolist($key2);
    }
  }
}
  
function myquote($s) {	
  $replaceQuote = "\\'";

	if ($replaceQuote[0] == '\\'){
	  $s = str_replace('\\','\\\\',$s);
	}
	return  str_replace("'",$replaceQuote,$s);
}
		
function getdirnr($msg_id) {
  if ($msg_id%10000==0) {
    $dir_nr = $msg_id/10000;
  } else {$dir_nr = 0;}
  return $dir_nr;
}

function checkdir($dirname,$htaccess) {
  global $hashmap;
  
  error_reporting (E_ERROR | E_PARSE);
  if (!is_dir($dirname)) {
    $dirname2 = $dirname;
	if ($dirname2[strlen($dirname2)-1]=="/") $dirname2 = substr($dirname2,0,-1);
	$dirname2 = substr($dirname2,0,strrpos($dirname2,"/"));
    if (is_writeable($dirname2)) {
      mkdir($dirname,0777);
    } else {die($hashmap["index_att_dir_does_not_exist"]." ".$dirname);}
  }
  if (!is_writeable($dirname)) {
    die($hashmap["index_att_dir_does_not_exist"]." ".$dirname);
  }
  if (!file_exists($dirname."index.htm")) {
    $fd = fopen($dirname."index.htm", "w");
    fwrite($fd, "You are not allowed to view this folder.");
    fclose($fd);
  }
  if (!file_exists($dirname."index.html")) {
    $fd = fopen($dirname."index.html", "w");
    fwrite($fd, "You are not allowed to view this folder.");
    fclose($fd);
  }
  if ($htaccess and !file_exists($dirname.".htaccess")) {
    $fd = fopen($dirname.".htaccess", "w");
    fwrite($fd, "Order deny,allow\nDeny from all\n");
	// AuthName \"MoreGroupWare Store - No Access\"\nAuthType Basic\nrequire mgw\n");
    fclose($fd);
  } elseif (!$htaccess and file_exists($dirname.".htaccess")) {
    unlink($dirname.".htaccess");
  }
  error_reporting  (E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

}

function hasrights($theright,$mbox_id,$username) {
  global $conn;
  return true;
}

function mboxname_replace($mboxname) {
global $hashmap;
  
  switch ($mboxname) {
    case "publictrash": $mboxname = $hashmap["webmail2_func_public_trash"]; break;
    case "public": $mboxname = $hashmap["webmail2_func_public_users"]; break;
    case "inbox": $mboxname = $hashmap["webmail2_func_inbox"]; break;
    case "draft": $mboxname = $hashmap["webmail2_func_drafts"]; break;
    case "sent": $mboxname = $hashmap["webmail2_func_sent"]; break;
    case "spam": $mboxname = $hashmap["webmail2_func_unwished"]; break;
    case "trash": $mboxname = $hashmap["webmail2_func_trash"]; break;
  }
  return $mboxname;
}

function shorten($mystr) {
  if ($mystr!="") {
    $helpstr = htmlnonspecialchars($mystr);
    if ($helpstr[0]=="<") {$mystr = str_replace(array("&lt;","&gt;"),array("",""),$mystr);}
  }
  return $mystr;
}

function shorten2($header_from_to2) {
if (trim($header_from_to2)!="") {
  $header = split(",",$header_from_to2);
  $full = "";
  foreach ($header as $key=>$header_from_to) {
    $helper = trim(strip_tags($header_from_to));
    
    if ($helper != "") {
      if ($helper[0] == "'" and $helper[strlen($helper)-1] == "'") {
        $helper = substr($helper,1,strlen($helper)-2);
      } else if ($helper[0] == "\"" and $helper[strlen($helper)-1] == "\"") {
        $helper = substr($helper,1,strlen($helper)-2);
      }
    } else {$helper = trim($header_from_to);}

//    echo $helper." ".$helper[strlen($helper)-1]."<br>\n";
    if ($helper!="") {
      if ($helper[0] == "<" and $helper[strlen($helper)-1] == ">") {
        $helper = substr($helper,1,strlen($helper)-2);
      }
      if ($helper[strlen($helper)-1] == ")") {
        $thename = substr($helper,strpos($helper,"(")+1,strlen($helper)-strpos($helper,"(")-2);
        if ($thename != "") {$helper = $thename;}
      }
    }
    if ($full != "") {$full .= ", ";}
    $full .= $helper;
  }
  
  if ($full!="") {
    if ($full[0] == "'" or $full[0] == "\"") {
      $full = substr($full,1);
    }
    if ($full[strlen($full)-1] == "'" or $full[strlen($full)-1] == "\"") {
      $full = substr($full,0,strlen($full)-1);
    }
    return $full;
  } else {
    return $header_from_to2;
  }
} else {
  return $header_from_to2;
}
}

function calc_ebene(&$tree,$ebene) {

  global $folders;
  if (is_array($tree) and count($tree)!=0) {
    foreach ($tree as $key=>$key2) {
      $folders[$key][4]=str_repeat("&nbsp;&nbsp;&nbsp;",$ebene);
      if (is_array($key2) and count($key2)!=0) {
        calc_ebene($tree[$key],$ebene+1);
      }
    }
  }
}

function addtotree($parent,&$tree,$element) {
  if (is_array($tree) and count($tree)!=0 and $parent!=0) {
    if (isset($tree[$parent])) {
      $tree[$parent][$element] = "";
    } else {
      foreach ($tree as $key=>$key2) {
        if (is_array($key2) and count($key2)!=0) {
          addtotree($parent,$tree[$key],$element);
        }
      }
      /*
      if ($ebene1 == $ebene) {
        unset($tree[$element]);
        $tree[$element] = "";
      }
      */
    }
  } else if ($parent == 0) {
    $tree[$element] = "";
  }
}
  
function create_boxes ($boxes) {
  global $conn;

  foreach ($boxes as $key=>$box) {
    if (!boxexist2($box[0],$box[1],$box[2])) {
	  $new_id  = mgw_genID('mgw__seq_mailboxes',3);
      if ($box[0]=="trash" or $box[0]=="spam") {$isintrash=1;} else {$isintrash=0;}
      if ($box[0]=="draft") {$isdraft=1;} elseif ($box[0]=="sent") {$isdraft=2;} else {$isdraft=0;}
      $sql = "INSERT INTO mgw_webmail2_mailboxes (createdby,created,mbox_id,user_id, mboxname, mboxparent, mbox_protect,isintrash,isdraft) VALUES (".(int)$box[2].",".time().",".(int)$new_id.",".(int)$box[2].",'".$box[0]."','".$box[1]."',1,".(int)$isintrash.",".(int)$isdraft.")";
      if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
      
      if ($box[0]=="inbox") {
        $msg_id = mgw_genID('mgw__seq_messages');
        $uid = "<".date("YmdHi").".".substr(ereg_replace("/","X",md5(mt_rand(1,6000))),0,12)."@".$_SERVER["SERVER_NAME"].">";

        $sql = "INSERT INTO mgw_webmail2_messages (notified,msg_cache,message_id,account_name,uid,type,mbox_id,header_from,header_to,header_cc,header_bcc,header_replyto,header_date,header_subject,header_size,header_inreplyto,msg_body,recentbit,readbit,replybit,draftbit,flaggedbit,forwardbit,attachbit,labelbit) VALUES('0','9426c311e76888b3b2368150cd05f362',".(int)$msg_id.",'','".$uid."','eml',".(int)getboxid("inbox",0,$box[2]).",'Thomas Bley <thomas.bley@simple-groupware.de>','MoreGroupWare-User','','','','".time()."','Small Webmail Manual #1',".filesize("docu/docu1.eml").",'','docu/docu1.eml','1','0','0','0','3','0','1','0')";
        if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
      }
    }
  }
}

function getboxid($boxname,$parent,$user_id) {
  global $conn;
  $sql = "select mbox_id from mgw_webmail2_mailboxes where mboxname='".$boxname."' and user_id=".(int)$user_id;
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
  $row = $res->FetchRow();
  $mbox_id = $row["mbox_id"];
  return $mbox_id;
}

function boxexist($box_id,$user_id) {
  global $conn;
  $sql = "select mbox_id from mgw_webmail2_mailboxes where mbox_id=".(int)$box_id." and user_id=".(int)$user_id;
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
  $row = $res->FetchRow();
  if ($row["mbox_id"]!="") {return true;} else {return false;}
}

function boxexist2($boxname,$parent,$user_id) {
  global $conn;
   $sql = "select mbox_id from mgw_webmail2_mailboxes where mboxparent=".(int)$parent." and mboxname='".$boxname."' and user_id=".(int)$user_id;
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
  $row = $res->FetchRow();
  if ($row["mbox_id"]!="") {return true;} else {return false;}
}

function has_write_rights_mbox($box_id,$user_id) {
  global $conn;
  $sql = "select mbox_id from mgw_webmail2_mailboxes where mbox_id=".(int)$box_id." and (user_id=".(int)$user_id." or user_id=0)";
    if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
    $row = $res->FetchRow();
  if ($row["mbox_id"]!="") {return true;} else {return false;}
}

function has_read_rights_mbox($box_id,$user_id) {
  global $conn;
  $sql = "select mbox_id from mgw_webmail2_mailboxes where mbox_id=".(int)$box_id." and (user_id=".(int)$user_id." or user_id=0)";
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
  $row = $res->FetchRow();
  if ($row["mbox_id"]!="") {return true;} else {return false;}
}

function has_read_rights_mail($mail_id,$user_id) {
  global $conn;
  $sql = "select mbox_id from mgw_webmail2_messages where message_id=".(int)$mail_id;
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
  $row = $res->FetchRow();

  if ($row["mbox_id"]!="") {

    $sql = "select mbox_id from mgw_webmail2_mailboxes where mbox_id=".(int)$row["mbox_id"]." and (user_id=".(int)$user_id." or user_id=0)";
    if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
    $row = $res->FetchRow();
    if ($row["mbox_id"]!="") {return true;} else {return false;}
  } else {
    return false;
  }
}

function has_write_rights_mail($mail_id,$user_id) {
  global $conn;
  $sql = "select mbox_id from mgw_webmail2_messages where message_id=".(int)$mail_id;
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
  $row = $res->FetchRow();

  if ($row["mbox_id"]!="") {

    $sql = "select mbox_id from mgw_webmail2_mailboxes where mbox_id=".(int)$row["mbox_id"]." and (user_id=".(int)$user_id." or user_id=0)";
    if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
    $row = $res->FetchRow();
    if ($row["mbox_id"]!="") {return true;} else {return false;}
  } else {
    return false;
  }
}

function isintrash($box_id) {
  global $conn;
  if ($box_id != "" and is_numeric($box_id) and $box_id > 0) {
    $sql = "select isintrash from mgw_webmail2_mailboxes where mbox_id=".(int)$box_id;
    if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
    $row = $res->FetchRow();
    if ($row["isintrash"]=="") {return 0;} else {return $row["isintrash"];}
  } else return 0;
}

function isdraft($box_id) {
  global $conn;
  if ($box_id != "" and is_numeric($box_id) and $box_id > 0) {
    $sql = "select isdraft from mgw_webmail2_mailboxes where mbox_id=".(int)$box_id;
    if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
    $row = $res->FetchRow();
    if ($row["isdraft"]=="") {return 0;} else {return $row["isdraft"];}
  } else return 0;
}

function getboxname($box_id) {
  global $conn;
  $sql = "select mboxname from mgw_webmail2_mailboxes where mbox_id=".(int)$box_id;
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
  $row = $res->FetchRow();
  return $row["mboxname"];
}

function getmessagecount($boxname) {
  global $conn;
  $sql = "select message_id from mgw_webmail2_messages where mbox_id=".(int)$boxname;
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
  $messagecount = $res->RecordCount();
  return $messagecount;
}

function getmessagecount_unread($boxname) {
  global $conn;
  $sql = "select message_id from mgw_webmail2_messages where readbit=1 and mbox_id=".(int)$boxname;
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
  $messagecount = $res->RecordCount();
  return $messagecount;
}

function htmlnonspecialchars($strvar) {
  $strvar=ereg_replace('&gt;', '>', $strvar);
  $strvar=ereg_replace('&lt;', '<', $strvar);
  $strvar=ereg_replace('&quot;', "\"", $strvar);
  $strvar=ereg_replace('&amp;', '&', $strvar);
  return $strvar;
}

function decode_mime_string ($string) {
  if (eregi("=?([A-Z,0-9,-]+)?([A-Z,0-9,-]+)?([A-Z,0-9,-,=,_]+)?=", $string)) {
    $coded_strings = explode('=?', $string);
    $counter = 1;
    $string = $coded_strings[0];
    while ($counter < sizeof($coded_strings)) {
      $elements = explode('?', $coded_strings[$counter]);
      if (isset($elements[1]) and eregi("Q", $elements[1])) {
        $elements[2] = str_replace('_', ' ', $elements[2]);
        $elements[2] = eregi_replace("=([A-F,0-9]{2})", "%\\1", $elements[2]);
        $string .= urldecode($elements[2]);
      } else {
        if (isset($elements[2])) {$elements[2] = str_replace('=', '', $elements[2]);}
        if (isset($elements[2]) and $elements[2]) { $string .= base64_decode($elements[2]); }
      }
      if (isset($elements[3]) && $elements[3] != '') {
        $elements[3] = ereg_replace("^=", '', $elements[3]);
        $string .= $elements[3];
      }
      $string .= " ";
      $counter++;
    }
  }
  return $string;
}

function getboxprot($box_id) {
  global $conn;
  $sql = "select mbox_protect from mgw_webmail2_mailboxes where mbox_id=".(int)$box_id;
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
  $row = $res->FetchRow();
  return $row["mbox_protect"];
}

?>
