<?php
// veneden api/utils
function randomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
function nvl($v,$r){
    if (is_null($v))
        return($r);
    else
        return($v);
}
function dlookup($db, $campo, $tabla, $where){
    try {
        $sql = "SELECT `" . $campo . "` retval " . 
               "FROM   `" . $tabla . "` " . 
               "WHERE  " . $where;
        $rs = $db->query($sql);
        $row = $rs->fetch_assoc();
        return($row["retval"]);
    } catch (Exception $e){
        return(null);
    }
}
function isSessionValid($db, $sessionid){
    // Validar sessionid activo
    $sql =  "SELECT COUNT(*) cnt, min(id) id " .
            "FROM   users " .
            "WHERE  sessionid = '" . $sessionid . "' " .
            "AND    validthru > NOW() ";
    if (!$rs = $db->query($sql)){
        header("HTTP/1.1 500");
        echo (json_encode(array("msg"=>$db->error)));
        die();
    }
    $row = $rs->fetch_assoc();
    if ($row["cnt"]<=0){
        header("HTTP/1.1 401");
        echo (json_encode(array("msg"=>"Sesión inválida o expirada")));
        die();
    }
    return($row["id"]);
}
function setAudit($db, $module, $sessionid, $dsc){
    try {
        // obtener usuario
        $sql = "SELECT id " . 
               "FROM   users " . 
               "WHERE  sessionid = '" . $sessionid . "' ";
        $rs = $db->query($sql);
        $row = $rs->fetch_assoc();
        $userid = $row["id"];
        
        // incluir auditoria
        $sql = "INSERT INTO audit (module, userid, dsc) " .
               "VALUES            ('" . $module . "', '" . $userid . "', '" . $dsc . "')";
        if ($rs = $db->query($sql)){
            return(true);
        }else{
            return(false);
        }
    } catch (Exception $e){
        return(false);
    }
}
function tienePrivilegio($db, $sessionid, $privilegeid){
    try {
        // obtener usuario
        $sql = "SELECT id " . 
               "FROM   users " . 
               "WHERE  sessionid = '" . $sessionid . "' ";
        $rs = $db->query($sql);
        $row = $rs->fetch_assoc();
        $userid = $row["id"];
        
        // incluir auditoria
        $sql = "SELECT COUNT(*) cnt " .
               "FROM   userprivileges " .
               "WHERE  userid=" . $userid . " " . 
               "AND    privilegeid=" . $privilegeid;
        $rs = $db->query($sql);
        $row = $rs->fetch_assoc();
        if ((integer) $row["cnt"] > 0){
            return(true);
        }else{
            return(false);
        }
    } catch (Exception $e){
        return(false);
    }
}
function parametrosValidos($parms, $campos){
    $out = true;
    foreach ($campos as $campo){
        if ($out)
            $out = isset($parms[$campo]) && trim($parms[$campo])!="";
    }
    return ($out);
}
function badEnd($htmlError, $output){
    header("HTTP/1.1 ".$htmlError);
    echo (json_encode($output));
    die();
}

function enviarCorreo($from, $to, $subject, $body){
    if (strpos($to, '@hotmail.com') !== false || strpos($to, '@outlook.com') !== false) {
        
        $headers = 'From: ' .$from . "\r\n" .
        'Reply-To: '.$from . "\r\n" .
        'X-Mailer: PHP/' . phpversion()."\r\n".
        "Content-Type: text/html; charset=UTF-8\r\n";
    
        mail($to, $subject, $body, $headers);
        
        return true;
    } else {
        $mail = new PHPMailer();

        $mail->isSMTP();
        $mail->CharSet = 'UTF-8';
        $mail->Encoding = 'base64';
        $mail->SMTPSecure = false;
        $mail->SMTPAutoTLS = false;
        $mail->SMTPOptions = array(
             'ssl' => array(
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            )
        );
        //Enable SMTP debugging
        // 0 = off (for production use)
        // 1 = client messages
        // 2 = client and server messages
        $mail->SMTPDebug = 0;
        $mail->Debugoutput = 'html';
        $mail->Host = "mail.ormve.org";
        $mail->Port = 587;
        $mail->SMTPAuth = true;
        $mail->Username = 'no-responder@ormve.org';
        $mail->Password = "5Q1FkC7NXQ1zxFs";
        $mail->setFrom('no-responder@ormve.org', 'ORMVE');
        $mail->addAddress($to);
        $mail->Subject = $subject;
        //$mail->msgHTML(file_get_contents('forgot.html'), __DIR__);
        $mail->isHTML(true);
        //$mail->msgHTML = $body;
        $mail->Body = $body;
        //if ($altbody=="")
        //    $mail->AltBody = $body;
        //else
        //    $mail->AltBody = $altbody;
        //send the message, check for errors
        
        return ($mail->send());
    }
}
?>
