<?php
// +----------------------------------------------------------------+
// | util.php														|
// +----------------------------------------------------------------+
// | Function: Folder Manager - View/Modify/Delete account folders  |
// | Used to view and save account preferences/settings				|
// +----------------------------------------------------------------+
// | AtMail Open - Licensed under the Apache 2.0 Open-source License|
// | http://opensource.org/licenses/apache2.0.php                   |
// +----------------------------------------------------------------+

require_once('header.php');

require_once('Session.php');
require_once('Global.php');
require_once('GetMail.php');
require_once('Language.php');

session_start();

// get the requested function
$var['func'] = $_REQUEST['func'];
$func = "util_{$var['func']}";

if (!function_exists($func)) {
	$func = str_replace("<", "&lt;", $func);
	$func = str_replace(">", "&gt;", $func);
	die("requested function '$func' does not exist");
}

$atmail = new AtmailGlobal();
$auth =& $atmail->getAuthObj();

$var = array();

$atmail->status = $auth->getuser( $atmail->SessionID );

$atmail->username = $auth->username;
$atmail->pop3host = $auth->pop3host;

// Print the error screen if the account has auth errors, or session timeout.
if ( $atmail->status == 1 )
	$atmail->auth_error();
if ( $atmail->status == 2 )
	$atmail->session_error();

// Load the account preferences
$atmail->loadprefs(1);

// If using the XUL interface, toggle to use the XP HTML templates
if ($atmail->LoginType == 'xul')
{
	$atmail->LoginType = 'xp';
	if (!$var['func'])
		$var['func'] = 'start';
}

if ($var['func'] != 'rename' && $var['func'] != 'delfolderxp')
	$atmail->httpheaders();

$var['languagebox'] = $atmail->languages(2);
$var['languagebox'] = str_replace("value='$atmail->Language'", "value='$atmail->Language' selected", $var['languagebox']);
$var['languagebox'] = str_replace("<select", "<select class=\"select\"", $var['languagebox']);

$mail = new GetMail(array(
  'Username' => $atmail->username,
  'Pop3host' => $atmail->pop3host,
  'Password' => $auth->password,
  'Mode'     => $atmail->Mode,
  'Type'     => $atmail->MailType)
);

// Disable EmailToFolder rules for POP3 - Not implemented until UIDL support
if($mail->MailType == 'pop3')
$pref['allow_EmailToFolderRules'] = 0;

$var['atmailstyle'] = $atmail->parse( "html/$atmail->Language/$atmail->LoginType/atmailstyle.css" );
$var['atmailstyle'] .= $atmail->parse("html/$atmail->Language/$atmail->LoginType/atmailstyle-form.css");

// now call the requested function
$func();

$atmail->end();


// Print the attachment window
function util_show()
{
	global $mail, $atmail, $var;

    $mail->login();

    $folders = $mail->listfolders();

	// sort the folders by name
	$folders = GetMail::_sort_folders($folders);

	// Create a new folder-tree element
	$mail->newfolder_tree();

	$var['SentMsgs'] = $var['InboxMsgs'] = $var['DraftsMsgs'] = $var['SpamMsgs'] = 0;

	// Disable new msg count till phase2
	//list($var['InboxMsgs'],) = $mail->showunread('INBOX');

	// Loop through each of the folders
    foreach ($folders as $folder)
    {
		if ($folder == 'Sent') {
			//list($var['SentMsgs'],) = $mail->showunread($folder);
			//$var['SentMsgs'] = 0;intval($var['SentMsgs']);
			continue;
		}

		// Mask the existing Trash folder, as the copy we want as defined via the Webadmin
		if ($folder == 'Trash') {
			//list($var['TrashMsgs'],) = $mail->showunread($folder);
			//$var['TrashMsgs'] = intval($var['TrashMsgs']);
			continue;
		}

		// Mask the existing Trash folder, as the copy we want as defined via the Webadmin
		if ($folder == 'Spam') {
			//list($var['SpamMsgs'],) = $mail->showunread($folder);
			//$var['SpamMsgs'] = intval($var['SpamMsgs']);
			continue;
		}

		// Mask the existing Trash folder, as the copy we want as defined via the Webadmin
		if ($folder == 'Drafts') {
			//list($var['DraftsMsgs'],) = $mail->showunread($folder);
			//$var['DraftsMsgs'] = intval($var['DraftsMsgs']);
			continue;
		}

		$var['xulfolder'] .= "myArray.push('$folder');\n";

		// Skip any sub-folders, we only want the base folders
		if ( strpos($folder, $mail->Deliminator) !== false )
			continue;

		// Append the folders to the $var['folders'] element to display in the template
		// Disable new msg count till phase2
		//$var['folders'] .= $mail->folder_depth($folder, $start, $folders, true, true);
		$var['folders'] .= $mail->folder_depth($folder, 'fld2', $folders, true, false);
    }

	// Take out
	$var['xulfolder'] = preg_replace('/,$/', '', $var['xulfolder']);

    echo $atmail->parse( "html/$atmail->Language/myfolders.js", $var );
}

