<?php

$error = 0;
$message = '';
$tplfile = 'password.tpl';

if (isset($_POST['password'])) {
    $password = $_POST['password'];
    if (isset($_POST['confirmpwd']) && $password == $_POST['confirmpwd']) {
        $pwlen = strlen($password);
        if (isset($conf['pwminlen']) && $pwlen < $conf['pwminlen']) {
            $message = USS_ERR_006;
            $rc = false;
        } else if (isset($conf['pwmaxlen']) && $pwlen > $conf['pwmaxlen']) {
            $message = USS_ERR_007;
            $rc = false;
        }
        if ($rc && isset($conf['pwallow'])) {
            foreach ($conf['pwallow'] as $pwallow) {
                if (!preg_match("/$pwallow/", $password)) {
                    $message = USS_ERR_005;
                    $rc = false;
                    break;
                }
            }
        }
        if ($rc && isset($conf['pwdeny'])) {
            foreach ($conf['pwdeny'] as $pwdeny) {
                if (preg_match("/$pwdeny/", $password)) {
                    $message = USS_ERR_005;
                    $rc = false;
                    break;
                }
            }
        }

        if ($rc) {
            $rc = ldap_mod_replace($ldap, $_SESSION['userdn'], array('userPassword' => $password));
            if (!$rc) {
                $error = 1;
                $log->crit(logformat("Changing password failed: ". ldap_error($ldap)));
                $message = USS_ERR_001;
            } else {
                $log->notice(logformat("Changing password succeeded"));
                $message = USS_NML_001;
            }
        }
    } else {
        $error = 1;
        $message = USS_ERR_003;
    }
}

$smarty = new Smarty();
$smarty->template_dir = 'templates';
$smarty->compile_dir = 'templates_c';

$smarty->assign('username', $_SESSION['username']);
$smarty->assign('error', $error);
$smarty->assign('message', $message);
$smarty->assign('uri', $_SERVER['SCRIPT_NAME']);
if (isset($conf['useotp']) && $conf['useotp']) {
    $smarty->assign('useotp', 1);
}

$smarty->display($tplfile);
?>
