<?

// SET BLOGHOSTER VERSION
$bh_version = "2.10";

// COMPENSATE FOR NO MAGIC QUOTES
if(!@get_magic_quotes_gpc()) { 
$_GET = array_map('addslashes', $_GET); 
$_POST = array_map('addslashes', $_POST); 
$_COOKIE = array_map('addslashes', $_COOKIE); 
}

// SHOW HELP TIP
function tip($tip_id) {
global $admin_info;
$tip_info = mysql_fetch_assoc(mysql_query("SELECT * FROM bhost_tips WHERE tip_id='$tip_id'"));

$server_array = explode("/", $_SERVER['PHP_SELF']);
$server_array_mod = array_pop($server_array);
$array_count = count($server_array)-1;
if($server_array[$array_count] == "manager") {
$tip_url = "../tip.php?tip_id=$tip_id";
$image_url = "../images/tip.gif";
} else {
$tip_url = "./tip.php?tip_id=$tip_id";
$image_url = "./images/tip.gif";
}
if($admin_info[tips] == 1 & $tip_info[tip] != "") {
echo "&nbsp;
<a href='$tip_url' target='targetname' onClick='window.open(\"\",this.target,\"left=\"+((screen.width-400)/2)+\",top=\"+((screen.height-300)/2)+\",width=400,height=300,toolbar=0,resizable=0,scrollbars=1\");'>
<noscript><a href='$tip_url' target='_blank' border='0'></noscript>
<img src='$image_url' border='0'></a>
";
}
}



// SHOW HELP TIP
function tip2($tip_title, $tip_text) {
global $admin_info;
$server_array = explode("/", $_SERVER['PHP_SELF']);
$server_array_mod = array_pop($server_array);
$array_count = count($server_array)-1;
if($server_array[$array_count] == "manager") {
$tip_url = "../tip.php?tip_id=0&title=$tip_title&text=$tip_text";
$image_url = "../images/tip.gif";
} else {
$tip_url = "./tip.php?tip_id=0&title=$tip_title&text=$tip_text";
$image_url = "./images/tip.gif";
}
if($admin_info[tips] == 1 & $tip_title != "" & $tip_text != "") {
echo "&nbsp;
<a href='$tip_url' target='targetname' onClick='window.open(\"\",this.target,\"left=\"+((screen.width-400)/2)+\",top=\"+((screen.height-300)/2)+\",width=400,height=300,toolbar=0,resizable=0,scrollbars=1\");'>
<noscript><a href='$tip_url' target='_blank' border='0'></noscript>
<img src='$image_url' border='0'></a>
";
}
}



// ERROR DISPLAY
function show_error($error) {
if($error != "") { echo "<div class='help'><img src='".url("/images/", "./images/error_icon.gif")."' border='0' class='error'><font class='error'> $error</font></div>"; }
}



//RETURNS BEFORE, AFTER, AND BETWEEN FOR STRINGS
function before($this, $inthat) {
 return substr($inthat, 0, strpos($inthat, $this));
}

function after($this, $inthat) {
 if(!is_bool(strpos($inthat, $this))) {
  return substr($inthat, strpos($inthat,$this)+strlen($this));
 } else {
  return false;
 }
}

function between($this, $that, $inthat) {
 return before($that, after($this, $inthat));
}//END before(), after(), and between() functions


// FIND NUMBER OF OCCURRENCES OF CONTAINERS IN TEMPLATE
function occurrencecount($this, $that, $inthat, $count) {
 $newinthat = after("$that", after("$this", $inthat));
 if($newinthat != false) {
 $count = $count + 1;
 return occurrencecount($this, $that, $newinthat, $count);
 } else {
 return $count;
 }
}//END occurrencecount() function


//CHANGES TIMEZONE
function timezone($time) {

global $weblog_info;
$time = $time-(date("Z")-(date("I")*3600));

if($weblog_info[timezone] == -12) { $new_time = $time - 43200; }
if($weblog_info[timezone] == -11) { $new_time = $time - 39600; }
if($weblog_info[timezone] == -10) { $new_time = $time - 33000; }
if($weblog_info[timezone] == -9) { $new_time = $time - 32400; }
if($weblog_info[timezone] == -8) { $new_time = $time - 28800; }
if($weblog_info[timezone] == -7) { $new_time = $time - 25200; }
if($weblog_info[timezone] == -6) { $new_time = $time - 21600; }
if($weblog_info[timezone] == -5) { $new_time = $time - 18000; }
if($weblog_info[timezone] == -4) { $new_time = $time - 14400; }
if($weblog_info[timezone] == -3.3) { $new_time = $time - 11880; }
if($weblog_info[timezone] == -3) { $new_time = $time - 10800; }
if($weblog_info[timezone] == -2) { $new_time = $time - 7200; }
if($weblog_info[timezone] == -1) { $new_time = $time - 3600; }
if($weblog_info[timezone] == 0) { $new_time = $time; }
if($weblog_info[timezone] == 1) { $new_time = $time + 3600; }
if($weblog_info[timezone] == 2) { $new_time = $time + 7200; }
if($weblog_info[timezone] == 3) { $new_time = $time + 10800; }
if($weblog_info[timezone] == 3.3) { $new_time = $time + 11880; }
if($weblog_info[timezone] == 4) { $new_time = $time + 14400; }
if($weblog_info[timezone] == 4.3) { $new_time = $time + 15480; }
if($weblog_info[timezone] == 5) { $new_time = $time + 18000; }
if($weblog_info[timezone] == 5.5) { $new_time = $time + 19800; }
if($weblog_info[timezone] == 6) { $new_time = $time + 21600; }
if($weblog_info[timezone] == 7) { $new_time = $time + 25200; }
if($weblog_info[timezone] == 8) { $new_time = $time + 28800; }
if($weblog_info[timezone] == 9) { $new_time = $time + 32400; }
if($weblog_info[timezone] == 9.3) { $new_time = $time + 33480; }
if($weblog_info[timezone] == 10) { $new_time = $time + 33000; }
if($weblog_info[timezone] == 11) { $new_time = $time + 39600; }
if($weblog_info[timezone] == 12) { $new_time = $time + 43200; }

return $new_time;

}//END timezone() function



//CHANGES TIME TO SERVER TIME
function untimezone($time) {

global $weblog_info;

if($weblog_info[timezone] == -12) { $time = $time + 43200; }
if($weblog_info[timezone] == -11) { $time = $time + 39600; }
if($weblog_info[timezone] == -10) { $time = $time + 33000; }
if($weblog_info[timezone] == -9) { $time = $time + 32400; }
if($weblog_info[timezone] == -8) { $time = $time + 28800; }
if($weblog_info[timezone] == -7) { $time = $time + 25200; }
if($weblog_info[timezone] == -6) { $time = $time + 21600; }
if($weblog_info[timezone] == -5) { $time = $time + 18000; }
if($weblog_info[timezone] == -4) { $time = $time + 14400; }
if($weblog_info[timezone] == -3.3) { $time = $time + 11880; }
if($weblog_info[timezone] == -3) { $time = $time + 10800; }
if($weblog_info[timezone] == -2) { $time = $time + 7200; }
if($weblog_info[timezone] == -1) { $time = $time + 3600; }
if($weblog_info[timezone] == 0) { $time = $time; }
if($weblog_info[timezone] == 1) { $time = $time - 3600; }
if($weblog_info[timezone] == 2) { $time = $time - 7200; }
if($weblog_info[timezone] == 3) { $time = $time - 10800; }
if($weblog_info[timezone] == 3.3) { $time = $time - 11880; }
if($weblog_info[timezone] == 4) { $time = $time - 14400; }
if($weblog_info[timezone] == 4.3) { $time = $time - 15480; }
if($weblog_info[timezone] == 5) { $time = $time - 18000; }
if($weblog_info[timezone] == 5.5) { $time = $time - 19800; }
if($weblog_info[timezone] == 6) { $time = $time - 21600; }
if($weblog_info[timezone] == 7) { $time = $time - 25200; }
if($weblog_info[timezone] == 8) { $time = $time - 28800; }
if($weblog_info[timezone] == 9) { $time = $time - 32400; }
if($weblog_info[timezone] == 9.3) { $time = $time - 33480; }
if($weblog_info[timezone] == 10) { $time = $time - 33000; }
if($weblog_info[timezone] == 11) { $time = $time - 39600; }
if($weblog_info[timezone] == 12) { $time = $time - 43200; }

$new_time = $time-((date("I")*3600)-date("Z"));

return $new_time;

}//END untimezone() function



