<?php


    # Account editing
    


    # login
    include_once 'data_connect.php';
    include_once 'log.php';
    


    # user rights - admins only
    if (get_account($_SESSION['userID'])['rights'] != 'administrator') {
        header('Location:opensaved.php');
        exit();
    }
    


    # user rights - owner only can access own account edit page
    if (isset($_GET['userid'])) {
        
        $s = getXMLSettings();
        if ($_GET['userid'] == (string)$s['ownerid'] && $_SESSION['userID'] != (string)$s['ownerid']) {
            header('Location:accmanage.php');
            exit();
        }
    }




    
    # validate account info - only permitted users
    function username_validate() {
        
        
        # validate values starting from less important:
        # username must not be over 40 chars long
        # cannot register a username if it is already taken by another user
        # owner cannot remove own admin rights
        # nobody can edit owner account, except owner
        
        
        # username must not be too long or contain all characters
        $usr = str_replace(['&','/','  ','$',',',':',';','=','<','>','%','{','}','^','~','[',']','`','\\','\'','"'],'',$_POST['username']);
        if ((strlen($usr) < 3) || (strlen($usr) > 40))
            $er = 'account_username_not_valid';


        
        $s = getXMLSettings();


        # username already exists
        $usernames=[];
        $logfile = simplexml_object('log.xml','l',null);
        foreach($logfile->user as $user) {
            if (get_account($_POST['hiddenid'])['name'] == $user->name)
                continue;
            $usernames[] = $user->name;
        }
        

        if (array_search($usr,$usernames) !== false)
            $er = 'account_username_exists';



        # owner cannot remove own admin rights
        if ($_POST['accounttype'] != 'administrator' && $_POST['hiddenid'] == (string)$s['ownerid'])
            $er = 'account_could_not_modify';


        # owner only can edit own account
        if ($_POST['hiddenid'] == (string)$s['ownerid'] && $_SESSION['userID'] != (string)$s['ownerid'])
            $er = 'owner_account_could_not_modify';


        
        if (isset($er)) {
            $_SESSION[$er] = 1;
            return false;
        }
        else 
            return $usr;
        
    }



    function edit_account() {
    
        
        if ($_POST['hiddenname'] != null) {
            
            $stg = simplexml_object('settings.xml','l',null);
            $usr = username_validate();

            if ($usr === false) {
                header('Location:accmanage.php');
                exit;
            }
                
            # update account
            $updt = update_account($_POST['hiddenid'],'set');
            
            if ($updt === false)
                $_SESSION['account_missing'] = true;
            
            # if we confirm account update was succesful, update the username in the session
            else {
                
                if ($_SESSION['userID'] == $_POST['hiddenid'])
                    $_SESSION['username'] = $usr;
                
                $_SESSION['account_modified'] = true;
                
            }
        }

        header('Location:accmanage.php');
        return true;
    }
    




    function create_account() {
        
        
        $usr = str_replace('  ','',$_POST['username']);
        $psw = str_replace(' ','',$_POST['password']);
        $typ = $_POST['accounttype'];
        $usr = username_validate();
            
        
        if ($usr === false) {
            header('Location:accmanage.php');
            exit;
        }
        
                
        if  ($_POST['hiddenname'] == null)  {

            #create new account
            include 'set-cost.php';
            $pshs = password_hash($psw, PASSWORD_DEFAULT,["cost" => $cost]);

            $logsave = simplexml_object('log.xml','e',null);

            $id = md5(microtime());
            $newuser = $logsave->addChild('user','');
            $newuser->addChild('name',$usr);
            $newuser->addChild('pshs',$pshs);
            $newuser->addChild('rights',$typ);
            $newuser->addChild('login','none');
            $newuser->addChild('ip',' ');
            $newuser->addChild('created',time());
            $newuser->addChild('icon','../images/userimage.png');
            $newuser->addChild('editorname',$usr);
            $newuser->addChild('texteditor','on');
            $newuser->addChild('theme','light');
            $subres = $newuser->addChild('results','');
            $subres->addChild('posts','5');

            if ($typ == 'administrator')
                $subres->addChild('pages','5');

            $subres->addChild('images','5');
            $newuser->addChild('userID',$id);

            simplexml_object_save('log.xml',$logsave,null);


            $_SESSION['account_created'] = true;
            header('Location:accmanage.php');
            return true;

        }
    }



    if (isset($_POST['password']))
        create_account();
    
    elseif (isset($_POST['username']))
        edit_account();

    

    # extensions
    include 'command.php'
        
        
        
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Users - Account info</title>
<link rel="stylesheet" type="text/css" href="cmstyle.css">
<?php include 'csstheme.php' ?>
</head>
<body>
<?php


    # panel
    include 'mypanel.php'



?>
    <div class="main">
        <h1 class="inbl"><a href="accmanage.php" title="Back to Accounts">&larr;</a> Account information</h1>
        <div id="main-container">
            <div class="results">
                <form action="account.php" method="POST" name="acc" style="margin-left:30px;width:500px">
                    <!-- Current username hidden -->
                    <input name="hiddenname" type="text" value="<?php if (isset($_GET['userid'])) print get_account($_GET['userid'])['name'] ?>" hidden>
                    <!-- Current user id hidden -->
                    <input name="hiddenid" type="text" value="<?php if (isset($_GET['userid'])) print $_GET['userid'] ?>" hidden>
                    
                    <!-- Username -->
                    <label for="account-username" class="label-acc">Username</label>
                    <input name="username" type="text" id="account-username" class="inp-acc" title="Username" value="<?php if (isset($_GET['userid'])) print get_account($_GET['userid'])['name'] ?>" placeholder="username">
                    <div class="clear"></div>
                    <!-- Password -->
                    <?php if (!isset($_GET['userid'])) : ?>
                    
                    <label for="account-password" class="label-acc">Password</label>
                    <input name="password" type="password" id="account-password" class="inp-acc" title="Password" value="" placeholder="password">                        
                    <div class="clear"></div>
                        
                    <?php endif ?>
                    
                    
                    <!-- Account type -->
                    <label for="select-type" class="label-acc">Account type</label>
                    <select name="accounttype" id="select-type">
                        <?php
    
    
                        if (isset($_GET['userid'])) {
                            
                            $cur_owner = $xmls['ownerid'];

                            if ($_GET['userid'] == $cur_owner)
                                print '<option>administrator</option>'.PHP_EOL;

                            else {

                                $type = get_account($_GET['userid'])['rights'];
                                print '<option>'.$type.'</option>'.PHP_EOL;

                                
                                if ($type == 'administrator')
                                    print '<option>author</option>'.PHP_EOL;
                                else    
                                    print '<option>administrator</option>'.PHP_EOL;

                            }
                        
                        }
                        
                        else 
                            print '<option>administrator</option>'.PHP_EOL.'<option>author</option>'.PHP_EOL
                        
                    ?>
                    </select>
                    <div class="clear"></div>
                    <div class="clear"></div>
                    <input type="submit" class="stylish-button" value="Submit account" title="Submit account">
                </form>
            </div>
        </div>
    </div>
    <?php


                            
    # plugins                        
    include 'execute.php'

                            

    ?>
</body>
</html>