<?php
/*
 *   This file is part of NOALYSS.
 *
 *   NOALYSS isfree software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   NOALYSS isdistributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with NOALYSS; if not, write to the Free Software
 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
// Copyright (2014) Author Dany De Bontridder <dany@alchimerys.be>
require_once NOALYSS_INCLUDE.'/lib/ac_common.php';

if (!defined('RECOVER'))
    die('Appel direct ne sont pas permis');
define('SIZE_REQUEST', 70);



$http=new HttpInput();
/**
 * @file
 * @brief 
 * @param type $name Descriptionara
 */
$action=$http->request("id","string", "");
if ($action=="") :
    /*
     * Display dialog box
     */
    ?>
    Donnez votre login ou votre email
    <form method="POST">
        <input type="hidden" value="send_email" name="id">
        <input type="hidden" value="recover" name="recover">
        login <input type="text"   name="login">
        or 
        email <input type="text" name="email">
        <input type="submit" name="send_email" value="Envoi email">
    </form>
    <?php
elseif ($action=="send_email") :
    /*
     * Check if user exists, if yes save a recover request
     */
    $login_input=$http->request("login", "string","");
    $email_input=$http->request("email", "string","");
    $cn=new Database(0);
    $valid=false;
    if (trim($login_input)!=""):
        $array=$cn->get_array("select use_id,use_email,use_login from ac_users where lower(use_login)=lower($1) "
               , array($login_input));
    elseif (trim($email_input)!=""):
        $array=$cn->get_array("select use_id,use_email,use_login from ac_users where  "
                ."  lower(use_email)=lower($1) ", array( $email_input));

    else:
       return;
    endif;


    if ($cn->size()!=0):
        list($user_id, $user_email, $user_login)=array_values($array[0]);
        if (trim($user_email)!=" ") :
            $valid=true;
        endif;
    endif;


    if ($valid==true):
        $request_id=generate_random_string(SIZE_REQUEST, 0);
        $user_password=generate_random_password(10);
        // exist a valid request for this user ?
        $exist_request= $cn->get_array("select request , password from recover_pass 
                        where use_id=$1 and created_on > now() - interval '12 hours'",[$user_id]);
        if ( empty($exist_request ) ) {
             /* save the request into  */
            $cn->exec_sql("insert into recover_pass(use_id,request,password,created_on,created_host) "
                    ." values ($1,$2,$3,now(),$4)", array($user_id, $request_id, $user_password, $_SERVER['REMOTE_ADDR']));
        } else {
            $request_id=$exist_request[0]["request"];
            $user_password=$exist_request[0]['password'];
            /* if too many request , there is a bug somewhere , so record an warning */
            if ( count($exist_request)> 1 ){
                record_log("WRE109 Trop de request pour ".var_export($exist_request,true));
            }
            
        }
        /*
         * send an email
         */
        $mail=new Sendmail();
        $mail->set_from(ADMIN_WEB);
        $mail->set_format("HTML");
        $mail->mailto($user_email);
        $mail->set_subject("NOALYSS : Réinitialisation de mot de passe");
        $noalyss_url=NOALYSS_URL;
        $message=<<<EOF
     <p>Bonjour,
      <br/>
Une demande de réinitialisation de votre mot de passe a été demandée par <b>{$_SERVER['REMOTE_ADDR']}</b>
<br/>
<ul>
    <li>
Votre nom d'utilisateur est <b>{$user_login}</b>
    </li>
    <li>
Votre mot de passe est <b>{$user_password}</b>
    </li>
</ul>
</p>
<p>
Suivez ce lien pour activer le changement ou ignorer ce message si vous n'êtes pas l'auteur de cette demande.
<br/>
Ce lien ne sera actif que 12 heures.
   
   <a title="noalyss" href="{$noalyss_url}/index.php?recover&id=req&req={$request_id}">{$noalyss_url}/index.php?recover&id=req&req={$request_id}</a>
</p>   
   <p>
   Merci d'utiliser NOALYSS
   <br/>
   <br/>
   <br/>
   
Cordialement,
   <br/>
   <br/>

Noalyss team
      </p>
      <p>
               <i> Si cet email est dans vos spams, ajoutez l'expéditeur dans votre carnet d'adresse</i>
               </p>
EOF;
        $mail->set_message($message);
        $mail->compose();
        $mail->send();
        echo '<p style="position:absolute;z-index:2;top:25px;left: 50px; background-color:whitesmoke;">
L\'email a été envoyé avec un lien et le nouveau mot de passe, vérifiez vos spams</p>';
    endif;
elseif ($action=="req") :
    $http=new HttpInput();
    $request_id=$http->request("req","string", "");
    if (noalyss_strlentrim($request_id)==SIZE_REQUEST) :
        $cn=new Database(0);

        $value=$cn->get_value("select password from recover_pass where request=$1 and created_on > now() - interval '12 hours' and recover_on is null", array($request_id));
        if ($cn->get_affected()>0) :
            $cn->exec_sql("update ac_users set use_pass=md5(rp.password) from recover_pass as rp where rp.use_id=ac_users.use_id and request=$1", array($request_id));
            $cn->exec_sql("update recover_pass set recover_by=$1 , recover_on=now() where request=$2", array($_SERVER['REMOTE_ADDR'],$request_id));
            ?>
    <p style="position:absolute;z-index:2;top:25px;left: 50px; background-color:whitesmoke;">
            Opération réussie , vous pouvez vous connecter avec votre nouveau mot de passe
             
    </p>
            <?php
        endif;
    else:
        die("Requête inconnue");
    endif;
endif;