// BUMP LOGIN LOG
function bumplog() {
$log_entries = mysql_num_rows(mysql_query("SELECT l_id FROM bhost_log"));
if($log_entries > 300) {
 $greatest_log = mysql_fetch_assoc(mysql_query("SELECT l_id FROM bhost_log ORDER BY l_id ASC LIMIT 0,1"));
 mysql_query("DELETE FROM bhost_log WHERE l_id='$greatest_log[l_id]'");
 bumplog();
}
}//END bumplog() function


//RANDOM CODE GENERATOR FUNCTION
function randomcode($len="8") {
$code = NULL;
for($i=0;$i<$len;$i++) {
$char = chr(rand(48,122));
while(!ereg("[a-zA-Z0-9]", $char)) {
if($char == $lchar) { continue; }
$char = chr(rand(48,90));
}
$pass .= $char;
$lchar = $char;
}
return $pass;
} //END randomcode() function


// CHECKS FOR DUPLICATE TIMES
function duplicatetime($date, $e_id) {
global $weblog_info;
if($e_id == 0) {
$other_entries = mysql_num_rows(mysql_query("SELECT e_id FROM bhost_entries WHERE w_id='$weblog_info[w_id]' AND date='$date'"));
} else {
$other_entries = mysql_num_rows(mysql_query("SELECT e_id FROM bhost_entries WHERE w_id='$weblog_info[w_id]' AND e_id <> '$e_id' AND date='$date'"));
}
if($other_entries == 0) {
return $date;
} else {
$newdate = $date+1;
return duplicatetime($newdate, $e_id);
}
} //END duplicatetime() function



// MAKE A NEGATIVE TIMESTAMP
function MakeTime() {

   $objArgs = func_get_args();
   $nCount = count($objArgs);
   if ($nCount < 7) {
       $objDate = getdate();
       if ($nCount < 1)
           $objArgs[] = $objDate["hours"];
       if ($nCount < 2)
           $objArgs[] = $objDate["minutes"];
       if ($nCount < 3)
           $objArgs[] = $objDate["seconds"];
       if ($nCount < 4)
           $objArgs[] = $objDate["mon"];
       if ($nCount < 5)
           $objArgs[] = $objDate["mday"];
       if ($nCount < 6)
           $objArgs[] = $objDate["year"];
       if ($nCount < 7)
           $objArgs[] = -1;
   }
   $nYear = $objArgs[5];
   $nOffset = 0;

if($nYear < 1970) {
$nOffset = -2019686400;
$objArgs[5] += 64;
 if($nYear < 1942) {
  $objArgs[6] = 0;
 }
}


   return call_user_func_array("mktime", $objArgs) + $nOffset;
}


// CONVERT A NEGATIVE TIMESTAMP TO A DATE
function MakeDate($time) {

$date = Array();

if($time < 0) {
$nOffset = -2019686400;
$time = $time - $nOffset;
$date[0] = cdate("n", $time);
$date[1] = cdate("j", $time);
$date[2] = cdate("Y", $time)-64;
$date[3] = cdate("F", $time);
} else {
$date[0] = cdate("n", $time);
$date[1] = cdate("j", $time);
$date[2] = cdate("Y", $time);
$date[3] = cdate("F", $time);
}
return $date;
}


// RETURN AGE WITH A GIVEN BIRTHDAY
function myAge($DOB) // YYYY-MM-DD
{
$DOBArray = explode("-", $DOB);
$DobYear = $DOBArray[0];
$DobMonth = $DOBArray[1];
$DobDay = $DOBArray[2];
$TodayDay = date('d');
$TodayMonth = date('m');
$TodayYear = date('Y');
if (($TodayMonth > $DOBArray[1]) || (($TodayMonth == $DOBArray[1]) && ($TodayDay >= $DOBArray[2]))) {
$AgeYear = $TodayYear - $DOBArray[0];
} else {
$AgeYear = $TodayYear - $DOBArray[0] - 1;
}
$dayofyear = date('z', mktime(0, 0, 0, date("m"), date("d"), date("Y")));
$dayofyear = $dayofyear+1;
$dayofbday = date('z', mktime(0, 0, 0, $DobMonth, $DobDay, date("Y")));
if ($dayofbday > $dayofyear) { $days = 365 - ($dayofbday - $dayofyear); } else { $days = ($dayofyear - $dayofbday); }
return $AgeYear;
} //END myAge() function



