<?php

/**
 * rank information:
 * 0	guest / none
 * 1	user
 * 2	player
 * 3	moderator
 * 4	super_moderator
 * 5	supidupicounselor
 * 6	counselor_1
 * 7	counselor_2
 * 8	gm_counselor
 * 9	gamemaster
 * 10	elder_gamemaster
 * 11	deputy developer
 * 12	developer
 * 13	co_admin
 * 14	admin
 */

class Account
{
	var $ID 					= 0;

    var $bb_useraccount			= array();

    var $access 				= array();

    var $flag_field				= array( 'show_email',
                                         'get_newsletter',
                                         'block',
                                         'activation'
                                       );
	var $access_flag_field	= array( 'root',
                                         'files',
                                         'templates',
                                         'screenshots',
                                         'faq',
                                         'library',
                                         'applications',
                                         'patcher',
					 'wep',
					 'teamspeak',
					 'gamesys',
					 'activation',
					 'charadministration', // administrate chars 
					 'viewchars',  // view char details and use searchfunction; subset of charadministration
					 'testserver',
					 'accounts_admin_restricted',
					 'questitems_authorisieren',
					 'testserver',
					 'logs',
					 'questcharadministration', // create questchars and allow questcharmanipulation
					 'badguys', // Aktenschrank
					 'miete', // Mieterübersicht
					 'vendoren', // Vendoren & Verkaufslisten
					 'npcs', 
					 'rohstoffe',
					 'spawns',
					 'enginequests'
                                       );

    var $ranknames		= array( 'Gast',
    					 'Benutzer',
                                         'Spieler',
                                         'Moderator',
                                         'Super-Moderator',
                                         'Berater',
                                         'Counselor-I',
                                         'Counselor-II',
                                         'GM-Counselor',
                                         'GameMaster',
                                         'Elder-GameMaster',
                                         'Stv. Developer',
                                         'Developer',
                                         'Co-Administrator',
                                         'Administrator'
                                       );

    var $groups					= array( 'Keine',
                                         'Administratoren',
                                         'Homepage/Grafik',                                         
                                         'Weltenbau',
                                         'Support',
                                         'Quest',
                                         'Technik',
                                         'Spielsystem',
                                         'Testteam',
                                         'Sonstiges'
                                       );

    var $fields					= array();

    function Account( $account, $new_account = false )
    {
        global $MySQL;
        static $fields;

        $this->fields =& $fields;
        if( $this->fields == null || ( is_array( $this->fields ) && count( $this->fields ) == 0 ) )
        	$this->init_fields();

        if( !$new_account )
        {
        	if( is_int( $account ) )
	            $account_info = $MySQL->query_first( sprintf("SELECT * FROM server.accounts WHERE accountid= %d", $account), MYSQL_ASSOC );
	        elseif( is_string( $account ) )
	            $account_info = $MySQL->query_first( sprintf("SELECT * FROM server.accounts WHERE name='%s'", me_escape($account)), MYSQL_ASSOC );

	        elseif( !$new_account )
	            return;
	            
        	if( is_empty( $account_info['accountid'] ) )
        		return;

        	foreach( $this->fields as $field )
	        {
	            //if( isset( $account_info[$field['name']] ) )
	                //eval( '$this->'.$field['name'].' = stripslashes( $account_info[\''.$field['name'].'\'] );' );
	                $this->$field['name'] = stripslashes( $account_info[$field['name']] );
	        }

	        $this->ID = $this->accountid;

	        $i = 0;
	        foreach( $this->flag_field as $flag_name )
	        {
	            //eval( '$this->'.$flag_name.' = $this->get_flag( '.$i.' );' );
	            $this->$flag_name = $this->get_flag( $i );
	            $i++;
	        }

	        $i = 0;
	        foreach( $this->access_flag_field as $access_flag_name )
	        {
	            //eval( '$this->access[\''.$access_flag_name.'\'] = $this->get_flag( '.$i.', true );' );
	            $this->access[$access_flag_name] = $this->get_flag( $i, true );
	            $i++;
	        }

	        $this->get_bbuserinfo();
        }
        else
        {
        	$this->flags = 0;
            $this->access_flags = 0;
        }
    }

