Hey, Would you like to work at Home ?? Just click here No need to pay, just register free and activate your account and get data Entry Work at your Home.

Thursday, December 6, 2007

util.inc.php

/*
+----------------------------------------------------------------------+
| BasiliX - Copyright (C) 2000-2002 Murat Arslan |
| Contributions from: |
| Mike Peters |
+----------------------------------------------------------------------+
*/

// This file includes several useful functions..
// -----------------------------------------------------------------------

// You may want to set this, if when attaching a file to the message the connection
// hangs up due to time out.
set_time_limit(0);

// get an array containing some configuration details
function get_conf()
{
$conf = array();
// Should we use javascript?
if($_GET['is_js'])
{
$conf['is_js'] = $_GET['is_js'];
}
else if($_POST['is_js']){
$conf['is_js'] = $_POST['is_js'];
}
else {
$conf['is_js'] = 0;
}
// Are we using ssl?
if($_GET['is_ssl'])
{
$conf['is_ssl'] = $_GET['is_ssl'];
}
else if($_POST['is_ssl']){
$conf['is_ssl'] = $_POST['is_ssl'];
}
else {
$conf['is_ssl'] = 0;
}
// All domains?
if($_GET['is_alldomains'])
{
$conf['is_alldomains'] = $_GET['is_alldomains'];
}
else if($_POST['is_alldomains']){
$conf['is_alldomains'] = $_POST['is_alldomains'];
}
else {
$conf['is_alldomains'] = 0;
}
return $conf;
}

function url_redirect($url = "") {
global $BSX_BASEHREF;
$conf = get_conf();
$is_ssl = $conf['is_ssl'];
$is_js = $conf['is_js'];
$is_alldomains = $conf['is_alldomains'];
$SESSID = $_COOKIE['BSX_SESSID'];

if($url == "") $url = $BSX_BASEHREF;
if($is_ssl || $GLOBALS["SERVER_PORT"] == 443) {
if(eregi("\?", $url))
$url .= "&is_ssl=" . ($is_ssl > 0 ? $is_ssl : 1);
else
$url .= "?is_ssl=" . ($is_ssl > 0 ? $is_ssl : 1);
$url = ereg_replace("http://", "https://", $url);
}
if($is_js) {
if(eregi("\?", $url))
$url .= "&is_js=" . $is_js;
else
$url .= "?is_js=" . $is_js;
}
if($SESSID) {
if(eregi("\?", $url))
$url .= "&SESSID=" . $SESSID;
else
$url .= "?SESSID=" . $SESSID;
}
if($is_alldomains) {
if(eregi("\?", $url))
$url .= "&is_alldomains=" . $is_alldomains;
else
$url .= "?is_alldomains=" . $is_alldomains;
}
Header("Location: " . $url);
exit();
}

// gets the array index of a domain
function domain2index($domain) {
global $bsx_domains, $bsx_domains_cnt;
$domain1 = strtolower($domain);
for($i = 0 ; $i < $bsx_domains_cnt ; $i++) {
$domain2 = strtolower($bsx_domains[$i]["domain"]);
if($domain1 == $domain2) return $i;
}
return -1;
}


// gets the domain name of an index
function index2domain($indx) {
global $bsx_domains;
$domain = $bsx_domains[$indx]["domain"];
if($domain == "") return false;
return $domain;
}


// Turkce karakterler (turkish characters)
// tr -> us
// 199 -> 67
// 208 -> 71
// 214 -> 79
// 220 -> 85
// 221 -> 73
// 222 -> 83
// 231 -> 99
// 240 -> 103
// 246 -> 111
// 252 -> 117
// 253 -> 105
// 254 -> 115

function make_readable($name) {
$newname = "";
for($i = 0 ; $i < strlen($name) ; $i++) {
$z = ord($name[$i]);
switch($z) {
case 199:
$newname .= chr(67);
break;
case 208:
$newname .= chr(71);
break;
case 214:
$newname .= chr(79);
break;
case 220:
$newname .= chr(85);
break;
case 221:
$newname .= chr(73);
break;
case 222:
$newname .= chr(83);
break;
case 231:
$newname .= chr(99);
break;
case 240:
$newname .= chr(103);
break;
case 246:
$newname .= chr(111);
break;
case 252:
$newname .= chr(117);
break;
case 253:
$newname .= chr(105);
break;
case 254:
$newname .= chr(115);
break;
default:
$newname .= chr($z);
}
}
// we converted the tr chars to us chars

// now we need to get rid of unreadable chars
// i.e we allow: A-Z, a-z, 0-9 and blank
$name2 = $newname;
$newname = "";
for($i = 0 ; $i < strlen($name2) ; $i++) {
$z = ord($name2[$i]);
if($z == 32) $newname .= " ";
if(($z < 48) || (($z > 57) && ($z < 65)) ||
(($z > 90) && ($z < 97)) || ($z > 122)) continue;
$newname .= $name2[$i];
}
return $newname;
}

// convert the size in bytes to kB/mB
function convert_size($byte) {
if($byte == 0) // no need to calculate
return "0kB";
if($byte < 1000) // i guess users dont want to see the size like 1020 bytes
return "$byte" . " B";
$rem = $byte / 1024.0;
$kb = sprintf("%.1f", $rem);
$remkb = sprintf("%d", $rem);
if($remkb < 1000) // kilobytes is ok
return "$kb" . "kB";
$rem2 = $remkb / 1024.0;
$mb = sprintf("%.1f", $rem2);
return "$mb" . "mB"; // finally megabytes
}

// simple decrypt of a string
function decode_strip($str) {
$str2 = stripslashes(urldecode($str));
return trans_tr($str2);
}