// DISPLAY URLS
function url($file, $weblog, $username="", $e_id="0", $year="", $month="", $extras="", $page="", $category="") {
global $admin_info;
$url = "";
$server_array = explode("/", $_SERVER['PHP_SELF']);
$server_array_mod = array_pop($server_array);

$array_count = count($server_array)-1;
if($server_array[$array_count] == "admin" | $server_array[$array_count] == "manager") {
$server_array_mod = array_pop($server_array);
}

$server_info = implode("/", $server_array);
$prefix = "http://".$_SERVER['HTTP_HOST'].$server_info."/";


// SUBDIRECTORY STYLE URLS
if($admin_info[url] == 1) {
 if($file == "/images/") {
   $url = $prefix."$weblog";
 } elseif($file == "album") {
   $url = $prefix."albums/$username/$extras";
 } elseif($file == "archive") {
   if($year == "" | $month == "") {
     $url = "$prefix$weblog/$file/$extras";
   } else {
     $url = "$prefix$weblog/$file/$year/$month/$extras";
   }
 } elseif($file == "browse") {
   $extras = str_replace(" ", "+", $extras);
   $url = "$prefix$file.php?$extras";
 } elseif($file == "delete_comment") {
   $url = "$prefix$file.php?w=$weblog&e_id=$e_id$extras";
 } elseif($file == "delete_trackback") {
   $url = "$prefix$file.php?w=$weblog&e_id=$e_id$extras";
 } elseif($file == "edit_comment") {
   $url = "$prefix$file.php?w=$weblog&e_id=$e_id$extras";
 } elseif($file == "entry") {
   $entry_info = mysql_fetch_assoc(mysql_query("SELECT title FROM bhost_entries WHERE e_id='$e_id'"));
   if($entry_info[title] != "") { $stripped_title = urlencode($entry_info[title]).".html"; }
   if($extras != "") { $extras = "?".$extras; }
   $url = "$prefix$weblog/$e_id/$stripped_title$extras";
 } elseif($file == "entry_rss") {
   $url = "$prefix$weblog/$e_id/$extras";
 } elseif($file == "friends") {
   if($page != "") { $page = "page".$page."/"; }
   $url = "$prefix$weblog/friends/$page$extras";
 } elseif($file == "index") {
   if($page != "") { $page = "page".$page."/"; }
   $url = "$prefix$weblog/$page$extras";
 } elseif($file == "index_cat") {
   $category = str_replace(" ", "+", $category);
   if($page != "") { $page = "page".$page."/"; }
   $url = "$prefix$weblog/$category/$page$extras";
 } elseif($file == "login") {
   $url = "$prefix$file.php?w=$weblog&e_id=$e_id$extras";
 } elseif($file == "podcast") {
   $url = "$prefix$file.php?w=$weblog$extras";
 } elseif($file == "post_comment") {
   $url = "$prefix$file.php?w=$weblog&e_id=$e_id$extras";
 } elseif($file == "profile") {
   $url = $prefix."profiles/$username/$extras";
 } elseif($file == "profile_nouser") {
   $url = $prefix."profile.php";
 } elseif($file == "sendlink") {
   $url = "$prefix$file.php?w=$weblog&e_id=$e_id$extras";
 } elseif($file == "signup") {
   $url = "$prefix$file.php?w=$weblog&e_id=$e_id$extras";
 } elseif($file == "rss") {
   $url = "$prefix$file.php?w=$weblog$extras";
 } elseif($file == "trackback") {
   $url = "$prefix$file.php?e_id=$e_id";
 } else {
   $url = "$prefix$file";
 }


// SUBDOMAIN STYLE URLS
} elseif($admin_info[url] == "2") {
if(substr($_SERVER['HTTP_HOST'], 0, 4) == "www.") {
 $host = substr($_SERVER['HTTP_HOST'], 4);
} else {
 $host = $_SERVER['HTTP_HOST'];
}
$prefix2 = "http://$weblog.".$host."/";
$prefix2 = str_replace("$weblog.$weblog.", "$weblog.", $prefix2);
 if($file == "/images/") {
   $url = $prefix."$weblog";
 } elseif($file == "album") {
   $url = $prefix."albums/$username/$extras";
 } elseif($file == "archive") {
   if($year == "" | $month == "") { $url = "$prefix2$file/$extras"; } else { $url = "$prefix2$file/$year/$month/$extras"; }
 } elseif($file == "browse") {
   $extras = str_replace(" ", "+", $extras);
   $url = "$prefix$file.php?$extras";
 } elseif($file == "delete_comment") {
   $url = "$prefix$file.php?w=$weblog&e_id=$e_id$extras";
 } elseif($file == "delete_trackback") {
   $url = "$prefix$file.php?w=$weblog&e_id=$e_id$extras";
 } elseif($file == "edit_comment") {
   $url = "$prefix$file.php?w=$weblog&e_id=$e_id$extras";
 } elseif($file == "entry") {
   $entry_info = mysql_fetch_assoc(mysql_query("SELECT title FROM bhost_entries WHERE e_id='$e_id'"));
   if($entry_info[title] != "") { $stripped_title = urlencode($entry_info[title]).".html"; }
   if($extras != "") { $extras = "?".$extras; }
   $url = "$prefix2$e_id/$stripped_title$extras";
 } elseif($file == "entry_rss") {
   $url = "$prefix2$e_id/$extras";
 } elseif($file == "friends") {
   if($page != "") { $page = "page".$page."/"; }
   $url = $prefix2."friends/$page$extras";
 } elseif($file == "index") {
   if($page != "") { $page = "page".$page."/"; }
   $url = "$prefix2$page$extras";
 } elseif($file == "index_cat") {
   $category = str_replace(" ", "+", $category);
   if($page != "") { $page = "page".$page."/"; }
   $url = "$prefix2$category/$page$extras";
 } elseif($file == "login") {
   $url = "$prefix$file.php?w=$weblog&e_id=$e_id$extras";
 } elseif($file == "podcast") {
   $url = "$prefix$file.php?w=$weblog$extras";
 } elseif($file == "post_comment") {
   $url = "$prefix$file.php?w=$weblog&e_id=$e_id$extras";
 } elseif($file == "profile") {
   $url = $prefix."profiles/$username/$extras";
 } elseif($file == "profile_nouser") {
   $url = $prefix."profile.php";
 } elseif($file == "sendlink") {
   $url = "$prefix$file.php?w=$weblog&e_id=$e_id$extras";
 } elseif($file == "signup") {
   $url = "$prefix$file.php?w=$weblog&e_id=$e_id$extras";
 } elseif($file == "rss") {
   $url = "$prefix$file.php?w=$weblog$extras";
 } elseif($file == "trackback") {
   $url = "$prefix$file.php?e_id=$e_id";
 } else {
   $url = "$prefix$file";
 }


// STANDARD URLS
} else {
 if($file == "/images/") {
   $url = $prefix."$weblog";
 } elseif($file == "album") {
   $url = "$prefix$file.php?u=$username$extras";
 } elseif($file == "archive") {
   $url = "$prefix$file.php?w=$weblog&y=$year&m=$month$extras";
 } elseif($file == "browse") {
   $extras = str_replace(" ", "+", $extras);
   $url = "$prefix$file.php?$extras";
 } elseif($file == "delete_comment") {
   $url = "$prefix$file.php?w=$weblog&e_id=$e_id$extras";
 } elseif($file == "delete_trackback") {
   $url = "$prefix$file.php?w=$weblog&e_id=$e_id$extras";
 } elseif($file == "edit_comment") {
   $url = "$prefix$file.php?w=$weblog&e_id=$e_id$extras";
 } elseif($file == "entry") {
   $url = "$prefix$file.php?w=$weblog&e_id=$e_id$extras";
 } elseif($file == "entry_rss") {
   $url = $prefix."entry.php?w=$weblog&amp;e_id=$e_id$extras";
 } elseif($file == "friends") {
   if($page == "") { $page = ""; } else { $page = "&page=$page"; }
   $url = $prefix."friends.php?w=$weblog$page$extras";
 } elseif($file == "index") {
   if($page == "") { $page = ""; } else { $page = "&page=$page"; }
   $url = "$prefix?w=$weblog$page$extras";
 } elseif($file == "index_cat") {
   $category = str_replace(" ", "+", $category);
   if($page == "") { $page = ""; } else { $page = "&page=$page"; }
   $url = "$prefix?w=$weblog&category=$category$page$extras";
 } elseif($file == "login") {
   $url = "$prefix$file.php?w=$weblog&e_id=$e_id$extras";
 } elseif($file == "podcast") {
   $url = "$prefix$file.php?w=$weblog$extras";
 } elseif($file == "post_comment") {
   $url = "$prefix$file.php?w=$weblog&e_id=$e_id";
 } elseif($file == "profile") {
   $url = "$prefix$file.php?u=$username$extras";
 } elseif($file == "profile_nouser") {
   $url = $prefix."profile.php";
 } elseif($file == "sendlink") {
   $url = "$prefix$file.php?w=$weblog&e_id=$e_id$extras";
 } elseif($file == "signup") {
   $url = "$prefix$file.php?w=$weblog&e_id=$e_id$extras";
 } elseif($file == "rss") {
   $url = "$prefix$file.php?w=$weblog$extras";
 } elseif($file == "trackback") {
   $url = "$prefix$file.php?e_id=$e_id";
 } else {
   $url = "$prefix$file";
 }
}


$n = basename($_SERVER['PHP_SELF']);
if($file != "/images/" & ($n == "preview.php" | $n == "previewcomment.php" | $n == "previewentry.php")) {
$url = "#";
}

return $url;
}


// DATE FUNCTION (FOR TRANSLATIONS AS WELL)
function cdate($format, $time="") {
global $multi_language;

if($time == "" & $time != 0) { $time = time(); }

 if($multi_language != "yes") {
  return date($format, $time);
 } else {
  $date_letters = Array("a", "A", "B", "c", "D", "d", "F", "m", "M", "I", "i", "g", "h", "H", "G", "j", "l", "L", "n", "O", "r", "S", "s", "t", "U", "W", "w", "Y", "y", "z", "Z", "T");
  $strftime_letters = Array("%p", "%p", "", "", "%a", "%d", "%B", "%m", "%b", "", "%M", "%I", "%I", "%H", "%H", "%e", "%A", "", "%m", "", "", "", "%S", "", "", "%V", "%w", "%Y", "%y", "%j", "", "%Z");
  $new_format = str_replace($date_letters, $strftime_letters, $format);
  return strftime($new_format, $time);
 }
}


// ANTISPAM FUNCTION
function antispam($tb_blog_name, $tb_title, $tb_excerpt, $tb_url) {
global $weblog_info;
$is_spam = "no";



//URL BLACKLIST
if($is_spam == "no") {
$blacklist = explode(" ", trim($weblog_info[tb_blacklist]));
for($s=0;$s<count($blacklist);$s++) {
if(strpos($tb_url, $blacklist[$s]) === FALSE) {
  $is_spam = "no";
} else {
  $is_spam = "yes";
}}}



if($is_spam == "yes") {
  //TRACKBACK IS SPAM
  return true;
} else {
  //TRACKBACK IS NOT SPAM
  return false;
}
}