    function refresh_wbb_access()
    {
        global $settings, $MySQL, $n;       

        $wbb_db = $settings['wbb_db'];

        if( $this->bb_userid <= 0 || empty( $this->bb_userid ) )
        	return;

        $access = array();

        foreach( explode( ",", $this->wbb_access ) as $board )
        {
        	$access[] = intval( trim( $board ) );
        }

        if( $this->rank == 6 || $this->rank == 7 || $this->rank == 8 || $this->rank == 9 )
        {
        	switch( $this->group )
            {
            	default:
                case 0:
                	break;
                case 2:
                // HP/Grafik
                	array_push( $access, 61, 62, 125, 66, 67, 116, 117 ); break;
                case 3:
                //Weltenbau
                	array_push( $access, 58, 103, 104, 120, 121, 65, 105, 106 ); break;
                case 4:
                // Support
                	array_push( $access, 129, 132 ); break;
                case 5:
                // Quest
                	array_push( $access, 63, 133, 134, 139 ); break;
                case 6:
                // Technik
                	array_push( $access, 59, 60, 123 ); break;
                case 7:
                // Spielsystem
                	array_push( $access, 71 ); break;
                case 8:
                // Testteam
                	array_push( $access, 128 ); break;
            }
        }

        $access = array_unique( $access );

        $MySQL->query( sprintf("DELETE FROM %s.bb%d_access WHERE userid = %d", $wbb_db, $n, $this->bb_userid ));

        $i = 0;
        foreach( $access as $board )
        {
            if( $board != 0 )
            {
            	$MySQL->query( sprintf("INSERT INTO %s.bb%d_access (boardid,userid,can_view_board, can_enter_board, can_read_thread, can_start_topic, can_reply_topic, can_use_search) VALUES (%d,%d, 1, 1, 1, 1, 1, 1)", $wbb_db, $n, $board, $this->bb_userid ));
        		$i++;
            }
        }

       	$MySQL->query( sprintf("UPDATE %s.bb%d_users SET useuseraccess = ".( ( $i > 0 ) ? '1' : '0' )." WHERE userid = %d", $wbb_db, $n, $this->bb_userid ));
    }

    function refresh_wbb_groupdata()
	{
	    global $settings, $MySQL, $n;

        $wbb_db = $settings['wbb_db'];

        if( $this->bb_userid <= 0 || empty( $this->bb_userid ) )
        	return;

        $groupids = array();

        if( $this->access['root'] )
                array_push( $groupids, 16 );

        switch( $this->rank )
        {
            case 2:
                array_push( $groupids, 8 ); break;
            case 3:
                array_push( $groupids, 3 ); break;
            case 4:
                array_push( $groupids, 2 ); break;
            case 5:
                array_push( $groupids, 22 ); break;
            case 6:
            case 7:
                array_push( $groupids, 9 ); $title = "Counselor (".$this->groups[$this->group].")"; break;
            case 8:
                array_push( $groupids, 17 ); $title = "GM-Counselor (".$this->groups[$this->group].")"; break;
            case 9:
                array_push( $groupids, 11 ); $title = "GameMaster (".$this->groups[$this->group].")"; break;
            case 10:
                array_push( $groupids, 12 ); $title = "EGM (".$this->groups[$this->group].")"; break;
            case 11:
                array_push( $groupids, 13 ); $title = "Stv. Developer (".$this->groups[$this->group].")"; break;
            case 12:
                array_push( $groupids, 13 ); $title = "Developer (".$this->groups[$this->group].")"; break;
            case 13:
                array_push( $groupids, 1, 16 ); $title = "Co-Administrator"; break;
            case 14:
                array_push( $groupids, 1, 16 ); break;
        }

        reset( $groupids );

        if( isset( $title ) && $title != '' )
            $MySQL->query( sprintf("UPDATE %s.bb%d_users SET title = '%s' WHERE userid = %d", $wbb_db, $n, $title, $this->bb_userid ));
        else
            $MySQL->query( sprintf("UPDATE %s.bb%d_users SET title = '' WHERE userid = %d", $wbb_db, $n, $this->bb_userid ));

        require_once( '../wbb2/acp/lib/functions_me.php' );
        change_groupcomb( $this->bb_userid, $groupids );
	}

    function init_fields()
    {
        global $MySQL;

        $fields = array();


        $mysql_fields = mysql_list_fields( 'server', 'accounts', $MySQL->conn_id );
  
        mysql_list_fields('web', 'applications', $MySQL->conn_id );
	    $columns = mysql_num_fields( $mysql_fields );


	    for ($i = 0; $i < $columns; $i++)
        {
        	$field = array();
            $field_name = mysql_field_name( $mysql_fields, $i );
            $field['name'] = $field_name;
            $flags = explode( " ", mysql_field_flags( $mysql_fields, $i ) );
            $field['not_null'] = in_array( "not_null", $flags );
            $field['auto_increment'] = in_array( "auto_increment", $flags );
            $field['type'] = mysql_field_type( $mysql_fields, $i );
            $fields[$field_name] = $field;
        }

        $this->fields = $fields;
    }

