###############################################################################
# Load.pl                                                                     #
###############################################################################
# YaBB: Yet another Bulletin Board                                            #
# Open-Source Community Software for Webmasters                               #
# Version:        YaBB 2.2.1                                                  #
# Packaged:       March 5, 2008                                               #
# Distributed by: http://www.yabbforum.com                                    #
# =========================================================================== #
# Copyright (c) 2000-2008 YaBB (www.yabbforum.com) - All Rights Reserved.     #
# Software by:  The YaBB Development Team                                     #
#               with assistance from the YaBB community.                      #
# Sponsored by: Xnull Internet Media, Inc. - http://www.ximinc.com            #
#               Your source for web hosting, web design, and domains.         #
###############################################################################

$loadplver = 'YaBB 2.2.1 $Revision: 1.41.2.4 $';

require "$sourcedir/System.pl";

$lLoaded = "1";

sub LoadBoardControl {
	my ($cntcat, $cntboard, $cntpic, $cntdescription, $cntmods, $cntmodgroups, $cnttopicperms, $cntreplyperms, $cntpollperms, $cntzero, $dummy, $dummy, $dummy, $cnttotals);
	$binboard = "";
	$annboard = "";

	### AK108: This is dangerous and seemingly unneeded.
#	fopen(FORUMCONTROL, "+<$boardsdir/forum.control");
#	seek FORUMCONTROL, 0, 0;

	fopen(FORUMCONTROL, "$boardsdir/forum.control") || &fatal_error('cannot_open', "$boardsdir/forum.control", 1);
	my @boardcontrols = <FORUMCONTROL>;
	fclose(FORUMCONTROL);
	$maxboards = $#boardcontrols;

	foreach my $boardline (@boardcontrols) {
		$boardline =~ s/[\r\n]//g; # Built in chomp

		($cntcat, $cntboard, $cntpic, $cntdescription, $cntmods, $cntmodgroups, $cnttopicperms, $cntreplyperms, $cntpollperms, $cntzero, $cntmembergroups, $cntann, $cntrbin, $cntattperms, $cntminageperms, $cntmaxageperms, $cntgenderperms,) = split(/\|/, $boardline);
		## create a global boards array
		push(@allboards, $cntboard);

		$cntdescription =~ s/\&/\&amp;/g;

		%{ $uid . $cntboard } = (
			'cat'          => $cntcat,
			'description'  => $cntdescription,
			'pic'          => $cntpic,
			'mods'         => $cntmods,
			'modgroups'    => $cntmodgroups,
			'topicperms'   => $cnttopicperms,
			'replyperms'   => $cntreplyperms,
			'pollperms'    => $cntpollperms,
			'zero'         => $cntzero,
			'membergroups' => $cntmembergroups,
			'ann'          => $cntann,
			'rbin'         => $cntrbin,
			'attperms'     => $cntattperms,
			'minageperms'  => $cntminageperms,
			'maxageperms'  => $cntmaxageperms,
			'genderperms'  => $cntgenderperms,);
		if ($cntann == 1)  { $annboard = $cntboard; }
		if ($cntrbin == 1) { $binboard = $cntboard; }
	}
}

sub LoadIMs {
	if ($PM_level == 0 ) { return; }
	if ($PM_level == 2 && (!$iamadmin && !$iamgmod && !$iammod)) { return; }
	if ($PM_level == 3 && (!$iamadmin && !$iamgmod)) { return; }
	if ($maintenance && !$iamadmin) { $username = 'Guest'; $iamguest = 1; }
	if (!$iamguest && $username ne '' && $action ne 'logout') {
		# Require it. If successful, copy mnum to minnum, as it's that way in the original code below
		&buildIMS($username, 'load');
		@folderCount = split(/\|/, ${$username}{'PMfoldersCount'});
	}
	if (!$iamguest) {
		$newcount = ${$username}{'PMimnewcount'} || 0;
		if ($newcount == 1) { $imnewtext = qq~1 $load_txt{'155'}~; }
		elsif ($newcount == 0) { $imnewtext = $load_txt{'nonew'}; }
		else { $imnewtext = qq~${$username}{'PMimnewcount'} $load_txt{'154'}~; }
		if (${$username}{'PMmnum'} == 1) { $yyim = qq~$load_txt{'152'} <a href="$scripturl?action=im">${$username}{'PMmnum'} $load_txt{'471'}</a>, $imnewtext~; }
		elsif (${$username}{'PMmnum'} == 0 && $newcount == 0) { $yyim = qq~$load_txt{'152'} <a href="$scripturl?action=im">${$username}{'PMmnum'} $load_txt{'153'}</a>~; }
		else { $yyim = qq~$load_txt{'152'} <a href="$scripturl?action=im">${$username}{'PMmnum'} $load_txt{'153'}</a>, $imnewtext~; }
		if (!$user_ip && $iamadmin) { $yyim .= qq~<br /><b>$load_txt{'773'}</b>~; }
	}
}