// TEMPLATE VARIABLE REPLACE FUNCTION
function variable_replace($template) {

$template = preg_replace("/(<%windowtitle%>)/i", "<%WindowTitle%>", $template); 
$template = preg_replace("/(<%title%>)/i", "<%Title%>", $template); 
$template = preg_replace("/(<%description%>)/i", "<%Description%>", $template); 
$template = preg_replace("/(<%avatar%>)/i", "<%Avatar%>", $template);
$template = preg_replace("/(<%email%>)/i", "<%Email%>", $template);
$template = preg_replace("/(<%calendar%>)/i", "<%Calendar%>", $template);
$template = preg_replace("/(<%friendslist%>)/i", "<%FriendsList%>", $template);
$template = preg_replace("/(<%profileurl%>)/i", "<%ProfileURL%>", $template); 
$template = preg_replace("/(<%mainpageurl%>)/i", "<%MainPageURL%>", $template); 
$template = preg_replace("/(<%archiveurl%>)/i", "<%ArchiveURL%>", $template); 
$template = preg_replace("/(<%friendspageurl%>)/i", "<%FriendsPageURL%>", $template); 
$template = preg_replace("/(<%sitefeedurl%>)/i", "<%SiteFeedURL%>", $template); 
$template = preg_replace("/(<%albumurl%>)/i", "<%AlbumURL%>", $template);
$template = preg_replace("/(<%podcasturl%>)/i", "<%PodcastURL%>", $template);
$template = preg_replace("/(<link>)/i", "<Link>", $template); 
$template = preg_replace("/(<\/link>)/i", "</Link>", $template); 
$template = preg_replace("/(<%linktitle%>)/i", "<%LinkTitle%>", $template);
$template = preg_replace("/(<%linkurl%>)/i", "<%LinkURL%>", $template);
$template = preg_replace("/(<ifpages>)/i", "<IfPages>", $template); 
$template = preg_replace("/(<\/ifpages>)/i", "</IfPages>", $template); 
$template = preg_replace("/(<earlierlink>)/i", "<EarlierLink>", $template); 
$template = preg_replace("/(<\/earlierlink>)/i", "</EarlierLink>", $template); 
$template = preg_replace("/(<laterlink>)/i", "<LaterLink>", $template); 
$template = preg_replace("/(<\/laterlink>)/i", "</LaterLink>", $template); 
$template = preg_replace("/(<%currentpage%>)/i", "<%CurrentPage%>", $template); 
$template = preg_replace("/(<%totalpages%>)/i", "<%TotalPages%>", $template); 
$template = preg_replace("/(<friends>)/i", "<Friends>", $template); 
$template = preg_replace("/(<\/friends>)/i", "</Friends>", $template); 
$template = preg_replace("/(<%friendusername%>)/i", "<%FriendUsername%>", $template); 
$template = preg_replace("/(<%friendurl%>)/i", "<%FriendURL%>", $template); 
$template = preg_replace("/(<members>)/i", "<Members>", $template); 
$template = preg_replace("/(<\/members>)/i", "</Members>", $template); 
$template = preg_replace("/(<%memberusername%>)/i", "<%MemberUsername%>", $template); 
$template = preg_replace("/(<%memberurl%>)/i", "<%MemberURL%>", $template); 
$template = preg_replace("/(<categories>)/i", "<Categories>", $template); 
$template = preg_replace("/(<\/categories>)/i", "</Categories>", $template); 
$template = preg_replace("/(<%category%>)/i", "<%Category%>", $template); 
$template = preg_replace("/(<%categoryurl%>)/i", "<%CategoryURL%>", $template); 
$template = preg_replace("/(<recententry>)/i", "<RecentEntry>", $template); 
$template = preg_replace("/(<\/recententry>)/i", "</RecentEntry>", $template); 
$template = preg_replace("/(<%recententrytitle%>)/i", "<%RecentEntryTitle%>", $template); 
$template = preg_replace("/(<%recententrydate%>)/i", "<%RecentEntryDate%>", $template); 
$template = preg_replace("/(<%recententrytime%>)/i", "<%RecentEntryTime%>", $template); 
$template = preg_replace("/(<entry>)/i", "<Entry>", $template); 
$template = preg_replace("/(<\/entry>)/i", "</Entry>", $template); 
$template = preg_replace("/(<%entrydate%>)/i", "<%EntryDate%>", $template); 
$template = preg_replace("/(<%entrytitle%>)/i", "<%EntryTitle%>", $template); 
$template = preg_replace("/(<%entryurl%>)/i", "<%EntryURL%>", $template); 
$template = preg_replace("/(<%entrybody%>)/i", "<%EntryBody%>", $template); 
$template = preg_replace("/(<%entryauthor%>)/i", "<%EntryAuthor%>", $template); 
$template = preg_replace("/(<%entryauthoravatar%>)/i", "<%EntryAuthorAvatar%>", $template);
$template = preg_replace("/(<%entryauthorurl%>)/i", "<%EntryAuthorURL%>", $template);
$template = preg_replace("/(<%entrytime%>)/i", "<%EntryTime%>", $template); 
$template = preg_replace("/(<ifcategoriesallowed>)/i", "<IfCategoriesAllowed>", $template); 
$template = preg_replace("/(<\/ifcategoriesallowed>)/i", "</IfCategoriesAllowed>", $template); 
$template = preg_replace("/(<%entrycategory%>)/i", "<%EntryCategory%>", $template);
$template = preg_replace("/(<ifcommentsallowed>)/i", "<IfCommentsAllowed>", $template); 
$template = preg_replace("/(<\/ifcommentsallowed>)/i", "</IfCommentsAllowed>", $template); 
$template = preg_replace("/(<ifcommentpostallowed>)/i", "<IfCommentPostAllowed>", $template); 
$template = preg_replace("/(<\/ifcommentpostallowed>)/i", "</IfCommentPostAllowed>", $template); 
$template = preg_replace("/(<%commentposturl%>)/i", "<%CommentPostURL%>", $template); 
$template = preg_replace("/(<%entrycommentcount%>)/i", "<%EntryCommentCount%>", $template); 
$template = preg_replace("/(<comment>)/i", "<Comment>", $template); 
$template = preg_replace("/(<\/comment>)/i", "</Comment>", $template); 
$template = preg_replace("/(<commentedit>)/i", "<CommentEdit>", $template); 
$template = preg_replace("/(<\/commentedit>)/i", "</CommentEdit>", $template); 
$template = preg_replace("/(<commentdelete>)/i", "<CommentDelete>", $template); 
$template = preg_replace("/(<\/commentdelete>)/i", "</CommentDelete>", $template); 
$template = preg_replace("/(<%commentauthorip%>)/i", "<%CommentAuthorIP%>", $template); 
$template = preg_replace("/(<%commenttitle%>)/i", "<%CommentTitle%>", $template); 
$template = preg_replace("/(<%commentbody%>)/i", "<%CommentBody%>", $template); 
$template = preg_replace("/(<%commentauthor%>)/i", "<%CommentAuthor%>", $template); 
$template = preg_replace("/(<%commentauthoravatar%>)/i", "<%CommentAuthorAvatar%>", $template); 
$template = preg_replace("/(<%commentdate%>)/i", "<%CommentDate%>", $template); 
$template = preg_replace("/(<%commenttime%>)/i", "<%CommentTime%>", $template); 
$template = preg_replace("/(<%commenturl%>)/i", "<%CommentURL%>", $template); 
$template = preg_replace("/(<ifmainpage>)/i", "<IfMainPage>", $template); 
$template = preg_replace("/(<\/ifmainpage>)/i", "</IfMainPage>", $template); 
$template = preg_replace("/(<ifentrypage>)/i", "<IfEntryPage>", $template); 
$template = preg_replace("/(<\/ifentrypage>)/i", "</IfEntryPage>", $template); 
$template = preg_replace("/(<ifarchivepage>)/i", "<IfArchivePage>", $template); 
$template = preg_replace("/(<\/ifarchivepage>)/i", "</IfArchivePage>", $template); 
$template = preg_replace("/(<%archiveinfo%>)/i", "<%ArchiveInfo%>", $template); 
$template = preg_replace("/(<iffriendspage>)/i", "<IfFriendsPage>", $template); 
$template = preg_replace("/(<\/iffriendspage>)/i", "</IfFriendsPage>", $template); 
$template = preg_replace("/(<iftrackbacksallowed>)/i", "<IfTrackbacksAllowed>", $template);
$template = preg_replace("/(<\/iftrackbacksallowed>)/i", "</IfTrackbacksAllowed>", $template);
$template = preg_replace("/(<%entrytrackbackurl%>)/i", "<%EntryTrackbackURL%>", $template);
$template = preg_replace("/(<%trackbackcount%>)/i", "<%TrackbackCount%>", $template);
$template = preg_replace("/(<trackback>)/i", "<Trackback>", $template);
$template = preg_replace("/(<\/trackback>)/i", "</Trackback>", $template);
$template = preg_replace("/(<trackbackdelete>)/i", "<TrackbackDelete>", $template);
$template = preg_replace("/(<\/trackbackdelete>)/i", "</TrackbackDelete>", $template);
$template = preg_replace("/(<%trackbackblogname%>)/i", "<%TrackbackBlogName%>", $template);
$template = preg_replace("/(<%trackbackurl%>)/i", "<%TrackbackURL%>", $template);
$template = preg_replace("/(<%trackbacktitle%>)/i", "<%TrackbackTitle%>", $template);
$template = preg_replace("/(<%trackbackexcerpt%>)/i", "<%TrackbackExcerpt%>", $template);
$template = preg_replace("/(<%trackbackdate%>)/i", "<%TrackbackDate%>", $template);
$template = preg_replace("/(<%trackbacktime%>)/i", "<%TrackbackTime%>", $template);
$template = preg_replace("/(<%trackbackrdf%>)/i", "<%TrackbackRDF%>", $template);



return $template;
}