    function get_bbuserinfo()
    {
        global $MySQL, $n, $settings;

        if( $this->bb_userid > 0 )
        {
        	$bb_account = $MySQL->query_first( sprintf("SELECT * FROM %s.bb%d_users WHERE userid = %d", $settings['wbb_db'], $n, $this->bb_userid ));

            if( $bb_account['blocked'] == 1 || $bb_account['activation'] != 1 )
            {
            	$this->bb_userid = 0;
                $this->save( 'bb_userid' );
            }
            else
            	$this->bb_useraccount = $bb_account;
        }
    }

    function get_flag( $index, $access_flag = false )
    {
        if( $access_flag )
        	return ( $this->access_flags & ( 1 << $index ) ) != 0;
        else
        	return ( $this->flags & ( 1 << $index ) ) != 0;
    }

    function set_flag( $index, $value, $access_flag = false )
    {
        if( $access_flag )
        {
            if ( $value )
	            $this->access_flags |= ( 1 << $index );
	        else
	            $this->access_flags &= ~( 1 << $index );
        }
        else
        {
        	if ( $value )
	            $this->flags |= ( 1 << $index );
	        else
	            $this->flags &= ~( 1 << $index );
        }
    }

    function update_flags()
    {
        reset( $this->flag_field );
        for( $i = 0; $i < count( $this->flag_field ); $i++ )
        {
            //eval( 'if( isset( $this->'.current( $this->flag_field ).' ) ) $this->set_flag( '.$i.', $this->'.current( $this->flag_field ).' );' );
            $currflag = current( $this->flag_field );
            if( isset( $this->$currflag ) ) $this->set_flag( $i, $this->$currflag);

            next( $this->flag_field );
        }

        reset( $this->access_flag_field );
        for( $i = 0; $i < count( $this->access_flag_field ); $i++ )
        {
            //eval( 'if( isset( $this->access[\''.current( $this->access_flag_field ).'\'] ) ) $this->set_flag( '.$i.', $this->access[\''.current( $this->access_flag_field ).'\'], true );' );
            $currflag = current( $this->access_flag_field );
            if( isset( $this->access[$currflag] ) ) $this->set_flag( $i, $this->access[$currflag], true );

            next( $this->access_flag_field );
        }
    }

    function check_access( $password )
    {
        return ( ( $this->password == $password ) && ( $this->activation == 1 ) && ( $this->block == 0 ) );
    }

    function can_access( $module )
    {
    	if( $this->access['root'] )
        	return true;

        switch( $module )
        {
            case 'accounts_admin':
            case 'settings_admin':
            case 'user_gallery_comments':
            	return ( $this->rank >= 13 ); break;
            case 'betastatus_admin':
            case 'send_message':
            case 'user_gallery_admin':
            	return ( $this->rank >= 10 ); break;
	    	case 'wep_admin':
				return ( $this->rank >= 11 || $this->access['wep'] ); break;
            case 'files':
            	return ( $this->rank >= 5 || $this->access['files'] ); break;
            case 'screenshots_admin':
            	return ( $this->rank >= 11 || $this->access['screenshots'] ); break;
            case 'faqs_admin':
            	return ( $this->rank >= 11 || $this->access['faq'] ); break;
            case 'applications_view':
            	return ( $this->rank >= 10 ); break;
            case 'templates_admin':
            	return ( $this->rank >= 13 || $this->access['templates'] ); break;
            case 'library':
            	return ( $this->rank >= 11 || $this->access['library'] ); break;
            case 'applications':
            	return ( $this->rank >= 11 || $this->access['applications'] ); break;
            case 'patcher':
            	return ( $this->rank >= 13 || $this->access['patcher'] ); break;
            case 'stafflist_intern':
            	return ( $this->rank >= 3 ); break;
            case 'status':
            	return ((($this->group == 4 || $this->group == 5) && $this->rank >= 5) || $this->rank >= 9); break;
            case 'staff':
            	return ( $this->rank >= 5 ); break;
            case 'teamspeak':
            	return ( $this->rank >= 3 || $this->access['teamspeak'] ); break;
            case 'gamesys':
            	return ( $this->access['gamesys'] ); break;
            case 'activation':
            	return ( $this->rank >= 13 || $this->access['activation'] ); break;
            case 'accounts_admin_restricted':
            	return ( $this->access['accounts_admin_restricted'] || $this->access['accounts_admin']); break;
            case 'questitems_authorisieren':
            	return ( $this->access['questitems_authorisieren'] ); break;
            case 'testserver':
            	return ( $this->rank >= 10 || $this->access['testserver'] ); break;
            case 'logs':
            	return ( $this->rank >= 10 || $this->access['logs'] ); break;
            case 'charadministration':
            	return($this->access['charadministration'] || $this->rank >= 11);
            	break;
            case 'viewchars':
            	return($this->access['charadministration'] || $this->access['viewchars'] || $this->rank >= 9);
            	break;
            case 'questcharadministration':
            	return($this->access['questcharadministration'] || $this->rank >= 11);
            	break;
            case 'badguys':
            	return($this->access['badguys'] || $this->rank >= 11);
				case 'miete':
					return($this->access['miete'] || $this->rank >= 11);
				case 'vendoren':
					return($this->access['vendoren'] || $this->rank >= 11);
				case 'npcs':
					return($this->access['npcs'] || $this->rank >= 11);
				case 'spawns':
					return($this->access['spawns'] || $this->rank >= 11);
				case 'rohstoffe': 
					return($this->access['rohstoffe'] || $this->rank >= 11);
				case 'enginequests':
					return($this->access['enginequests'] || $this->rank >= 11);
            default:
            	return false; break;
        }
    }

