<?php
#
#   PHP routine to set new password for user
#

#
#   MD5 Hash
#
#   Linux command line: echo -n "string" | sha1sum
#   PHP command:  sha1("string");
#

#
#   Get 'posted' password information
#
$QCUser = $_POST['username'];
$QColdpass = sha1($_POST['oldpass']);
$QCnewpass = sha1($_POST['newpass']);

#
#   If unable to open account file, return error message
#
$authfile = "account";
$authorized = 0;
$fh = fopen($authfile,'r');
if (! $fh) {
  echo "Unable to open account file";
  return;
  }

#
#   Attempt to verify username/password against data in account file.
#
$contents = array();
while ( !feof($fh)) {
  $line = fgets($fh);
  $contents[] = $line;
  $info = split(",",$line);
  if ( ($QCUser == trim($info[0]) )  &&  ($QColdpass == trim($info[1]) ) ) {
    $authorized = 1;
    }
  }
fclose($fh);

#
#   If hash of old password does not match value in file, return error
#
if ( $authorized != 1) {
  echo "Old password does not match password on file.";
  return;
  }

#
#   Update contents of authorization file stored in memory
#
$i=0;
while ($contents[$i]) {
  $info = split(",",$contents[$i]);
  if ($QCUser == trim($info[0])) {
    $contents[$i] = "$QCUser, $QCnewpass\n";
    }
  $i++;
  }

#
#   Attempt to write username/password data to account file.
#
$fh = fopen($authfile,'w');
if (! $fh) {
  echo "Unable to open account file for writing.";
  return;
  }
for ($i=0; $i<count($contents); $i++ ) {
  fwrite($fh, $contents[$i]);
  }
fclose($fh);
echo 0;
return;

?>