// REPLACES TEMPLATE VARIABLES IN TEMPLATES
function bh_engine($template) {
global $admin_info, $weblog_info, $owner_info, $owner_group_info, $user_info, $user_status, $group_info, $thism, $thisy, $privacy, $functions1;


// REPLACE RELATIVE PATHS WITH ABSOLUTE PATHS IF SUBDOMAIN URLS ARE ON
if($admin_info[url] == "1") {
$server_array = explode("/", $_SERVER['PHP_SELF']);
$server_array_mod = array_pop($server_array);
$server_info = implode("/", $server_array);
$prefix = "http://".$_SERVER['HTTP_HOST'].$server_info."/images/templates/";
$template = str_replace("./images/templates/", "$prefix", $template);
}

// CHECK FOR MISSING AVATAR FIRST
$avatar = $owner_info[avatar];
$avatar_stripped = str_replace(" ", "", $avatar);
if($avatar_stripped == "" OR $avatar_stripped == "http://") {
$avatar = url("/images/", "images/noavatar2.gif");
}

// CHANGE <, >, ", AND STATIC VARIABLES
$search_array = Array("&lt;", "&gt;", "&quot;", "<%Title%>", "<%Description%>", "<%Avatar%>", "<%Email%>", "<%ProfileURL%>", "<%MainPageURL%>", "<%ArchiveURL%>", "<%SiteFeedURL%>", "<%FriendsPageURL%>", "<%AlbumURL%>", "<%PodcastURL%>");
$replace_array = Array("<", ">", "\"", "$weblog_info[title]", "$weblog_info[description]", "$avatar", "$owner_info[email]", url("profile", "", "$owner_info[username]"), url("index", "$weblog_info[weblog]"), url("archive", "$weblog_info[weblog]"), url("rss", "$weblog_info[weblog]"), url("friends", "$weblog_info[weblog]"), url("album", "", "$owner_info[username]"), url("podcast", "$weblog_info[weblog]"));
$template = str_replace($search_array, $replace_array, $template);



// INPUT MEMBERS
$memberscount = occurrencecount("<Members>", "</Members>", $template, "0");
for($f=0;$f<$memberscount;$f++) {
 $insert = "";
 $members = between("<Members>", "</Members>", $template);
  $where = "u_id='$owner_info[u_id]'";
  $admins = explode(",", trim($weblog_info[level1]));
  for($a=0;$a<count($admins);$a++) {
   if($admins[$a] != "") { $where .= " OR u_id='$admins[$a]'"; }
  }
  $members2 = explode(",", trim($weblog_info[level2]));
  for($a=0;$a<count($members2);$a++) {
   if($members2[$a] != "") { $where .= " OR u_id='$members2[$a]'"; }
  }
 $allmembers = mysql_query("SELECT username FROM bhost_users WHERE ($where)");
 while($member = mysql_fetch_assoc($allmembers)) {
 $insert .= $members;
 $insert = str_replace("<%MemberUsername%>", "$member[username]", $insert);
 $insert = str_replace("<%MemberURL%>", url("profile", "", "$member[username]"), $insert);
 }
 $template = str_replace("<Members>".$members."</Members>", $insert, $template);
}


// INPUT FRIENDS
$friendscount = occurrencecount("<Friends>", "</Friends>", $template, "0");
for($f=0;$f<$friendscount;$f++) {
 $insert = "";
 $friends = between("<Friends>", "</Friends>", $template);
  $where = "u_id='$owner_info[u_id]'";
  $where_not = "friend_u_id <> '$owner_info[u_id]'";
 if($weblog_info[friends] == "1" | $weblog_info[friends] == "2") {
  $admins = explode(",", trim($weblog_info[level1]));
  for($a=0;$a<count($admins);$a++) {
   if($admins[$a] != "") { $where .= " OR u_id='$admins[$a]'"; $where_not .= " AND friend_u_id <> '$admins[$a]'"; }
  }
 }
 if($weblog_info[friends] == "2") {
  $members = explode(",", trim($weblog_info[level2]));
  for($a=0;$a<count($members);$a++) {
   if($members[$a] != "") { $where .= " OR u_id='$members[$a]'"; $where_not .= " AND friend_u_id <> '$members[$a]'"; }
  }
 }
 $allfriends = mysql_query("SELECT DISTINCT friend_u_id AS friend_u_id FROM bhost_friends WHERE ($where) AND ($where_not)");
 while($friend = mysql_fetch_assoc($allfriends)) {
 $friend_info = mysql_fetch_assoc(mysql_query("SELECT u_id, username FROM bhost_users WHERE u_id='$friend[friend_u_id]'"));
 $insert .= $friends;
 $insert = str_replace("<%FriendUsername%>", "$friend_info[username]", $insert);
 $insert = str_replace("<%FriendURL%>", url("profile", "", "$friend_info[username]"), $insert);
 }
 $template = str_replace("<Friends>".$friends."</Friends>", $insert, $template);
}


// INPUT LINKS
$linkscount = occurrencecount("<Link>", "</Link>", $template, "0");
for($f=0;$f<$linkscount;$f++) {
 $insert = "";
 $link = between("<Link>", "</Link>", $template);
 if($weblog_info[links_url] != "") {
 $links_url = explode("<!>", trim($weblog_info[links_url]));
 $links_title = explode("<!>", trim($weblog_info[links_title]));
 for($l=0;$l<count($links_url);$l++) { 
 $insert .= $link;
 if(str_replace(" ", "", $links_title[$l]) == "") { $links_title[$l] = $links_url[$l]; }
 $insert = str_replace("<%LinkTitle%>", "$links_title[$l]", $insert);
 $insert = str_replace("<%LinkURL%>", "$links_url[$l]", $insert);
 }}
 $template = str_replace("<Link>".$link."</Link>", $insert, $template);
}


// INPUT ENTRY CATEGORIES
if($owner_group_info[allow_entry_cat] != "1") {
 $categoriescount = occurrencecount("<Categories>", "</Categories>", $template, "0");
 for($a=0;$a<$categoriescount;$a++) {
 $template = str_replace("<Categories>".between("<Categories>", "</Categories>", $template)."</Categories>", "", $template);
 }
 $template = str_replace("<%Category%>", "", $template);
 $template = str_replace("<%CategoryURL%>", "", $template);
} else {
$categoriescount = occurrencecount("<Categories>", "</Categories>", $template, "0");
for($f=0;$f<$categoriescount;$f++) {
 $insert = "";
 $categories = between("<Categories>", "</Categories>", $template);
 $entrycats = mysql_query("SELECT * FROM bhost_entrycategories WHERE w_id='$weblog_info[w_id]'");
 while($entrycat_info = mysql_fetch_assoc($entrycats)) {
 $insert .= $categories;
 $insert = str_replace("<%Category%>", "$entrycat_info[name]", $insert);
 $insert = str_replace("<%CategoryURL%>", url("index_cat", "$weblog_info[weblog]", "", "0", "", "", "", "", "$entrycat_info[name]"), $insert);
 }
 $template = str_replace("<Categories>".$categories."</Categories>", $insert, $template);
}}


// INPUT RECENT ENTRIES
$recententrycount = occurrencecount("<RecentEntry>", "</RecentEntry>", $template, "0");
for($r=0;$r<$recententrycount;$r++) {
 $insert = "";
 $recententry = between("<RecentEntry>", "</RecentEntry>", $template);
 $recent = mysql_query("SELECT e_id, title, date FROM bhost_entries WHERE w_id='$weblog_info[w_id]' AND draft='0' $privacy ORDER BY date DESC LIMIT $weblog_info[recent_entries]");
 while($recent_info = mysql_fetch_assoc($recent)) {

  if(str_replace(" ", "", $recent_info[title]) == "") { $title = "<i>$functions1</i>"; } else { $title = $recent_info[title]; }
  $title = str_replace("&lt;", "<", $title);
  $title = str_replace("&gt;", ">", $title);
  $insert .= $recententry;
  $insert = str_replace("<%RecentEntryTitle%>", "<a href='".url("entry", "$weblog_info[weblog]", "", "$recent_info[e_id]")."'>$title</a>", $insert);
  $insert = str_replace("<%RecentEntryDate%>", "<a href='".url("entry", "$weblog_info[username]", "", "$recent_info[e_id]")."'>".cdate("$weblog_info[format_date]", timezone($recent_info[date]))."</a>", $insert);
  $insert = str_replace("<%RecentEntryTime%>", "<a href='".url("entry", "$weblog_info[username]", "", "$recent_info[e_id]")."'>".cdate("$weblog_info[format_time]", timezone($recent_info[date]))."</a>", $insert);
 }
 $template = str_replace("<RecentEntry>".$recententry."</RecentEntry>", $insert, $template);
}


// INPUT CALENDAR
include "./include/calendar_mod.php";
if($thisy != "" & $thism != "") { $year = $thisy; $month = $thism; } else { $time = time(); $year = cdate("Y", $time); $month = cdate("n", $time); }
$prev_year = ($month > 1) ? $year : $year - 1;
$next_year = ($month < 12) ? $year : $year + 1;
$prev_month = ($prev_year == $year) ? $month - 1 : 12;
$next_month = ($next_year == $year) ? $month + 1 : 1;
$prev_month_url = url("archive", "$weblog_info[weblog]", "", "", "$prev_year", "$prev_month");
$next_month_url = url("archive", "$weblog_info[weblog]", "", "", "$next_year", "$next_month");
$pn = array('&laquo;'=>"$prev_month_url", '&raquo;'=>"$next_month_url");
$this_month = url("archive", "$weblog_info[weblog]", "", "", "$year", "$month");
$month_date = mktime(0, 0, 0, $month, 1, $year);
$next_month_date = mktime(0, 0, 0, $next_month, 1, $next_year);
$month_entries = mysql_query("SELECT e_id, title, date FROM bhost_entries WHERE w_id='$weblog_info[w_id]' AND date >= '$month_date' AND date < '$next_month_date' AND draft='0' $privacy ORDER BY date DESC");
$prev_d = 0;
while($month_info = mysql_fetch_assoc($month_entries)) {
 $d = cdate("j", $month_info[date]);
 if($d != $prev_d) {
  $days[$d] = array(url("index", "$weblog_info[weblog]", "", "", "", "", "&thisy=$year&thism=$month&thisd=$d", "", ""), 'linked-day');
  $prev_d = $d;
 }
}    
$template = str_replace("<%Calendar%>", generate_calendar($year, $month, $days, 3, $this_month, 1, $pn), $template);


// REPLACE ADS AT TOP
if(($owner_group_info[show_ad] == 1 OR $owner_group_info[show_ad] == 3) AND $owner_group_info[html_ad] != "") {
  // FIRST CHECK FOR BODY TAG
  if(preg_match("/<(body)(.*)>/i", $template, $match1)) {
  $template = str_replace($match1[0], "$match1[0]$owner_group_info[html_ad]", $template); 
  // IF BODY TAG CANNOT BE FOUND, CHECK FOR HEAD TAG
  } elseif(preg_match("/<(head)(.*)>/i", $template, $match2)) {
  $template = str_replace($match2[0], "$owner_group_info[html_ad]$match2[0]", $template); 
  // IF BODY AND HEAD TAGS CANT BE FOUND, STICK AD AT VERY TOP
  } else {
  $template = "$owner_group_info[html_ad]$template"; 
  }
}

// REPLACE ADS AT BOTTOM
if(($owner_group_info[show_ad] == 2 OR $owner_group_info[show_ad] == 3) AND $owner_group_info[html_ad_bottom] != "") {
  // FIRST CHECK FOR ENDING BODY TAG
  if(preg_match("/(<\/body>)/i", $template, $match1)) {
  $template = str_replace($match1[0], "$owner_group_info[html_ad_bottom]$match1[0]", $template); 
  } elseif(preg_match("/<(\/html)(.*)>/i", $template, $match2)) {
  $template = str_replace($match2[0], "$owner_group_info[html_ad_bottom]$match2[0]", $template); 
  } else {
  $template = "$template$owner_group_info[html_ad_bottom]"; 
  }
}

return $template;
}





