<?PHP
// Original code by Rick Warner 2002-2007
//
require ("pagestuff.php");

$returntoadd = "<html><head><meta HTTP-EQUIV=\"REFRESH\" CONTENT=\"0;URL=useradd.php?typo=yes\"></head></html>";
$returntoaddpass = "<html><head><meta HTTP-EQUIV=\"REFRESH\" CONTENT=\"0;URL=useradd.php?passwrong=yes\"></head></html>";
$returntoadduid = "<html><head><meta HTTP-EQUIV=\"REFRESH\" CONTENT=\"0;URL=useradd.php?uidused=yes\"></head></html>";
$returntoedit = "<html><head><meta HTTP-EQUIV=\"REFRESH\" CONTENT=\"0;URL=useredit.php?typo=yes\"></head></html>";
$returntoeditnoroot = "<html><head><meta HTTP-EQUIV=\"REFRESH\" CONTENT=\"0;URL=useredit.php?noroot=yes\"></head></html>";
$returntoeditpass = "<html><head><meta HTTP-EQUIV=\"REFRESH\" CONTENT=\"0;URL=useredit.php?passwrong=yes\"></head></html>";
$returntoaccounts = "<html><head><meta HTTP-EQUIV=\"REFRESH\" CONTENT=\"0;URL=useraccounts.php\"></head></html>";
$returntoaccountslater = "<html><head><meta HTTP-EQUIV=\"REFRESH\" CONTENT=\"3;URL=useraccounts.php\"></head></html>";

$accountfailed = "no";

$account=requestIfSet('account');
$command=requestIfSet('command');
$password=requestIfSet('password');
$passrepeat=requestIfSet('passrepeat');
$shell=requestIfSet('shell');
$fullname=requestIfSet('fullname','settousername');
$mcmsadmin=requestIfSet('mcmsadmin');
$forcepwchange=requestIfSet('forcepwchange','off');
$groups=requestIfSet('groups');
$UID=requestIfSet('UID','auto');
$GID=requestIfSet('GID','auto');

//FIXME - validate provided info