function util_rename()
{
	global $mail, $atmail;

	$mail->login();

	$newfolder = urldecode($_REQUEST['NewFolder']);
	$newfolder = str_replace('\\', '', $newfolder);
	$curfolder = urldecode($_REQUEST['Folder']);
	
	// Rename the specified mailbox
	// We are only passed the new folders name and not its
	// full path so we need to create the full path so that it
	// is not just renamed to INBOX.newfoldername
	$del = preg_quote($mail->Deliminator, '/');
	$newfolder = preg_replace("/[^{$del}]+$/", $newfolder, $curfolder);
    $mail->renamefolder($curfolder, $newfolder);

	// Delete any message filters that match the foldername
	$sort_subject = $atmail->getsort('EmailSubject','hash' );
	foreach ($sort_subject as $k => $v)
	{
		if ($v == $_REQUEST['Folder'])
		{
			$atmail->delsort($k,'EmailSubject');
			$atmail->addsort('', $k, $newfolder);
		}
	}

	$sort_email   = $atmail->getsort('EmailAddress','hash' );
	foreach ($sort_email as $k =>$v)
	{
		if ($v == $curfolder)
		{
			$atmail->delsort($k,'EmailAddress');
			$atmail->addsort($k,'', $newfolder);
		}
	}

	header("Location: html/$atmail->Language/$atmail->LoginType/heading/mboxhead.html");
	$atmail->end();
}