// IMAGE VERIFICATION
function image_verification($code) {
global $admin_info;

if(!function_exists('gd_info')) { exit(); }

$code = strrev($code);
$code = preg_replace("([a-zA-Z])", "-", $code); 
$number = explode("-", $code);
for($c = 0; $c < 7; $c++) {
$d = $c + 5;
$mul[$c] = $number[$d];
}
for($c = 0; $c < 7; $c++) {
$d = $c - 1;
$num[$c] = $number[$d] / $mul[$c];
}
for($c = 1; $c < 7; $c++) {
if(!is_int($num[$c])) { exit(); }
}

header("Content-type: image/png"); 
$img_handle = @ImageCreate(67, 20); 
$back_color = @ImageColorAllocate($img_handle, 246, 246, 246); 

$count = 0;
while($count < 6) {
$count++;
$x_axis = -5 + ($count * 10);
$color1 = rand(001, 150);
$color2 = rand(001, 150);
$color3 = rand(001, 150);
$txt_color[$count] = @ImageColorAllocate($img_handle, $color1, $color2, $color3); 
$size = 5;
@ImageString($img_handle, $size, $x_axis, 2, "$num[$count]", $txt_color[$count]); 
}

$pixel_color = @ImageColorAllocate($img_handle, 100, 100, 100); 

$count = 0;
while($count < 20) {
$count++;
$randx = rand(1,67);
$randy = rand(1,20);
@ImageSetPixel($img_handle, $randx, $randy, $pixel_color);
}

@ImagePng($img_handle); 

exit();
}








// RANDOM LETTER FUNCTION
function randLetter() {
 $int = rand(0,51);
 $a_z = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
 $rand_letter = $a_z[$int];
 return $rand_letter;
}












// GET FILE HEADERS (MIME TYPE AND SIZE)
function get_file_headers($file) {
 set_time_limit(60); 
 $url = parse_url($file);
 $host = $url[host];
 $path = $url[path];
 if($url[query] != "") { $path .= "?$url[query]"; }
 if($url[port] != "") { $port = $url[port]; } else { $port = 80; }
 $send_head = "HEAD $path HTTP/1.1\r\nHOST: $host\r\n\r\n";
 if($handle = @fsockopen($host, $port, $err_num, $err_msg, 3)) {
  $response = "";
  fputs($handle, $send_head);
  while(!feof($handle) & strpos($response, "\r\n\r\n") === FALSE) {
   $response .= fgets($handle, 4096);
  }
  fclose($handle);
  preg_match_all('/(.*?): (.*)\r/', $response, $matches);
  for($i=0;$i<count($matches[1]);$i++) {
   $key = strtolower($matches[1][$i]);
   $headers[$key] = $matches[2][$i];
  }

  preg_match('/.*([0-9]{3}).*/', $response, $return);
  $headers[response] = $return[1];
  return $headers;
 } else {
  return false;
 }
}