function mcms_add_user($username,$password,$uid,$gid,$fullname,$shell,$groups,$forcepwchange) {
    global $ldapconn, $ldapdn, $mcmsadmin;

    if ($_SESSION['usesLDAP']=="yes") {
        if(ldap_add_user($username,$password,$uid,$gid,$fullname,$shell,$forcepwchange)) {
            if(!file_exists("/home/".$username)) {
                microwayPerformCommand("cp -a /etc/skel /home/" . $username);

                if ($uid == "auto") { 
                    $filter="(&(objectClass=posixAccount)(cn=".$username."))";
                    $sr=ldap_search($ldapconn, $ldapdn, $filter,["uidnumber"]);
                    if($sr==FALSE) {
                        echo "ldap_search failed";
                        exit(2);
                    }
                    $info = ldap_get_entries($ldapconn, $sr);
                    if ($info == FALSE || $info["count"] != 1) {
                        echo "Failed to acquire new uid for account.";
                        exit(1);
                    } else $uid=$info[0]['uidnumber'][0];
                }

                if ($gid == "auto") { 
                    $filter="(&(objectClass=posixAccount)(cn=".$username."))";
                    $sr=ldap_search($ldapconn, $ldapdn, $filter,["gidnumber"]);
                    if($sr==FALSE) {
                        echo "ldap_search failed";
                        exit(2);
                    }
                    $info = ldap_get_entries($ldapconn, $sr);
                    if ($info == FALSE || $info["count"] != 1) {
                        echo "Failed to acquire new gid for account";
                        exit(1);
                    } else $gid=$info[0]['gidnumber'][0];
                }

                list($rcode,$result) = microwayPerformCommand("chown -R $uid:$gid /home/" . $username);
                if ($rcode != 0 ) {
                  echo "Changing ownership of the new home directory failed with the following error:<br>$result";
                }
            }
            ldap_user_set_groups($username,$groups);
        } else return FALSE;
    } else {
        //if(add_nis_user
        if ($groups!="") {
	    $grouplist="-G " . preg_replace("/,*$/","",str_replace(array("\n","\r"),array(",",""),$groups));
        } else {
            $grouplist="";
        }

        if ($fullname != "settousername") {
            $fullcommand = "-c '".$fullname."'";
        } else {
            $fullcommand = "-c '".$username."'";
        }
        if ($uid == "auto" || $uid == "") {
            $uidcommand = "";
        } else {
            $uidcommand = "-u $uid";
        }
        if ($gid == "auto" || $gid == "") {
            $gidcommand = "";
        } else {
            $gidcommand = "-g $gid";
        }
//FIXME - check results
        microwayPerformCommand ("/usr/sbin/useradd -m -s $shell $fullcommand $uidcommand $gidcommand $grouplist $username");
        microwayPerformCommandInput ("/usr/sbin/chpasswd", "$username:$password");
        if ($forcepwchange == "on") microwayPerformCommand ("chage -d 0 $username");
        if($_SESSION['usesNIS']=="yes") microwayPerformCommand ("cd /var/yp ; make");

        if ($_SESSION['hasNFShome'] != "yes") {
            microwayPerformCommand ("cd /home ; tar cf ".$username.".tar $username ; /usr/local/bin/rcpf ".$username.".tar /home; rcom tar xf /home/".$username.".tar -C /home ; rcom rm /home/".$username.".tar");
        }


    }

//config that's the same for LDAP and NIS
    if ($mcmsadmin == "on") {
        $output = exec ("grep -w $username /etc/mcms/users");
        if ($output != $username) {
            list($rcode,$result) = microwayPerformCommand ("echo $username >> /etc/mcms/users");
        }
    } else {
        $output = exec ("grep -w $username /etc/mcms/users");
        if ($output == $username) {
            list($rcode,$result) = microwayPerformCommand ("sed -i /etc/mcms/users -e '/^" . $username . "$/d'");
        }
    }

//Create ssh keys if they don't already exist
    if(!file_exists("/home/" . $username . "/.ssh")) {
        microwayPerformCommand("mkdir /home/" . $username . "/.ssh");
    }
    if(!file_exists("/home/" . $username . "/.ssh/id_rsa")) {
        microwayPerformCommand("ssh-keygen -t rsa -N '' -f /home/" . $username . "/.ssh/id_rsa -q");
    }
    if(!file_exists("/home/" . $username . "/.ssh/authorized_keys")) {
        microwayPerformCommand("cp /home/" . $username . "/.ssh/id_rsa.pub /home/" . $username . "/.ssh/authorized_keys");
    }
    microwayPerformCommand("chown -R $uid:$gid /home/" . $username . "/.ssh");
    microwayPerformCommand ("chmod 600 ~".$username."/.ssh/authorized_keys");

//handle non-NFS home if needed
    if ($_SESSION['hasNFShome'] != "yes") {
        microwayPerformCommand ("cd /home ; tar cf ".$username.".tar $username ; rcpf ".$username.".tar /home; rcom-parallel -w tar xf /home/".$username.".tar -C /home ; rcom-parallel -w rm /home/".$username.".tar");
    }
    return TRUE;
}

function mcms_del_user($username) {
    if ($_SESSION['usesLDAP']=="yes") {
        if(ldap_del_user($username)) {
            $allgroups=ldap_get_groups();
            foreach($allgroups as $group) {
                ldap_group_del_member($group['name'],$username);
            }
            return TRUE;
        } else return FALSE;
    } else {
        microwayPerformCommand ("/usr/sbin/userdel $username");
        if($_SESSION['usesNIS']=="yes") microwayPerformCommand ("cd /var/yp ; make");
        return TRUE;

        if ($username == "root" || $username == "nobody") {
            $output = "Cannot delete account $username";
            $usernamefailed = "yes";
        } else {
            list($rcode,$result) = microwayPerformCommand ("/usr/sbin/userdel $username");
            if ( $rcode != 0 ) {
                $output = "Deleting account $username failed with the following output:<br>$result";
                $usernamefailed = "yes";
            } else {
                if($_SESSION['usesNIS']=="yes") microwayPerformCommand ("cd /var/yp ; make");
                $output = "User account: $username deleted.";
                return TRUE;
            }
        }
    }
}

//perform user add
if ($command == "Add User") {
    if ($account == "" || $account=="root" || $password == "" || $passrepeat == "" || $shell == "") {
        echo $returntoadd;
        exit ();
    }
    if (substr_count ($account, " ") > 0) {     //tests for spaces in account name- invalid input
        echo $returntoadd;
        exit ();
    }
    if ($password != $passrepeat) {     //error-go back
        echo $returntoaddpass;
        exit ();
    }

    if(mcms_add_user($account,$password,$UID,$GID,$fullname,$shell,$groups,$forcepwchange)) {
       $output = "User account: $account created.";
    } else { 
       $output = "User account: $account creation failed.";
    }
}
//used for pass back from delete cancel
else if ($command == "Cancel") {
    echo $returntoaccounts;
    exit ();
}
//actually perform user delete after regular delete confirms
else if ($command == "Delete User") {
    if ($account == "") {
        echo $returntoedit;
        exit (1);
    }

    if(mcms_del_user($account)) {
       $output = "User account: $account deleted.";
    } else { 
       $output = "User account: $account deletion failed.";
    }
}