    function insert()
    {
    	global $MySQL;

        $this->update_flags();

        if( isset( $this->icq ) && $this->icq > 0 )
        	$icq = $this->icq;
        else
        	$icq = "NULL";

        $MySQL->query( sprintf("INSERT INTO server.accounts (name, password, email, icq, flags, access_flags, style_id, register_time, rank, max_characters )
        				VALUES ( '%s', '%s', '%s', %d, %d, %d, %d, ".time().", %d, 3 )"
        				, me_escape( $this->name ), $this->password, me_escape( $this->email ), $icq, $this->flags, $this->access_flags, $this->style_id, $this->rank ));

        $this->ID = $MySQL->insert_id();
    }

    function save()
    {
        global $MySQL, $settings;
		
        $this->update_flags();
        
        $row = $MySQL->query_first( sprintf("SELECT name FROM server.accounts WHERE accountid=%d", $this->ID ));
        $oldname = $row['name'];
        
        $save_array = array();
        $tosave = array();

        if( func_num_args() > 0 )
        {
            for( $i = 0; $i < func_num_args(); $i++ )
    		{
            	if( isset( $this->fields[func_get_arg( $i )] ) )
            	{
                    $tosave[] = func_get_arg( $i );
            	}  
            }
        }
        else {
        	// wir speichern alles und nicht nur bestimmte Felder
            foreach( $this->fields as $field )
                $tosave[] = $field['name'];
        }   
            
        // hier auch Teamspeak sichern
        
        $tspath = $settings['teamspeak_path'];
        
	    if( strlen($tspath) > 0 )
	    {
          $dbhandle = sqlite_open( $tspath, 0666, $error );
	          	
		  if( !$error )
		  {
		  	$res = sqlite_query( $dbhandle, "SELECT COUNT(*) FROM ts2_clients WHERE s_client_name='".$this->name."' LIMIT 1" );
    		$count = intval( sqlite_fetch_single( $res ) );
			  	
		  	if( $this->can_access( 'teamspeak' ) )
		  	{		  		  			
				if( $count > 0 )
				{				
					$tsadmin = 0;
					
					if( $this->group == 1)
					{
						$tsadmin = -1;
					}
					
					sqlite_query( $dbhandle, "UPDATE ts2_clients SET b_client_privilege_serveradmin='".$tsadmin."' WHERE s_client_name='".$this->name."'" );
				}	
		  	}
		  	else
		  	{
		  		if( $count > 0 )
		  		{
		  			sqlite_query( $dbhandle, "DELETE FROM ts2_clients WHERE s_client_name='".$this->name."'" );	
		  		}
		  	}
    		sqlite_close( $dbhandle );
		  }
	    }

        if( count( $tosave ) > 0 )
        {
            foreach( $tosave as $savefield )
            {
                $value = $this->$savefield;
                	
                if( (!$this->fields[$savefield]['not_null']) && is_string( $value ) && empty( $value ) ) //|| ( is_int( $value ) && $value == 0 ) ) )
                {
                    $value = null;
                }               
                           
                if( is_int( $value ) )
                	$save_array[] = sprintf(' `%s` = \'%d\'', $savefield, $value);     
                else if( $value == null )
                	$save_array[] = sprintf(' `%s` = null', $savefield);
                else
                	$save_array[] = sprintf(' `%s` = \'%s\'', $savefield, me_escape($this->$savefield));

            }
            
            $sql_set_string = implode( ',', $save_array );
            $MySQL->query( sprintf("UPDATE server.accounts SET %s WHERE accountid = %d", $sql_set_string, $this->ID) );
        }
    }
}

?>