function util_info()
{
	global $mail, $atmail, $var, $domains;

    $mail->login();
	$reload = false;

	// We keep the folder info in session to speed up page loading as
    // when we have large folders this can take a while. Data stays valid
    // for 15 minutes
    //if (isset($_SESSION['folderinfo']) && ($_SESSION['folderinfo']['created'] < (time() - 900))) {
    //	unset($_SESSION['folderinfo']);
    //}

	if (isset($_REQUEST['renamefolder']) && !empty($_REQUEST['curname']) && !empty($_REQUEST['foldername'])) {
		if ($_REQUEST['curname'] != 'Sent' && $_REQUEST['curname'] != 'Trash' &&
		    $_REQUEST['curname'] != 'Drafts' && $_REQUEST['curname'] != 'Spam') {
			$new_folder = $_REQUEST['foldername'];
			$mail->renamefolder(str_replace('/', $mail->Deliminator, $_REQUEST['curname']),
			                    str_replace('/', $mail->Deliminator, $new_folder));
			$reload = true;
			//$_SESSION['folderinfo'][$new_folder] = $_SESSION['folderinfo'][$_REQUEST['curname']];
			//unset($_SESSION['folderinfo'][$_REQUEST['curname']]);
		}
	}

    // The user selects to create a new mailbox
    if ( $_REQUEST['creatembox'] )
    {
		$folder = $_REQUEST['foldername'];
        $mail->newfolder($folder);

        // Add the folder to the session data if required
        //if (isset($_SESSION['folderinfo']) && !preg_match('^(inbox|spam|trash|drafts|sent)$/i', $folder)) {
        //	$_SESSION['folderinfo'][$folder]['msgs'] = 0;
        //	$_SESSION['folderinfo'][$folder]['size'] = 0;
		//}

		$reload = true;
    }

    // A folder is set to delete
    elseif ( $_REQUEST['delete'] )
    {
		$del = urldecode($_REQUEST['delete']);

		if ($_REQUEST['purge'] == 1) {
			$mail->purgefolder($del);	
		} else {
			$mail->delfolder($del);
		}

        // Update the folder data in the session if required
        //if (isset($_SESSION['folderinfo']) && preg_match('/^(inbox|spam|trash|drafts|sent)$/i', $del)) {
        //	$_SESSION['folderinfo'][$del]['msgs'] = 0;
        //	$_SESSION['folderinfo'][$del]['size'] = 0;
		//} elseif (isset($_SESSION['folderinfo'])) {
        //	unset($_SESSION['folderinfo'][$del]);
        //	unset($_SESSION['folderinfo'][$del]);
		//}


		if ($_REQUEST['purge'] != 1 && $del != 'Trash' && $del != 'Spam')
		{
			// Delete any message filters that match the foldername
			$sort_subject = $atmail->getsort( 'EmailSubject', 'hash' );
			foreach ($sort_subject as $k => $v)
			{
				if ($v == $del)
					$atmail->delsort($k, 'EmailSubject') ;
			}

			$sort_email   = $atmail->getsort( 'EmailAddress', 'hash' );
			foreach ($sort_email as $k => $v)
			{
				if ($v == $del)
					$atmail->delsort($k, 'EmailAddress');
			}
		}
		$reload = true;
    }

    // Add a new Email to the Spam List
    elseif ( $_REQUEST['spamadd'] )
        $atmail->addspamer();

    // Delete an address from the SpamList
    elseif ( $_REQUEST['spamdel'] )
        $atmail->delspamer();

    // The user is setting an autoreply . Either adding or deleting
    elseif ( $_REQUEST['addreply'] || $_REQUEST['deletereply'] )
    {
        if ( $_REQUEST['addreply'] )
        	$atmail->AutoReply = $_REQUEST['AutoReply'];
        elseif ( $_REQUEST['deletereply'] )
        	$atmail->AutoReply = '';

        $atmail->saveautoreply( $atmail->AutoReply );
    }

    // Add a new rule to the mail filters
    elseif ( $_REQUEST['addsort'] )
        $atmail->addsort();

    elseif ( $_REQUEST['delsort'] )
        $atmail->delsort( $_REQUEST['delete_sort'], $_REQUEST['type'] );

    // Find the folder names , size and number of messages
    $folders = $mail->listfolders();

	// sort the folders by name
	$folders = GetMail::_sort_folders($folders);

    // Make a select box with the foldernames
    $var['folderbox'] = $var['renamefolderbox'] = $mail->folder_select( 'Inbox', $folders, false);

    // Remove System folders from rename options
    $patterns = array("<option value=\"Trash\">Trash</option>",
                      "<option value=\"Spam\">Spam</option>",
                      "<option value=\"Drafts\">Drafts</option>",
                      "<option value=\"Sent\">Sent</option>");
    $var['renamefolderbox'] = str_replace($patterns, '', $var['renamefolderbox']);
    $var['renamefolderbox'] = '<option value="">--</option>' . $var['renamefolderbox'];

	$var['folderbox'] = str_replace("value=\"Trash\"", "value=\"Trash\" selected", $var['folderbox']);
	//$var['folderbox'] = preg_replace('/<option value="erase">.*?<\/option>/', '', $var['folderbox']);
	//$var['folderbox'] = preg_replace('/<option value="" style=\'color: gray;\'>.*?<\/option>/', '', $var['folderbox']);

	// Translate the mailbox folders into another language
	$var['folderbox'] = Language::folder_language( $var['folderbox'], $atmail->Language, null);

	list($var['usedquota'], $var['totalquota']) = $mail->getquota();

    // The size of our quota in Kb
	if (!$var['totalquota'])
	{
		$var['totalquota'] = $atmail->UserQuota;
		$var['totalquota'] = sprintf("%2.0f", $var['totalquota']);
	}

	if ($var['usedquota'] > 0 && $var['totalquota'] > 0)
	{
		$var['used'] = ( $var['usedquota'] / $var['totalquota']) * 100;

		if ($var['used'] < 1)
			$var['used'] = '1%';
		else
			$var['used'] = round($var['used'], 2) . '%';
	}

	$var['used_percent'] = $var['used']? $var['used'] : '1%';

    foreach ($folders as $folder)
    {
        // Retrieve the foldername without any / extension
		$folderlink = $mail->folder_getlink($folder);

        list( $num, $size ) = $mail->sizefolder($folderlink);

		// Get the data from the session if it exists
		//if (isset($_SESSION['folderinfo'][$folder]) && $_SESSION['folderinfo'][$folder]['msgs'] > 0) {
		//	$num = $_SESSION['folderinfo'][$folder]['msgs'];
		//	$size = $_SESSION['folderinfo'][$folder]['size'];
		//} else {
		// Implement cache function soon - Read the size for the moment
        //	list( $num, $size ) = $mail->sizefolder($folderlink);
        //	$_SESSION['folderinfo'][$folder] = array('msgs' => $num, 'size' => $size);
        //	$_SESSION['folderinfo']['created'] = time();
		//}

		// Skip Inbox for the POP3 protocol
        if ( strtoupper($folder) == 'INBOX' && !$domains[$atmail->pop3host] && $atmail->MailType == 'pop3' )
        	continue;

        // Change the display language, depending on the user language login
        $foldername = Language::folder_language( $folder, $atmail->Language, 1 );
        
        $var['folders'] .= $atmail->parse("html/$atmail->Language/$atmail->LoginType/foldertr.html", array(
          'Folder'     => $folder,
		  'FolderLink' => $folderlink,
          'FolderName' => $foldername,
          'Size'       => $size,
          'MsgNum'     => $num,
          'SystemFolder' => $mail->isAtmailFolder($folder)
        ));
    }

    // Make a select box with our list of spammers
    $var['spam_select'] = $atmail->spam_select();
    $var['sort_email']  = $atmail->getsort('EmailAddress');
    $var['sort_subj']   = $atmail->getsort('EmailSubject');


	// Translate the mailbox folders into another language
	$var['sort_email'] = $mail->folder_select_lang( $var['sort_email'], $atmail->Language, 1 );
	$var['sort_subj'] = $mail->folder_select_lang( $var['sort_subj'], $atmail->Language, 1 );


	$var['reloadFolders'] = (isset($_REQUEST['noreload']) || $reload == false) ? 'false' : 'true';

    print $atmail->parse( "html/$atmail->Language/$atmail->LoginType/folders.html", $var );
}