// MOBLOGGING CHECK FUNCTION
function check_moblog($w_id) {
 global $admin_info, $mobile_folder_name, $mobile_folder_description;
 if($w_id == "") { return; }
 if(mysql_num_rows(mysql_query("SELECT * FROM bhost_weblogs WHERE w_id='$w_id'")) != 1) { return; }
 $weblog_info = mysql_fetch_assoc(mysql_query("SELECT * FROM bhost_weblogs WHERE w_id='$w_id'"));
 $owner_info = mysql_fetch_assoc(mysql_query("SELECT * FROM bhost_users WHERE u_id='$weblog_info[u_id]'"));
 $owner_group_info = mysql_fetch_assoc(mysql_query("SELECT * FROM bhost_groups WHERE g_id='$owner_info[g_id]'"));
 $moblog_type = "";
 $secret_email = $weblog_info[moblog_secret].strstr($admin_info[moblog_email], "@");


 // CHECK TIME SINCE LAST CHECK!!!!!!!!!!!
 $now = time();
 if($weblog_info[moblog_last_check]+($admin_info[moblog_frequency]*60) >= $now) { return; }
 mysql_query("UPDATE bhost_weblogs SET moblog_last_check='$now' WHERE w_id='$weblog_info[w_id]'");

if($owner_group_info[allow_moblogging] == "1") {
 if($admin_info[moblog_port] == "110") { $moblog_type = "/pop3/notls"; }

 if($mbox = @imap_open("{".$admin_info[moblog_server].":".$admin_info[moblog_port].$moblog_type."}INBOX", "$admin_info[moblog_email]", "$admin_info[moblog_password]")) {
 
  $emails = explode("<!>", str_replace(" ", "", $weblog_info[moblog_emails]));
  $users = explode("<!>", str_replace(" ", "", $weblog_info[moblog_users]));
  for($e=0;$e<count($emails);$e++) {
   if(str_replace(" ", "", $emails[$e]) != "") {
    $author_info = mysql_fetch_assoc(mysql_query("SELECT * FROM bhost_users WHERE u_id='$users[$e]'"));
    $author_group_info = mysql_fetch_assoc(mysql_query("SELECT * FROM bhost_groups WHERE g_id='$author_info[g_id]'"));
    $criteria = "ALL TO $secret_email FROM $emails[$e]";
    $messages = imap_search($mbox, "$criteria");
    if($messages) {
     for($m=0;$m<count($messages);$m++) {
      $message_id = $messages[$m];
      $message_info = array();
      $headers = imap_headerinfo($mbox, $message_id);
      $structure = imap_fetchstructure($mbox, $message_id);
      $message_info[title] = $headers->subject;
      $message_info[date] = duplicatetime($headers->udate, 0);
       
      $partsarray = array();
      parse_email_parts($mbox, $message_id, $structure, "", $partsarray);
        
      $message_info[body] = "";
      ksort($partsarray);
      foreach($partsarray as $full_part) {
       if($full_part[type] == "HTML") {
        $message_info[body] = $full_part[string];
       } elseif($full_part[type] == "PLAIN" & $message_info[body] == "") {
        $message_info[body] = $full_part[string];
       } elseif($full_part[type] == "ATTACHMENT" & $full_part[binary] != "") {
        if($author_group_info[allow_uploads] == 1) {
         if(mysql_num_rows(mysql_query("SELECT f_id FROM bhost_folders WHERE u_id='$author_info[u_id]' AND folder='$mobile_folder_name'")) != 1) {
          mysql_query("INSERT INTO bhost_folders (u_id, in_album, folder, description) VALUES ('$author_info[u_id]', '0', '$mobile_folder_name', '$mobile_folder_description')");
         }
         $folder_info = mysql_fetch_assoc(mysql_query("SELECT * FROM bhost_folders WHERE u_id='$author_info[u_id]' AND folder='$mobile_folder_name'"));
         $extensions = explode(",", strtolower($author_group_info[uploads_extensions]));
         $ext = str_replace(".", "", strtolower(strrchr($full_part[filename], ".")));
         $type = $full_part[mime];
         if(in_array($ext, $extensions)) {
          $is_error = "";
          if(($ext == "jpg" OR $ext == "jpeg" OR $ext == "jpe") AND ($type != "image/jpeg" AND $type != "image/jpg" AND $type != "image/jpe" AND $type != "image/pjpeg" AND $type != "image/pjpg" AND $type != "image/x-jpeg" AND $type != "image/x-jpg")) { 
           $is_error = "yes"; 
          } elseif($ext == "gif" AND ($type != "image/gif" AND $type != "image/x-gif")) { 
           $is_error = "yes";
          } elseif($ext == "png" AND ($type != "image/png" AND $type != "image/x-png")) { 
           $is_error = "yes";
          } elseif($ext == "tiff" AND ($type != "image/tif" AND $type != "image/tiff")) { 
           $is_error = "yes";
          } elseif($ext == "bmp" AND ($type != "image/bmp" AND $type != "image/x-bmp")) { 
           $is_error = "yes";
          } elseif(($ext == "html" OR $ext == "htm") AND $type != "text/html") { 
           $is_error = "yes";
          } elseif($ext == "css" AND $type != "text/css") { 
           $is_error = "yes";
          } elseif($ext == "txt" AND $type != "text/plain") { 
           $is_error = "yes";
          } elseif($ext == "xml" AND $type != "text/xml") { 
           $is_error = "yes";
          } elseif(($ext == "mpeg" OR $ext == "mpg" OR $ext == "mpe") AND ($type != "video/mpeg" AND $type != "video/x-mpeg")) { 
           $is_error = "yes";
          } elseif(($ext == "mp3" OR $ext == "mp2" OR $ext == "mpga") AND ($type != "audio/mpeg" AND $type != "audio/x-mpeg")) { 
           $is_error = "yes";
          } elseif(($ext == "kar" OR $ext == "mid" OR $ext == "midi") AND ($type != "audio/midi" AND $type != "audio/mid")) { 
           $is_error = "yes";
          } elseif(($ext == "aif" OR $ext == "aifc" OR $ext == "aiff") AND $type != "audio/x-aiff") { 
           $is_error = "yes";
          } elseif($ext == "wav" AND ($type != "audio/x-wav" AND $type != "audio/wav")) { 
           $is_error = "yes";
          } elseif(($ext == "ram" OR $ext == "ra") AND $type != "audio/x-pn-realaudio") { 
           $is_error = "yes";
          } elseif($ext == "zip" AND ($type != "application/zip" AND $type != "application/x-zip" AND $type != "application/x-zip-compressed")) { 
           $is_error = "yes";
          } elseif($ext == "pdf" AND $type != "application/pdf") { 
           $is_error = "yes";
          } elseif($ext == "doc" AND $type != "application/msword") { 
           $is_error = "yes";
          } elseif($ext == "rtf" AND $type != "application/rtf") { 
           $is_error = "yes";
          } elseif($ext == "rtx" AND $type != "application/richtext") { 
           $is_error = "yes";
          } elseif($ext == "xls" AND $type != "application/x-excel") { 
           $is_error = "yes";
          } elseif($ext == "gz" AND $type != "application/x-gzip") { 
           $is_error = "yes";
          } elseif($ext == "js" AND $type != "application/x-javascript") { 
           $is_error = "yes";
          } elseif(($ext == "pps" OR $ext == "ppt" OR $ext == "ppz") AND $type != "application/x-javascript") { 
           $is_error = "yes";
          } elseif($ext == "sit" AND $type != "application/x-stuffit") { 
           $is_error = "yes";
          } elseif($ext == "tar" AND $type != "application/x-tar") { 
           $is_error = "yes";
          }
     
          $space_allowed = $author_group_info[uploads_space] * 1024;
          $filesize = strlen($full_part[binary]);
          $files = mysql_fetch_assoc(mysql_query("SELECT sum(filesize) AS size FROM bhost_uploads WHERE u_id='$author_info[u_id]'"));
          $space_used = $files[size]+$filesize;
          if($space_used > $space_allowed) { $is_error = "yes"; }
          
          if($is_error != "yes") {
           $filename = $full_part[filename];
           mysql_query("INSERT INTO bhost_uploads (u_id, f_id, location, ext, filesize, name, description) VALUES ('$author_info[u_id]', '$folder_info[f_id]', 'folder', '$ext', '$filesize', '$filename', '')");
           $image_info = mysql_fetch_assoc(mysql_query("SELECT * FROM bhost_uploads WHERE u_id='$author_info[u_id]' AND f_id='$folder_info[f_id]' AND location='folder' AND filesize='$filesize' AND name='$filename' AND description='' ORDER BY up_id DESC LIMIT 1"));
              
           $server_array = explode("/", $_SERVER['PHP_SELF']);
           $server_array_mod = array_pop($server_array);
           $array_count = count($server_array)-1;
           if($server_array[$array_count] == "admin" | $server_array[$array_count] == "manager") {
            $server_array_mod = array_pop($server_array);
            $new_path = "../";
           } else {
            $new_path = "./";
           }
           
           $server_info = implode("/", $server_array)."/";
           $newfilename = "$image_info[up_id].$ext";
           $letter = strtolower(substr($author_info[username], 0, 1));
           $path = "uploads/$letter/$author_info[username]/$newfilename";
           
           $fp = fopen($new_path.$path,"w+");
           if(!fwrite($fp, $full_part[binary])) {
            mysql_query("DELETE FROM bhost_uploads WHERE up_id='$image_info[up_id]' AND u_id='$author_info[u_id]'");
           } else {
            @chmod($path, 0777);
            $dimension = @getimagesize($new_path.$path);
            if($dimension[0] != "" AND $dimension[1] != "") { $dimensions = "$dimension[0]x$dimension[1]"; }
            mysql_query("UPDATE bhost_uploads SET dimensions='$dimensions' WHERE up_id='$image_info[up_id]' AND u_id='$author_info[u_id]'");
            $attach_id = between("<", ">", $full_part[id]);
            if(strstr($attach_id, $message_info[body]) === false) {
             if($dimension) {
              $message_info[body] .= "<br><br><img src='http://".$_SERVER['HTTP_HOST'].$server_info.$path."' border='0'>";
             } else {
              $message_info[body] .= "<br><br>Attached file: <a href='http://".$_SERVER['HTTP_HOST'].$server_info.$path."'>$filename</a>";
             }
            } else {
             $message_info[body] = str_replace("cid:$attach_id", "http://".$_SERVER['HTTP_HOST'].$server_info.$path, $message_info[body]);
            }
           }
           fclose($fp);
          }
         }
        }
       }
      }
      
      // INSERT ENTRY
      $bad_words = explode(",", trim($admin_info[banned_badwords]));
      $bad_words_replace = explode(",", trim($admin_info[banned_badwords_replace]));
      $message_info[body] = str_replace("'", "&#39;", str_replace($bad_words, $bad_words_replace, $message_info[body]));
      $message_info[title] = str_replace("<", "&lt;", str_replace(">", "&gt;", str_replace("'", "&#39;", str_replace($bad_words, $bad_words_replace, $message_info[title]))));
      if($weblog_info[moblog_publish] == "1") { $draft = "0"; } else { $draft = "1"; }
      mysql_query("INSERT INTO bhost_entries (w_id, author_u_id, ec_id, title, contents, draft, privacy, date, comments, trackbacks) VALUES ('$weblog_info[w_id]', '$author_info[u_id]', '0', '$message_info[title]', '$message_info[body]', '$draft', '3', '$message_info[date]', '$weblog_info[default_comments]', '$weblog_info[default_trackbacks]')");
      mysql_query("UPDATE bhost_users SET num_entries=num_entries+1 WHERE u_id='$author_info[u_id]'");
      mysql_query("UPDATE bhost_weblogs SET num_entries=num_entries+1 WHERE w_id='$weblog_info[w_id]'");      

      // DELETE EMAIL
      imap_delete($mbox, $message_id);
     }
    }
   }
  }
   
  imap_close($mbox, CL_EXPUNGE);
//  return;
 } else {
//  return false;
 }
} else {
// return false;
}

return;
}