//perform user delete
else if ($command == "Delete") {
    if (!isset ($account) || $account == "") {
        echo $returntoedit;
        exit (1);
    }
    if ($account == "root") {
        echo $returntoeditnoroot;
        exit (1);
    }
    $output = "Are you sure you want to delete $account?</H2></TD></TR><TR><TD align=center><FORM action=userapply.php method=POST><input type=hidden name=account value=$account>" .
              "<input type=submit name=command value=\"Delete User\">&nbsp;&nbsp;<INPUT type=submit name=command value=Cancel></FORM><H2>";
}
//perform user update/edit
else if ($command == "Update") {
    if ($account == "" || $shell == "") {
        echo $returntoedit;
        exit ();
    }
    if (substr_count ($account, " ") > 0) {     //tests for spaces in account name- invalid input
        echo $returntoedit;
        exit ();
    }
    if ($password != "" || $passrepeat != "") {
        if ($password != $passrepeat) {
            echo $returntoeditpass;
            exit ();
        }
        if (substr_count ($password, " ") > 0) {    //tests for spaces in password- invalid input
            echo $returntoedit;
            exit ();
        }
    }
    if ($groups != "" && $account == "root") {
        echo "You cannot set groups for the root user, and you should not have even been able to get here.<BR>\n";
        exit(1);
    }
 
    if ($mcmsadmin == "on") {
        $output = exec ("grep -w $account /etc/mcms/users");
        if ($output != $account) {
            microwayPerformCommand ("echo $account >> /etc/mcms/users");
        }
    } else {
        $output = exec ("grep -w $account /etc/mcms/users");
        if ($output == $account) {
            microwayPerformCommand ("sed -i /etc/mcms/users -e '/^" . $account . "$/d'");
        }
    }

    if (substr_count ($shell, " ") > 0) {
        echo $returntoedit;
        exit ();
    }

    if ($account == "root") {
        microwayPerformCommandAll ("/usr/sbin/usermod ".$fullcommand." -s $shell $account");
        if ($password != "")
            microwayPerformCommandInputAll ("/usr/sbin/chpasswd", "$account:$password");
    } else {

        if($_SESSION['usesLDAP']=="yes" && ldap_user_exists($account)) {
            //handle updates for LDAP
            ldap_update_user($account,$password,$fullname,$shell,$forcepwchange);
            ldap_user_set_groups($account,$groups);
        } else { 
            //the following if-thens test if certain parameters are set
            if ( $fullname != "" && $fullname != "settousername" ) {
                $fullcommand = "-c '".$fullname."'";
            } else {
                $fullcommand = "-c '".$account."'";
            }
            if ($password != "") $passcommand = "yes";
            else $passcommand = "no";

    
            if ($groups!="") {
                $grouplist="-G " . preg_replace("/,*$/","",str_replace(array(" ","\n","\r"),array(",",",",""),$groups));
            } else $grouplist="";

            microwayPerformCommand ("/usr/sbin/usermod " . $fullcommand . " $grouplist -s $shell $account");
            if ($passcommand == "yes")
                microwayPerformCommandInput ("/usr/sbin/chpasswd", "$account:$password");
            microwayPerformCommand ("cd /var/yp ; make");
            if ($forcepwchange == "on")
                microwayPerformCommand ("chage -d 0 $account");
        } 
        if ($account == $_SESSION['currentUser'] && $password!="") {
            $_SESSION['currentPassword'] = $password;
        }
    }
    $output = "User account: $account updated";
} else {
    echo $returntoaccounts;
    exit ();
}

pageInit (true);
if ($command != "Delete") {
    if ($accountfailed != "yes") {
        $_SESSION['refreshTo'] = "useraccounts.php?clearrefresh=yes";
        $_SESSION['refreshTime'] = 3;
    }
}
pageStart ("Accounts&nbsp;page");
echo "<TABLE width=\"70%\">";
echo "<TR><TD><H2>$output</H2></TD></TR>";
echo "</TABLE>";

if (isset ($command) && $command != "Delete") {
    if ($accountfailed == "yes") {
        echo "Process failed.  Click <A HREF=useraccounts.php?clearrefresh=yes>here</A> to return to account management.";
    } else {
        echo "Returning to account administration in 3 seconds.<BR>Click <A HREF=useraccounts.php?clearrefresh=yes>here</A> if not redirected automatically.";
    }
}

pageEnd ();
?>