function decode_mime($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 < count($coded_strings)) {
$elements = explode('?', $coded_strings[$counter]);
if(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 {
$elements[2] = str_replace('=', '', $elements[2]);
if ($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 handle_emails($str) {
global $BSX_BASEHREF, $BSX_LAUNCHER;
$SESSID = $_COOKIE['BSX_SESSID'];
$conf = get_conf();
$is_ssl = $conf['is_ssl'];
$is_js = $conf['is_js'];

$url = $BSX_BASEHREF . "/" . $BSX_LAUNCHER . "?RequestID=CMPSNEW&premail=-1";
if($SESSID) $url .= "&SESSID=$SESSID";
if($is_js) $url .= "&is_js=$is_js";
if($is_ssl || $GLOBALS["SERVER_PORT"] == 443) $url .= "&is_ssl=" . $is_ssl;
$url .= "&cmps_to";
return(ereg_replace("([A-Za-z0-9._-]+\@[[:alnum:].[a-zA-Z0-9_-]+[a-zA-Z]+)",
"<a href='$url=\\1'>\\1< /a>", $str));
}
function handle_urls($str) {
// Replaced with handle_links
return handle_links($str);
}
function handle_links($str) {
// Slip in a target='_new' to existing tags
$str = preg_replace("/(?<=<a href=\')((news|(ht|f)tp(s?):\/\/).*?)[\'>]/ie", "'\\1'.'\' target=\'_new\' '", $str);
// Make links of text mail, news, ftp, ftps, http and https addresses
$str = handle_emails($str);
$str = preg_replace("/(?<!<a href=\')((news|(ht|f)tp(s?):\/\/)[^\s]*)[^\'>]/ie", "'<a href=\''.'\\1'.'\' target=\'_new\' >'.'\\1'.'</a>'", $str);
return $str;
}

function put_ahref($href, $name, $linkid = "", $title = "") {
$conf = get_conf();
$is_ssl = $conf['is_ssl'];
$is_js = $conf['is_js'];

$url = $GLOBALS["BSX_BASEHREF"] . "/" . $GLOBALS["BSX_LAUNCHER"] . "?" . $href;
if($GLOBALS["SESSID"]) $url .= "&SESSID=" . $GLOBALS["SESSID"];
if($is_js) $url .= "&is_js=" . $is_js;
if($is_ssl || $GLOBALS["SERVER_PORT"] == 443) $url .= "&is_ssl=" . $is_ssl;
if($GLOBALS["expand_folders"]) $url .= "&expand_folders=1";

$output = "<a href=\"$url\"";
if($linkid != "") $output .= " id=\"$linkid\"";
if($title != "") $output .= " title=\"" . htmlspecialchars($title) . "\"";

$output .= ">$name</a>";
echo $output;
}

function nbsp($str) {
if(is_string($str)) {
if(empty($str)) return " ";
return " $str ";
}
return " $str ";
}

function start_form($name, $extra = "") {
global $BSX_BASEHREF, $BSX_LAUNCHER;
global $is_ssl;

$posturl = $BSX_BASEHREF . "/" . $BSX_LAUNCHER;
echo "<form name=\"$name\" method=\"POST\" action=\"$posturl\" $extra>\n";
}

function stop_form() {
global $is_nocookie, $is_alldomains;
$SESSID = $_COOKIE['BSX_SESSID'];
$conf = get_conf();
$is_ssl = $conf['is_ssl'];
$is_js = $conf['is_js'];
$is_alldomains = $conf['is_alldomains'];

if($SESSID)
echo "<input type=\"hidden\" name=\"SESSID\" value=\"$SESSID\">";
if($is_js)
echo "<input type=\"hidden\" name=\"is_js\" value=\"$is_js\">";
if($is_ssl | $GLOBALS["SERVER_PORT"] == "443")
echo "<input type=\"hidden\" name=\"is_ssl\" value=\"$is_ssl\">";
if($is_nocookie)
echo "<input type=\"hidden\" name=\"is_nocookie\" value=\"$is_nocookie\">";
if($is_alldomains)
echo "<input type=\"hidden\" name=\"is_alldomains\" value=\"$is_alldomains\">";
echo "</form>\n";
}

// push the pages of the mbox
function push_pages($nmsgs) {
global $sort, $fromMsg, $fromPage, $lng, $mbox, $nextPage, $prevPage;
global $pluspsize;
// TODO: get user set using a function
$user_set = $_COOKIE['user_set'];
$fromPage = $_GET['fromPage'];
$fromMsg = $_GET['fromMsg'];
$nextPage = $_GET['nextPage'];
$prevPage = $_GET['prevPage'];

// print the More pages stuff
// --
// well, this is not necessary for most of us, but hey, may be we use this feature?
// --
// this routine is written just for the people who has hundreds (may be thousands) of messages
// staying just in one mailbox.
// --
// kinda complicated stuff but it works.
// --
$pages = ceil($nmsgs / $user_set["psize"]);
$pgcnt = 0;
if($pages != 1) { // if we have pages
echo $lng->p(228);
if($fromPage) {
$prevPage = $fromPage - 10; // if we are not on the firstPage
if($fromPage * $user_set["psize"] == $fromMsg) $prevMsg = $fromMsg - $user_set["psize"]; // if this page is x1 (e.g 21, 31, 41, etc)
else $prevMsg = $fromMsg - (10 * $user_set["psize"]); // if this page is x1 make it (x-1)1 (e.g 23 -> 13, 45 -> 35, etc)
put_ahref("RequestID=MBOXLST&mbox=" . urlencode($mbox) . "&sort=" . $sort . "&fromMsg=" . $prevMsg . "&fromPage=" . $prevPage, " « ");
} else $fromPage = 0;
for($i = $fromPage ; $i < $pages ; $i++, $pgcnt++) {
$this_from = $i * $user_set["psize"];
if($pgcnt == 10) {
$nextPage = $i;
if(($nextPage - 1) * $user_set["psize"] == $fromMsg) $nextMsg = $fromMsg + $user_set["psize"];
else {
$nextMsg = $fromMsg + (10 * $user_set["psize"]);
if($nextMsg > $nmsgs) // what if the next page does not exist?
$nextMsg = $nextPage * $user_set["psize"]; // if so, make the next page the first page of the next 10
}
put_ahref("RequestID=MBOXLST&mbox=" . urlencode($mbox) . "&sort=" . $sort . "&fromMsg=" . $nextMsg . "&fromPage=" . $nextPage, " »");
break; // not user set (max 10 "more pages")
}
$j = $i + 1;
if($pgcnt) echo " <small>·</small> ";
if($this_from != $fromMsg)
put_ahref("RequestID=MBOXLST&mbox=" . urlencode($mbox) . "&sort=" . $sort . "&fromMsg=" . $this_from . "&fromPage=" . $fromPage, $j);
else echo "<b>$j </b>";
}
}

// attach the nextPage stuff to the Previous|XXX|Next.
if((($fromPage + 1) * $user_set["psize"]) == $pluspsize) $prevPage = $fromPage - 10;
else $prevPage = $fromPage;
if((($fromPage + 10) * $user_set["psize"]) == $pluspsize) $nextPage = $fromPage + 10;
else $nextPage = $fromPage;
}

function push_errinfo() {
global $err_msg, $info_msg;
if(!empty($err_msg)) {
echo "";
echo "\n";
echo "\n";
echo "
 $err_msg 
";
echo "\n";
} else if(!empty($info_msg)) {
echo "";
echo "\n";
echo "\n";
echo "
 $info_msg 
";
echo "\n";
}
}

function push_pagehdr() {
$m = $GLOBALS["pagehdr_msg"];
$u = $GLOBALS["username"];
$d = $GLOBALS["domain_name"];
echo "";
echo "
<b>";
echo $m . ":< /b> " . $u . "@" . $d;
echo "
\n";
}

// select box for settings
function push_langs() {
global $bsx_lang;
global $set_lang;

echo "<select name='set_lang' size='1'>\n";
for($i = 0 ; $i < count($bsx_lang) ; $i++) {
echo "\n";
}
echo "</select>\n";
}

// build the js array for theme preview
function push_jsthemes() {
global $bsx_theme;

echo "\n";
}

// select box for themes
function push_themes() {
global $bsx_theme, $set_theme, $theme_stats;
global $BSX_BASEHREF;

echo "<select name='set_theme' size='1' onChange='javascript:previewTheme(\"$BSX_BASEHREF\", this);'>\n";
for($i = 0 ; $i < count($bsx_theme) ; $i++) {
if(!$bsx_theme[$i]["active"]) continue;
echo "\n";
else
echo ">" . $bsx_theme[$i]["desc"] . "\n";
}
echo "</select>\n";
}

// if the server basilix runs on has lots of virtual domains, and if you want their
// users use this webmail system, they need to select their domain from the select box
// and login. so if the user types "abc.com" as an address which is one of the virtual domains
// hosted on that machine, we'll push him a login form not selectable but abc.com instead.
function check_desired_domain() {
global $bsx_domains, $bsx_domains_cnt;

$http_host = strtolower($GLOBALS["HTTP_HOST"]);
for($i = 0 ; $i < $bsx_domains_cnt ; $i++) {
if(strtolower($bsx_domains[$i]["domain"]) == $http_host) return $i;
}
return -1;
}

// safe exec
function sexec($cmd) {
// cleanup the cmd to prevent running of shell commands
// on exec() call.
$cmd = eregi_replace("[^-A-Za-z0-9_/\. ]", "", $cmd);
@exec($cmd);
}

// correct strings (if they have "../")
function sstrings() {
$okg = 0;
while(list($gk, $gv) = each($GLOBALS)) {
if($okg || $gk == "PHP_SELF") {
if(is_string($GLOBALS[$gk])) {
$GLOBALS[$gk] = ereg_replace("\.\./", "", $gv);
}
$okg = 1;

}
}
}

// correct turkish chars wrt the translation table
// @TODO Is this needed if we are using encoding correctly? It seems like a
// lot of overhead for all but a limited number of users.
function trans_tr($str) {
$trans = array(
"ı" => "",
"ğ" => "",
"ş" => "",
"Ğ" => "",
"Ş" => "",
"İ" => ""
);
return strtr($str, $trans);
}

// Remove unwanted html tags
function removeEvilTags($source)
{
$allowedTags = '< h1><b><br><br /><i><a><ul><li> < pre>
< blockquote>< img>';
//$source = nl2br($source);
$source = strip_tags($source, $allowedTags);
return preg_replace('/<(.*?)>/ie', "'<'.removeEvilAttributes('\\1').'>'", $source);
}

// Remove unwanted attributes from the allowed tags
function removeEvilAttributes($tagSource)
{
$stripAttrib = 'javascript:|onclick|ondblclick|onmousedown|onmouseup|onmouseover|'.
'onmousemove|onmouseout|onkeypress|onkeydown|onkeyup';
return stripslashes(preg_replace("/$stripAttrib/i", 'forbidden', $tagSource));
}
sstrings();
?>

mysql.class.php

mysql.class.php is used to handle mysql database

/*
+----------------------------------------------------------------------+
| BasiliX - Copyright (C) 2000-2002 Murat Arslan |
| Contributions from: |
| Mike Peters |
| Christofer Algotsson |
+----------------------------------------------------------------------+
*/

// MySQL related stuff (tired of commenting)
// -----------------------------------------------------------------------
class MySQL {
var $socket = "";
var $dbname = "";
var $dbhost = "";
var $dbuser = "";
var $dbpass = "";

function MySQL() {
// init
global $BSX_DB_USER, $BSX_DB_PASS, $BSX_DB_NAME, $BSX_DB_HOST;
$this->dbuser = $BSX_DB_USER;
$this->dbpass = $BSX_DB_PASS;
$this->dbname = $BSX_DB_NAME;
$this->dbhost = $BSX_DB_HOST;
}
// errors
function error($text) {
$err_no = mysql_errno();
$err_msg = mysql_error();
printf("MySQL ERROR: %s (%d):
%s
\n",
$err_msg, $err_no, $text);
exit();
}

// connect to the db
function open() {
$i = mysql_connect($this->dbhost, $this->dbuser, $this->dbpass);
if(!$i)
$this->error("Error connecting to the database server.");
if(!mysql_select_db($this->dbname, $i))
$this->error("Error selecting the database.");
$this->socket = $i;
}

// close the connection
function close() {
if($this->socket) mysql_close($this->socket);
$this->socket = "";
}

// select the rows and append them to an array
function select_rows($query) {
if(empty($this->socket)) return false;

$results = mysql_query($query, $this->socket);
if(!$results || empty($results)) return false;

$i = 0;
$data = array();
while($row = mysql_fetch_array($results)) {
$data[$i] = $row;
$i++;
}
mysql_free_result($results);
return $data;
}

// insert a row
function insert_row($query) {
if(empty($this->socket)) return false;
$rc = mysql_query($query);
if($rc == false) return false;
$id = mysql_insert_id($this->socket);
return $id;
}

// sessions
function session_create($u, $d, $p, $s, $t, $h, $a) {
if($h == "") $h = "Unknown";
$query = "INSERT INTO SESSION (USERNAME,DOMAIN,PASSWORD,SESSIONID,LASTACCESS,LASTTIME,LASTHOST,LASTADDR) ";
$query .= "VALUES ('$u', '$d', '$p','$s','$t','$t','$h','$a')";
$rc = $this->insert_row($query);
return $rc;
}

function session_update($r, $p, $s, $t, $h, $a) {
if($h == "") $h = "Unknown";
$query = "UPDATE SESSION SET SESSIONID='$s',PASSWORD='$p',LASTTIME='$t',LASTHOST='$h',LASTADDR='$a' WHERE CUSTOMERID='".(int)$r."'";
$rc = mysql_query($query);
return $rc;
}

function session_checkuser($u, $d) {
$query = "SELECT CUSTOMERID,LASTTIME,LASTHOST,LASTADDR FROM SESSION WHERE USERNAME='$u' AND DOMAIN='$d'";
return $this->select_rows($query);
}

function session_zero($s) {
$query = "UPDATE SESSION SET PASSWORD='',SESSIONID='' WHERE SESSIONID='$s'";
$rc = mysql_query($query);
return $rc;
}

function session_getuservals($s) {
$query = "SELECT CUSTOMERID,USERNAME,DOMAIN FROM SESSION WHERE SESSIONID='".$s."'";
$data = $this->select_rows($query);
if(!empty($data)) {
$tt = time();
$query = "UPDATE SESSION SET LASTACCESS='$tt' WHERE SESSIONID='".$s."'";
$rc = mysql_query($query);
}
return $data;
}
function session_getpassword($u, $s) {
$query = "SELECT PASSWORD FROM SESSION WHERE SESSIONID='".$s."' AND USERNAME='".$u."' LIMIT 1";
$data = $this->select_rows($query);
return pwdecrypt($data[0][0]);
}
// online users
function online_users() {
$t = time();
$query = "SELECT COUNT(*) CNT FROM SESSION WHERE PASSWORD != '' AND ($t - LASTACCESS < 900)"; #15m
$data = $this->select_rows($query);
$ou = $data[0]["CNT"];
return $ou;
}

// address book
// load the addressbook items of the user
function get_allabook($cid) {
$query = "SELECT * FROM ADDRESSBOOK WHERE OWNERID='".(int)$cid."' ORDER BY NICKNAME";
return $this->select_rows($query);
}

// load the addressbook group items of the user
function get_allabookgrp($cid) {
$query = "SELECT * FROM ADDRESSBOOKGRP WHERE OWNERID='".(int)$cid."' ORDER BY GRPNAME";
return $this->select_rows($query);
}

// add an entry
function addr_add($cid, $nick, $email, $name, $tel, $fax, $note) {
$nick = addslashes($nick);
$email = addslashes($email);
$name = addslashes($name);
$tel = addslashes($tel);
$fax = addslashes($fax);
$note = addslashes($note);
$query = "INSERT INTO ADDRESSBOOK (OWNERID, NICKNAME, EMAIL, NAME, TELEPHONE, FAX, NOTE) VALUES ";
$query .= "('".(int)$cid."', '$nick','$email','$name','$tel','$fax','$note')";
$rc = $this->insert_row($query);
return $rc;
}

// delete an entry
function addr_delitem($cid, $id) {
// first erase the user from the groups
$this->addr_delitemgrp($cid, $id);
$query = "DELETE FROM ADDRESSBOOK WHERE OWNERID='".(int)$cid."' AND ROWID='".(int)$id."'";
$rc = mysql_query($query);
if($rc == false) return false;
$ar = mysql_affected_rows($this->socket);
if($ar == 0) return false;
else return true;
}

// user -> which groups
function addr_uid2grps($cid, $id) {
$query = "SELECT AG.MEMBERS MEMBERS, AG.GRPNAME GRPNAME, AG.ROWID ROWID ";
$query .= "FROM ADDRESSBOOKGRP AG, ADDRESSBOOK A ";
$query .= "WHERE AG.OWNERID='".(int)$cid."' AND AG.OWNERID=A.OWNERID AND ";
$query .= "(MEMBERS LIKE '$id,%' OR MEMBERS LIKE '%,$id,%' OR MEMBERS LIKE '%,$id' OR MEMBERS='$id') ";
$query .= "GROUP BY ROWID";
$data = $this->select_rows($query);
if(empty($data)) return false;
return $data;
}

// erase the user from all the groups he is subscribed.
function addr_delitemgrp($cid, $id) {
// first find out to which groups this user subscribed.
$grps = $this->addr_uid2grps($cid, $id);
if(empty($grps)) return 0;
$ret = 0;
for($i = 0 ; $i < count($grps) ; $i++) {
$cur_grp = $grps[$i];
$rowid = $cur_grp["ROWID"];
$members = $cur_grp["MEMBERS"];
$m_arr = explode(",", $members);
$nmembers = "";
for($j = 0 ; $j < count($m_arr) ; $j++) {
if($m_arr[$j] != $id) {
if(empty($nmembers)) $nmembers = $m_arr[$j];
else $nmembers = $nmembers . "," . $m_arr[$j];
}
}
$query = "UPDATE ADDRESSBOOKGRP SET MEMBERS='$nmembers' WHERE OWNERID='".(int)$cid."' AND ROWID='".(int)$rowid."'";
$ret += mysql_query($query);
}
return $ret;
}

// update an entry
function addr_update($cid, $rowid, $nick, $email, $name, $tel, $fax, $note) {
$nick = addslashes($nick);
$email = addslashes($email);
$name = addslashes($name);
$tel = addslashes($tel);
$fax = addslashes($fax);
$note = addslashes($note);
$query = "UPDATE ADDRESSBOOK SET NICKNAME='$nick',EMAIL='$email',NAME='$name',TELEPHONE='$tel',FAX='$fax',NOTE='$note' ";
$query .= "WHERE OWNERID=$cid AND ROWID=$rowid";
return mysql_query($query);
}

// retrieve an entry
function addr_getitem($cid, $rowid) {
$query = "SELECT * FROM ADDRESSBOOK WHERE OWNERID='".(int)$cid."' AND ROWID='".(int)$rowid."'";
return $this->select_rows($query);
}

// add a new group
function addr_addgrp($cid, $name) {
$name = addslashes($name);
$query = "INSERT INTO ADDRESSBOOKGRP (OWNERID, GRPNAME) VALUES ";
$query .= "('".(int)$cid."','$name')";
$rc = $this->insert_row($query);
return $rc;
}

// delete a group
function addr_delgrp($cid, $id) {
$query = "DELETE FROM ADDRESSBOOKGRP WHERE OWNERID='".(int)$cid."' AND ROWID='".(int)$id."'";
$rc = mysql_query($query);
if($rc == false) return false;
$ar = mysql_affected_rows($this->socket);
if($ar == 0) return false;
else return true;
}

// retrieve the members of the group
function addr_grpmem($cid, $id) {
$query = "SELECT MEMBERS FROM ADDRESSBOOKGRP WHERE OWNERID='".(int)$cid."' AND ROWID='".(int)$id."'";
$dat = $this->select_rows($query);
$members = $dat[0]["MEMBERS"];
$mem_arr = explode(",", $members);
if(count($members) == 1 && empty($mem_arr[0])) return array();
return $mem_arr;
}

function addr_uid2nick($cid, $id) {
$query = "SELECT NICKNAME FROM ADDRESSBOOK WHERE OWNERID='".(int)$cid."' AND ROWID='$id'";
$dat = $this->select_rows($query);
$nick = $dat[0]["NICKNAME"];
return $nick;
}

// retrieve the name of the group
function addr_getgrpname($cid, $id) {
$query = "SELECT GRPNAME FROM ADDRESSBOOKGRP WHERE OWNERID='".(int)$cid."' AND ROWID='".(int)$id."'";
$data = $this->select_rows($query);
if(empty($data)) return "";
return $data[0]["GRPNAME"];
}

// add user to a group
function addr_grpaddmem($cid, $gid, $uid) {
$query = "SELECT MEMBERS FROM ADDRESSBOOKGRP WHERE OWNERID='".(int)$cid."' AND ROWID='".(int)$gid."'";
$dat = $this->select_rows($query);
$members = $dat[0]["MEMBERS"];
if(empty($members)) $nmembers = $uid;
else {
$mem_arr = explode(",", $members);
for($i = 0 ; $i < count($mem_arr) ; $i++) {
if($mem_arr[$i] == $uid) return false;
}
$nmembers = $members . "," . $uid;
}
$nmembers = addslashes($nmembers);
$query = "UPDATE ADDRESSBOOKGRP SET MEMBERS='$nmembers' WHERE OWNERID='".(int)$cid."' AND ROWID='".(int)$gid."'";
return mysql_query($query);
}

// delete a user from the group
function addr_grpdelmem($cid, $gid, $uid) {
$members = $this->addr_grpmem($cid, $gid);
if(empty($members)) return false;
$nmembers = "";
for($i = 0 ; $i < count($members) ; $i++) {
if($members[$i] != $uid) {
if(empty($nmembers)) $nmembers = $members[$i];
else $nmembers = $nmembers . "," . $members[$i];
}
}
$query = "UPDATE ADDRESSBOOKGRP SET MEMBERS='$nmembers' WHERE OWNERID='".(int)$cid."' AND ROWID='".(int)$gid."'";
return mysql_query($query);
}

// update the memberlist (via javascript)
function addr_update_memberlist($cid, $gid, $memberlist) {
$query = "UPDATE ADDRESSBOOKGRP SET MEMBERS='$memberlist' WHERE OWNERID='".(int)$cid."' AND ROWID='".(int)$gid."'";
return mysql_query($query);
}

// settings
// save
function settings_save($cid, $lang, $name, $sign, $sort, $rsort, $sent, $trash, $psize, $theme, $ifexpand, $pn, $rt) {
$name = addslashes($name);
$sign = addslashes($sign);
$rt = addslashes($rt);

$query = "UPDATE SETTINGS SET ";
$query .= "NAME='$name', SIGN='$sign', LANG='$lang', SORT='$sort', RSORT='$rsort',";
$query .= "PSIZE='$psize', SAVESENT='$sent', MOVETRASH='$trash', THEME='$theme', IFEXPAND='$ifexpand'";
$query .= ",PREVNEXT='$pn',REPLYTO='$rt' WHERE CUSTOMERID='".(int)$cid."'";
return mysql_query($query);
}

// load
function settings_load($cid) {
$query = "SELECT * FROM SETTINGS WHERE CUSTOMERID='".(int)$cid."'";
return $this->select_rows($query);
}

// init
function settings_init($cid) {
$query = "INSERT INTO SETTINGS (CUSTOMERID) VALUES ('".(int)$cid."')";
return $this->insert_row($query);
}

function settings_theme_usage() {
$query = "SELECT COUNT(*) CNT, THEME FROM SETTINGS GROUP BY THEME";
return $this->select_rows($query);
}

// sendmsgs table
// create a new mail to be sent
function sendmsgs_init($cid) {
$t = time();
$query = "INSERT INTO SENDMSGS (CUSTOMERID, MSGDATE) VALUES ('".(int)$cid."', '$t')";
$rc = mysql_query($query);
if($rc == false) return false;
$id = mysql_insert_id($this->socket);
return $id;
}

// load drafts
function sendmsgs_load_drafts($cid) {
$query = "SELECT * FROM SENDMSGS WHERE CUSTOMERID='".(int)$cid."'";
return $this->select_rows($query);
}

// load the premail
function sendmsgs_load_premail($cid, $pm) {
$query = "SELECT * FROM SENDMSGS WHERE CUSTOMERID='".(int)$cid."' AND MSGID='".(int)$pm."'";
$data = $this->select_rows($query);
return $data[0];
}

// delete the selected draft
function sendmsgs_del_draft($cid, $pm) {
$query = "DELETE FROM SENDMSGS WHERE CUSTOMERID='".(int)$cid."' AND MSGID='".(int)$pm."'";
$rc = mysql_query($query);
if($rc == false) return false;
$ar = mysql_affected_rows($this->socket);
if($ar == 0) return false;
else return true;
}

// remove the empty drafts
function sendmsgs_del_empty_drafts($cid) {
$query = "DELETE FROM SENDMSGS WHERE CUSTOMERID='".(int)$cid."' AND MSGTO is NULL AND MSGCC is NULL ";
$query .= "AND MSGBCC is NULL AND MSGSUBJECT is NULL AND MSGBODY is NULL AND MSGATCHS is NULL";
$rc = mysql_query($query);
if($rc == false) return false;
$ar = mysql_affected_rows($this->socket);
if($ar == 0) return false;
else return true;
}

// load the attachments
function sendmsgs_load_atchs($cid, $pm) {
$query = "SELECT MSGATCHS FROM SENDMSGS WHERE CUSTOMERID='".(int)$cid."' AND MSGID='".(int)$pm."'";
$data = $this->select_rows($query);
if(empty($data)) return "";
return $data[0]["MSGATCHS"];
}
// save the draft
function sendmsgs_update_premail($cid, $pm, $from, $to, $cc, $bcc, $subject, $body) {
$from = addslashes($from);
$to = addslashes($to);
$cc = addslashes($cc);
$bcc = addslashes($bcc);
$subject = addslashes($subject);
$body = addslashes($body);

$t = time();

$query = "UPDATE SENDMSGS SET MSGFROM='$from', MSGTO='$to', MSGCC='$cc', MSGBCC='$bcc'";
$query .= ", MSGSUBJECT='$subject', MSGBODY='$body', MSGDATE='$t' WHERE CUSTOMERID='".(int)$cid."' AND MSGID='".(int)$pm."'";
return mysql_query($query);
}

// update only the attachments
function sendmsgs_update_premail_atchs($cid, $pm, $atchs) {
$atchs = addslashes($atchs);

$t = time();
$query = "UPDATE SENDMSGS SET MSGATCHS='$atchs', MSGDATE='$t' WHERE CUSTOMERID='".(int)$cid."' AND MSGID='".(int)$pm."'";
return mysql_query($query);
}

// check if this premail is owned by the customer
function sendmsgs_check_premail($cid, $pm) {
$query = "SELECT COUNT(*) CNT FROM SENDMSGS WHERE CUSTOMERID='".(int)$cid."' AND MSGID='".(int)$pm."'";
$data = $this->select_rows($query);
if(empty($data)) return 0;
return $data[0]["CNT"];
}

// remove the draft since its sent
function sendmsgs_del_premail($cid, $pm) {
$query = "DELETE FROM SENDMSGS WHERE CUSTOMERID='".(int)$cid."' AND MSGID='".(int)$pm."'";
$rc = mysql_query($query);
if($rc == false) return false;
$ar = mysql_affected_rows($this->socket);
if($ar == 0) return false;
else return true;
}

// update the folders of the user
function folders_update($cid, $fstr) {
$query = "UPDATE SESSION SET LASTFOLDERS='$fstr' WHERE CUSTOMERID='".(int)$cid."'";
return mysql_query($query);
}

// load the folders of the user
function folders_load($cid) {
$query = "SELECT LASTFOLDERS FROM SESSION WHERE CUSTOMERID='".(int)$cid."'";
$data = $this->select_rows($query);
if(empty($data)) return array();
return $data[0];
}
}
?>

imap.class.php

imap.class.php is used to retrieve email from given mailbox in secure way.

You need to provide hostname,username , password, port
It retrieve email from your mailbox. You are flexible to use this class as you wish.


<?php
/*
+----------------------------------------------------------------------+
| BasiliX - Copyright (C) 2000-2002 Murat Arslan <arslanm@basilix.org> |
| Contributions from: |
| Mike Peters <mike@ice2o.com> |
+----------------------------------------------------------------------+
*/


// IMAP package, this is used to handle imap related functions easier
// -----------------------------------------------------------------------
class IMAP {
var $imapstr = 0;
var $user = "";
var $pass = "";
var $host = "";
var $port = "";

function IMAP() {
// do nothing
}

// create an imap connection
function open($username, $password, $host, $port, $notls = 0) {
if($notls>0)$notls_str="/notls";
$i = @imap_open("{" . $host . ":" . $port . $notls_str . "}INBOX", $username, $password);
if(!$i) return false;
$this->imapstr = $i;
$this->user = $username;
$this->pass = $password;
$this->host = $host;
$this->port = $port;
return true;
}

// close the imap connection

function close() {
if($this->imapstr) imap_close($this->imapstr);
$this->imapstr = 0;
return true;
}

// are we connected?
function ifok() {
if(!$this->imapstr) return false;
return true;
}

// create a mbox
function crtmbox($mbox) {
if(!$this->ifok()) return false;
return imap_createmailbox($this->imapstr, "{" . $this->host . ":" . $this->port . "}" . $mbox);
}

// delete a mbox

function delmbox($mbox) {
if(!$this->ifok()) return false;
return imap_deletemailbox($this->imapstr, "{" . $this->host . ":" . $this->port . "}" . $mbox);
}

// rename a mbox

function renmbox($old, $new) {
if(!$this->ifok()) return false;
return imap_renamemailbox($this->imapstr,
"{" . $this->host . ":" . $this->port . "}" . $old,
"{" . $this->host . ":" . $this->port . "}" . $new);
}

// list the subscribed mboxes in a dir (cyrus/courier)

function lstscrbed($dir) {
if(!$this->ifok()) return false;
return imap_listsubscribed($this->imapstr, "{" . $this->host . ":" . $this->port . "}", $dir);
}

// list the mboxes in a dir
function lstmbox($dir) {
if(!$this->ifok()) return false;
return imap_listmailbox($this->imapstr, "{" . $this->host . ":" . $this->port . "}", $dir);
}

function getmailboxes($dir) {
if(!$this->ifok()) return false;
return imap_getmailboxes($this->imapstr, "{" . $this->host . ":" . $this->port . "}", $dir);
}
function getmboxes($dir) {
$mboxes = $this->getmailboxes($dir);
$i = 0;
$ret = array();
if(empty($mboxes)) return $ret;
while(list($key, $val) = each($mboxes)) {
$delim = $val->delimiter;
$name = imap_utf7_decode($val->name);
$name_arr = explode($delim, $name);
$j = count($name_arr) - 1;
$mbox_name = $name_arr[$j];
if($mbox_name == "") continue; // the DIRECTORY itself

$ret[$i++] = $mbox_name;
}
sort($ret);
return $ret;
}

// reopen the desired mbox (just the name of the mbox)
function reopbox($mbox) {
if(!$this->ifok()) return false;
return imap_reopen($this->imapstr, "{" . $this->host . ":" . $this->port . "}" . $mbox);
}

// reopen the desired mbox (full mbox name should be given as $mbox)

function reopbox2($mbox) {
if(!$this->ifok()) return false;
return imap_reopen($this->imapstr, $mbox);
}

// mailbox info
function mboxinfo() {
if(!$this->ifok()) return false;
return imap_mailboxmsginfo($this->imapstr);
}

// sort the mbox
function mboxsrt($criteria, $reverse) {
if(!$this->ifok()) return false;
return imap_sort($this->imapstr, $criteria, $reverse, SE_NOPREFETCH);
}

// retrieve the header of the message

function msghdr($msgnum) {
if(!$this->ifok()) return false;
return imap_header($this->imapstr, $msgnum);
}

// get the UID of the message
function msguid($msgnum) {
if(!$this->ifok()) return false;
return imap_uid($this->imapstr, $msgnum);
}

// get the NO of the message
function msgno($msguid) {
if(!$this->ifok()) return false;
return imap_msgno($this->imapstr, $msguid);
}

// fetch the structure

function ftchstr($msgnum) {
if(!$this->ifok()) return false;
return imap_fetchstructure($this->imapstr, $msgnum);
}

// fetch the header of the message
function ftchhdr($msgnum) {
if(!$this->ifok()) return false;
return imap_fetchheader($this->imapstr, $msgnum);
}


// delete the specified message
function rmmail($uid) {
if(!$this->ifok()) return false;
$msgno = $this->msgno($uid);
return imap_delete($this->imapstr, $msgno);
}

// move the specifed msg to mbox B

function mvmail($uid, $tombox) {
if(!$this->ifok()) return false;
return imap_mail_move($this->imapstr, $uid, $tombox, CP_UID);
}

// expunge the mailbox
function expng() {
if(!$this->ifok()) return false;
return imap_expunge($this->imapstr);
}

// fetch the body of the message
function ftchbody($msgno, $part) {
if(!$this->ifok()) return false;
return imap_fetchbody($this->imapstr, $msgno, $part, NONE);
}

// set the flags

function setflg($seq, $flg) {
if(!$this->ifok()) return false;
return imap_setflag_full($this->imapstr, $seq, $flg);
}

// search messages
function srch($q) {
if(!$this->ifok()) return false;
return imap_search($this->imapstr, $q, SE_UID);
}

// append to sent mail
function apnd($m, $b) {
if(!$this->ifok()) return false;
return @imap_append($this->imapstr, "{" . $this->host . ":" . $this->port . "}" . $m, $b);
}
}

$imap = new IMAP;

?>


imap2.inc.php

/*
+----------------------------------------------------------------------+
| BasiliX - Copyright (C) 2000-2002 Murat Arslan |
| Contributions from: |
| Mike Peters |
+----------------------------------------------------------------------+
*/
if(empty($_POST['password']) && $_COOKIE['BSX_User'])
{
$username = $_COOKIE['BSX_User'];
$sql = new MySQL;
$sql->open();
$password = $sql->session_getpassword($_COOKIE['BSX_User'], $_COOKIE['BSX_SESSID']);
}
else {
$password = $_POST['password'];
$username = $_POST['username'];
}

$IMAP_DOMAIN = $bsx_domains["$domain"]["domain"];
$IMAP_ISVIRTUAL = $bsx_domains["$domain"]["isvirtual"];
$IMAP_HOST = $bsx_domains["$domain"]["imap_host"];
$IMAP_PORT = $bsx_domains["$domain"]["imap_port"];
$SMTP_HOST = $bsx_domains["$domain"]["smtp_host"];
$IMAP_STYPE = $bsx_domains["$domain"]["imap_stype"];
$IMAP_NOTLS = $bsx_domains["$domain"]["notls"];

// here decide what to do
if($IMAP_STYPE == 3) $BSX_MDIR = "Inbox.";

// virtual or non-virtual connection
if($IMAP_ISVIRTUAL) {
$virtual_username = $username . "@" . $IMAP_DOMAIN;
$imap_ok = imap_connect($virtual_username, $password, $IMAP_HOST, $IMAP_PORT, $IMAP_NOTLS);
} else {
$imap_ok = imap_connect($username, $password, $IMAP_HOST, $IMAP_PORT, $IMAP_NOTLS);
}
if($imap_ok == false) {
if($relogin) {
$incfile = "login-relogin.htx.php";
} else {
$incfile = "login-new.htx.php";
}
$LOGIN_ERR = $lng->p(61);
$BODY_ONLOAD = "onLoad='document.loginForm.password.focus();'";
include("$BSX_HTXDIR/header.htx.php");
include("$BSX_HTXDIR/$incfile");
include("$BSX_HTXDIR/footer.htx.php");
my_exit();
}
?>

compose.inc.php

/*
+----------------------------------------------------------------------+
| BasiliX - Copyright (C) 2000-2002 Murat Arslan |
| Contributions from: |
| Mike Peters |
| Cristofer Algotsson |
| Ch. Thielecke |
+----------------------------------------------------------------------+

*/

// Compose message functions
// -----------------------------------------------------------------------


function push_compose_abook() {
global $RequestID, $lng;
global $BSX_HTXDIR, $BSX_THEMEDIR, $BSX_VERSION;
global $BSX_BASEHREF, $BSX_LAUNCHER;

include("$BSX_HTXDIR/header.htx.php");
include("$BSX_HTXDIR/compose-abook.htx.php");
include("$BSX_HTXDIR/footer.htx.php");
}

function push_compose() {
global $customerID, $RequestID, $sql, $lng;
global $BSX_HTXDIR, $BSX_THEMEDIR, $BSX_VERSION;
global $BSX_BASEHREF, $BSX_LAUNCHER;
global $BSX_SENTMAIL_NAME, $BSX_TRASH_NAME;
global $SESSID, $BODY_ONLOAD;
global $abook_items, $abook_items_cnt;
global $abook_grpitems, $abook_grpitems_cnt;
global $err_msg, $info_msg;
$conf = get_conf();
$is_ssl = $conf['is_ssl'];
$is_js = $conf['is_js'];

// --
global $premail, $cmps_atchs;


global $cmps_from, $cmps_to, $cmps_cc, $cmps_bcc;
global $cmps_subject, $cmps_body, $cmps_atchlist;

global $cmps_f0, $cmps_f1, $cmps_f2; global $cmps_s0, $cmps_s1, $cmps_s2;
global $cmps_c0, $cmps_c1, $cmps_c2;

$user_set = $_COOKIE['user_set'];

$cmps_sign = $user_set["sign"];
if(empty($cmps_from)) $cmps_from = $user_set["name"];

if(empty($cmps_to))
$BODY_ONLOAD="onLoad='document.composeMail.cmps_to.focus();'";

$BODY_ONUNLOAD="onUnLoad='closeWins();'";

$cwurl = $BSX_BASEHREF . "/" . $BSX_LAUNCHER . "?RequestID=CMPSCLNUP" . "&is_js=" . $is_js . "&is_ssl=" . $is_ssl;
if($SESSID) $cwurl .= "&SESSID=" . $SESSID;

if(empty($cmps_atchlist)) $cmps_atchlist = $lng->p(411);

include("$BSX_HTXDIR/header.htx.php");
include("$BSX_HTXDIR/menu.htx.php");
include("$BSX_HTXDIR/compose-new.htx.php");
include("$BSX_HTXDIR/footer.htx.php");
}

function abook_fetch_field($abook_items, $id, $what) {
global $abook_items_cnt;

for($i = 0 ; $i < $abook_items_cnt ; $i++) {
if($abook_items[$i]["id"] == $id) {
return $abook_items[$i]["$what"];
}
}
}

function js_getmembers($memberlist, $abook_items) {
global $abook_items_cnt;

$rstr = "";
$glue = "";
$tmp_arr = explode(",", $memberlist);
for($i = 0 ; $i < count($tmp_arr) ; $i++) {
$idx = $tmp_arr[$i];
$tmp_name = abook_fetch_field($abook_items, $idx, "name");
$tmp_email = abook_fetch_field($abook_items, $idx, "email");
if(empty($tmp_name)) $rstr .= $glue . $tmp_email;
else $rstr .= $glue . "\"" . $tmp_name . "\" <" . $tmp_email . ">";
$glue = ",";
}
return $rstr;
}

function js_getitems($tmp) {
if(empty($tmp["name"])) return $tmp["email"];
else return "\"" . $tmp["name"] . "\" <" . $tmp["email"] . ">";
}

function push_jsaddrs() {
global $abook_items_cnt, $abook_grpitems_cnt;
global $abook_items, $abook_grpitems;

echo "\n";
}

function compose_rmatchs($total_atchs) {
global $atch_dir;

$tmp_atchs = explode(chr(2), $total_atchs);
for($j = 0 ; $j < count($tmp_atchs) ; $j++) {
$tmp_atchstr = $tmp_atchs[$j];
$tmp_arr = explode(chr(3), $tmp_atchstr);
$tmp_file = $tmp_arr[0];
$tmp_filepath = $atch_dir . "/" . $tmp_file;
if(empty($tmp_file) || !file_exists($tmp_filepath)) continue;
$tmp_remove = "/bin/rm -f $tmp_filepath";
@sexec($tmp_remove);
}
}

function compose_rmpremail() {
global $sql;
global $premail;
global $customerID;

$sql->sendmsgs_del_premail($customerID, $premail);
}

function prepare_data($d) {
$nd = ereg_replace("\r", "", $d);
$nd = ereg_replace("\n", "\r\n", $nd);
return $nd;
}

function generate_rcpt_header($myarr, $str, &$cmps_rcpts, &$msg_header, &$farr) {
global $tmp_glue;

for($j = 0 ; $j < count($myarr) ; $j++) {
$tmp_rcpt_arr = $myarr[$j];
$tmp_mbox = $tmp_rcpt_arr->mailbox;
$tmp_host = $tmp_rcpt_arr->host;
$tmp_name = $tmp_rcpt_arr->personal;
if(empty($tmp_mbox) && empty($tmp_host)) continue;
$tmp_email = $tmp_mbox . "@" . $tmp_host;
$cmps_rcpts .= $tmp_glue . $tmp_email;
$tmp_glue = " ";

if(!empty($tmp_name)) {
$tmp_rcpt = "\"" . $tmp_name . "\" <" . $tmp_email . ">";
} else {
$tmp_rcpt = $tmp_email;
}

$msg_header .= $str . ": " . $tmp_rcpt . "\r\n";
$farr[] = $tmp_rcpt;
}
}


function compose_sendmail() {
global $BSX_ATTACH_DIR, $BSX_VERSION;
global $BSX_BASEHREF, $BSX_LAUNCHER, $BSX_LIBDIR;
global $BSX_HTXDIR, $BSX_THEMEDIR, $BSX_SENTMAIL;
global $BSX_SENTMAIL_NAME, $BSX_TRASH_NAME, $BSX_MDIR;
global $SESSID, $BODY_ONLOAD;
global $BSX_USE_SENDMAIL, $BSX_SENDMAIL_PATH;
global $customerID, $RequestID, $sql, $imap, $lng;
global $bsx_domains, $domain_name, $domain, $username, $password;

global $info_msg, $err_msg;
global $atch_dir;
// --
global $premail;

global $cmps_from, $cmps_to, $cmps_cc, $cmps_bcc;
global $cmps_subject, $cmps_body, $cmps_sign, $cmps_atchlist;

// TODO: Function for this
$user_set = $_COOKIE['user_set'];

include("$BSX_HTXDIR/header.htx.php");

echo $total_atchs = load_atchs($customerID, $_POST['premail']);

// generate header
$atch_dir = $BSX_ATTACH_DIR . "/" . "$domain_name" . "/" . "$username";
$msg_header = "";

// in replyto
if(!empty($cmps_fromMsgID)) {
$msg_header .= "In-Reply-To: $cmps_fromMsgID\r\n";
}

// replyto
if(!empty($user_set["replyto"])) {
if(!empty($user_set["name"])) {
$repto = "\"" . $user_set["name"] . "\" <" . $user_set["replyto"] . ">";
} else {
$repto = $user_set["replyto"];
}
} else {
if(!empty($user_set["name"])) {
$repto = "\"" . $user_set["name"] . "\" <" . $username . "@" . $domain_name . ">";
} else {
$repto = $username . "@" . $domain_name;
}
}

// from subject etc
$cmps_from_email = $username . "@" . $domain_name;
$msg_header .= "Message-ID: \r\n";
$msg_header .= "X-Mailer: BasiliX " . $BSX_VERSION . " -- http://www.basilix.org\r\n";
$msg_header .= "X-SenderIP: " . $GLOBALS["REMOTE_ADDR"] . "\r\n";
$msg_header .= "Date: " . date("D, d M Y H:i:s T", time()) . "\r\n";
$msg_header .= "From: " . $cmps_from . " <" . $cmps_from_email . ">\r\n";
$msg_header .= "Reply-To: " . $repto . "\r\n";
$cmps_subject = empty($cmps_subject) ? "(no subject)" : $cmps_subject;
$msg_header .= "Subject: " . $cmps_subject . "\r\n";


// all recipients
$cmps_rcpts = "";
$tmp_glue = "";
if(!empty($cmps_to)) {
$cmps_to_arr = imap_rfc822_parse_adrlist($cmps_to, $domain_name);
generate_rcpt_header($cmps_to_arr, "To", &$cmps_rcpts, &$msg_header, &$farr);
}
if(!empty($cmps_cc)) {
$cmps_cc_arr = imap_rfc822_parse_adrlist($cmps_cc, $domain_name);
generate_rcpt_header($cmps_cc_arr, "Cc", &$cmps_rcpts, &$msg_header, &$farr);
}
if(!empty($cmps_bcc)) {
$cmps_bcc_arr = imap_rfc822_parse_adrlist($cmps_bcc, $domain_name);
generate_rcpt_header($cmps_bcc_arr, "Bcc", &$cmps_rcpts, &$msg_header, &$farr);
}

$cmps_finalinfo = $farr;

// include signature
if($cmps_sign) $cmps_body .= "\r\n-- \r\n" . $user_set["sign"];

// generate attachments
$msg_boundary = md5(uniqid(time())) . "-" . time();
$msg_body = "";

if(!empty($total_atchs)) {
$msg_header .= "MIME-Version: 1.0\r\n";
$msg_header .= "Content-Type: multipart/mixed; boundary=\"" . $msg_boundary . "\"\r\n\r\n";
$msg_header .= "--" . $msg_boundary . "\r\n";
$msg_header .= "Content-Type: text/plain\r\n\r\n";
$msg_header .= $cmps_body . "\r\n\r\n";

$tmp_atchs = explode(chr(2), $total_atchs);
$atched = 0;
for($j = 0 ; $j < count($tmp_atchs) ; $j++) {
$tmp_arr = explode(chr(3), $tmp_atchs[$j]);
$tmp_file = $tmp_arr[0];
$tmp_content = $tmp_arr[1];
$tmp_size = $tmp_arr[2];
$tmp_filepath = $atch_dir . "/" . $tmp_file;
if(empty($tmp_file) || !file_exists($tmp_filepath)) continue;
$tmp_fp = fopen($tmp_filepath, "r");
$tmp_filein = fread($tmp_fp, filesize($tmp_filepath));
fclose($tmp_fp);
$msg_header .= "--" . $msg_boundary . "\r\n";
if(empty($tmp_content)) $tmp_content = "application/octet-stream";
else $tmp_content = strtolower($tmp_content);
$msg_header .= "Content-Type: " . $tmp_content . "\r\n";

// New attachment code adapted from egroupware
$handle = fopen($tmp_filepath, 'rb');
$tmp_data = '';
while ( $chunk = fread ( $handle, 57)) {
$tmp_data .= base64_encode ( $chunk) . "\r\n";
}
fclose ( $handle);

$msg_header .= "Content-Transfer-Encoding: base64\r\n";
$msg_header .= "Content-Description: $tmp_file\r\n";
$tmp_type = strtok($tmp_content, "/");
if($tmp_type == "image") $tmp_disp = "inline";
else $tmp_disp = "attachment";
$msg_header .= "Content-Disposition: " . $tmp_disp . "; filename=\"" . $tmp_file . "\"\r\n\r\n";
$msg_header .= $tmp_data;
$atched = 1;
}
}
if($atched) {
$msg_header .= "--" . $msg_boundary . "--\r\n";
} else {
$msg_body = "\r\n" . $cmps_body . "\r\n";
}


// prepare the datas
$msg_header = prepare_data($msg_header);
$msg_body = prepare_data($msg_body);
$msg_body = trans_tr($msg_body);

// log the sent mails to find the abusers or harassment e-mail senders quickly (just in case)
// we log these:
// 1 - date time
// 2 - the IP address of the user
// 3 - the name of the sender (e.g; Murat Arslan)
// 4 - the email address of the sender (e.g; arslanm@basilix.org)
// 5 - the subject of the email
// 6 - the To part
// 7 - the Cc part
// 8 - the Bcc part
// --
$logfile = "/var/log/webmail/BASILIX_" . $domain_name;
$fplog = @fopen($logfile, "a+");
if($fplog) {
$logbuf = date("d/m/Y H:i:s", time()) . "|" . $GLOBALS["REMOTE_ADDR"] . "|";
$logbuf .= $cmps_from . "|";
$logbuf .= $username . "@" . $domain_name . "|";
$logbuf .= $cmps_subject . "|" . $cmps_to . "|" . $cmps_cc . "|" . $cmps_bcc;
$logbuf .= "\n";
fwrite($fplog, $logbuf);
fclose($fplog);
}
// -- end of log

// send the mail
$ok_sent = false;
// echo "CMPS_FROM: [$cmps_from_email]
\n";
// echo "CMPS_RCPTS: [$cmps_rcpts]
\n";
// echo "MSG_HEADER: [$msg_header]
\n";
// echo "MSG_BODY: [$msg_header]
\n";
// echo $cmps_finalinfo;
// $zzz = count($cmps_finalinfo);
// echo "($zzz)
\n";
// for($i = 0 ; $i < count($cmps_finalinfo) ; $i++) {
// echo "RCPT: [" . $cmps_finalinfo[$i] . "]
\n";
// }
// exit();
if($BSX_USE_SENDMAIL && @is_executable($BSX_SENDMAIL_PATH)) {
// use sendmail to send the mail
$pmail = popen("$BSX_SENDMAIL_PATH -i -f$cmps_from_email -- $cmps_rcpts", "w");
$prc = fputs($pmail, $msg_header . "\r\n");
$prc += fputs($pmail, $msg_body);
if(pclose($pmail) != 0) $prc = 0;
else $ok_sent = true;
} else {
// send it via SMTP
require("$BSX_LIBDIR/smtp.class.php");

$SMTP_HOST = $bsx_domains["$domain"]["smtp_host"];
$smtp = new SMTP($SMTP_HOST);

// debug
// $smtp->togdebug();

$rc = $smtp->connect();
if(!rc) {
switch($rc) {
case -4:
err_exit($lng->p(455));
case -5:
err_exit($lng->p(456));
default:
err_exit($lng->p(457));
}
}
$msg_rcpt = explode(" ", $cmps_rcpts);
if(!($smtp->mailfrom("<" . $username . "@" . $domain_name . ">")
&& $smtp->rcptall($msg_rcpt)
&& $smtp->startdata()
&& $smtp->senddata($msg_header)
&& $smtp->senddata($msg_body)
&& $smtp->stopdata()
&& $smtp->disconnect())) {
$msg_errno = $smtp->geterr(&$msg_error, &$msg_srverror);
$err_msg = "SMTP Error $msg_errno:
";
$err_msg .= "Error Message is: " . htmlspecialchars($msg_error) . "
";
$err_msg .= "Server $SMTP_HOST replied: " . $msg_srverror . "
\n";
} else {
$ok_sent = true;
}
}

// successfuly sent
if($ok_sent == true) {
compose_rmatchs($total_atchs);
compose_rmpremail();
$info_msg = $lng->p(444);

if($user_set["savesent"]) {
// append to sent mail
require("$BSX_LIBDIR/imap2.inc.php");
$imap->reopbox($BSX_MDIR.BSX_SENTMAIL_NAME);
$imap->apnd($BSX_MDIR.$BSX_SENTMAIL_NAME, $msg_header . "\r\n\r\n" . $msg_body);
}
}

include("$BSX_HTXDIR/menu.htx.php");
include("$BSX_HTXDIR/compose-finalinfo.htx.php");
include("$BSX_HTXDIR/footer.htx.php");
}

function reply_data($d) {
$d = "> " . $d; // put a leading "> "
$nd = ereg_replace("\r", "", $d);
$nd = ereg_replace("\n", "\r\n> ", $nd);
$nd = substr($nd, 0, strlen($nd) - 2); // get rid of trailing "> "
return $nd;
}

require("$BSX_LIBDIR/readmsg.inc.php");
function get_reply($ID, $what = 0) { // 0 (default) = reply, 1 = reply all, 2 = forward
global $BSX_MDIR, $BSX_ATTACH_DIR, $BODY_ONLOAD, $mbox;
global $cmps_to, $cmps_cc, $cmps_subject, $cmps_body;
global $err_msg, $info_msg, $body_type;
global $lng, $imap, $username, $domain_name;

global $cmps_atchs;

$ID = (int)$ID;
// --
if(strtoupper($mbox) != "INBOX")
if(!$imap->reopbox($BSX_MDIR . $mbox)) return;
// -

$mbox_info = $imap->mboxinfo();
$msg_no = $imap->msgno($ID);
if(!$msg_no) {
$err_msg = $lng->p(445);
return;
}

$msg_header = $imap->msghdr($msg_no);
$msg_str = $imap->ftchstr($msg_no);

$reply_obj = $msg_header->reply_to[0];

if(is_object($reply_obj)) {
$reply_addr = $reply_obj->mailbox . "@" . strtolower($reply_obj->host);
if(empty($reply_obj->personal))
$msg_from = $reply_addr;
else
$msg_from = decode_mime($reply_obj->personal) . " <$reply_addr>";
} else {
$msg_from = "";
}

// clean the "," for possible mistakes
$cmps_to = ereg_replace(",", "", $msg_from);
$my_addr = $username . "@" . strtolower($domain_name);
$glue = ",";


if($what == 1) { // replying to all
// generate "to"
for($i = 0 ; $i < count($msg_header->to) ; $i++) {
$to_obj = $msg_header->to[$i];
if(is_object($to_obj)) {
$to_addr = $to_obj->mailbox . "@" . strtolower($to_obj->host);
if($to_addr == $my_addr) continue;
if(empty($to_obj->personal))
$msg_to = $to_addr;
else
$msg_to = ereg_replace(",", "", decode_mime($to_obj->personal)) . " <$to_addr>";
$cmps_to .= $glue . $to_addr;
}
}
$cmps_cc = "";
$glue = "";
// and "cc"
for($i = 0 ; $i < count($msg_header->cc) ; $i++) {
$cc_obj = $msg_header->cc[$i];
if(is_object($cc_obj)) {
$cc_addr = $cc_obj->mailbox . "@" . strtolower($cc_obj->host);
if($cc_addr == $my_addr) continue;
if(empty($cc_obj->personal))
$msg_cc = $cc_addr;
else
$msg_cc = ereg_replace(",", "", decode_mime($cc_obj->personal)) . " <$cc_addr>";
$cmps_cc .= $glue . $cc_addr;
$glue = ",";
}
}
}

if($what == 2 && check_atch($msg_no) == true) { // get the attachments
$atch_dir = $BSX_ATTACH_DIR . "/" . "$domain_name" . "/" . "$username";
$cmd = "/bin/mkdir -m 0700 -p $atch_dir";
@sexec($cmd);

$cmps_atchs = "";
$glue = "";
for($i = 0 ; $i <= count($msg_str->parts) ; $i++) {
$tmp_type="";$tmp_subtype="";$tmp_file="";$tmp_filepath="";

// attachment part
if(!$i) {
$atch_part = $msg_str->parts[0];
if(!is_object($atch_part))
$atch_part = $msg_str;
} else {
$atch_part = $msg_str->parts[$i];
}

if(!is_object($atch_part)) continue;

// content type
$tmp_type = $body_type[$atch_part->type];
$tmp_subtype = strtolower($atch_part->subtype);
if(empty($tmp_subtype)) $tmp_subtype = "x-unknown";
$tmp_content = $tmp_type . "/" . $tmp_subtype;

if(empty($tmp_type)) {
switch($tmp_subtype) {
case "html":
case "plain":
case "enriched":
$tmp_type = "text";
break;
case "rfc822":
case "delivery-status":
$tmp_type = "message";
break;
default:
$tmp_type = "application";
break;
}
}
// filename
if($atch_part->ifparameters) {
while(list(, $atch_param) = each($atch_part->parameters)) {
switch(strtolower($atch_param->attribute)) {
case "filename":
case "name":
$tmp_file = $atch_param->value;
break;
}
}
}
if($atch_part->ifdparameters && empty($tmp_file)) {
while(list(, $atch_param) = each($atch_part->dparameters)) {
switch(strtolower($atch_param->attribute)) {
case "filename":
case "name":
$tmp_file = $atch_param->value;
break;
}
}
}
if(empty($tmp_file)) {
switch($tmp_subtype) {
case "html":
$tmp_file = "message.html";
break;
case "rfc822":
$tmp_file = "message.txt";
break;
case "delivery-status":
$tmp_file = "message.txt";
break;
case "plain":
$tmp_file = "message.txt";
break;
case "enriched":
$tmp_file = "message.rtf";
break;
case "pgp-signature":
$tmp_file = "pgp-signature.txt";
break;
}
}

if(empty($tmp_file)) {
if(!$i) {
$tmp_file = "msg$ID.txt";
$tmp_content = "text/plain";
} else {
$tt = time();
$tmp_file = "unknown_file_$tt.dat";
$tmp_content = "application/x-unknown";
}
}

$tmp_filepath = $atch_dir . "/" . $tmp_file;

// the file itself
$tmp_encoding = $atch_part->encoding;
$tmp_encfunc = "enc_func" . $tmp_encoding;
$atch_body = $imap->ftchbody($msg_no, $i + 1);
$tmp_filein = $tmp_encfunc($atch_body);

// ok copy and ready the file there
$fp = fopen($tmp_filepath, "wb");
if(!$fp) continue; // wtf?
fwrite($fp, $tmp_filein);
fclose($fp);
$tmp_size = filesize($tmp_filepath);

// finally set variables
$cmps_atchs = $cmps_atchs . $glue . $tmp_file . chr(3) . $tmp_content . chr(3) . $tmp_size;
$glue = chr(2);
}
}

$msg_body = check_body($msg_no, $ID, $imap->ftchbody($msg_no, 1));
$msg_date = date("d M Y H:i T", $msg_header->udate);
$msg_subject = $msg_header->subject;
$cmps_subject = decode_mime($msg_subject);

if($what == 0 || $what == 1) {
$lng->sb(446); $lng->sr("%d", $msg_date); $wrote_str = $lng->sp();
if(strtolower(substr($cmps_subject, 0, 3)) != "re:")
$cmps_subject = "Re: " . $cmps_subject;
$cmps_body = $wrote_str . "\r\n\r\n" . reply_data($msg_body);

$BODY_ONLOAD="onLoad='document.composeMail.cmps_body.focus();'";
} else {
$fwd_str = $lng->p(447);
$lng->sb(448); $lng->sr("%d", $msg_date); $date_str = $lng->sp();
$lng->sb(449); $lng->sr("%f", $msg_from); $from_str = $lng->sp();
$lng->sb(450); $lng->sr("%s", $msg_subject); $subj_str = $lng->sp();
if(strtolower(substr($cmps_subject, 0, 4)) != "fwd:")
$cmps_subject = "Fwd: " . $cmps_subject;
$cmps_body = $fwd_str . "\r\n" . $date_str . "\r\n" . $from_str . "\r\n" . $subj_str . "\r\n\r\n" . prepare_data($msg_body);

// since we'll forward, empty the "To" part and focus
$cmps_to = "";
$BODY_ONLOAD="onLoad='document.composeMail.cmps_to.focus();'";
}
}

function load_drafts($cid) {
global $sql;
return $sql->sendmsgs_load_drafts($cid);
}

function cmps_newmsg($cid) {
global $sql;
return $sql->sendmsgs_init($cid);
}

function load_details($cid, $pm) {
global $sql;
return $sql->sendmsgs_load_premail($cid, $pm);
}
function del_draft($cid, $pm) {
global $sql, $atch_dir;

$total_atchs = load_atchs($cid, $pm);
compose_rmatchs($total_atchs);
return $sql->sendmsgs_del_draft($cid, $pm);
}
function del_empty_drafts($cid) {
global $sql;
return $sql->sendmsgs_del_empty_drafts($cid);
}

function load_atchs($cid, $pm) {
global $sql;
return $sql->sendmsgs_load_atchs($cid, $pm);
}

function check_premail($cid, $pm) {
global $sql;
return $sql->sendmsgs_check_premail($cid, $pm);
}

function update_atchs($cid, $pm, $atchs) {
global $sql;
return $sql->sendmsgs_update_premail_atchs($cid, $pm, $atchs);
}

function update_premail($cid, $pm, $from, $to, $cc, $bcc, $subject, $body) {
global $sql;
return $sql->sendmsgs_update_premail($cid, $pm, $from, $to, $cc, $bcc, $subject, $body);
}

function is_already_attached($file, $filelist) {
$tmp_arr = explode(chr(2), $filelist);
for($i = 0 ; $i < count($tmp_arr) ; $i++) {
$tmp_arr2 = explode(chr(3), $tmp_arr[$i]);
if($tmp_arr2[0] == $file) return true;
}
return false;
}
function remove_atchfile($before, $rmfile) {
$after = "";
$tmp_arr = explode(chr(2), $before);
$glue = "";
for($i = 0 ; $i < count($tmp_arr) ; $i++) {
if(empty($tmp_arr[$i])) continue;
$tmp_arr2 = explode(chr(3), $tmp_arr[$i]);
$file = $tmp_arr2[0];
$type = $tmp_arr2[1];
$size = $tmp_arr2[2];
if($file == $rmfile) continue;
$after .= $glue . $file . chr(3) . $type . chr(3) . $size;
$glue = chr(2);
}
return $after;
}

?>

folder.inc.php

/*
+----------------------------------------------------------------------+
| BasiliX - Copyright (C) 2000-2002 Murat Arslan |
| Contributions from: |
| Mike Peters |
+----------------------------------------------------------------------+
*/

// Folder related functions, create mbox, folder list, etc..
// -----------------------------------------------------------------------
function crt_sentmail($imap) {
global $BSX_SENTMAIL_NAME, $BSX_MDIR, $lng;
if(@$imap->crtmbox($BSX_MDIR . $BSX_SENTMAIL_NAME) == false)
err_exit($lng->p(182));
}

function crt_trash($imap) {
global $BSX_TRASH_NAME, $BSX_MDIR, $lng;
global $IMAP_STYPE;
if(@$imap->crtmbox($BSX_MDIR . $BSX_TRASH_NAME) == false)
err_exit($lng->p(181));
}

function folder_list(&$total, &$mbox_cnt, $stype) {
global $imap, $BSX_MDIR, $BSX_SENTMAIL_NAME, $BSX_TRASH_NAME;

// list the folders of the user
$total["msg"] = 0;
$total["size"] = 0;
$total["unread"] = 0;

// first inbox
$inbox_info = $imap->mboxinfo();
$inbox_nmsgs = $inbox_info->Nmsgs;
$inbox_unread = $inbox_info->Unread;
$inbox_size = $inbox_info->Size;
$mboxes[0]["name"] = "Inbox";
$mboxes[0]["unread"] = $inbox_unread;
$mboxes[0]["nmsgs"] = $inbox_nmsgs;
$mboxes[0]["size"] = convert_size($inbox_size);
$total["msg"] += $inbox_nmsgs;
$total["size"] += $inbox_size;
$total["unread"] += $inbox_unread;

// then other mboxes

if($stype == 2 || $stype == 3) { // Courier or Cyrus
$other_list = $imap->lstmbox($BSX_MDIR . "%");
// courier 0.21 returns array to function imap_listsubscribed()
// whereas 1.3.8 returns "string".
// weird..
$sep = "}";
} else { // wu-imapd
$other_list = $imap->lstmbox($BSX_MDIR . "%");
$sep = "/";
}

if($stype == 3) {
$sent_mail_ok = 0;
for($i = 0 ; $i < count($other_list) ; $i++) {
$str2 = $other_list[$i];
$str2_arr = explode($sep, $str2);
$str2_mbox = $str2_arr[1];
$str2_mbox_arr = explode(".", $str2_mbox);
$srv_sentmail = $str2_mbox_arr[1];
// {imap_host:143}INBOX.Sent Mail
if($srv_sentmail == $BSX_SENTMAIL_NAME) $sent_mail_ok = 1;
}
if(!$sent_mail_ok) { // create the sent mail
crt_sentmail($imap);
// and reload the other mailboxes
$other_list = $imap->lstmbox($BSX_MDIR . "%");
}

}

if(empty($other_list) && $stype != 3) {
crt_sentmail($imap);
crt_trash($imap);
$other_list = $imap->lstmbox($BSX_MDIR . "%");
if(!$other_list) return false;
}

for($mbox_cnt = 1 ; $mbox_cnt <= count($other_list) ; $mbox_cnt++) {
$j = $mbox_cnt - 1;
if(!$imap->reopbox2($other_list[$j])) return array();
$other_info = $imap->mboxinfo();
$other_arr = explode($sep, $other_info->Mailbox);
if($stype == 3) { // courier
$other2_arr = explode(".", $other_arr[1]);
$tmp_name = "";
$glue = "";
for($k = 1; $k < count($other2_arr) ; $k++) {
$tmp_name .= $glue . $other2_arr[$k];
$glue = ".";
}
} else {
$j = count($other_arr) - 1;
$tmp_name = $other_arr[$j];
}
$mboxes[$mbox_cnt]["name"] = imap_utf7_decode($tmp_name);
$total["unread"] += $mboxes[$mbox_cnt]["unread"] = $other_info->Unread;
$total["msg"] += $mboxes[$mbox_cnt]["nmsgs"] = $other_info->Nmsgs;
$total["size"] += $mbox_size = $other_info->Size;
$mboxes[$mbox_cnt]["size"] = convert_size($mbox_size);
}
return $mboxes;
}

function empty_folder($mbox) {
global $BSX_MDIR, $imap;

if(strtoupper($mbox) != "INBOX") {
$bsx_mbox = $BSX_MDIR . $mbox;
$imap->reopbox($bsx_mbox);
} else $bsx_mbox = "Inbox";

$mbox_info = $imap->mboxinfo();
$mbox_nmsgs = $mbox_info->Nmsgs;

$seq = "1";
for($i = 2 ; $i <= $mbox_info->Nmsgs ; $i++) $seq .= ",$i";

if(!$imap->setflg($seq, "\\Deleted")) return false;
$imap->expng();
return true;
}
?>

readmsg.inc.php

/*
+----------------------------------------------------------------------+
| BasiliX - Copyright (C) 2000-2002 Murat Arslan |
| Contributions from: |
| Christofer Algotsson |
| Mike Peters |
+----------------------------------------------------------------------+
*/

// Msg reading
// ------------------------------------------------------------------

/*
Just in case.. I got a message with this header, so we better let users
see this message. Well, this is the header of the email I received:

MIME-Version: 1.0
Content-Type: text/plain; charset=iso-8859-1
Content-Transfer-Encoding: quotedGMprintable
^^^^^^^^^^^^^^^^^
No X-Mailer. Probably a newbie spam lamer. But anyway, we need to inform the user.
On the other hand the imap server (IMAP4rev1 v12.264) didnot set the
"encoding" variable to "5" (other) which was expected. It set to "6" so I
added another "other" encoding type with code 6.
*/

$unknown_enc = "
INFO: The encoding algorithm of the current message is not one of: ";
$unknown_enc .= "7bit, 8bit, binary, base64, quoted_printable. This is not something I can do since ";
$unknown_enc .= "the encoding this message used is not a standard. If this is an emergency ";
$unknown_enc .= "e-mail, please inform the person who sent this e-mail to you, and suggest him/her ";
$unknown_enc .= "to re-send the message with one of the above encoding algorithms. If this is not ";
$unknown_enc .= "the case, simply you can ignore/delete this message.
";


// Primary body types
$body_type = array(
0 => 'text',
1 => 'multipart',
2 => 'message',
3 => 'application',
4 => 'audio',
5 => 'image',
6 => 'video',
7 => 'other'
);

$atch_type = array(
"text" => $lng->p(275),
"application" => $lng->p(276),
"audio" => $lng->p(277),
"image" => $lng->p(278),
"video" => $lng->p(279)
);



// Transfer encoding types
$encode_type = array(
0 => '7bit',
1 => '8bit',
2 => 'binary',
3 => 'base64',
4 => 'quoted_printable',
5 => 'other',
6 => 'other'
);

// and their related functions
function enc_func0($body) { // 7bit
return $body;
}

function enc_func1($body) { // 8bit
return enc_func4(imap_8bit($body));
}

function enc_func2($body) { // binary
return enc_func3(imap_binary($body));
}

function enc_func3($body) { // base64
return imap_base64($body);
}

function enc_func4($body) { // quoted-printable
return imap_qprint($body);
}

function enc_func5($body) { // other
global $unknown_enc;
return $unknown_enc . $body;
}

function enc_func6($body) { // another 'other'
global $unknown_enc;
return $unknown_enc . $body;
}

function enc_func($body) { // no encoding
return $body;
}

// Checks the body and applies the necessary decodings
function check_body($msg_no, $msg_uid, $msg_body) {
global $imap, $lng;

$msg_str = $imap->ftchstr($msg_no);
if(is_array($msg_str->parts)) $msg_bpart = $msg_str->parts[0];
else $msg_bpart = $msg_str;
$msg_type = $msg_bpart->type;
$msg_subtype = $msg_bpart->subtype;
if($msg_subtype != "PLAIN" && $msg_subtype != "HTML") {
return $lng->p(258);
}
$msg_encoding = $msg_bpart->encoding;
$enc_func = "enc_func" . $msg_encoding;
if(function_exists($enc_func))
$new_body = $enc_func($msg_body);
else
$new_body = enc_func($msg_body);
if(strlen($new_body) < 3) $new_body = $lng->p(258);
return $new_body;
}

// Checks if the message has an attachment
function check_atch($msg_no) {
global $imap, $body_type;

$msg_str = $imap->ftchstr($msg_no);
$msg_btype = $msg_str->type;
$msg_ifdisp = $msg_str->ifdisposition;
if($msg_btype == 1 || $msg_ifdisp == 1) return true;
return false;
}


// Find the attachments in the message
function find_atch($msg_no) {
global $imap, $body_type, $lng, $atch_type;
global $BSX_BASEHREF, $BSX_LAUNCHER;
global $ID, $mbox, $msg_cbody;

$msg_str = $imap->ftchstr($msg_no);
$msg_ifdisp = $msg_str->ifdisposition;

for($i = 1, $j = 0 ; $i < count($msg_str->parts) ; $i++) {
// type/subtype, disposition
$atch_part = $msg_str->parts[$i];

$tmp_type = $body_type[$atch_part->type];
if(empty($tmp_type)) $tmp_type = "text";

$msg_atch[$j]["type"] = $tmp_type;
$tmp_subtype = strtolower($atch_part->subtype);
if(empty($tmp_subtype)) $tmp_subtype = "x-unknown";
$msg_atch[$j]["subtype"] = $tmp_subtype;
$msg_atch[$j]["disposition"] = ($atch_part->ifdisposition) ? strtolower($atch_part->disposition) : "attachment";

// size
$msg_atch[$j]["size"] = convert_size($atch_part->bytes);

// filename
if($atch_part->ifparameters) {
while(list(, $atch_param) = each($atch_part->parameters)) {
switch(strtolower($atch_param->attribute)) {
case "filename":
case "name":
$msg_atch[$j]["name"] = $atch_param->value;
break;
}
}
}
if($atch_part->ifdparameters && empty($msg_atch[$j]["name"])) {
while(list(, $atch_param) = each($atch_part->dparameters)) {
switch(strtolower($atch_param->attribute)) {
case "filename":
case "name":
$msg_atch[$j]["name"] = $atch_param->value;
break;
}
}
}


// description
if(isset($atch_part->ifdescription)) $msg_atch[$j]["desc"] = $atch_part->description;
else {
if(!empty($msg_atch[$j]["name"])) $msg_atch[$j]["desc"] = $msg_atch[$j]["name"];
else $msg_atch[$j]["name"] = "unknown file";
}

// --file
if(empty($msg_atch[$j]["name"])) $msg_atch[$j]["name"] = preg_replace('|\W|', '_', $msg_atch[$j]["desc"]);
if(empty($msg_atch[$j]["name"])) { // still no filename
switch($msg_atch[$j]["subtype"]) {
case "html":
$msg_atch[$j]["name"] = "message.html";
$msg_atch[$j]["desc"] = $lng->p(269);
break;
case "rfc822":
$msg_atch[$j]["name"] = "message.txt";
$msg_atch[$j]["desc"] = $lng->p(270);
break;
case "delivery-status":
$msg_atch[$j]["name"] = "message.txt";
$msg_atch[$j]["desc"] = $lng->p(271);
break;
case "plain":
$msg_atch[$j]["name"] = "message.txt";
$msg_atch[$j]["desc"] = $lng->p(272);
break;
case "enriched":
$msg_atch[$j]["name"] = "message.rtf";
$msg_atch[$j]["desc"] = $lng->p(273);
break;
case "pgp-signature":
$msg_atch[$j]["name"] = "pgp-signature.txt";
$msg_atch[$j]["desc"] = $lng->p(280);
break;
}
if(empty($msg_atch[$j]["name"])) // still no filename??
$msg_atch[$j]["name"] = $lng->p(274);
}
// -- desc
if(empty($msg_atch[$j]["desc"])) { // no description
switch($msg_atch[$j]["subtype"]) {
case "html":
$msg_atch[$j]["desc"] = $lng->p(269);
break;
case "rfc822":
$msg_atch[$j]["desc"] = $lng->p(270);
break;
case "delivery-status":
$msg_atch[$j]["desc"] = $lng->p(271);
break;
case "plain":
$msg_atch[$j]["desc"] = $lng->p(272);
break;
case "enriched":
$msg_atch[$j]["desc"] = $lng->p(273);
break;
}
if(empty($msg_atch[$j]["desc"])) // no desc?
$msg_atch[$j]["desc"] = $atch_type[$msg_atch[$j]["type"]];
}
// -- DBG
// echo "NAME: " . $msg_atch[$j]["name"] . "
\n";
// echo "DESC: " . $msg_atch[$j]["desc"] . "
\n";
// echo "DISP: " . $msg_atch[$j]["disp"] . "
\n";
// echo "TYPE: " . $msg_atch[$j]["type"] . "
\n";
// echo "SUBTYPE: " . $msg_atch[$j]["subtype"] . "
\n";
// --
$j++;
}
return $msg_atch;
}

// Push the desired attachment of the message
function push_msgatch($part) {
global $imap, $mbox, $ID;
global $BSX_MDIR;
global $body_type, $lng;

if(strtoupper($mbox) != "INBOX") $imap->reopbox($BSX_MDIR . $mbox);

$msg_no = $imap->msgno($ID);
$msg_str = $imap->ftchstr($msg_no);

if(!$part) {
$atch_part = $msg_str->parts[0];
if(!is_object($atch_part))
$atch_part = $msg_str;
} else {
$atch_part = $msg_str->parts[$part];
}

settype($myatch, "object");

// type/subtype, disposition
$myatch->type = $body_type[$atch_part->type];
$myatch->subtype = strtolower($atch_part->subtype);
if(empty($myatch->subtype)) $myatch->subtype = "x-unknown";
if(empty($myatch->type)) {
switch($myatch->subtype) {
case "html":
case "plain":
case "enriched":
$myatch->type = "text";
break;
case "rfc822":
case "delivery-status":
$myatch->type = "message";
break;
default:
$myatch->type = "application";
break;
}
}

// disposition
switch(strtolower($myatch->type)) {
case "image":
case "text":
$myatch->disp = "inline";
break;
}

if(empty($myatch->disp))
$myatch->disp = ($atch_part->ifdisposition) ? strtolower($atch_part->disposition) : "attachment";

// filename
if($atch_part->ifparameters) {
while(list(, $atch_param) = each($atch_part->parameters)) {
switch(strtolower($atch_param->attribute)) {
case "filename":
case "name":
$myatch->name = $atch_param->value;
break;
}
}
}
if($atch_part->ifdparameters) {
while(list(, $atch_param) = each($atch_part->dparameters)) {
switch(strtolower($atch_param->attribute)) {
case "filename":
case "name":
$myatch->name = $atch_param->value;
break;
}
}
}

// description
if(isset($atch_part->ifdescription)) $myatch->desc = $atch_part->description;
else {
if(!empty($myatch->name)) $myatch->desc = $myatch->name;
else $myatch->desc = $lng->p(274);
}
// if(empty($myatch->name)) $myatch->name = preg_replace('|\W|', '_', $myatch->desc);
if(empty($myatch->name)) {
switch($myatch->subtype) {
case "html":
$myatch->name = "message.html";
break;
case "rfc822":
$myatch->name = "message.txt";
break;
case "delivery-status":
$myatch->name = "message.txt";
break;
case "plain":
$myatch->name = "message.txt";
break;
case "enriched":
$myatch->name = "message.rtf";
break;
case "pgp-signature":
$myatch->name = "pgp-signature.txt";
break;
}
}

if(empty($myatch->name)) {
$tt = time();
if(!$part)
$myatch->name = "msg$ID.txt";
else
$myatch->name = "unknown_file_$tt.dat";
if(empty($myatch->desc))
$myatch->desc = "unknown-description-$tt";
}


// body
$atch_body = $imap->ftchbody($msg_no, $part + 1);
$msg_encoding = $atch_part->encoding;
$enc_func = "enc_func" . $msg_encoding;
$myatch->body = $enc_func($atch_body);

// -- DBG
// echo "NAME: " . $myatch->name . "
\n";
// echo "DESC: " . $myatch->desc . "
\n";
// echo "DISP: " . $myatch->disp . "
\n";
// echo "ENCODING: " . $msg_encoding . "
\n";
// echo "TYPE: " . $myatch->type . "
\n";
// echo "SUBTYPE: " . $myatch->subtype . "
\n";
// --

// Push it
Header("Content-Type: $myatch->type/$myatch->subtype");
Header("Content-Disposition: $myatch->disp; filename=\"" . $myatch->name . "\"");
echo $myatch->body;
my_exit();
}

// Get the header of the message
function get_msghdr($mbox, $msg_uid) {
global $imap;

// --
if(strtoupper($mbox) != "INBOX")
if(!$imap->reopbox($mbox)) return "no header";
// -

$msg_no = $imap->msgno($msg_uid);
return $imap->ftchhdr($msg_no);
}

// Retrieve the information about the message
function get_msg($mbox, $msg_uid, &$msg_no, &$msg_atchlist) {
global $imap, $lng, $err_msg, $body_type;
global $BSX_BASEHREF, $BSX_LAUNCHER;

// --
if(strtoupper($mbox) != "INBOX")
if(!$imap->reopbox($mbox)) return array();
// -

$mbox_info = $imap->mboxinfo();
$msg_no = $imap->msgno($msg_uid);
if(!$msg_no) {
$err_msg = $lng->p(259);
return array();
}

$msg_header = $imap->msghdr($msg_no);
$msg_str = $imap->ftchstr($msg_no);

$from_obj = $msg_header->from[0];

// the from part
if(is_object($from_obj)) {
$from_addr = $from_obj->mailbox . "@" . strtolower($from_obj->host);
if(empty($from_obj->personal))
$msg_detailed["from"] = $from_addr;
else
$msg_detailed["from"] = decode_mime($from_obj->personal) . " <$from_addr>";
$msg_detailed["fromaddr"] = $from_addr;
} else {
$msg_detailed["from"] = $lng->p(7);
}

// to
$msg_detailed["to"] = $msg_header->to;

// cc
$msg_detailed["cc"] = $msg_header->cc;

// the header
$msg_detailed["header"] = $imap->ftchhdr($msg_no);

// date and the subject
$msg_detailed["date"] = date("d M Y H:i", $msg_header->udate);
$msg_subject = (chop($msg_header->subject == "")) ? $lng->p(267) : $msg_header->subject;
$msg_detailed["subject"] = decode_mime($msg_subject);

// the body part
$msg_cbody = check_body($msg_no, $msg_uid, $imap->ftchbody($msg_no, 1));

// the attachments if any
if(check_atch($msg_no))
$msg_atchlist = find_atch($msg_no);

$msg_detailed["body"] = removeEvilTags($msg_cbody);

$msg_detailed["body"] = nl2br(handle_links($msg_detailed["body"]));;
$msg_detailed["subject"] = htmlspecialchars($msg_detailed["subject"]);
$msg_detailed["from"] = htmlspecialchars($msg_detailed["from"]);
return $msg_detailed;
}

function push_msgdetail($ID, $mbox) {
global $RequestID;
global $lng, $err_msg, $info_msg, $imap;
global $bsx_mboxes, $bsx_mboxes_curmbox, $sentmail_upper;
global $BSX_BASEHREF, $BSX_LAUNCHER;
global $BSX_HTXDIR, $BSX_THEMEDIR, $BSX_MDIR;
global $BSX_VERSION;
global $BSX_SENTMAIL_NAME, $BSX_TRASH_NAME;
global $SESSID;
if($mbox == "" || (int)$ID == 0) my_exit();
// TODO: Funtion to handle this
$user_set = $_COOKIE['user_set'];
$sort = $_GET['sort'];

if(strtoupper($mbox) != "INBOX") $bsx_mbox = $BSX_MDIR . $mbox;
else $bsx_mbox = "Inbox";

// collect the information
$msg_detailed = get_msg($bsx_mbox, $ID, $msg_no, $msg_atchlist);
$bsx_mboxes = getbsxmboxes();

// prev next if set
if($user_set["prevnext"]) {
if(empty($sort)) $sort = $user_set["sort"];
if($sort == 2) $sort_arr = $imap->mboxsrt(SORTFROM, $user_set["rsort"]);
else if($sort == 3) $sort_arr = $imap->mboxsrt(SORTSUBJECT, $user_set["rsort"]);
else if($sort == 4) $sort_arr = $imap->mboxsrt(SORTSIZE, $user_set["rsort"]);
else if($sort == 5) $sort_arr = $imap->mboxsrt(SORTTO, $user_set["rsort"]);
else $sort_arr = $imap->mboxsrt(SORTDATE, $user_set["rsort"]);

$msg_previd = -1;
$msg_found = 0;
$msg_nextid = -1;
$c = count($sort_arr);
for($i = 0 ; $i < $c ; $i++) {
$cur_msg = $sort_arr[$i];
$msg_header = $imap->msghdr($cur_msg);
$dest_uid = $imap->msguid($msg_header->Msgno);
if($msg_found) {
$msg_nextid = $dest_uid;
break;
}
if($dest_uid == $ID) {
$msg_found++;
continue;
}
$msg_previd = $dest_uid;
}
}

// --
if(empty($msg_detailed)) {
if(empty($err_msg)) $err_msg = $lng->p(259);
$msg_not_found = 1;
}

// print the information about the message
include("$BSX_HTXDIR/header.htx.php");
include("$BSX_HTXDIR/menu.htx.php");
include("$BSX_HTXDIR/readmsg.htx.php");
include("$BSX_HTXDIR/footer.htx.php");
}

function push_msgprint() {
global $RequestID;
global $lng;
global $BSX_BASEHREF, $BSX_LAUNCHER;
global $BSX_HTXDIR, $BSX_THEMEDIR, $BSX_MDIR;
global $BSX_VERSION;
$mbox = $_GET['mbox'];
$ID = $_GET['ID'];

if(strtoupper($mbox) != "INBOX") $bsx_mbox = $BSX_MDIR . $mbox;
else $bsx_mbox = "Inbox";

// collect the information
$msg_detailed = get_msg($bsx_mbox, $ID, $msg_no, $msg_atchlist);

// print the information about the message
include("$BSX_HTXDIR/header.htx.php");
include("$BSX_HTXDIR/printmsg.htx.php");
echo "</ body> </ html>\n";
// include("$BSX_HTXDIR/footer.htx.php");
}

function push_msghdr() {
global $RequestID;
global $lng;
global $BSX_BASEHREF, $BSX_LAUNCHER;
global $BSX_HTXDIR, $BSX_THEMEDIR, $BSX_MDIR;
global $BSX_VERSION;
global $SESSID;
$mbox = $_GET['mbox'];
$ID = $_GET['ID'];

if(strtoupper($mbox) != "INBOX") $bsx_mbox = $BSX_MDIR . $mbox;
else $bsx_mbox = "Inbox";

$msg_header = get_msghdr($bsx_mbox, $ID);

// print the information about the message
include("$BSX_HTXDIR/header.htx.php");
include("$BSX_HTXDIR/readmsg-header.htx.php");
// include("$BSX_HTXDIR/footer.htx.php");
echo "</ body> </ html>\n";
}

function push_tocc($attr, $tocc) {
global $lng;

for($i = 0 ; $i < count($tocc) ; $i++) {
if(!$i) {
echo "" . nbsp($attr) . "";
} else {
echo " ";
}
$tocc_obj = $tocc[$i];
if(is_object($tocc_obj)) {
$tocc_addr = $tocc_obj->mailbox . "@" . strtolower($tocc_obj->host);
if(empty($tocc_obj->personal))
$tocc_complete = $tocc_addr;
else
$tocc_complete = htmlspecialchars(decode_mime($tocc_obj->personal) . " <$tocc_addr>");
} else {
$tocc_complete = $lng->p(7);
}
echo "" . nbsp($tocc_complete) . "\n";
}
}
?>

smtp.class.php

/*
+----------------------------------------------------------------------+
| BasiliX - Copyright (C) 2000-2002 Murat Arslan |
| Contributions from: |
| Mike Peters |
+----------------------------------------------------------------------+
*/

// SMTP connection to send mail
// -----------------------------------------------------------------------
// note1:
// the error messages in fact are only for the system admins since
// endusers are not interested in the RCPT or the DATA requests.
// so, after configuring the SMTP_HOSTS for the domains, check them
// by sending a mail to yourself.
// --
// so if you get a feedback like "hey i cant send my mail. it said
// _RCPT TO error_", then check this file out.
// --
// note2:
// Another error code is -104 which is about switching to DATA transfer
// mode. If the server replied 503 RCPT first (or something like that)
// it is about "invalid" email addresses which are used to pass to "RCPT TO"
// command. We need a "isEmail" javascript or something like that to check
// the e-mail addresses whether they are valid or not just before the user
// hits the send the mail button.
// --
class SMTP {
var $socket = "";
var $host = "";
var $port = 25;
var $error = "";
var $errno = "";
var $errserver = "";
var $timeout = 15; // enough?
var $debug = 0;


function SMTP($h) {
$this->host = $h;
$this->error = $this->errno = $this->socket = $this->errserver = "";
}

// toggle debugging
function togdebug() {
if($this->debug)
$this->debug = 0;
else
$this->debug = 1;
}

// debug - print output if debugging
function ifdebug($m) {
if($this->debug) {
echo "DEBUG: " . htmlspecialchars(rtrim($m)) . "
\n";
flush();
}
}

// send a data to the socket
function senddata($data) {
if(empty($data)) return true;
$this->ifdebug($data);
if(!@fputs($this->socket, $data, strlen($data))) {
$this->errno = -100;
$this->error = "unable to send data to $this->host:$this->port";
return false;
}
return true;
}

// read data from socket
function readdata() {
$data = "";
while(1) {
if(feof($this->socket)) return 0;
$data .= @fgets($this->socket, 128);

$this->ifdebug($data);

$len = strlen($data);
if($len > 2 && substr($data, $len - 2, 2) == "\r\n") {
$line = substr($data, 0, $len - 2);
return $data;
}
}
}

// can i be your friend?
function verify($code) {
while(($data = $this->readdata())) {
$mcode = strtok($data, " ");
if(strlen($mcode) == 3) {
if($mcode == $code) return true;
$this->errserver = $data;
return false;
}
}
$this->errserver = $data;
return false;
}

// connect to the smtp host
function connect() {
global $REMOTE_ADDR;
$this->ifdebug("Connecting to $this->host:$this->port, timeout is $this->timeout seconds.");
$i = @fsockopen($this->host, $this->port, &$errno, $error, $this->timeout);
if(!$i) {
$this->error = $error;
$this->errno = $errno;
return $errno;
}
$this->socket = $i;

if(!$this->verify(220) || !$this->senddata("HELO $REMOTE_ADDR\r\n") || !$this->verify(250)) {
fclose($i);
$this->error = "the server didnot take notice at my greeting (HELO $REMOTE_ADDR)";
$this->errno = -101;
$this->socket = "";
return 0;
}
return 1;
}

function disconnect() {
fclose($this->socket);
$this->socket = "";
return true;
}

// send the MAIL FROM data
function mailfrom($f) {
if(!$this->senddata("MAIL FROM: " . $f . "\r\n") || !$this->verify(250)) {
$this->errno = -102;
$this->error = "the server didnot send the 250 OK string to my MAIL FROM request";
return false;
}
return true;
}

// Send the RCPT TO Data
function rcptto($a) {
if(!$this->senddata("RCPT TO: <$a>\r\n") || !$this->verify(250)) {
$this->errno = -103;
$this->error = "RCPT TO error for $a";
return false;
}
return true;
}

// send all the recipients to the server
function rcptall($all) {
for($j = 0 ; $j < count($all) ; $j++) {
if(!$this->rcptto($all[$j]))
return false;
}
return true;
}

// start sending the mail data
function startdata() {
if(!$this->senddata("DATA\r\n") || !$this->verify(354)) {
$this->errno = -104;
$this->error = "cannot switch to DATA transfer mode";
return false;
}
return true;
}

// stop, tell mta to send the mail now
function stopdata() {
if(!$this->senddata(".\r\n") || !$this->verify(250)) {
$this->errno = -105;
$this->error = "cannot _end_ the data transfer";
return false;
}
return true;
}

// launch another command, maybe?
function mycmd($cmd, $ret) {
if(!$this->senddata($cmd) || !$this->verify($ret)) {
$this->errno = -106;
$this->error = "the command $cmd didnot return $ret";
return false;
}
return true;
}

// receive the errno/msg
function geterr(&$error, $srverr) {
$error = $this->error;
$srverr = $this->errserver;
return $this->errno;
}
}
?>
Your Ad Here