function util_settings()
{
	global $pref, $atmail, $var;

    if ( isset($_POST['save']) )
    {
		$previnterface = $atmail->LoginType;
		$prevlanguage = $atmail->Language;

		$atmail->savesettings();
		$atmail->loadprefs();

		if ($previnterface == 'xp' && $atmail->XUL && $atmail->LoginType != 'simple')
		{
			// Mask the current interface is using the XUL theme
			$previnterface = 'xp';
			$atmail->LoginType = 'xp';
		}

		// If the user has toggled to change the interface, reload the entire frame, otherwise just load the new settings window
		if ($previnterface != $atmail->LoginType || $atmail->Language != $prevlanguage )
		{
			// Change the users color settings, if logging into the XP interface
			if ( $atmail->LoginType == 'xp' || $atmail->LoginType == 'xul' )
			{
			    $atmail->changecolor(array(
			      'PrimaryColor'   => "#EBE9E4",
			      'SecondaryColor' => "#F4F4F4",
			      'ThirdColor'     => "#FAFAFA",
			      'HeaderColor'    => "#F5F5F5",
			      'HeadColor'      => "#06082C",
			      'BgColor'        => "#F9F9F9",
			      'TextColor'      => "#06082C",
			      'TextHeadColor'  => "#303030",
			      'LinkColor'      => "#000000",
			      'VlinkColor'     => "#000033",
			      'OnColor'        => "#F3F3F3",
			      'OffColor'       => "#FFFFFF",
			      'SelectColor'    => "#E4EEF8",
			      'TopBg'          => "imgs/graygrad.gif"
			    ));

			}
			elseif( $atmail->LoginType == 'simple' || $atmail->LoginType == 'ajax')
			{
			    $atmail->changecolor(array(
			      'PrimaryColor'   => "#EBE9E4",
			      'SecondaryColor' => "#F8FBFD",
			      'ThirdColor'     => "#FAFAFA",
			      'HeaderColor'    => "#F5F5F5",
			      'HeadColor'      => "#06082C",
			      'BgColor'        => "#F9F9F9",
			      'TextColor'      => "#06082C",
			      'TextHeadColor'  => "#303030",
			      'LinkColor'      => "#000000",
			      'VlinkColor'     => "#000033",
			      'OnColor'        => "#F3F3F3",
			      'OffColor'       => "#FFFFFF",
			      'SelectColor'    => "#FAF7F7",
			      'TopBg'          => "imgs/graygrad.gif"
			    ));
			}

			if ($atmail->XUL && $atmail->LoginType == 'xp')
			{
				$refresh = <<<EOF
<script language="JavaScript">
window.parent.location.href='parse.php?file=html/$atmail->Language/xul/xullogin.html&frame=1&XUL=1';
</script>
EOF;

			}
			elseif ($atmail->LoginType == 'simple' && $atmail->Ajax)
			{
				$refresh = <<<EOF
<script language="JavaScript">
parent.parent.location.href='parse.php?file=html/$atmail->Language/simple/showmail_interface.html&ajax=1';
</script>
EOF;

			}
			elseif ($atmail->LoginType == 'xul')
			{
				$refresh = <<<EOF
<script language="JavaScript">
window.parent.location.href='parse.php?file=html/$atmail->Language/xul/xullogin.html&frame=1&XUL=1';
</script>
EOF;

			}
			else
			{
				$refresh = <<<EOF
<script language="JavaScript">
parent.parent.location.href='parse.php?file=html/$atmail->Language/$atmail->LoginType/$atmail->LoginType.html&frame=1';
</script>
EOF;
			}

			print $refresh;
			$atmail->end();
		}
    }
    // generate pgp key
	elseif ( isset($_REQUEST['pgpsave']) )
	{
		$atmail->savesettingspgp(
			array(
				'PKIenable' => $_REQUEST['PKIenable'],
				'PGPenable' => $_REQUEST['PGPenable'],
				'PGPsign'   => $_REQUEST['PGPsign'],
				'PGPappend' => $_REQUEST['PGPappend']
				)
		);

		$atmail->loadprefs();
		if ($atmail->XUL)
			$atmail->LoginType = 'xp';
	}

	// Load the users PGP key if required
	if ($atmail->PGPenable && file_exists($pref['gpg_path']))
	{
		require_once('PGP.php');

		$userWrkDir;

		if ($atmail->MailDir)
			$userWrkDir	= $atmail->MailDir;
		else
			$userWrkDir= $atmail->tmpdir;

		$ownFile = $atmail->tmpdir . ".ht$auth->SessionID";

		$pgp = new PGP( array('wrkDir' => "$userWrkDir/pgp", 'ownFile' => $ownFile) );

		$var['PGPkey'] = $pgp->readPublickey();
	}

	$var['Tab'] 		= $_REQUEST['Tab'];

    $settings = $atmail->parse( "html/$atmail->Language/$atmail->LoginType/settings.html", $var );

	#$settings =~ s/<option value="$atmail->UserLanguage"/<option value="$atmail->UserLanguage" selected/g;

    $settings = str_replace("<option value=\"$atmail->MboxOrder\"", "<option value=\"$atmail->MboxOrder\" selected", $settings);
    $settings = str_replace("<option value=\"$atmail->EmailHeaders\"", "<option value=\"$atmail->EmailHeaders\" selected", $settings);


    if ( $atmail->TimeZone != '' )
    {
		$tz = $atmail->TimeZone;
        $settings = str_replace("<option value=\"$tz\"", "<option value=\"$tz\" selected", $settings);
    }

    $settings = str_replace("<option value=\"$atmail->MsgNum\"", "<option value=\"$atmail->MsgNum\" selected", $settings);
    $settings = str_replace("<option value=\"$atmail->FontStyle\"", "<option value=\"$atmail->FontStyle\" selected", $settings);
    $settings = str_replace("<option name='Refresh' value=\"$atmail->Refresh\"", "<option name='Refresh' value=\"$atmail->Refresh\" selected", $settings);
    $settings = str_replace("<option name='DisplayImages' value=\"$atmail->DisplayImages\"", "<option name='DisplayImages' value=\"$atmail->DisplayImages\" selected", $settings);

	// If not using the Ajax interface, preselect the Logintype in the pulldown
	if(!$atmail->Ajax)
		$settings = str_replace("<option value=\"$atmail->LoginType\"", "<option value=\"$atmail->LoginType\" selected", $settings);

	$settings = str_replace("<option value=\"$atmail->Language\"", "<option value=\"$atmail->Language\" selected", $settings);
    $settings = str_replace("<option name='LeaveMsgs' value=\"$atmail->LeaveMsgs\">Yes", "<option value=\"$atmail->LeaveMsgs\" selected>Yes", $settings);
	$settings = str_replace("<option name='LeaveMsgs' value=\"$atmail->LeaveMsgs\">No", "<option value=\"$atmail->LeaveMsgs\" selected>No", $settings);
    $settings = str_replace("<option value=\"$atmail->TimeFormat\"", "<option value=\"$atmail->TimeFormat\" selected", $settings);
	$settings = str_replace("<option value=\"$atmail->DateFormat\"", "<option value=\"$atmail->DateFormat\" selected", $settings);
	$settings = str_replace("<option value=\"$atmail->EmailEncoding\"", "<option value=\"$atmail->EmailEncoding\" selected", $settings);

	if ( $atmail->EmptyTrash )
    	$settings = str_replace('name="EmptyTrash"', 'name="EmptyTrash" checked', $settings);

    if ( $atmail->HtmlEditor )
    	$settings = str_replace('name="HtmlEditor"', 'name="HtmlEditor" checked', $settings);

    if ( $atmail->NewWindow )
    	$settings = str_replace('name="NewWindow"', 'name="NewWindow" checked', $settings);

    if ( $atmail->AutoTrash )
    	$settings = str_replace('name="AutoTrash"', 'name="AutoTrash" checked', $settings);

    if ( $atmail->Advanced )
    	$settings = str_replace('name="Advanced"', 'name="Advanced" checked', $settings);

    if ( $atmail->PGPappend )
    	$settings = str_replace('name="PGPappend"', 'name="PGPappend" checked', $settings);

	if ( $atmail->PGPsign )
		$settings = str_replace('name="PGPsign"', 'name="PGPsign" checked', $settings);

	if ( $atmail->SMIMEencrypt );
		$settings = str_replace('name="SMIMEencrypt"', 'name="SMIMEencrypt" checked', $settings);

	if ( $atmail->SMIMEsign )
		$settings = str_replace('name="SMIMEsign"', 'name="SMIMEsign" checked', $settings);

	if ( $atmail->AutoComplete )
		$settings = str_replace('name="AutoComplete"', 'name="AutoComplete" checked', $settings);

	$settings = str_replace("<option value=\"$atmail->PGPenable\">PGP", "<option value=\"$atmail->PGPenable\" selected>PGP", $settings);
	$settings = str_replace("<option value=\"$atmail->PGPenable\">S/MIME", "<option value=\"$atmail->PGPenable\" selected>S/MIME", $settings);

	$settings = preg_replace("/<option value=\"$atmail->PKIenable\">(Enabled|Disabled)/", "<option value=\"$atmail->PKIenable\" selected>\$1", $settings);
	//$settings = str_replace("<option value=\"$atmail->PKIenable\">Disabled", "<option value=\"$atmail->PKIenable\" selected>Disabled", $settings);

	if ($refresh)
		print $refresh;
	else
		print $settings;
}

