<?php

include './core.php';

if( !isset( $user ) || (!$user->can_access( 'accounts_admin' ) && !$user->can_access('accounts_admin_restricted')) ) access_error();

if( isset( $_REQUEST['edit_account'] ) )
{
    
	
	$Smarty->assign( 'block_opts', Array( 'Nein', 'Ja' ) );
    $Smarty->assign( 'activation_opts', Array( 'Nein', 'Ja' ) );

    $formvalues_assigned = false;

    $eaccount = new Account( (int) intval( $_REQUEST['edit_account'] ) );
	$Smarty->assign( 'eaccount', $eaccount );
	
	if(!$user->can_access( 'accounts_admin' ) && $eaccount->rank >= $user->rank)
		access_error();

    if( isset( $_POST['send_form'] ) )
    {
        $form_errors = array();

	    if( !check_fields( 'name', 'email', 'style', 'block', 'activation', 'rank', 'group' ) )
	        $form_errors[] = form_error( 'uncomplete' );
	    else
	    {
            if( strlen( $_POST['name'] ) > 20 )
            	$form_errors[] = form_error( 'toolong_name' );
            if( strlen( $_POST['email'] ) > 150 || strlen( $_POST['intern_email'] ) > 150 )
            	$form_errors[] = form_error( 'toolong_email' );
            if( !eregi( '@' , $_POST['email'] ) || !eregi( '.' ,$_POST['email'] ) )
	            $form_errors[] = form_error( 'unvalid_email' );
            if( strlen( $_POST['icq'] ) > 12 || strlen( $_POST['intern_icq'] ) > 12 )
            	$form_errors[] = form_error( 'toolong_icq' );
            if( strlen( $_POST['away_msg'] ) > 255 )
            	$form_errors[] = form_error( 'toolong_away_msg' );

            if( stripslashes( $_POST['name'] ) != $eaccount->name )
            {
            	list( $ncount ) = $MySQL->query_first( sprintf("SELECT COUNT(*) FROM server.accounts WHERE name = '%s'", me_escape($_POST['name'])) );
            	if( $ncount > 0 )
                	$form_errors[] = form_error( 'name_chosen_already' );
            }
            
            if(!$user->can_access( 'accounts_admin' ) && intval($_REQUEST['rank']) >= $user->rank)
            	$form_errors[] = form_error( 'accounts_admin_restricted' );
	    }

        $access_data = array();
        foreach( $eaccount->access_flag_field as $field )
        {
            $thisfield = false;

            if( isset( $_POST['access'] ) )
            {
            	foreach( $_POST['access'] as $row )
	            {
	                if( $row == $field )
	                    $thisfield = true;
	            }
            }

            $access_data[$field] = $thisfield;
        }
        $_REQUEST['access'] = $access_data;
        
        if(!$user->can_access( 'accounts_admin' ) && ((!$eaccount->access['root'] && $_REQUEST['access']['root']) || ($eaccount->access['root'] && !$_REQUEST['access']['root'])))
        	$form_errors[] = form_error( 'accounts_admin_restricted' );
        	
        if(!$user->can_access( 'accounts_admin' ) && ((!$eaccount->access['accounts_admin_restricted'] && $_REQUEST['access']['accounts_admin_restricted']) || ($eaccount->access['accounts_admin_restricted'] && !$_REQUEST['access']['accounts_admin_restricted'])))
        	$form_errors[] = form_error( 'accounts_admin_restricted' );

	    if( count( $form_errors ) > 0 )
	    {
            $Smarty->assign( 'form_errors', $form_errors );
            assign_formvalues( 'name', 'email', 'show_email', 'icq', 'get_newsletter', 'style', 'away_msg', 'block', 'activation', 'rank', 'group', 'access', 'intern_email', 'intern_icq' );
        	$formvalues_assigned = true;
        }
	    else
	    {
        	$bbgc = false;

            $eaccount->name				= $_POST['name'];
            $eaccount->email			= $_POST['email'];
            $eaccount->show_email		= ( isset( $_POST['show_email'] ) && $_POST['show_email'] == "1" );
            $eaccount->icq				= $_POST['icq'];
            $eaccount->get_newsletter	= ( isset( $_POST['get_newsletter'] ) && $_POST['get_newsletter'] == "1" );
            $eaccount->style_id			= intval( $_POST['style'] );
            $eaccount->away_msg			= $_POST['away_msg'];
            $eaccount->block			= ( $_POST['block'] == "1" );
            $eaccount->gs_block			= intval( $_POST['block'] );

            if( $_POST['activation'] == "1" && !$eaccount->activation )
            {
            	$eaccount->activation = true;
                $MySQL->query( sprintf("DELETE FROM account_activation_codes WHERE accountid = %d", $eaccount->ID ));
            }
            elseif( $_POST['activation'] == "0" && $eaccount->activation )
            	$eaccount->activation = false;

            if( $eaccount->rank != intval( $_POST['rank'] ) )
            {
            	$eaccount->rank				= intval( $_POST['rank'] );
                $bbgc = true;
            }

            if( $eaccount->group != intval( $_POST['group'] ) )
            {
            	$eaccount->group			= intval( $_POST['group'] );
                $bbgc = true;
            }

            $eaccount->access			= $_REQUEST['access'];
            $eaccount->intern_email		= $_POST['intern_email'];
            $eaccount->intern_icq		= $_POST['intern_icq'];

            if( !isset( $_POST['wbb_access'] ) || $eaccount->wbb_access != $_POST['wbb_access'] )
            {
                if( !isset( $_POST['wbb_access'] ) )
                	$eaccount->wbb_access = '';
                else
                	$eaccount->wbb_access		= $_POST['wbb_access'];

                if( !$bbgc )
                	$eaccount->refresh_wbb_access();
            }

            if( isset( $_POST['delete_user_picture'] ) && $_POST['delete_user_picture'] == '1' )
            {
            	$rem_picture = $MySQL->query_first( sprintf("SELECT * FROM user_pictures WHERE accountid = %d", $eaccount->ID ));
	            $imgurl = combine_path( $settings['user_gallery_dir'], $rem_picture['accountid'].'.'.$rem_picture['extension'] );
	            unlink( $imgurl );
                $MySQL->query( sprintf("DELETE FROM user_pictures WHERE accountid = %d", $eaccount->ID ));
            }

            if( $bbgc )
            {
            	$eaccount->refresh_wbb_access();
            	$eaccount->refresh_wbb_groupdata();
            }

            // TODO: RunUO Account-Optionen speichern

            $eaccount->save( 'flags', 'access_flags', 'name', 'email', 'icq', 'style_id', 'away_msg', 'rank', 'group', 'intern_email', 'intern_icq', 'wbb_access', 'gs_block' );

            // Charaktereinstellungen speichern
            
            //$MySQL->query( "START TRANSACTION" );
/* von Arahil entfernt, weil lästig und fehleranfällig
            $result = $MySQL->fetch_complete( sprintf("SELECT chartype, COUNT(*) as zahl FROM server.chars WHERE accountid = %d AND aktiviert != 9 AND testserver = 0 GROUP BY chartype", intval($eaccount->ID)), true);
            $anum_playerchars = $result['player']['zahl'];
            $anum_questchars = $result['quest']['zahl'];
            $anum_staffchars = $result['staff']['zahl'];
            
            // Überprüfe, ob neue Einstellung weniger Charaktere zulässt, als aktuell auf dem Account => keine Änderungen vornehmen
            	if($anum_playerchars > intval($_POST['player_chars']) || $anum_staffchars > intval($_POST['staff_chars'])) {
            		//$MySQL->query( "ROLLBACK");
            		$form_errors[] = "Charaktereinstellungen wurden nicht gespeichert! Mehr Charaktere vorhanden, als erlaubt. Pr&uuml;fen und ggf. l&ouml;schen!";
            		$Smarty->assign( 'form_errors', $form_errors );
            	}
            // Überprüfe, ob Anzahl zulässiger Charaktere > 5 => keine Änderungen vornehmen
				elseif($anum_questchars + intval($_POST['player_chars']) + intval($_POST['staff_chars']) > 5) {
					//$MySQL->query( "ROLLBACK");
					$form_errors[] = "Charaktereinstellungen wurden nicht gespeichert! Maximal 5 Charaktere zul&auml;ssig";					
					$Smarty->assign( 'form_errors', $form_errors );
				}
				else {
*/
					// speichern
					$MySQL->query( sprintf("UPDATE server.accounts SET max_characters = %d, max_staffcharacters = %d WHERE accountid = %d", intval($_POST['player_chars']), intval($_POST['staff_chars']), intval($eaccount->ID) ));	
					//$MySQL->query( "COMMIT");
// 				}
            
            $Smarty->assign( 'saved', true );
        }
    }
    elseif( isset( $_POST['delete_user'] ) )
    {
    	$dbhandle = sqlite_open( $settings['teamspeak_path'], 0666, $error );	
		if( $error )
		{
			exit( $error );
		}
			
  		$res = sqlite_query( $dbhandle, "SELECT COUNT(*) FROM ts2_clients WHERE s_client_name='".$eaccount->name."' LIMIT 1" );
  		$count = intval( sqlite_fetch_single( $res ) );
		if( $count > 0 )
		{				
			sqlite_query( $dbhandle, "DELETE FROM ts2_clients WHERE s_client_name='".$eaccount->name."'" );
		}
		
		sqlite_close( $dbhandle );
    	
    	$MySQL->query( sprintf("DELETE FROM server.accounts WHERE accountid = %d", $eaccount->ID ));
        $MySQL->query( sprintf("DELETE FROM user_pictures WHERE accountid = %d", $eaccount->ID ));
        $MySQL->query( sprintf("DELETE FROM user_locations WHERE accountid = %d", $eaccount->ID ));
        $MySQL->query( sprintf("DELETE FROM messages WHERE receiver = %d", $eaccount->ID ));

        set_location( 'accounts_admin.php?'.SID );
    }

    if( !$formvalues_assigned )
    {
	    $formvalues = array();
	    $formvalues['name']             = $eaccount->name;
	    $formvalues['email']            = $eaccount->email;
	    $formvalues['show_email']       = $eaccount->show_email;
	    $formvalues['icq']              = $eaccount->icq;
	    $formvalues['get_newsletter']   = $eaccount->get_newsletter;
	    $formvalues['style']            = $eaccount->style_id;
	    $formvalues['away_msg']         = $eaccount->away_msg;
	    $formvalues['block']            = $eaccount->block ? '1' : '0';
	    $formvalues['activation']       = $eaccount->activation ? '1' : '0';
	    $formvalues['rank']             = $eaccount->rank;
	    $formvalues['group']            = $eaccount->group;
	    $formvalues['access']           = $eaccount->access;
	    $formvalues['intern_email']     = $eaccount->intern_email;
	    $formvalues['intern_icq']       = $eaccount->intern_icq;
        $formvalues['wbb_access']		= $eaccount->wbb_access;    
	    
        list($formvalues['player_chars'])	= $MySQL->query_first( sprintf("SELECT max_characters FROM server.accounts WHERE accountid = %d",intval($eaccount->ID) ));
	    list($formvalues['staff_chars'])	= $MySQL->query_first( sprintf("SELECT max_staffcharacters FROM server.accounts WHERE accountid = %d",intval($eaccount->ID) ));
		
	    $Smarty->assign( 'formvalues', $formvalues );
	}

    $user_picture = $MySQL->query_first( sprintf("SELECT accountid FROM user_pictures WHERE accountid = %d", intval($eaccount->ID) ));
    $Smarty->assign( 'no_user_picture', !( $user_picture['accountid'] > 0 ) );

    $Smarty->assign( 'char_dropdown', array(0,1,2,3,4,5));
    $Smarty->assign( 'num_playerchars', $MySQL->query_first( sprintf("SELECT COUNT(*) FROM server.chars WHERE accountid = %d AND chartype = 'player'", intval($eaccount->ID) )));
    $Smarty->assign( 'num_questchars', $MySQL->query_first( sprintf("SELECT COUNT(*) FROM server.chars WHERE accountid = %d AND chartype = 'quest'",  intval($eaccount->ID) )));
    $Smarty->assign( 'num_staffchars', $MySQL->query_first( sprintf("SELECT COUNT(*) FROM server.chars WHERE accountid = %d AND chartype = 'staff'", intval($eaccount->ID)  )));
    
    $page['content'] = $Smarty->fetch( 'accounts_admin_form.tpl' );

	$Smarty->assign( 'page', $page );
	$Smarty->display( 'main.tpl' );
}
elseif( isset( $_REQUEST['change_boardlink'] ) )
{
    $eaccount = new Account( (int) intval( $_REQUEST['change_boardlink'] ) );
	$Smarty->assign( 'eaccount', $eaccount );
	
	if(!$user->can_access( 'accounts_admin' ) && $eaccount->rank >= $user->rank)
		access_error();

    if( isset( $_POST['send_form'] ) )
    {
        $form_errors = array();

	    if( !check_fields( 'bb_username' ) )
	        $form_errors[] = form_error( 'uncomplete' );
        else
        {
            $bb_account = $MySQL->query_first( sprintf("SELECT userid, password, blocked, activation FROM %s.bb%d_users WHERE username='%s'", $settings['wbb_db'], $n, me_escape( $_POST['bb_username'] )) );

            if( $bb_account['userid'] > 0 )
            {
            	if( $bb_account['blocked'] == 1 || $bb_account['activation'] != 1 )
                	$form_errors[] = form_error( 'bad_bbuser' );

                list( $userlinks ) = $MySQL->query_first( sprintf("SELECT COUNT(*) FROM server.accounts WHERE bb_userid = %d", $bb_account['userid'] ));
        		if( $userlinks > 0 )
            		$form_errors[] = form_error( 'bb_already_linked' );
            }
            else
            	$form_errors[] = form_error( 'no_bbuser' );
        }

	    if( count( $form_errors ) > 0 )
	    {
	        $Smarty->assign( 'form_errors', $form_errors );
	    }
	    else
	    {
            $eaccount->bb_userid = $bb_account['userid'];
            $eaccount->refresh_wbb_access();
            $eaccount->refresh_wbb_groupdata();
            $eaccount->save( 'bb_userid' );

            display_message( 'bbedit_success', false );
        }

        assign_formvalues( 'bb_username' );
    }

    if( isset( $_POST['delete_link'] ) )
    {
    	if( $eaccount->bb_userid > 0 )
        {
        	resetWBBAccount( $eaccount->bb_userid );
            $eaccount->bb_userid = 0;
        	$eaccount->save( 'bb_userid' );

            display_message( 'bbdelete_success', false );
        }
    }

    $Smarty->display( 'accounts_admin_change_boardlink.tpl' );
}
elseif( isset( $_REQUEST['change_password'] ) )
{
    $eaccount = new Account( (int) intval( $_REQUEST['change_password'] ) );
	$Smarty->assign( 'eaccount', $eaccount );
	
	if(!$user->can_access( 'accounts_admin' ) && $eaccount->rank >= $user->rank)
		access_error();

    if( isset( $_POST['send_form'] ) )
    {
        $form_errors = array();

	    if( !check_fields( 'new_password', 'new_password_ver' ) )
	        $form_errors[] = form_error( 'uncomplete' );
        else
        {
            if( $_POST['new_password'] != $_POST['new_password_ver'] )
            	$form_errors[] = form_error( 'password_nomatch' );
        }

	    if( count( $form_errors ) > 0 )
	    {
	        $Smarty->assign( 'form_errors', $form_errors );
	    }
	    else
	    {
            $eaccount->password = md5( $_POST['new_password'] );
            $eaccount->save( 'password' );

            display_message( 'passwordchange_success', false );
        }
    }

    $Smarty->display( 'accounts_admin_change_password.tpl' );
}
else
{
    $Smarty->assign('can_access_all', $user->can_access('accounts_admin'));
	
	if( isset( $_POST['send_form'] ) )
    {
        $form_errors = array();

        if( isset( $_POST['sid'] ) )
            $nofields = ( count( $_POST ) < 3 );
        else
        	$nofields = ( count( $_POST ) < 2 );

        if( $nofields )
        	$form_errors[] = form_error( 'no_searchfields' );

        if( count( $form_errors ) > 0 )
	    {
	        $Smarty->assign( 'form_errors', $form_errors );
	    }
	    else
	    {
        	$search_conditions = array();

            if( check_fields( 'name' ) )
            	$search_conditions[] = sprintf("`name` LIKE '%s'", me_escape( $_POST['name'] ));
            if( check_fields( 'email' ) )
            	$search_conditions[] = sprintf("`email` LIKE '%s'", me_escape( $_POST['email'] ));
            if( check_fields( 'icq' ) )
            	$search_conditions[] = sprintf("`icq` LIKE '%s'", me_escape($_POST['icq']));
            if( check_fields( 'rank' ) )
            	$search_conditions[] = sprintf("`rank` = %d", intval( $_POST['rank'] ));
            if( check_fields( 'group' ) )
            	$search_conditions[] = sprintf("`group` = %d", intval( $_POST['group'] ));

            $search_conditions[] = 1;
            $search_condstring = implode( ' &&', $search_conditions );

            $result_accounts = $MySQL->fetch_complete( sprintf("SELECT accountid, name, email, icq, `group`, rank FROM server.accounts WHERE %s ORDER BY name", $search_condstring ));

            $Smarty->assign( 'result_accounts', $result_accounts );

            $page['content'] = $Smarty->fetch( 'accounts_admin_searchresults.tpl' );
        }
    }
    else if(isset($_REQUEST['extrausers_hp'])) {
		$result_accounts = $MySQL->fetch_complete( "SELECT accountid, name, email, icq, `group`, rank FROM server.accounts WHERE (access_flags IS NOT NULL AND access_flags > 0) ORDER BY name" );
        $Smarty->assign( 'result_accounts', $result_accounts ); 
    	
    	$page['content'] = $Smarty->fetch( 'accounts_admin_searchresults.tpl' );
	}
	else if(isset($_REQUEST['extrausers_board'])) {
		$result_accounts = $MySQL->fetch_complete( "SELECT accountid, name, email, icq, `group`, rank FROM server.accounts WHERE (wbb_access IS NOT NULL AND wbb_access!='') ORDER BY name" );
        $Smarty->assign( 'result_accounts', $result_accounts ); 
    	
    	$page['content'] = $Smarty->fetch( 'accounts_admin_searchresults.tpl' );
	}
    else
    {
    	$page['content'] = $Smarty->fetch( 'accounts_admin_search.tpl' );
    }

	$Smarty->assign( 'page', $page );
	$Smarty->display( 'main.tpl' );
}

?>