sub LoadCensorList {
	if ($#censored > 0 || -s "$langdir/$language/censor.txt" < 3 || !-e "$langdir/$language/censor.txt") { return; }
	fopen(CENSOR, "$langdir/$language/censor.txt") || &fatal_error("cannot_open","$langdir/$language/censor.txt", 1);
	while (chomp($buffer = <CENSOR>)) {
		$buffer =~ s/\r(?=\n*)//g;
		if ($buffer =~ m/\~/) {
			($tmpa, $tmpb) = split(/\~/, $buffer);
			$tmpc = 0;
		} else {
			($tmpa, $tmpb) = split(/=/, $buffer);
			$tmpc = 1;
		}
		push(@censored, [$tmpa, $tmpb, $tmpc]);
	}
	fclose(CENSOR);
}

sub LoadBots {
	if(-e "$vardir/bots.hosts") {
		fopen(BOTS, "$vardir/bots.hosts") || &fatal_error("cannot_open","$vardir/bots.hosts", 1);
		@botlist = <BOTS>;
		fclose (BOTS);
		foreach (@botlist) {
			chomp $_;
			# Allow the use of regexes with pipe characters in botflags
			$_ =~ /^(.*)\|(.*?)$/;
			$botflag = $1;
			$botname = $2;
			push(@all_bots, $botflag);
			$bot_id{$botflag} = $botflag;
			$bot_name{$botflag} = $botname;
		}
	}
}

sub Is_Bot {
	my $bothost = $_[0];
	foreach (@all_bots){
		chomp $_;
		if ($bothost =~ m/$_/) {return $_; }
	}
}

sub LoadUserSettings {
	&LoadBoardControl;
	$iamguest = $username eq 'Guest' ? 1 : 0;
	if ($username ne 'Guest') {
		&LoadUser($username);
		$iammod = &is_moderator($username);
		if (${$uid.$username}{'position'} eq 'Administrator' || ${$uid.$username}{'position'} eq 'Global Moderator' || $iammod) { $staff = 1; }
		else { $staff = 0; }
		$sessionvalid = 1;
		if ($sessions == 1 && $staff == 1) {
			$cursession = &encode_password($user_ip);
			chomp $cursession;
			if (${$uid.$username}{'session'} ne $cursession || ${$uid.$username}{'session'} ne $cookiesession) { $sessionvalid = 0; }
		}
		$spass = ${$uid.$username}{'password'};

		# Make sure that if the password doesn't match
		# That you get FULLY Logged out
		if ($spass ne $password && $action ne 'logout') {
			&UpdateCookie("delete");
			$username           = 'Guest';
			$iamguest           = '1';
			$iamadmin           = '';
			$iamgmod            = '';
			$password           = '';
			@settings           = ();
			@immessages         = ();
			$yyim               = "";
			$realname           = '';
			$realemail          = '';
			$ENV{'HTTP_COOKIE'} = '';
			$yyuname            = "";
			if (!$guestaccess) {
				$yySetLocation = qq~$scripturl?action=login~;
			} else {
				$yySetLocation = qq~$scripturl~;
			}
			&redirectexit;
		} else {
			$realname  = ${$uid.$username}{'realname'};
			$realemail = ${$uid.$username}{'email'};
			$iamadmin  = (${$uid.$username}{'position'} eq 'Administrator' && $sessionvalid == 1) ? 1 : 0;
			$iamgmod   = (${$uid.$username}{'position'} eq 'Global Moderator' && $sessionvalid == 1) ? 1 : 0;
			if ($sessionvalid == 1) { ${$uid.$username}{'session'} = $cursession; }
			&CalcAge($username, "calc");
		}
	} else {
		$username = '';
		&FormatUserName($username);
		if ($ENV{REQUEST_METHOD} eq 'POST') {
		}
	}
	unless ($username) {
		&UpdateCookie("delete");
		$username           = 'Guest';
		$password           = '';
		@settings           = ();
		$realname           = '';
		$realemail          = '';
		$ENV{'HTTP_COOKIE'} = '';
	}
}

sub FormatUserName {
	my $user = $_[0];
	if ($useraccount{$user}) { return; }
	$useraccount{$user} = $user;
	if($do_scramble_id){$useraccount{$user} = &cloak($useraccount{$user});}
}

sub LoadUser {
	my ($user,$userextension) = @_;
	my $setting;
	if (!$userextension || $userextension eq ''){ $userextension = 'vars'; }
	if (($regtype == 1 || $regtype == 2) && -e "$memberdir/$user.pre") { $userextension = 'pre'; }
	elsif ($regtype == 1 && -e "$memberdir/$user.wait") { $userextension = 'wait'; }

	if (${$uid.$user}{'realname'} ne '') { return 1; }
	if ($user eq '') { return 1; }
	if ($diskalert == 1){ return 1; }		## prevents all profiles to be updated if the server is truly depleted
	$yyload .= qq~Loaded $user <br />~;
	if (-e "$memberdir/$user.$userextension") {
		fopen(LOADUSER, "$memberdir/$user.$userextension") || &fatal_error('cannot_open', "$memberdir/$user.$userextension", 1);
		my @settings = <LOADUSER>;
		fclose(LOADUSER);
		foreach $setting (@settings) {
			chomp $setting;
			unless (length($setting) == 0) {
				$setting =~ s/\'(.*?)\'\,\"(.*?)\"//ig;
				my $tag   = $1;
				my $value = $2;
				${$uid.$user}{$tag} = $value;
			}
		}
	} elsif (-e "$memberdir/$user.dat") {
		fopen(LOADOLDUSER, "$memberdir/$user.dat") || &fatal_error('cannot_open', "$memberdir/$user.dat", 1);
		my @settings = <LOADOLDUSER>;
		fclose(LOADOLDUSER);
		for (my $cnt = 0; $cnt < @settings; $cnt++) {
			$settings[$cnt] =~ s/[\r\n]//g;
			chomp $settings[$cnt];
		}
		$regtime = "$settings[14]";
		$regtime =~ s~(\d{2}\/\d{2}\/\d{2}).*?(\d{2}\:\d{2}\:\d{2})~&stringtotime("$1 at $2")~eis;
		%{ $uid . $user } = (
			'password'      => "$settings[0]",
			'realname'      => "$settings[1]",
			'email'         => "$settings[2]",
			'webtitle'      => "$settings[3]",
			'weburl'        => "$settings[4]",
			'signature'     => "$settings[5]",
			'postcount'     => "$settings[6]",
			'position'      => "$settings[7]",
			'icq'           => "$settings[8]",
			'aim'           => "$settings[9]",
			'yim'           => "$settings[10]",
			'gender'        => "$settings[11]",
			'usertext'      => "$settings[12]",
			'userpic'       => "$settings[13]",
			'regdate'       => "$settings[14]",
			'regtime'       => "$regtime",
			'location'      => "$settings[15]",
			'bday'          => "$settings[16]",
			'timeselect'    => "$settings[17]",
			'timeoffset'    => "$settings[18]",
			'hidemail'      => "$settings[19]",
			'msn'           => "$settings[20]",
			'template'      => "$settings[21]",
			'language'      => "$settings[22]",
			'lastonline'    => "$settings[23]",
			'lastpost'      => "$settings[24]",
			'lastim'        => "$settings[25]",
			'im_ignorelist' => "$settings[26]",
			'im_notify'     => "$settings[27]",
			'im_popup'      => "$settings[28]",
			'im_imspop'     => "$settings[29]",
			'cathide'       => "$settings[30]",
			'postlayout'    => "$settings[31]",);
	} else {
		return 1; # not found userfile
	}
	if (${$uid.$user}{'weburl'} && ${$uid.$user}{'weburl'} !~ m~\Ahttp://~ && ${$uid.$user}{'weburl'} !~ m~\Ahttps://~) { ${$uid.$user}{'weburl'} = "http://${$uid.$user}{'weburl'}"; }
	&ToChars(${$uid.$user}{'realname'});
	&LoadMiniUser($user);
	&FormatUserName($user);
	if ($stealthurl) {
		&MakeStealthURL(${$uid.$user}{'weburl'});
	}
	return 1;
}

sub is_moderator {
	my $user = $_[0];
	my ($testline, $nospace_position, $nospace_group);
	my $is_mod = 0;
	$bd_mod = 0;

	# load all board id's into a hash
	foreach $checkboard (@allboards) {
		$bd_mod++;

		# load moderator user id's into array
		$testline = ${$uid.$checkboard}{'mods'};
		$testline =~ s/ //g;
		@bdmods = split(/\,/, $testline);

		# load moderator groups into array
		$testline = ${$uid.$checkboard}{'modgroups'};
		$testline =~ s/ //g;
		@bdmodgroups = split(/\,/, $testline);

		# check if user is in the moderator list
		foreach $testline (@bdmods) {
			chomp $testline;
			if ($testline eq $user) { $is_mod = 1; }
		}

		# check if user is member of a moderatorgroup
		foreach $testline (@bdmodgroups) {
			chomp $testline;

			# Having a mod group with spaces causes this check to fail
			# So remove spaces in the group in the file
			$nospace_position = ${$uid.$user}{'position'};
			$nospace_position =~ s/ //g;

			if ($testline eq $nospace_position) { $is_mod = 1; }

			foreach $memberaddgroups (split(/\s*\,\s*/, ${$uid.$user}{'addgroups'})) {
				chomp $memberaddgroups;
				if ($testline eq $memberaddgroups) { $is_mod = 1; }
			}
		}
	}
	return $is_mod;
}

sub KillModerator {
	my $killmod = $_[0];
	my ($cntcat, $cntboard, $cntpic, $cntdescription, $cntmods, $cntmodgroups, $cnttopicperms, $cntreplyperms, $cntpollperms, $cntzero, $dummy, $dummy, $dummy, $cnttotals, @boardcontrol);
	fopen(FORUMCONTROL, "+<$boardsdir/forum.control") || &fatal_error('cannot_open', "$boardsdir/forum.control", 1);
	seek FORUMCONTROL, 0, 0;
	@oldcontrols = <FORUMCONTROL>;

	foreach $boardline (@oldcontrols) {
		chomp $boardline;
		if ($boardline ne "") {
			my (@oldmods, @newmods, $testmod);
			($cntcat, $cntboard, $cntpic, $cntdescription, $cntmods, $cntmodgroups, $cnttopicperms, $cntreplyperms, $cntpollperms, $cntzero, $cntpassword, $cnttotals, $cntattperms, $spare, $cntminageperms, $cntmaxageperms, $cntgenderperms) = split(/\|/, $boardline);
			chomp $spare;
			$cntmods =~ s/\, /\,/g;
			(@oldmods) = split(/\,/, $cntmods);
			foreach $testmod (@oldmods) {
				chomp $testmod;

				if ($killmod ne $testmod) {
					push(@newmods, $testmod);
				}
				$cntmods = join(",", @newmods);
			}
			push(@boardcontrol, "$cntcat|$cntboard|$cntpic|$cntdescription|$cntmods|$cntmodgroups|$cnttopicperms|$cntreplyperms|$cntpollperms|$cntzero|$cntpassword|$cnttotals|$cntattperms|$spare|$cntminageperms|$cntmaxageperms|$cntgenderperms\n");
		}
	}
	seek FORUMCONTROL, 0, 0;
	truncate FORUMCONTROL, 0;
	@boardcontrol = &undupe(@boardcontrol);
	print FORUMCONTROL @boardcontrol;
	fclose(FORUMCONTROL);
}

sub KillModeratorGroup {
	my $killmod = $_[0];
	my ($cntcat, $cntboard, $cntpic, $cntdescription, $cntmods, $cntmodgroups, $cnttopicperms, $cntreplyperms, $cntpollperms, $cntzero, $dummy, $dummy, $dummy, $cnttotals, @boardcontrol);
	fopen(FORUMCONTROL, "+<$boardsdir/forum.control") || &fatal_error('cannot_open', "$boardsdir/forum.control", 1);
	seek FORUMCONTROL, 0, 0;
	@oldcontrols = <FORUMCONTROL>;

	foreach $boardline (@oldcontrols) {
		chomp $boardline;
		if ($boardline ne "") {
			my (@oldmods, @newmods, $testmod);
			($cntcat, $cntboard, $cntpic, $cntdescription, $cntmods, $cntmodgroups, $cnttopicperms, $cntreplyperms, $cntpollperms, $cntzero, $cntpassword, $cnttotals, $cntattperms, $spare, $cntminageperms, $cntmaxageperms, $cntgenderperms) = split(/\|/, $boardline);
			chomp $cntgenderperms;
			$cntmodgroups =~ s/\, /\,/g;
			(@oldmods) = split(/\,/, $cntmodgroups);
			foreach $testmod (@oldmods) {
				chomp $testmod;

				if ($killmod ne $testmod) {
					push(@newmods, $testmod);
				}
				$cntmodgroups = join(",", @newmods);
			}
			push(@boardcontrol, "$cntcat|$cntboard|$cntpic|$cntdescription|$cntmods|$cntmodgroups|$cnttopicperms|$cntreplyperms|$cntpollperms|$cntzero|$cntpassword|$cnttotals|$cntattperms|$spare|$cntminageperms|$cntmaxageperms|$cntgenderperms\n");
		}
	}
	seek FORUMCONTROL, 0, 0;
	truncate FORUMCONTROL, 0;
	@boardcontrol = &undupe(@boardcontrol);
	print FORUMCONTROL @boardcontrol;
	fclose(FORUMCONTROL);
}

sub LoadUserDisplay {
	my $user = $_[0];
	if (exists ${$uid.$user}{'password'}) {
		if ($yyUDLoaded{$user}) { return 1; }
	} else {
		&LoadUser($user);
	}
	&LoadCensorList;

	if (${$uid.$user}{'weburl'} !~ m~\Ahttp://~ && ${$uid.$user}{'weburl'} !~ m~\Ahttps://~) { ${$uid.$user}{'weburl'} = "http://${$uid.$user}{'weburl'}"; }
	if ($sm) { ${$uid.$user}{'weburl'} = ${$uid.$user}{'weburl'} && ${$uid.$user}{'weburl'} ne q~http://~ ? qq~<a href="${$uid.$user}{'weburl'}" target="_blank">$img{'website_sm'}</a>~ : ''; }
	else { ${$uid.$user}{'weburl'} = ${$uid.$user}{'weburl'} && ${$uid.$user}{'weburl'} ne q~http://~ ? qq~<a href="${$uid.$user}{'weburl'}" target="_blank">$img{'website'}</a>~ : ''; }

	${$uid.$user}{'weburl'} = ${$uid.$user}{'weburl'} ? qq~${$uid.$user}{'weburl'}~ : '';
	&FromHTML(${$uid.$user}{'signature'});
	${$uid.$user}{'signature'} =~ s~\&\&~<br />~g;

	# do some ubbc on the signature
	$message     = ${$uid.$user}{'signature'};
	$displayname = ${$uid.$user}{'realname'};
	if ($enable_ubbc) {
		if (!$yyYaBBCloaded) { require "$sourcedir/YaBBC.pl"; }
		&DoUBBC;
	}
	&ToChars($message);
	${$uid.$user}{'signature'} = $message;

	# use height like code boxes do. Set to 200px at 15 newlines
	my $linecount = () = ${$uid.$user}{'signature'} =~ /\<br \/\>/g;
	if(${$uid.$user}{'signature'} && $linecount > 15) {${$uid.$user}{'signature'} = qq~<div class="scroll" style="float: left; font-size: 10px; font-family: verdana, sans-serif; overflow: auto; max-height: 200px; height: 200px; width: 99%;">${$uid.$user}{'signature'}</div>~}
	else {${$uid.$user}{'signature'} = ${$uid.$user}{'signature'} ? qq~<div class="scroll" style="float: left; font-size: 10px; font-family: verdana, sans-serif; overflow: auto; max-height: 200px; width: 99%;">${$uid.$user}{'signature'}</div>~ : '';}

	$themsnuser   = $user;
	$themsnname   = ${$uid.$user}{'realname'};
	$thegtalkuser = $user;
	$thegtalkname = ${$uid.$user}{'realname'};

	if ($UseMenuType == 0) {
		$yimimg   = qq~<img src="$imagesdir/yim.gif" alt="${$uid.$user}{'yim'}" border="0" />~;
		$aimimg   = qq~<img src="$imagesdir/aim.gif" alt="${$uid.$user}{'aim'}" border="0" />~;
		$skypeimg = qq~<img src="$imagesdir/skype.gif" alt="${$uid.$user}{'skype'}" border="0" />~;
		$msnimg   = qq~<img src="$imagesdir/msn3.gif" style="cursor: pointer" onclick="window.open('$scripturl?action=setmsn;msnname=$themsnuser','','height=80,width=340,menubar=no,toolbar=no,scrollbars=no'); return false" alt="$themsnname" border="0" />~;
		$gtalkimg = qq~<img src="$imagesdir/gtalk2.gif" style="cursor: pointer" onclick="window.open('$scripturl?action=setgtalk;gtalkname=$thegtalkuser','','height=80,width=340,menubar=no,toolbar=no,scrollbars=no'); return false" alt="$thegtalkname" border="0" />~;
		$icqimg   = qq~<img src="http://web.icq.com/whitepages/online?icq=${$uid.$user}{'icq'}&#38;img=5" alt="${$uid.$user}{'icq'}" border="0" />~;
	} elsif ($UseMenuType == 1) {
		$yimimg   = qq~<span class="imgwindowbg">YIM</span>~;
		$aimimg   = qq~<span class="imgwindowbg">AIM</span>~;
		$skypeimg   = qq~<span class="imgwindowbg">Skype/VoIP</span>~;
		$msnimg   = qq~<span class="imgwindowbg" style="cursor: pointer" onclick="window.open('$scripturl?action=setmsn;msnname=$themsnuser','','height=80,width=340,menubar=no,toolbar=no,scrollbars=no'); return false">MSN</span>~;
		$gtalkimg = qq~<span class="imgwindowbg" style="cursor: pointer" onclick="window.open('$scripturl?action=setgtalk;gtalkname=$thegtalkuser','','height=80,width=340,menubar=no,toolbar=no,scrollbars=no'); return false">GTalk</span>~;
		$icqimg   = qq~<span class="imgwindowbg">ICQ</span>~;
	} else {
		$yimimg   = qq~<img src="$html_root/Buttons/$language/yim.png" alt="${$uid.$user}{'yim'}" border="0" />~;
		$aimimg   = qq~<img src="$html_root/Buttons/$language/aim.png" alt="${$uid.$user}{'aim'}" border="0" />~;
		$skypeimg = qq~<img src="$html_root/Buttons/$language/skype.png" alt="${$uid.$user}{'skype'}" border="0" />~;
		$msnimg   = qq~<img src="$html_root/Buttons/$language/msn.png" style="cursor: pointer" onclick="window.open('$scripturl?action=setmsn;msnname=$themsnuser','','height=80,width=340,menubar=no,toolbar=no,scrollbars=no'); return false" alt="$themsnname" border="0" />~;
		$gtalkimg = qq~<img src="$html_root/Buttons/$language/gtalk.png" style="cursor: pointer" onclick="window.open('$scripturl?action=setgtalk;gtalkname=$thegtalkuser','','height=80,width=340,menubar=no,toolbar=no,scrollbars=no'); return false" alt="$thegtalkname" border="0" />~;
		$icqimg   = qq~<img src="$html_root/Buttons/$language/icq.png" alt="${$uid.$user}{'icq'}" border="0" />~;
	}

	$icqad{$user} = $icqad{$user} ? qq~<a href="http://web.icq.com/${$uid.$user}{'icq'}" target="_blank"><img src="$imagesdir/icqadd.gif" alt="${$uid.$user}{'icq'}" border="0" /></a>~ : '';
	${$uid.$user}{'icq'}   = ${$uid.$user}{'icq'}   ? qq~<a href="http://web.icq.com/${$uid.$user}{'icq'}" title="${$uid.$user}{'icq'}" target="_blank">$icqimg</a>~ : '';
	${$uid.$user}{'aim'}   = ${$uid.$user}{'aim'}   ? qq~<a href="aim:goim?screenname=${$uid.$user}{'aim'}&#38;message=Hi.+Are+you+there?">$aimimg</a>~              : '';
	${$uid.$user}{'skype'} = ${$uid.$user}{'skype'} ? qq~<a href="$scripturl?action=callto;username=$useraccount{$user}" target="_blank">$skypeimg</a>~                                                   : '';
	${$uid.$user}{'msn'}   = ${$uid.$user}{'msn'}   ? qq~$msnimg~                                                                                                    : '';
	${$uid.$user}{'gtalk'} = ${$uid.$user}{'gtalk'} ? qq~$gtalkimg~                                                                                                  : '';
	$yimon{$user} = $yimon{$user} ? qq~<img src="http://opi.yahoo.com/online?u=${$uid.$user}{'yim'}&#38;m=g&#38;t=0" border="0" alt="" />~ : '';
	${$uid.$user}{'yim'} = ${$uid.$user}{'yim'} ? qq~<a href="http://edit.yahoo.com/config/send_webmesg?.target=${$uid.$user}{'yim'}" target="_blank">$yimimg</a>~ : '';

	if ($showgenderimage && ${$uid.$user}{'gender'}) {
		${$uid.$user}{'gender'} = ${$uid.$user}{'gender'} =~ m~Female~i ? 'female' : 'male';
		${$uid.$user}{'gender'} = ${$uid.$user}{'gender'} ? qq~$load_txt{'231'}: <img src="$imagesdir/${$uid.$user}{'gender'}.gif" border="0" alt="${$uid.$user}{'gender'}" /><br />~ : '';
	} else {
		${$uid.$user}{'gender'} = '';
	}

	# Wrap words longer than 20 characters in user text
	if ($showusertext) {
		$message = ${$uid.$user}{'usertext'};
		$message = &Censor($message);
		&ToChars($message);
		${$uid.$user}{'usertext'} = $message;

		$wrapcut = 20;
		$wrapstr = ${$uid.$user}{'usertext'};
		&WrapChars;
		${$uid.$user}{'usertext'} = $wrapstr;

		${$uid.$user}{'usertext'} .= qq~<br />~;
	} else {
		${$uid.$user}{'usertext'} = "";
	}

	# Create the userpic / avatar html
	if ($showuserpic && $allowpics) {
		${$uid.$user}{'userpic'} ||= 'blank.gif';
		if (${$uid.$user}{'userpic'} =~ m~\A[\s\n]*http://~i) {
			${$uid.$user}{'userpic'}    = qq~${$uid.$user}{'userpic'}~;
			${$uid.$user}{'userownpic'} = 1;
		} else {
			${$uid.$user}{'userpic'}    = qq~$facesurl/${$uid.$user}{'userpic'}~;
			${$uid.$user}{'userownpic'} = 0;
		}
	} else {
		${$uid.$user}{'userpic'} = '<br />';
	}

	# Censor it
	${$uid.$user}{'signature'} = &Censor(${$uid.$user}{'signature'});
	${$uid.$user}{'usertext'}  = &Censor(${$uid.$user}{'usertext'});

	&LoadMiniUser($user);

	$yyUDLoaded{$user} = 1;
	return 1;
}

sub LoadMiniUser {
	my $user = $_[0];
	my $load = '';
	my $key  = '';
	$g = 0;
	my $dg = 0;
	my ($tempgroup, $temp_postgroup);
	my $noshow = 0;
	my $bold   = 0;

	$tempgroupcheck = ${$uid.$user}{'position'} || "";

	if (exists $Group{$tempgroupcheck} && $tempgroupcheck ne "") {
		($title, $stars, $starpic, $color, $noshow, $viewperms, $topicperms, $replyperms, $pollperms, $attachperms) = split(/\|/, $Group{$tempgroupcheck});
		$temptitle = $title;
		$tempgroup = $Group{$tempgroupcheck};
		if ($noshow == 0) { $bold = 1; }
		$memberunfo{$user} = "$tempgroupcheck";
	} elsif ($moderators{$user}) {
		($title, $stars, $starpic, $color, $noshow, $viewperms, $topicperms, $replyperms, $pollperms, $attachperms) = split(/\|/, $Group{'Moderator'});
		$temptitle         = $title;
		$tempgroup         = $Group{'Moderator'};
		$memberunfo{$user} = "$tempgroupcheck";
	} elsif (exists $NoPost{$tempgroupcheck} && $tempgroupcheck ne "") {
		($title, $stars, $starpic, $color, $noshow, $viewperms, $topicperms, $replyperms, $pollperms, $attachperms) = split(/\|/, $NoPost{$tempgroupcheck});
		$temptitle         = $title;
		$tempgroup         = $NoPost{$tempgroupcheck};
		$memberunfo{$user} = "$tempgroupcheck";
	}

	if (!$tempgroup) {
		foreach $postamount (sort { $b <=> $a } keys %Post) {
			if (${$uid.$user}{'postcount'} >= $postamount) {
				($title, $stars, $starpic, $color, $noshow, $viewperms, $topicperms, $replyperms, $pollperms, $attachperms) = split(/\|/, $Post{$postamount});
				$tempgroup = $Post{$postamount};
				last;
			}
		}
		$memberunfo{$user} = "$title";
	}

	if ($noshow == 1) {
		$temptitle = $title;
		foreach $postamount (sort { $b <=> $a } keys %Post) {
			if (${$uid.$user}{'postcount'} > $postamount) {
				($title, $stars, $starpic, $color, undef) = split(/\|/, $Post{$postamount},5);
				last;
			}
		}
	}

	if (!$tempgroup) {
		$temptitle   = "no group";
		$title       = "";
		$stars       = 0;
		$starpic     = "";
		$color       = "";
		$noshow      = 1;
		$viewperms   = "";
		$topicperms  = "";
		$replyperms  = "";
		$pollperms   = "";
		$attachperms = "";
	}

	# The following puts some new has variables in if this user is the user browsing the board
	if ($user eq $username) {
		if ($tempgroup) {
			($trash, $trash, $trash, $trash, $trash, $viewperms, $topicperms, $replyperms, $pollperms, $attachperms) = split(/\|/, $tempgroup);
		}
		${$uid.$user}{'perms'} = "$viewperms|$topicperms|$replyperms|$pollperms|$attachperms";
	}

	$userlink = ${$uid.$user}{'realname'} || $user;
	$userlink = qq~<b>$userlink</b>~;
	if (!$scripturl) { $scripturl = qq~$boardurl/YaBB.$yyext~; }
	if ($bold != 1) { $memberinfo{$user} = qq~$title~; }
	else {
		$memberinfo{$user} = qq~<b>$title</b>~;
	}
	&FormatUserName($user);
	if ($color ne "") {
		$link{$user}      = qq~<a href="$scripturl?action=viewprofile;username=$useraccount{$user}" style="color:$color;">$userlink</a>~;
		$col_title{$user} = qq~<span style="color: $color;">$memberinfo{$user}</span>~;
	} else {
		$link{$user}      = qq~<a href="$scripturl?action=viewprofile;username=$useraccount{$user}">$userlink</a>~;
		$col_title{$user} = qq~$memberinfo{$user}~;
	}
	$addmembergroup{$user} = "<br />";
	${$uid.$user}{'addgroups'} =~ s/\, /\,/g;
	foreach $addgrptitle (split(/\,/, ${$uid.$user}{'addgroups'})) {
		chomp $addgrptitle;
		foreach $key (sort { $a <=> $b } keys %NoPost) {
			($atitle, $t, $t, $t, $anoshow, $aviewperms, $atopicperms, $areplyperms, $apollperms, $aattachperms) = split(/\|/, $NoPost{$key});
			if ($addgrptitle eq $key && $atitle ne $title) {
				if ($user eq $username && !$iamadmin) {
					if ($aviewperms == 1)   { $viewperms   = 1; }
					if ($atopicperms == 1)  { $topicperms  = 1; }
					if ($areplyperms == 1)  { $replyperms  = 1; }
					if ($apollperms == 1)   { $pollperms   = 1; }
					if ($aattachperms == 1) { $attachperms = 1; }
					${$uid.$user}{'perms'} = "$viewperms|$topicperms|$replyperms|$pollperms|$attachperms";
				}
				if ($anoshow && $iamadmin) {
					$addmembergroup{$user} .= qq~($atitle)<br />~;
				} elsif (!$anoshow) {
					$addmembergroup{$user} .= qq~$atitle<br />~;
				}
			}
		}
	}
	$addmembergroup{$user} =~ s/<br \/>\Z//;

	if ($username eq "Guest") {
		$memberunfo{$user} = "Guest";
	}

	$topicstart{$user} = "";
	$viewnum = "";
	if ($INFO{'num'} || $FORM{'threadid'} && $user eq $username) {
		if ($INFO{'num'}) {
			$viewnum = $INFO{'num'};
		}
		elsif ($FORM{'threadid'}) {
			$viewnum = $FORM{'threadid'};
		}
		if ($viewnum =~ m~/~) { ($viewnum, undef) = split('/', $viewnum); }

		# No need to open the message file so many times.
		# Opening it once is enough to do the access checks.
		unless ($topicstarter) {
			if (-e "$datadir/$viewnum.txt") {
				fopen(TOPSTART, "$datadir/$viewnum.txt");
				$thetopic = <TOPSTART>;
				($t, $t, $t, $t, $topicstarter) = split(/[\|]/, $thetopic, 6);
				fclose(TOPSTART);
			}
		}

		if ($user eq $topicstarter) { $topicstart{$user} = "Topic Starter"; }
	}
	$memberaddgroup{$user} = ${$uid.$user}{'addgroups'};

	$starnum = $stars;
	$memberstartemp = '';
	if ($starpic !~ /\//) { $starpic = "$imagesdir/$starpic"; }
	while ($starnum-- > 0) {
		$memberstartemp .= qq(<img src="$starpic" border="0" alt="*" />);
	}
	$memberstar{$user} = $memberstartemp;

	return 1;
}

sub LoadCookie {
	foreach (split(/; /, $ENV{'HTTP_COOKIE'})) {
		$_ =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
		($cookie, $value) = split(/=/);
		$yyCookies{$cookie} = $value;
	}
	if ($yyCookies{$cookiepassword}) {
		$password      = $yyCookies{$cookiepassword};
		$username      = $yyCookies{$cookieusername} || 'Guest';
		$cookiesession = $yyCookies{$session_id};
	} else {
		$password = '';
		$username = 'Guest';
	}
	if(($yyCookies{'guestlanguage'} && !$FORM{'guestlang'} && $enable_guestlanguage) && $action ne "login" && $action ne "login2")	{
		$guestLang = $yyCookies{'guestlanguage'};
		$language = $guestLang;
	}
}

sub UpdateCookie {
	my ($what, $user, $passw, $sessionval, $pathval, $expire) = @_;
	my ($valid, $expiration);
	$valid = 0;
	if ($what eq "delete") {
		$expiration = "Thursday, 01-Jan-1970 00:00:00 GMT";
		if ($pathval eq "") { $pathval = qq~/~; }
		if(($iamguest && $FORM{'guestlang'} && $enable_guestlanguage) || ($iamguest && $guestLang) && $enable_guestlanguage)	{
			if($FORM{'guestlang'} && !$guestLang)	{$guestLang = qq~$FORM{'guestlang'}~;}
			$language = qq~$guestLang~;
			$cookiepassword = "guestlanguage";
			$passw = qq~$language~;
			$expire = "persistent";
			}
		$valid = 1;
	} elsif ($what eq "write") {
		$expiration = $expire;
		if ($pathval eq "") { $pathval = qq~/~; }
		$valid = 1;
	}
	if ($expire eq "persistent") { $expiration = "Sunday, 17-Jan-2038 00:00:00 GMT"; }

	if ($valid == 1) {
		$cookiewritten = "Cookie Prepared";
		$yySetCookies1 = cookie(
			-name    => "$cookieusername",
			-value   => "$user",
			-path    => "$pathval",
			-expires => "$expiration");
		$yySetCookies2 = cookie(
			-name    => "$cookiepassword",
			-value   => "$passw",
			-path    => "$pathval",
			-expires => "$expiration");
		$yySetCookies3 = cookie(
			-name    => "$cookiesession_name",
			-value   => "$sessionval",
			-path    => "$pathval",
			-expires => "$expiration");
		
	}
}

sub LoadAccess {
	$yesaccesses .= "$load_txt{'805'} $load_txt{'806'} $load_txt{'808'}<br />";
	$noaccesses = "";

	# Reply Check
	my $rcaccess = &AccessCheck($currentboard, 2) || 0;
	if ($rcaccess eq "granted") { $yesaccesses .= "$load_txt{'805'} $load_txt{'806'} $load_txt{'809'}<br />"; }
	else { $noaccesses .= "$load_txt{'805'} $load_txt{'807'} $load_txt{'809'}<br />"; }

	# Topic Check
	my $tcaccess = &AccessCheck($currentboard, 1) || 0;
	if ($tcaccess eq "granted") { $yesaccesses .= "$load_txt{'805'} $load_txt{'806'} $load_txt{'810'}<br />"; }
	else { $noaccesses .= "$load_txt{'805'} $load_txt{'807'} $load_txt{'810'}<br />"; }

	# Poll Check
	my $access = &AccessCheck($currentboard, 3) || 0;
	if ($access eq "granted") { $yesaccesses .= "$load_txt{'805'} $load_txt{'806'} $load_txt{'811'}<br />"; }
	else { $noaccesses .= "$load_txt{'805'} $load_txt{'807'} $load_txt{'811'}<br />"; }

	# Zero Post Check
	if ($username ne 'Guest') {
		if ($INFO{'zeropost'} != 1 && $rcaccess eq "granted") { $yesaccesses .= "$load_txt{'805'} $load_txt{'806'} $load_txt{'812'}<br />"; }
		else { $noaccesses .= "$load_txt{'805'} $load_txt{'807'} $load_txt{'812'}<br />"; }
	}

	$accesses = qq~$yesaccesses<br />$noaccesses~;
}

sub WhatTemplate {
	if (!-e "$vardir/template.cfg") {
		fopen(UPDATETEMPLATE, ">$vardir/template.cfg") || &fatal_error('cannot_open', "$vardir/template.cfg", 1);
		print UPDATETEMPLATE "\$templatesloaded = 1;\n";
		print UPDATETEMPLATE qq~\$templateset{'Forum default'} = "default|default|default|default|default|default|default|";\n~;
		fclose(UPDATETEMPLATE);
		$template = qq~Forum default~;
	}
	require "$vardir/template.cfg";
	$found = 0;
	while (($curtemplate, $value) = each(%templateset)) {
		if ($curtemplate eq $default_template) { $template = $curtemplate; $found = 1; }
	}
	if (!$found) { $template = 'Forum default'; }
	if (${$uid.$username}{'template'} ne '') {
		if (!exists $templateset{${$uid.$username}{'template'}}) {
			${$uid.$username}{'template'} = 'Forum default';
			&UserAccount($username, "update");
		}
		while (($curtemplate, $value) = each(%templateset)) {
			if ($curtemplate eq ${$uid.$username}{'template'}) { $template = $curtemplate; }
		}
	}
	chomp $templateset{$template};
	($usestyle, $useimages, $usehead, $useboard, $usemessage, $usedisplay, $usemycenter, $UseMenuType) = split(/\|/, $templateset{$template});

	if (!-e "$forumstylesdir/$usestyle.css") { $usestyle = 'default'; }
	if (!-e "$templatesdir/$usehead/$usehead.html") { $usehead = 'default'; }
	if (!-e "$templatesdir/$useboard/BoardIndex.template") { $useboard = 'default'; }
	if (!-e "$templatesdir/$usemessage/MessageIndex.template") { $usemessage = 'default'; }
	if (!-e "$templatesdir/$usedisplay/Display.template") { $usedisplay = 'default'; }
	if (!-e "$templatesdir/$usemycenter/MyCenter.template") { $usemycenter = 'default'; }

	if ($UseMenuType eq '') { $UseMenuType = $MenuType; }

	if (-d "$forumstylesdir/$useimages") { $imagesdir = "$forumstylesurl/$useimages"; }
	else { $imagesdir = "$forumstylesurl/default"; }
	$defaultimagesdir = "$forumstylesurl/default";
	$extpagstyle = qq~$forumstylesurl/$usestyle.css~;
	$extpagstyle =~ s~$usestyle\/~~g;
}

sub WhatLanguage {
	if (${$uid.$username}{'language'} ne '') {
		$language = ${$uid.$username}{'language'};
	} elsif($FORM{'guestlang'} && $enable_guestlanguage) {
		$language = $FORM{'guestlang'};
	} elsif($guestLang && $enable_guestlanguage)	{
		$language = $guestLang;
	} else	{
		$language = $lang;
	}

	&LoadLanguage('Main');
	&LoadLanguage('Menu');

	if ($adminscreen) {
		&LoadLanguage('Admin');
		&LoadLanguage('FA');
	}

}

## build the .ims from scratch
## here because its needed by admin and user
#messageid|[blank]|touser(s)|(ccuser(s))|(bccuser(s))|
#    subject|date|message|(parentmid)|(reply#)|ip|
#		messagestatus|flags|storefolder|attachment
## messagestatus = c(confidential)/h(igh importance)/s(tandard)
## parentmid stays same, reply# increments for replies, so we can build conversation threads
## storefolder = name of storage folder. Start with in & out for everyone. 
## flags - u(nread)/f(orwarded)/r(eplied)
##
####
#1	$mnum = 3;
#2	$imnewcount = 0;
#3	$moutnum = 17;
#4	$storenum = 0;
#5	$draftnum = 0;
#6	@folders  (name1|name2|name3);

# MF-B: new .ims file format
#	### UserIMS YaBB 2.2 Version ###
#	'${$username}{'PMmnum'}',"value"
#	'${$username}{'PMimnewcount'}',"value"
#	'${$username}{'PMmoutnum'}',"value"
#	'${$username}{'PMstorenum'}',"value"
#	'${$username}{'PMdraftnum'}',"value"
#	'${$username}{'PMfolders'}',"value"
#	'${$username}{'PMfoldersCount'}',"value"
#	'${$username}{'PMbcUnread'}',"value"
#	'${$username}{'PMbcLastRead'}',"value"
#	'${$username}{'PMbcCount'}',"value"

# usage: &buildIMS(<user>, 'tasks')
# tasks: load, update
# my @tag = qw(PMmnum PMimnewcount PMmoutnum PMstorenum PMdraftnum PMfolders PMfoldersCount PMbcUnread PMbcLastRead PMbcCount);

sub buildIMS {
	my @tag = qw(PMmnum PMimnewcount PMmoutnum PMstorenum PMdraftnum PMfolders PMfoldersCount PMbcUnread PMbcLastRead PMbcCount);

	&LoadLanguage('InstantMessage');
	## pull victim in
	my $builduser = $_[0];
	my $job = $_[1];
	$BCnewMessage = 0;
	my ($incurr, $inunr, $draftcount, $storetotal, $storefolders, $testfolders, @storefoldersCount, $storeCounts);
	if ($builduser =~ /\.vars$/) {
		my ($builduser, undef) = split(/\./, $builduser);
	}
	else { $member = $builduser; }

	if ($job eq 'load') { &load_IMS; }
	elsif ($job eq 'update') { &update_IMS; return; }

	if (${$builduser}{'PMfolders'} eq '') {
		$storefolders = 'in|out';
	} else {
		$storefolders = ${$builduser}{'PMfolders'};
		$testfolders = ${$builduser}{'PMfolders'};
		@currStoreFolders = split(/\|/, ${$builduser}{'PMfolders'});	
	}

	## inbox
	## if it exists, either load and count totals or parse and update format.
	if (-e "$memberdir/$builduser.msg") {
		fopen(USERMSG, "$memberdir/$builduser.msg") || &fatal_error('cannot_open', "$memberdir/$builduser.msg", 1); # open inbox
		my @messages = <USERMSG>;
		fclose(USERMSG);
		chomp @messages;
		# test the data for version
		## if in old format, needs rearranging
		if (split(/\|/, $messages[0]) > 8) {
			#   16 elements in new format, no more than 8 in old
			## new format, so just need to check the flags
			foreach my $message (@messages ) {
				## parse messages for flags
				my $flags = (split /\|/, $message)[12];
				if ($flags =~ /u/) { $inunr++; }  # if the message is flagged as u(nopened), add to the new count
			}
			$incurr = @messages;  ## mnum = count of list
		} else {
			&convert_MSG;
		}
		undef @messages;	
	}

	## do the outbox
	if (-e "$memberdir/$builduser.outbox") {
		fopen("OUTMESS", "$memberdir/$builduser.outbox") || &fatal_error('cannot_open', "$memberdir/$builduser.outbox", 1);		
		my @outmessages = <OUTMESS>;
		fclose("OUTMESS");
		chomp @outmessages;
		if (split(/\|/, $outmessages[0]) > 8) {
			# > 10 elements in new format, no more than 8 in old
			$outcurr = @outmessages;
		} else {
			&convert_OUTBOX;
		}
		undef @outmessages;
	}

	## do the draft store - slightly easier - only exists in y22
	if (-e "$memberdir/$builduser.imdraft") {
		fopen("DRAFTMESS", "$memberdir/$builduser.imdraft") || &fatal_error('cannot_open', "$memberdir/$builduser.imdraft", 1);
		my @draftmessages = <DRAFTMESS>;
		fclose("DRAFTMESS");
		if (@draftmessages) { $draftcount = @draftmessages; }
	}

	## grab the current list of store folders
	## else, create an entry for the two 'default ones' for the in/out status stuff
	
	if (-e "$memberdir/$builduser.imstore") {
		#4 $storenum = 0;
		#6 @folders  (name1|name2|name3)
		fopen(STOREMESS, "$memberdir/$builduser.imstore") || &fatal_error('cannot_open', "$memberdir/$builduser.imstore", 1);
		@imstore = <STOREMESS>;
		fclose (STOREMESS);
		chomp @imstore;
		if (@imstore) {
			if (split(/\|/, $imstore[0]) > 8) {
				# > 10 elements in new format, no more than 8 in old
				#messageid0|[blank]1|touser(s)2|(ccuser(s))3|(bccuser(s))4|
				#        subject5|date6|message7|(parentmid)8|(reply#)9|ip10|messagestatus11|storefolder12|flags13|attachment14
				my $storeUpdated = 0;
				my $storeMessLine = 0;
				foreach my $message (@imstore)	{
					my @messLine = split(/\|/, $message);
					## look through list for folder name
					if ($messLine[13] ne '') {
						if ("\|$testfolders\|" =~ m/\|$messLine[13]\|/g) { next; }
						if ("$testfolders\|" =~ m/^$messLine[13]\|/) { next; }
						if ("\|$testfolders" =~ m/\|$messLine[13]$/) { next; }
						push (@currStoreFolders, $messLine[13]);
					} else { # some folder missing within imstore
						$storeUpdated = 1;
						if ($messLine[1] ne '')	{ # from name so inbox	
							$messLine[13] = 'in';
						} else { # no from so outbox
							$messLine[13] = 'out';
						}
						$imstore[$storeMessLine] = join('|', @messLine);
					}
					$storeMessLine++;
				}
				if ($storeUpdated == 1) {
					fopen(STRMESS, "+>$memberdir/$builduser.imstore") || &fatal_error('cannot_open', "$memberdir/$builduser.imstore", 1);
					print STRMESS @imstore;
					fclose(STRMESS);
				}
				$storefolders = join('|', @currStoreFolders);	
			} else {
				undef @imstore;
				&convert_IMSTORE;
			}

			$storetotal = @imstore;
			## run through the messages and count against the folder name 
			for ($x=0; $x < $#currStoreFolders+1; $x++) { $storefoldersCount[$x] = 0; }
			for ($x=0; $x < $#imstore+1; $x++)	{
				my @messLine = split(/\|/, $imstore[$x]);
				for ($y=0; $y < $#currStoreFolders+1; $y++) {
					if ($messLine[13] eq $currStoreFolders[$y])	{
						$storefoldersCount[$y]++;
					}	
				} 
			}
			
			## now the folders are all totalled, find if any are still at 0.
			## if so, increment the 'empties' flag.
			## if this stays at 0, the 'delete empty folder' form is killed.
			for ($x=0; $x < $#currStoreFolders+1; $x++) {
				if ($storefoldersCount[$x] == 0) { $emptyPMfolders++; }
			}
			$storeCounts = join('|', @storefoldersCount);
			undef @imstore;
		} else {
			unlink "$memberdir/$builduser.imstore";
		}
	}

	#check broadcast messages
	if (-e "$memberdir/broadcast.messages") {
		fopen(BCMESS, "<$memberdir/broadcast.messages") || &fatal_error('cannot_open', "$memberdir/broadcast.messages", 1);
		my @bcmessages = <BCMESS>;
		fclose(BCMESS);
		my $newBC = 0;
		if (@bcmessages > 0) {
			foreach my $checkbcm (@bcmessages) {
				$icanview = 0;
				my ($mnum, $mfrom, $mto, undef) = split (/\|/, $checkbcm, 4);
				if ($mfrom eq $username) { $bccount++; next; }
				&BroadMessageView($mto);
				if ($icanview == 0) { next; }
				$bccount++;
				if (!$newBC) { ${$builduser}{'PMbcUnread'} = $mnum; $newBC = 1; }
			}
		}
		if (!@bcmessages) {
			${$builduser}{'PMbcUnread'} = '';
			${$builduser}{'PMbcLastRead'} = ''
		}
		undef @bcmessages;
	}

	${$builduser}{'PMmnum'} = $incurr || 0;
	${$builduser}{'PMimnewcount'} = $inunr || 0;
	${$builduser}{'PMmoutnum'} = $outcurr || 0;
	${$builduser}{'PMdraftnum'} = $draftcount || 0;
	${$builduser}{'PMstorenum'} = $storetotal || 0;
	${$builduser}{'PMfolders'} = $storefolders;
	${$builduser}{'PMfoldersCount'} = $storeCounts || 0;
	if (${$builduser}{'PMbcUnread'} > ${$builduser}{'PMbcLastRead'}) { $BCnewMessage = 1; }
	${$builduser}{'PMbcCount'} = $bccount || 0;
	&update_IMS;

	sub load_IMS {
		if (-e "$memberdir/$builduser.ims")	{
			fopen ("IMSFILE", "$memberdir/$builduser.ims") || &fatal_error('cannot_open', "$memberdir/$builduser.ims", 1);
			@ims = <IMSFILE>;
			fclose("IMSFILE");
		}

		if ($ims[0] =~ /###/) {
			foreach my $imsline (@ims) {
				chomp $imsline;
				unless (length($imsline) == 0 || $imsline =~ /###/) {
					$imsline =~ s/\'(.*?)\'\,\"(.*?)\"//ig;
					my $tag = $1;
					my $value = $2;
					${$builduser}{$tag} = $value;
				}
			}
		} else {
			## load old format and convert to new ##
			&convert_IMS;
		}
	}
	
	sub convert_IMS {
		${$builduser}{'PMmnum'} = $mnum || 0;
		${$builduser}{'PMimnewcount'} = $imnewcount || 0;
		${$builduser}{'PMmoutnum'} = $moutnum || 0;
		${$builduser}{'PMstorenum'} = $storenum || 0; 
		${$builduser}{'PMdraftnum'} = $draftnum || 0;
		${$builduser}{'PMfolders'} = $folders || qq~in|out~;
		${$builduser}{'PMfoldersCount'} = $foldersCount || 0;
		${$builduser}{'PMbcUnread'} = '';
		${$builduser}{'PMbcCount'} = 0;
		&update_IMS;
		&load_IMS;
	}
	
	sub update_IMS {
		fopen(UPDATE_IMS, ">$memberdir/$builduser.ims",1) || &fatal_error('cannot_open', "$memberdir/$builduser.ims", 1);
		print UPDATE_IMS qq~### UserIMS YaBB 2.2 Version ###\n\n~;
		for (my $cnt = 0; $cnt < @tag; $cnt++) {
			print UPDATE_IMS "\'$tag[$cnt]\'\,\"${$builduser}{$tag[$cnt]}\"\n";
		}
		fclose(UPDATE_IMS);
	}

	sub convert_MSG {
		# clean out msg file and rebuild in new format
		# new format:
		# messageid(0)|from(1)|touser(2)|ccuser(3)|bccuser(4)|subject(5)|date(6)|message(7)|parentmid(8)|reply#(9)|ip(10)|messagestatus(11)|flags(12)|storefolder(13)|attachment(14)
		# old format:
		# from(0)|subject(1)|date(2)|message(3)|messageid(4)|ip(5)|read/replied(6)
		fopen(OLDMESS, "+<$memberdir/$builduser.msg") || &fatal_error('cannot_open', "$memberdir/$builduser.msg", 1);
		my @oldmessages = <OLDMESS>;
		seek OLDMESS , 0, 0;
		chomp @oldmessages;
		foreach my $oldmessage (@oldmessages) { #parse messages for flags
			my @oldformat = split(/\|/,$oldmessage);
			# under old format, unread,and replied are exclusive, so no need to go mixing them
			if ($oldformat[6] == '1') { $oldformat[6] = 'u' ; $inunr++; }	# if 6 (status) is 1 then change to u(nread) flag
			elsif ($oldformat[6] == '2') { $oldformat[6] = 'r'; }				# if 6 (status) is 2 then change to r(eplied) flag
			# if any old style message ids still there, or odd blank ones, correct them to = date value
			if ($oldformat[4] < 101 || $oldformat[4] eq '') { $oldformat[4] = $oldformat[2]; }
			# reassemble to new format
			my $newmessage = "$oldformat[4]|$oldformat[0]|$builduser|||$oldformat[1]|$oldformat[2]|$oldformat[3]|$oldformat[4]|0|$oldformat[5]|s|$oldformat[6]||\n";
			# print back to file
			print OLDMESS "$newmessage";
		}
		$incurr = @oldmessages;  ## mnum = count of list
		fclose(OLDMESS);
		undef @oldmessages;
	}

	sub convert_OUTBOX {
		## clean out msg file and rebuild in new format
		fopen(OLDOUTBOX, "+<$memberdir/$builduser.outbox") || &fatal_error('cannot_open', "$memberdir/$builduser.outbox", 1);
		my @oldoutmessages = <OLDOUTBOX>;
		seek OLDOUTBOX, 0, 0;
		chomp @oldoutmessages;
		# clean out msg file and rebuild in new format
		# new format:
		# messageid(0)|from(1)|touser(2)|ccuser(3)|bccuser(4)|subject(5)|date(6)|message(7)|parentmid(8)|reply#(9)|ip(10)|messagestatus(11)|flags(12)|storefolder(13)|attachment(14)
		# old format:
		# from(0)|subject(1)|date(2)|message(3)|messageid(4)|ip(5)|read/replied(6)
		foreach my $oldmessage (@oldoutmessages) {
			my @oldformat = split(/\|/, $oldmessage);
			## if any old style message ids still there, or odd blank ones, correct them to = date value
			if ($oldformat[4] < 101 || $oldformat[4] eq '') { $oldformat[4] = $oldformat[2]; }
			## outbox can't be replied to ;) and forwarding doesn't exist in old format
			if (!$oldformat[6]) { $oldformat[6] = 'u' ; }
			elsif ($oldformat[6] == 1) { $oldformat[6] = ''; }
			my $newmessage = "$oldformat[4]|$builduser|$oldformat[0]|||$oldformat[1]|$oldformat[2]|$oldformat[3]|$oldformat[4]|0|$oldformat[5]|s|$oldformat[6]||\n";
			print OLDOUTBOX "$newmessage";
		}	
		$outcurr = @oldoutmessages;
		fclose(OLDOUTBOX);
		undef @oldoutmessages;
	}

	sub convert_IMSTORE {
		fopen(OLDIMSTORE, "+<$memberdir/$builduser.imstore") || &fatal_error('cannot_open', "$memberdir/$builduser.imstore", 1);
		my @oldstoremessages = <OLDIMSTORE>;
		chomp @oldstoremessages;
		seek OLDIMSTORE, 0, 0;
		# new format:
		# messageid(0)|from(1)|touser(2)|ccuser(3)|bccuser(4)|subject(5)|date(6)|message(7)|parentmid(8)|reply#(9)|ip(10)|messagestatus(11)|flags(12)|storefolder(13)|attachment(14)
		# old format:
		# from(0)|subject(1)|date(2)|message(3)|messageid(4)|ip(5)|read/replied(6)|folder/imwhere(7)
		foreach my $oldmessage (@oldstoremessages) {
			my @oldformat = split(/\|/, $oldmessage);
			my ($touser, $builduser);
			if ($oldformat[7] eq 'outbox') { 
				$oldformat[7]= 'out';
				$touser = $oldformat[0];
				$fromuser = $builduser;
				if (!$oldformat[6]) { $oldformat[6] = 'u'; }
				elsif ($oldformat[6] == 1) { $oldformat[6] = 'r'; }
			} elsif ($oldformat[7] eq 'inbox') { 
				$oldformat[7]= 'in';
				$touser = $builduser;
				$fromuser = $oldformat[0];
				if ($oldformat[6] == 1) { $oldformat[6] = 'u'; }
				elsif ($oldformat[6] == 2) { $oldformat[6] = 'r'; }
			} 
			my $newmessage = "$oldformat[4]|$fromuser|$touser|||$oldformat[1]|$oldformat[2]|$oldformat[3]|$oldformat[4]|0|$oldformat[5]|s|$oldformat[6]|$oldformat[7]|\n";
			print OLDIMSTORE "$newmessage";
			push (@imstore, $newmessage);
		}	
		fclose(OLDIMSTORE);
		undef @oldstoremessages;
	}

}

1;