// About page for @Mail - Used in XP interface
function util_about()
{
	global $atmail, $var;
    print $atmail->parse("html/$atmail->Language/about.html", array('os' => PHP_OS, 'atmailstyle' => $var['atmailstyle']));
}

function util_profile()
{
	global $atmail, $var, $pref;

    if ( $_REQUEST['save'] )
    {
        $var['status'] = $atmail->parse("html/$atmail->Language/msg/updated.html");
        $atmail->saveprofile();
    }

    $user = $atmail->getprofile();

    $settings = $atmail->parse("html/$atmail->Language/$atmail->LoginType/profile.html", array_merge($user, $var));
    $settings = str_replace("<option value=\"{$user['Gender']}\"", "<option value=\"{$user['Gender']}\" selected", $settings);
    $settings = str_replace("<option value=\"{$user['Industry']}\"", "<option value=\"{$user['Industry']}\" selected", $settings);
    $settings = str_replace("<option value=\"{$user['Occupation']}\"", "<option value=\"{$user['Occupation']}\" selected", $settings);
    $settings = str_replace("<option value=\"{$user['Country']}\"", "<option value=\"{$user['Country']}\" selected", $settings);
    $settings = preg_replace("/name=\"BirthDay\"(.*?)<option value=\"{$user['BirthDay']}\"/", 'name="BirthDay" $1'." <option value=\"{$user['BirthDay']}\" selected", $settings);
    $settings = preg_replace("/name=\"BirthMonth\"(.*?)<option value=\"{$user['BirthMonth']}\"/", 'name="BirthMonth" $1'." <option value=\"{$user['BirthMonth']}\" selected", $settings);

    print $settings;
}