function parse_email_parts($mbox, $message_id, $structure, $num, &$partsarray) {
 $numparts = count($structure->parts);
 if($numparts > 1) {
  if($num != "") { $num .= "."; }
  foreach($structure->parts as $part_num=>$part) {
   parse_email_parts($mbox, $message_id, $part, $num.($part_num+1), $partsarray);
  }
 } else {
  if($num == "") { $part = imap_body($mbox, $message_id); } else { $part = imap_fetchbody($mbox, $message_id, $num); }
   if($structure->type != 0) {
    if($structure->encoding == 4) { 
     $part = quoted_printable_decode($part); 
    } elseif($structure->encoding == 3) { 
     $part = base64_decode($part); 
    }
    $filename="";
    if(count($structure->dparameters) > 0) {
     foreach($structure->dparameters as $dparam){
      if ((strtoupper($dparam->attribute) == "NAME") | (strtoupper($dparam->attribute) == "FILENAME")) {
       $filename = $dparam->value;
      }
     }
    }
    if($filename == ""){
     if(count($structure->parameters) > 0) {
      foreach($structure->parameters as $param) {
       if((strtoupper($param->attribute)=='NAME') | (strtoupper($param->attribute)=='FILENAME')) {
        $filename=$param->value;
       }
      }
     }
    }
    if($filename != "") {
     if($structure->type == "0") {
      $type = "text";
     } elseif($structure->type == "1") {
      $type = "multipart";
     } elseif($structure->type == "2") {
      $type = "message";
     } elseif($structure->type == "3") {
      $type = "application";
     } elseif($structure->type == "4") {
      $type = "audio";
     } elseif($structure->type == "5") {
      $type = "image";
     } elseif($structure->type == "6") {
      $type = "video";
     } else {
      $type = "other";
     }
     $mime = $type."/".strtolower($structure->subtype);
     $partsarray[$num] = array('type'=>'ATTACHMENT', 'mime'=>$mime, 'filename'=>$filename, 'binary'=>$part, 'id'=>$structure->id);
    }
   } else {
    if($structure->encoding == 4) { 
     $part = quoted_printable_decode($part); 
    } elseif($structure->encoding == 3) { 
     $part = base64_decode($part); 
    }
    if(strtoupper($structure->subtype) == "PLAIN") { $part = str_replace("\n", "<br>", $part); }
    if(strtoupper($structure->subtype) == "HTML") { 
     $part = preg_replace("/(<body([^>]*)>)/i", "<body>", $part); 
     $part = preg_replace("/(<\/body>)/i", "</body>", $part); 
     if(strstr($part, "<body>") === false) { $part = "<body>".$part; }
     if(strstr($part, "</body>") === false) { $part = $part."</body>"; }
     $part = between("<body>", "</body>", $part);
    }
    $partsarray[$num] = array('type'=>$structure->subtype, 'string'=>$part);
   }
 }
 return;
}


// CHEADER FUNCTION CHANGES LOCATION HEADER TO REDIRECT FOR IIS PRIOR TO SETTING COOKIES
// USED ONLY IN login.php, manager/weblog_cookies.php, admin/admin_login.php, admin/user_cookies.php
function cheader($url) {

 if(ereg("Microsoft", $_SERVER['SERVER_SOFTWARE'])) {
  header("Refresh: 0; URL=$url");
 } else {
  header("Location: $url");
 }

 exit();
}




// CHECK EMAIL DNS RECORD
function checkdns_record($email) {

$elabel=explode("@",$email);
if(checkdnsrr($elabel[1], A)) {
 return true;
}

if(checkdnsrr($elabel[1], MX)) {
 return true;
}

return false;
}




// LOG TIME OF LAST USER ACTIVITY
function update_last_activity() {
global $user_info;

$time = time();
mysql_query("UPDATE bhost_users SET last_activity='$time' WHERE u_id='$user_info[u_id]'");
}






//BMP TO GD CONVERTER FUNCTION
function ConvertBMP2GD($src, $dest = false) {
 if(!($src_f = fopen($src, "rb"))) {
  return false;
 }
 if(!($dest_f = fopen($dest, "wb"))) {
  return false;
 }
 $header = unpack("vtype/Vsize/v2reserved/Voffset", fread($src_f,
14));
 $info = unpack("Vsize/Vwidth/Vheight/vplanes/vbits/Vcompression/Vimagesize/Vxres/Vyres/Vncolor/Vimportant",
fread($src_f, 40));
 
 extract($info);
 extract($header);

 if($type != 0x4D42) {  // signature "BM"
  return false;
 }

 $palette_size = $offset - 54;
 $ncolor = $palette_size / 4;
 $gd_header = "";
 // true-color vs. palette
 $gd_header .= ($palette_size == 0) ? "\xFF\xFE" : "\xFF\xFF"; 
 $gd_header .= pack("n2", $width, $height);
 $gd_header .= ($palette_size == 0) ? "\x01" : "\x00";
 if($palette_size) {
  $gd_header .= pack("n", $ncolor);
 }
 // no transparency
 $gd_header .= "\xFF\xFF\xFF\xFF";     

 fwrite($dest_f, $gd_header);

 if($palette_size) {
  $palette = fread($src_f, $palette_size);
  $gd_palette = "";
  $j = 0;
  while($j < $palette_size) {
   $b = $palette{$j++};
   $g = $palette{$j++};
   $r = $palette{$j++};
   $a = $palette{$j++};
   $gd_palette .= "$r$g$b$a";
  }
  $gd_palette .= str_repeat("\x00\x00\x00\x00", 256 - $ncolor);
  fwrite($dest_f, $gd_palette);
 }

 $scan_line_size = (($bits * $width) + 7) >> 3;
 $scan_line_align = ($scan_line_size & 0x03) ? 4 - ($scan_line_size &
0x03) : 0;

 for($i = 0, $l = $height - 1; $i < $height; $i++, $l--) {
  // BMP stores scan lines starting from bottom
  fseek($src_f, $offset + (($scan_line_size + $scan_line_align) *
$l));
  $scan_line = fread($src_f, $scan_line_size);
  if($bits == 24) {
   $gd_scan_line = "";
   $j = 0;
   while($j < $scan_line_size) {
    $b = $scan_line{$j++};
    $g = $scan_line{$j++};
    $r = $scan_line{$j++};
    $gd_scan_line .= "\x00$r$g$b";
   }
  }
  else if($bits == 8) {
   $gd_scan_line = $scan_line;
  }
  else if($bits == 4) {
   $gd_scan_line = "";
   $j = 0;
   while($j < $scan_line_size) {
    $byte = ord($scan_line{$j++});
    $p1 = chr($byte >> 4);
    $p2 = chr($byte & 0x0F);
    $gd_scan_line .= "$p1$p2";
   } $gd_scan_line = substr($gd_scan_line, 0, $width);
  }
  else if($bits == 1) {
   $gd_scan_line = "";
   $j = 0;
   while($j < $scan_line_size) {
    $byte = ord($scan_line{$j++});
    $p1 = chr((int) (($byte & 0x80) != 0));
    $p2 = chr((int) (($byte & 0x40) != 0));
    $p3 = chr((int) (($byte & 0x20) != 0));
    $p4 = chr((int) (($byte & 0x10) != 0));
    $p5 = chr((int) (($byte & 0x08) != 0));
    $p6 = chr((int) (($byte & 0x04) != 0));
    $p7 = chr((int) (($byte & 0x02) != 0));
    $p8 = chr((int) (($byte & 0x01) != 0));
    $gd_scan_line .= "$p1$p2$p3$p4$p5$p6$p7$p8";
   } $gd_scan_line = substr($gd_scan_line, 0, $width);
  }
    
  fwrite($dest_f, $gd_scan_line);
 }
 fclose($src_f);
 fclose($dest_f);
 return true;
} //END ConvertBMP2GD()



// CREATES IMAGE FROM BMP FUNCTION
function imagecreatefrombmp($filename) {
 $tmp_name = tempnam("/tmp", "GD");
 if(ConvertBMP2GD($filename, $tmp_name)) {
  $img = imagecreatefromgd($tmp_name);
  unlink($tmp_name);
  return $img;
 } return false;
} //END imagecreatefrombmp()

?>