<?php
/*************************************************************************************************

    ddnsadduser.php
    Make User Table for DDNS

        2013.07.27 Ver.1.0 Masashi.org
        2019.10.04 Ver.1.1 Masashi.org (mysqli etc)

        Note:
        $su is a flag for super user which has specific defined mail address.

***************************************************************************************************/
include "ddnscommon.php";

//
include "del_nday_file.php";
if(
del_nday_file(1)){die();}
//
//Items by POST method
$array = array("username","mailaddress","p_temp","password","confirm","reg");

for(
$i=0;$array[$i];$i++){
    $
$array[$i] = $_POST["{$array[$i]}"];
}

//Items by GET method

$temp $_GET['temp'];

// checking each value
if(!preg_match("/^[0-9a-z]+$/",$username) && $username){
    
$flag_illegal_username1;
    
$flag_illegal 1;
}

if(!
preg_match("/^[0-9a-z]+$/",$password) && $password){
    
$flag_illegal_password1;
    
$flag_illegal 1;
}

if(
$reg == "new"){
    if( (!
preg_match("/^[0-9a-z\.\-]+@[0-9a-z][0-9a-z\.\-]+\.[0-9a-z]+$/",$mailaddress) || preg_match("(,)",$mailaddress)) && $mailaddress){
        
$flag_illegal_mailaddress 1;
        
$flag_illegal 1;
    }
    
$su 0;
    if(
strstr($mailaddress,$su_mail)){
        
$su 1;
    }
}

$link mysqli_connect($db_host $db_user $db_pass $db_name);
if (
mysqli_connect_errno() > 0) {
  die(
"DB Connection error: " mysqli_connect_error());
}
$sql sprintf("SELECT * FROM userdata WHERE username='%s'",
        
mysqli_real_escape_string($link,$username));
$rs mysqli_query($link,$sql);
$item mysqli_fetch_array($rs);
if(
$reg == "new" && $item){
    
$flag_illegal_userregistered 1;
        
$flag_illegal 1;
}elseif(
$reg == "forget" && !$item){
    
$flag_illegal_usernotfound 1;
        
$flag_illegal 1;
}
mysqli_close($link);


/******************************  Output HTML header **********************************************/
include "ddnsheader.php";
echo<<<EOH
<TITLE>Register User ID for DDNS -{$org_name}-</TITLE>
</HEAD>
EOH;

echo<<<EOH
<BODY>
<h1>Register User ID for DDNS</h1>
EOH;