function util_logout()
{
	global $atmail, $mail;

    if ( $atmail->EmptyTrash )
    {
        $mail->delfolder('Trash');
    }
    print "<html><head></head><body><script language='javascript'> location.href='index.php?func=logout'</script></body></html>";
	$atmail->end();
}


function util_imapfolders()
{
	global $mail, $atmail, $var;

	$type = $_REQUEST['type'];
	$action = $_REQUEST['action'];
	$folder = $_REQUEST['FolderFilter'];
	$foldersub = $_REQUEST['FolderFilterSub'];

	// Subscribe to the selected mailboxes
	if ($action == 'add')
	{
		$id = $_REQUEST['id'];

		if (is_array($id))
		{
		  foreach ($id as $v)
		  {
			$mail->subscribe($v);
		  }
		}

	}

	// Unsubscribe the selected mailboxes
	if ($action == 'hide')
	{
		$id = $_REQUEST['id'];

		if (is_array($id))
		{
		  foreach ($id as $v)
		  {
		    $mail->unsubscribe($v);
		  }

		}

	}

	// If using the simple interface load the message folders into
	// a single table
	if ($atmail->LoginType == 'simple')
	{
		// List all the message folders from the server
		$folders = $mail->listfolders('' , 1);

		// Print a row foreach record
		foreach ($folders as $fol)
		{
			if (!preg_match("/$folder/i", $fol) && $folder)
				continue;
			$var['imapfolders_all'] .= $atmail->parse("html/$atmail->Language/$atmail->LoginType/imapfolder_row.html", array('FolderName' => $fol));
		}

		// List the subscribed mailboxes
		$subscribe = $mail->listfolders();

		// Print a row foreach record
		foreach ($subscribe as $sub)
		{
			if (!preg_match("/$foldersub/i", $sub) && $foldersub)
				continue;
			$var['imapfolders_subscribe'] .= $atmail->parse("html/$atmail->Language/$atmail->LoginType/imapfolder_row.html", array('FolderName' => $sub));
		}

		// Print the full table containing all the message folders
		print $atmail->parse("html/$atmail->Language/$atmail->LoginType/imapfolders.html", $var);

	}

	// List the message folders for the Professional/XP interface
	elseif ($type == 'list')
	{
		$var['lsub'] = $_REQUEST['lsub'];

		// Toggle which method to show the folders ; subscribed or all folders
		if ( $var['lsub'] )
			$folders = $mail->listfolders();
		else
		{
			$folders = $mail->listfolders('', 1);
			//$subscribe = $mail->listfolders('', '');
		}

		// Open the iframe table
		print $atmail->parse("html/$atmail->Language/$atmail->LoginType/imapfolders_head.html", $var);

		// Print a row foreach record
		foreach ($folders as $fol)
		{
			if (!preg_match("/$foldersub/i", $fol) && $foldersub || !preg_match("/$folder/i", $fol) && $folder)
				continue;

			print $atmail->parse("html/$atmail->Language/$atmail->LoginType/imapfolder_row.html", array('FolderName' => $fol));
		}

		// Print the table footer
		print $atmail->parse("html/$atmail->Language/$atmail->LoginType/imapfolders_bottom.html", array('action' => $action) );

	}
	else
	{
		// Print the master imapfolders panel
		print $atmail->parse("html/$atmail->Language/$atmail->LoginType/imapfolders.html", $var);
	}

}

?>