/*************************************************************************************************

    STEP 4.
    When temporary file name is sent by GET, show password input panel.

***************************************************************************************************/
if($temp){
    
$tempfile "./temporary/$temp";
    if(!
file_exists($tempfile)){
        echo 
"URL is invalid";
    }else{
        
$list file($tempfile);
        for(
$i=0;$list[$i];$i++){
            
$list[$i] = explode(",",$list[$i]);
            
$list[$list[$i][0]] = $list[$i][1];
        }
        if(
$list['reg'] == "new"){
            
$mailaddress $list['mailaddress'];
        }else{
            
$mailaddress "(intentionally blank)";
        }
        echo <<<EOF
<h2>STEP 4 : E-mail Confirmatin</h2>
<form action="
{$_SERVER['SCRIPT_NAME']}" method="post">
    <input type="hidden" name="username" value="
{$list['username']}">
    <input type="hidden" name="mailaddress" value="
{$list['mailaddress']}">
    <input type="hidden" name="p_temp" value="
$temp">
    <input type="hidden" name="reg" value="
{$list['reg']}">
    <table border=0>
        <tr>
            <td>User ID</td><td>:</td>
            <td>
                
{$list['username']}
            </td>
        </tr>
        <tr>
            <td>E-mail address</td><td>:</td>
            <td>
                
{$mailaddress}
            </td>
        </tr>
        <tr>
            <td>Password</td><td>:</td>
            <td>
                <input type="password" name="password" size=20 maxlength=20>
            </td>
        </tr>
    </table>
    <br />
    <input type="submit" value="Register User ID">
</form>
EOF;
    }


/*************************************************************************************************

    STEP 5. and STEP 6.
    When all data by POST, check them and proceed user registration.

***************************************************************************************************/
}elseif($username && ($mailaddress || $reg != "new") && $p_temp){
    
$pw_md5 md5($password);
    
$tempfile "./temporary/$p_temp";
    if(!
file_exists($tempfile)){
        echo 
"ERROR: Not found temporary file.<br /><br />";
        echo 
"<a href=\"./\">Return to homepage</a>";
        die();
    }
    
$list file($tempfile);
    for(
$i=0;$list[$i];$i++){
        
$list[$i] = explode(",",$list[$i]);
        
$list[$list[$i][0]] = $list[$i][1];
    }
    if(
$pw_md5 != $list['password']){

// STEP 6.

        
if($list['reg'] == "new"){
            
$mailaddress $list['mailaddress'];
        }else{
            
$mailaddress "(intentionally blank)";
        }

    echo <<<EOF
<h2>STEP 4 : E-mail Confirmatin</h2>
<form action="
{$_SERVER['SCRIPT_NAME']}" method="post">
    <input type="hidden" name="username" value="
{$list['username']}">
    <input type="hidden" name="mailaddress" value="
{$list['mailaddress']}">
    <input type="hidden" name="p_temp" value="
$p_temp">
    <input type="hidden" name="reg" value="
{$list['reg']}">
    <table border=0>
        <tr>
            <td>User ID</td><td>:</td>
            <td>
                
{$list['username']}
            </td>
        </tr>
        <tr>
            <td>E-mail address</td><td>:</td>
            <td>
                
{$mailaddress}
            </td>
        </tr>
        <tr>
            <td>Password</td><td>:</td>
            <td>
                <input type="password" name="password" size=20 maxlength=20>
            </td>
        </tr>
    </table>
    <br />
    <font color="red">Password is NOT match</font><br />
    <br />
    <input type="submit" value="Register User ID">
</form>
EOF;

// STEP 5.

    
}else{

        echo 
"<h2>STEP 5 : Result of Registration</h2>";

        
$link mysqli_connect($db_host $db_user $db_pass $db_name);
        if (
mysqli_connect_errno() > 0) {
          die(
"DB Connection error: " mysqli_connect_error());
        }
        
$sql sprintf("SELECT * FROM userdata WHERE username='%s'",
            
mysqli_real_escape_string($link,$username));
        
$rs mysqli_query($link,$sql);
        
$item mysqli_fetch_array($rs);

        if(
$reg == "new"){
            if(!
$item){
                
$htpasswd "./nic/.htpasswd";
                
$status shell_exec("/usr/local/bin/htpasswd -b $htpasswd $username $password");
                
$timestamp date('Y-m-d H:i:s');
                
$sql sprintf("INSERT INTO userdata VALUES ( '%s' , '%s' , '%s' , '$timestamp' , $su)",
                    
mysqli_real_escape_string($link,$username),
                    
mysqli_real_escape_string($link,$pw_md5),
                    
mysqli_real_escape_string($link,$mailaddress));
                
$rs mysqli_query($link,$sql);
                if(!
$rs){
                    echo 
$rs;
                    echo 
"Registration failure!<br />";
                    echo 
"Please contact to administration.<br />";
                    echo 
$adm_mail;
                }else{
                    echo 
"New registration has been completed!";
                 }
            }else{
                echo 
"The user name is already registered.<br />";
                echo 
"<a href=\"./ddnsadduser.php\">Please try other user name</a>";
            }
        }elseif(
$reg == "forget"){
            if(
$item){
                
$htpasswd "./nic/.htpasswd";
                
$status shell_exec("/usr/local/bin/htpasswd -b $htpasswd $username $password");
                
$sql sprintf("UPDATE userdata SET password='%s' WHERE username='%s'",
                    
mysqli_real_escape_string($link,$pw_md5),
                    
mysqli_real_escape_string($link,$username));
                
$rs mysqli_query($link,$sql);
                if(
$rs){
                    echo 
"Password has been changed!";
                }else{
                    echo 
"Registration failure!<br />";
                    echo 
"Please contact to administration.<br />";
                    echo 
$adm_mail;
                 }
            }else{
                echo 
"Your request is invalid.";
            }
        }else{
            echo 
"Your request is undefined.";
        }
        
mysqli_close($link);
        
unlink($tempfile);
    }


/*************************************************************************************************

    STEP 2. STEP 3.
    When 4 data are sent by POST, display confirmation panel.
    If $confirm == YES, create templary file and send a mail.

***************************************************************************************************/
}elseif($username && ($mailaddress || $reg != "new") && $password && !$flag_illegal){
        if(
$confirm == "YES"){
        echo <<<EOF
<h2>STEP 3 : Sending E-mail</h2>
EOF;
    }else{
        echo <<<EOF
<h2>STEP 2 : Confirm Sending Data</h2>
EOF;
    }
    if(
$reg == "forget" && !$mailaddress){
        
$e_mail="(intentionally blank)";
    }else{
        
$e_mail=$mailaddress;
    }
    echo <<<EOF
<table border=1>
    <tr>
        <td>User ID</td>
        <td>
            
$username
        </td>
    </tr>
    <tr>
        <td>E-mail address</td>
        <td>
            
$e_mail
        </td>
    </tr>
</table>

EOF;
    if(
$confirm == "YES"){
        include 
"rand_str.php";
        
$random rand_str(40,'all');
        
$tempfile "./temporary/$random";
        
touch($tempfile);
        
$dat = <<<EOF
username,$username,
password,
$password,
mailaddress,
$mailaddress,
reg,
$reg,
EOF;
        
$fp fopen($tempfile,"w");
        
fputs($fp,$dat);
        
fclose($fp);

        if(
$reg == "forget"){
            
$link mysqli_connect($db_host $db_user $db_pass $db_name);
            if (
mysqli_connect_errno() > 0) {
              die(
"DB Connection error: " mysqli_connect_error());
            }
            
$sql sprintf("SELECT email FROM userdata WHERE username='%s'",
                
mysqli_real_escape_string($link,$username));
            
$rs mysqli_query($link,$sql);
            
$item mysqli_fetch_array($rs);
            
mysqli_close($link);
            if(!
$item){die("<br />Your request is invalid.<hr /><a href=\"./\">Return to homepage</a> -".$org_name."-");}
            
$mailaddress $item['email'];
        }

        
$body "Pre-registration completed!\r\n";
        
$body $body."Proceed to Registration\r\n";
        
$body $body.$site_url.$_SERVER['SCRIPT_NAME']."?temp=".$random;

        
$body mb_convert_encoding($body,"JIS");
        
$subject mb_convert_encoding("Subject: ".$org_name." DDNS User pre-registration notice","JIS");

        
$msg_ng="<br />Sending mail failure<br />Please contact to administrator<br />".$adm_mail;
        
$msg_ok="<br />Pre-registration notice has been sent to your email address<br />Please proceed registration from an url in the email";
        
$msg=$msg_ng;

        
$sock fsockopen("localhost",25);
        
fputs($sock,"HELO ".$mail_srv."\r\n");
        
$result fgets($sock,128);
        if(
preg_match("(^220)",$result)){
            
fputs($sock,"MAIL FROM:<".$adm_mail.">\r\n");
            
$result fgets($sock,128);
            if(
preg_match("(^250)",$result)){
                
fputs($sock,"RCPT TO:<$mailaddress>\r\n");
                
$result fgets($sock,128);
                if(
preg_match("(^250)",$result)){
                    
fputs($sock,"DATA\r\n");
                    
$result fgets($sock,128);
                    if(
preg_match("(^250)",$result)){
                        
fputs($sock,"$subject\r\n");
                        
fputs($sock,"$body\r\n");
                        
$result fputs($sock,".\r\n");
                        if(
$result){
                            
$msg=$msg_ok;
                        }
                    }
                }
            }
        }
        echo 
$msg;
        
fclose($sock);

// STEP 2.

    
}else{
        
$password md5($password);
        echo <<<EOF
<br />
Click to confirm those informatin are correct.<br />
<br />
<form action="
{$_SERVER['SCRIPT_NAME']}" method="post">\n
    <input type="hidden" name="username" value="
$username">
    <input type="hidden" name="password" value="
$password">
    <input type="hidden" name="mailaddress" value="
$mailaddress">
    <input type="hidden" name="confirm" value="YES">
    <input type="hidden" name="reg" value="
$reg">
    <input type="submit" value="Confirm">
</form>
EOF;
    }


/*************************************************************************************************

    STEP 1.
    If there is no data for sending, show input form.

***************************************************************************************************/
}else{
    echo 
"<h2>STEP 1 : Input Data</h2>";
    if(
$username || $mailaddress || $password){

        if(!
$username){
            
$msg .= "User ID is missing.<br />";
        }
        if(
$flag_illegal_userregistered){
            
$msg .= "User ID is already registered.<br />";
        }
        if(
$flag_illegal_usernotfound){
            
$msg .= "User ID is invalid.<br />";
        }
        if(
$flag_illegal_username){
            
$msg .= "User ID is invalid. Please enter in ASCII.<br />";
        }
        if(!
$password){
            
$msg .= "Password is missing.<br />";
        }
        if(
$flag_illegal_password){
            
$msg .= "Password is invalid. Please enter in ASCII.<br />";
        }
        if(!
$mailaddress && $reg == "new"){
            
$msg .= "E-mail address is missing.<br />";
        }
        if(
$flag_illegal_mailaddress && $mailaddress){
            
$msg .= "E-mail address is invalid. Please enter correctly.<br />";
        }
    }
    echo <<<EOF
<form action="{$_SERVER['SCRIPT_NAME']}" method="post">
    <table border=0>
        <tr>
            <td>User ID</td><td>:</td>
            <td>
                <input type="text" name="username" size=20 maxlength=20 value="
$username">
            </td>
        </tr>
        <tr>
            <td>Password</td><td>:</td>
            <td>
                <input type="password" name="password" size=20 maxlength=20> If you forgot your password, put a new password in here.
            </td>
        </tr>
        <tr>
            <td>E-mail address</td><td>:</td>
            <td>
                <input type="text" name="mailaddress" size=40 maxlength=100 value="
$mailaddress">
            </td>
        </tr>
    </table>
    <p>
EOF;
    if(
$reg == "forget"){
        echo 
"<input type=\"radio\" name=\"reg\" value=\"new\">New Registration?";
        echo 
"<input type=\"radio\" name=\"reg\" value=\"forget\" checked>Forgot Password?";
    
//    echo "<input type=\"radio\" name=\"reg\" value=\"change\" disabled>Change Password?";
    
}elseif($reg == "change"){
        echo 
"<input type=\"radio\" name=\"reg\" value=\"new\">New Registration?";
        echo 
"<input type=\"radio\" name=\"reg\" value=\"forget\">Forgot Password?";
    
//    echo "<input type=\"radio\" name=\"reg\" value=\"change\" checked>Change Password?";
    
}else{
        echo 
"<input type=\"radio\" name=\"reg\" value=\"new\" checked>New Registration?";
        echo 
"<input type=\"radio\" name=\"reg\" value=\"forget\">Forgot Password?";
    
//    echo "<input type=\"radio\" name=\"reg\" value=\"change\" disabled>Change Password?";
    
}
    echo <<<EOF
    </p>
    <font color="red">
{$msg}</font>
    <br />
    <input type="submit" value="Register User ID">
</form>
EOF;
}
?>
<hr />
<a href="./">Return to homepage</a> -<?php echo $org_name?>-
</body>
</html>