loadServidoresEmail(); //print_r($resultado);print_r("\n"); if( $resultado ) { //Listado de Servidores de email disponibles $resultInfo['code'] = 0; $resultInfo['data'] = array( "total" => count($resultado) ,"servidores" => $resultado ); } else { $resultInfo['code'] = 1; $resultInfo['errorDes'] = "Se produjo un error al consultar el listado de servidores"; } } // Actualizar el estado de los servidores en la BD function updateEmailServer(&$resultInfo) { if( isset($_REQUEST["serlst"]) && !empty($_REQUEST["serlst"]) && !is_null($_REQUEST["serlst"]) ) { $server = new emailServer($GLOBALS['dbSQL']); $fecha = date("Y-m-d"); if( isset($_REQUEST["fecha"]) && !empty($_REQUEST["fecha"]) && !is_null($_REQUEST["fecha"]) ) { $fecha = $_REQUEST["fecha"]; } $servidores = json_decode($_REQUEST["serlst"],true); //print_r($servidores);print_r("\n");die; $resultado = $server->updateServidorEstadisticaContador($servidores,$fecha); //print_r($resultado);print_r("\n"); if( $resultado ) { //Listado de Servidores de email disponibles $resultInfo['code'] = 0; $resultInfo['data'] = array( "total" => count($resultado) ,"servidores" => $resultado ); } else { $resultInfo['code'] = 1; $resultInfo['errorDes'] = "Se produjo un error al actualizar el servidor"; } } else { $resultInfo['code'] = 1; $resultInfo['errorDes'] = "Parametros Faltantes"; } } //Listar los servidores disponibles en SEM function getSMTPEmailServer($totalEmailsToSend) { $server = new emailServer($GLOBALS['dbSQL']); $resultado = $server->getSMTPServer($totalEmailsToSend); //print_r($resultado);print_r("\n"); if( $resultado ) { return $resultado; } return false; } //Obtener un Servidor de SMTP disponible para el envio de un email function setEmailServer(&$emailInfo,&$servidores,$total) { for($i=0;$i<$total;$i++) { $umbralTmp = intval($servidores["result"][$i]["umbraltmp"]); $envio = intval($servidores["result"][$i]["envio"]); if( $umbralTmp <= $envio ) { $emailInfo["data"]["smtp"]=array( "user"=>$servidores["result"][$i]["serem_usuario"] ,"pass"=>$servidores["result"][$i]["serem_clave"] ,"smtp"=>$servidores["result"][$i]["serem_smtp"] ,"port"=>$servidores["result"][$i]["serem_puerto"] ); $servidores["result"][$i]["umbraltmp"] = $umbralTmp+1; return true; } } $emailInfo["data"]["smtp"] = false; return false; } //Obtener un Servidor de SMTP disponible para el envio de un email function setEmailMensajeServer(&$emailInfo,&$servidores,$total) { for($i=0;$i<$total;$i++) { $umbralTmp = intval($servidores["result"][$i]["umbraltmp"]); $envio = intval($servidores["result"][$i]["envio"]); if( $umbralTmp <= $envio ) { $emailInfo["smtp"]=array( "user"=>$servidores["result"][$i]["serem_usuario"] ,"pass"=>$servidores["result"][$i]["serem_clave"] ,"smtp"=>$servidores["result"][$i]["serem_smtp"] ,"port"=>$servidores["result"][$i]["serem_puerto"] ); $servidores["result"][$i]["umbraltmp"] = $umbralTmp+1; return true; } } $emailInfo["smtp"] = false; return false; } function callWebServiceSendingBlueAccess(&$resinfo=false) { //------------------------------------------------------------------------------ //Invocar al WebService //------------------------------------------------------------------------------ try { $url = $GLOBALS['WS_BROKER_EMAIL_ACCESS']; $params = array("customer" => $GLOBALS['WS_WHATSAPP_CUSTOMER']); ini_set("default_socket_timeout", 8000); $soapClient = new SoapClient(null, array('location' => $url,'uri' => 'urn:webservices', )); $resultado = $soapClient->getEmailAccess($params); $success = json_decode($resultado ,true); $resinfo = $success; // print_r("-----SB KEY----");print_r("\n"); // print_r($resultado);print_r("\n"); // print_r($resinfo); // print_r("-----*************----");print_r("\n"); return true; //------------------------------------------------------------------------------ } catch ( Exception $e ) { //Error al consultar el WS echo "Error al consultar el web service"; return false; } } function callWebServiceSendEmail($params,&$resinfo=false) { //------------------------------------------------------------------------------ //Invocar al WebService //------------------------------------------------------------------------------ try { $url = $GLOBALS['WS_BROKER_EMAIL']; ini_set("default_socket_timeout", 8000); $soapClient = new SoapClient(null, array('location' => $url,'uri' => 'urn:webservices', )); $resultado = $soapClient->sendEmail($params); $resinfo = json_decode($resultado ,true); // print_r("-----SB KEY----");print_r("\n"); // print_r($resultado);print_r("\n"); // print_r($resinfo); // print_r("-----*************----");print_r("\n"); return true; //------------------------------------------------------------------------------ } catch ( Exception $e ) { //Error al consultar el WS print_r("Error al consultar el web service");print_r("\n"); print_r($e->__toString());print_r("\n"); return false; } } function callWebServiceSendEmailAlerta($params,&$resinfo=false) { //------------------------------------------------------------------------------ //Invocar al WebService //------------------------------------------------------------------------------ try { // print_r("----------------");print_r("\n"); // print_r($params); // print_r("----------------");print_r("\n"); // die(" <<<<<"); $url = $GLOBALS['WS_BROKER_EMAIL']; ini_set("default_socket_timeout", 8000); $soapClient = new SoapClient(null, array('location' => $url,'uri' => 'urn:webservices', )); $resultado = $soapClient->sendEmailAlerta($params); $resinfo = json_decode($resultado ,true); // print_r("-----SB KEY----");print_r("\n"); // print_r($resultado);print_r("\n"); // print_r($resinfo); // print_r("-----*************----");print_r("\n"); return true; //------------------------------------------------------------------------------ } catch ( Exception $e ) { //Error al consultar el WS print_r("Error al consultar el web service");print_r("\n"); print_r($e->__toString());print_r("\n"); return false; } } // -------------------------------------------- // END SERVIDOR DE EMAILS // -------------------------------------------- function enviarEmailContacto() { $nombre = false; $email = false; $telefono = false; $comentario = false; //print_r($_REQUEST);die; if( !isset($_REQUEST['nombre']) || is_null($_REQUEST['nombre']) || empty($_REQUEST['nombre']) ) { return 1; //Nombre invalido/vacio } else { $nombre = base64_decode($_REQUEST['nombre']); } if( !isset($_REQUEST['email']) || is_null($_REQUEST['email']) || empty($_REQUEST['email']) ) { return 2; //Email invalido/vacio } else { $email = base64_decode($_REQUEST['email']); } if( !isset($_REQUEST['tel']) || is_null($_REQUEST['tel']) || empty($_REQUEST['tel']) ) { return 3; //Telefono invalido/vacio } else { $telefono = base64_decode($_REQUEST['tel']); } if( !isset($_REQUEST['mensaje']) || is_null($_REQUEST['mensaje']) || empty($_REQUEST['mensaje']) ) { return 4; //Comentario invalido/vacio } else { $comentario = base64_decode($_REQUEST['mensaje']); } $subject = "Consulta Web SMI"; $from = $GLOBALS['FROM']; $fromN = $GLOBALS['FROMN']; $body = ""; $body .= '-----------------------------------------------'. "\n"; $body .= 'Fecha: '. date("d/m/Y H:i:s") . "\n"; $body .= '-----------------------------------------------'. "\n"; $body .= 'Nombre: '. $nombre . "\n"; $body .= '-----------------------------------------------'. "\n"; $body .= 'Teléfono:'. $telefono . "\n"; $body .= '-----------------------------------------------'. "\n"; $body .= 'Email: '. $email . "\n"; $body .= '-----------------------------------------------'. "\n"; $body .= 'Mensaje: '. $comentario . "\n"; $uniq_id = md5(uniqid(time())); $Headers = "Date: ".RFCDate()."\r\n"; $Headers .= "Return-Path: ".$from."\r\n"; $Headers .= 'From: "'.$fromN.'" <'.$from.'>'."\r\n"; $Headers .= "Message-ID: <".$uniq_id."@localhost>"."\r\n"; $Headers .= "X-Priority: 3"."\r\n"; $Headers .= "MIME-Version: 1.0"."\r\n"; $Headers .= "Content-type: text/html; charset=iso-8859-1"."\r\n"; $exito = @mail(EMAIL_CONSULTAS, $subject, $body, $Headers); //$exito = @mail(EMAIL_INFOSMI, $subject, $body, $Headers); //$exito = @mail(EMAIL_ROMPEPELOTAS, $subject, $body, $Headers); $intentos=1; $reintentos=2; while ((!frmLoading) && ($intentos < $reintentos)) { sleep(5); $exito = @mail(EMAIL_CONSULTAS, $subject, $body, $Headers); //$exito = @mail(EMAIL_INFOSMI, $subject, $body, $Headers); //$exito = @mail(EMAIL_ROMPEPELOTAS, $subject, $body, $Headers); $intentos++; } print_r("exito[$exito]");die; return 0; } // -------------------------------------------- // OTROS // -------------------------------------------- function getEmail_CT_HTMLWs() { //*********************************************************** // HTML //*********************************************************** $msjHTML ='
 

Acuse de Confirmación de Turno

 
Los datos de turno, son los siguientes
 
N° Turno:   {turnoN}
Fecha:   {turnoF}
Hora:   {turnoH}
Obra Social:   {turnoO}
Plan:   {turnoP}
Profesional:   {turnoM}
Especialidad:   {turnoE}
 
[ ATENCIÓN: No responda este email, fue generado Automáticamente por el Sistema ]
 
Generado por: LandaMed Software de gestión integral de centros médicos - Desarrollado por Landaware I+D
'; return $msjHTML; } function getEmail_CCT_HTMLWs() { //*********************************************************** // HTML //*********************************************************** $msjHTML ='
 

Acuse de Cancelación de Turno

 
Los datos del turno Cancelado, son los siguientes
 
N° Turno:   {turnoN}
Fecha:   {turnoF}
Hora:   {turnoH}
Obra Social:   {turnoO}
Plan:   {turnoP}
Médico:   {turnoM}
Especialidad:   {turnoE}
 
[ ATENCIÓN: No responda este email, fue generado Automáticamente por el Sistema ]
 
Generado por: LandaMed Software de gestión integral de centros médicos - Desarrollado por Landaware I+D
'; return $msjHTML; } function getEmail_SI_HTML() { //*********************************************************** // HTML //*********************************************************** $msjHTML ='
 

Solicitud de Interconsulta

 
Profesional Solicitante {SOLICITANTE}
 
Profesional Efector {EFECTOR}
 
Fecha {FECHA}
 
{RESUMEN}
Detalle del Pedido de Interconsulta
 

Ante cualquier consulta, por favor, contactarse con:

consultorio@sanatorioduartequiros.com

Saludos cordiales,

Secretaria de turnos SDQ

 
[ ATENCIÓN: No responda este email, fue generado Automáticamente por el Sistema ]
 
Generado por: LandaMed Software de gestión integral de centros médicos - Desarrollado por Landaware I+D
'; return $msjHTML; } function sendEmailConfirmacionWs($tipo, $idTurno, $finalCall=false) { // Envio de emails de Alertas $body = ''; if( $tipo == TYPE_EMAIL_CT) { $infoTurno = getDataTurnoWs($idTurno); $datos = array(); $datos['id'] = $idTurno; $datos['info'] = array(); $datos['info'][0] = $infoTurno[0]; $datos['info'][1] = $infoTurno[1]; $datos['info'][2] = $infoTurno[2]; $datos['info'][3] = $infoTurno[3]; $datos['info'][4] = $infoTurno[4]; $datos['info'][5] = $infoTurno[5]; $datos['info'][6] = ''; $datos['info'][7] = ''; $datos['info'][8] = $infoTurno[10]; $datos['email'] = $infoTurno[9]; } if( $tipo == TYPE_EMAIL_CCT) { $datos = array(); $datos['id'] = $idTurno['id']; $datos['info'] = $idTurno['data']; $datos['email'] = $idTurno['data'][9]; } if( $tipo == TYPE_EMAIL_RC) { $datos = array(); $datos['dni'] = $idTurno['dni']; $datos['cl'] = $idTurno['cl']; $datos['email'] = $idTurno['email']; } // ---------------------- // VALIDACION DEL EMAIL // ---------------------- if( !(filter_var($datos['email'], FILTER_VALIDATE_EMAIL)) ) { //Email inválido return false; } else { switch($tipo) { //Confirmaicion de Alta de Turno case TYPE_EMAIL_CT: $txtSubject = "Confirmación de Turno"; $body = getEmail_CT_HTMLWs(); break; //Confirmaicion de Cancelacion de Turno case TYPE_EMAIL_CCT: $txtSubject = "Cancelación de Turno"; $body = getEmail_CCT_HTMLWs(); break; //Recuperar Clave case TYPE_EMAIL_RC: $txtSubject = "Recuperar Clave"; $body = '';//getEmail_CCT_HTMLWs(); break; } $body = getReplaceData($tipo, $body, $datos); $subject = $GLOBALS['SUBJECT'] . $txtSubject; $from = $GLOBALS['FROM']; $fromN = $GLOBALS['FROMN']; if( !$finalCall ) { saveEmailOnQueue($from,$subject,$tipo,$datos); } else { $uniq_id = md5(uniqid(time())); $Headers = "Date: ".RFCDate()."\r\n"; $Headers .= "Return-Path: ".$from."\r\n"; $Headers .= 'From: "'.$fromN.'" <'.$from.'>'."\r\n"; $Headers .= "Message-ID: <".$uniq_id."@localhost>"."\r\n"; $Headers .= "X-Priority: 3"."\r\n"; $Headers .= "MIME-Version: 1.0"."\r\n"; $Headers .= "Content-type: text/html; charset=iso-8859-1"."\r\n"; $exito = @mail($datos['email'], $subject, $body, $Headers); $intentos=1; $reintentos=2; while ((!$exito) && ($intentos < $reintentos)) { sleep(5); $exito = @mail($datos['email'], $subject, $body, $Headers); $intentos++; } } } } // -------------------------------------------- // END OTROS // -------------------------------------------- // -------------------------------------------- // RECORDATORIOS - PROCESOS POR LOTE // -------------------------------------------- function saveEmailOnQueue($from,$subject,$type,$datos) { if( isset($datos['email']) && !empty($datos['email']) && !is_null($datos['email']) && trim($datos['email'])!='' ) { $emailInfo = array(); $emailInfo['type'] = $type; $emailInfo['data'] = $datos; $output = encodeDataB64($emailInfo); $sql = " INSERT INTO dbo.[email] ([ema_fecha],[ema_smtp],[ema_from],[ema_to],[ema_cc],[ema_bcc],[ema_subjec],[ema_messag],[ema_attach],[ema_succes],[ema_send]) "; $sql.= " VALUES( getdate(),' ','".$from."','".trim($datos['email'])."',NULL,NULL,'".$subject."','".$output."',NULL,0,NULL )"; $rs = $GLOBALS['dbSQL']->Query($sql,true); if ( $rs ) { return true; } } return false; } function isEmailInProgress() { $sql = " SELECT COUNT(*) as total FROM dbo.[emails_in_process] WHERE [emprc_estado] IS NULL"; $rs = $GLOBALS['dbSQL']->Query($sql); if ( $rs ) { $rs = $GLOBALS['dbSQL']->getAll(); if(intval($rs[0]["total"])>=1) { return true; // Hay un proceso activo de envio de emails } } return false; //No hay un preoceso activo de envio de emails } function openEmailProgress() { $sql = " INSERT INTO dbo.[emails_in_process] (emprc_estado,emprc_tstamp_init) VALUES (NULL,GETDATE())"; $rs = $GLOBALS['dbSQL']->Query($sql,true); if ( $rs ) { return true; } return false; } function closeEmailProgress() { $sql = " UPDATE dbo.[emails_in_process] SET emprc_estado = 1, emprc_tstamp = GETDATE() WHERE emprc_estado IS NULL"; $rs = $GLOBALS['dbSQL']->Query($sql,true); if ( $rs ) { return true; } return false; } function processEmailQueue() { if(!isEmailInProgress()) { //Set in progress try { openEmailProgress(); $top = " TOP " . $GLOBALS['EMAIL_SEND_TOP']; $sql = " SELECT ".$top." * FROM dbo.[email] WHERE [ema_succes] = 0 AND ema_to LIKE '%@%.%'"; $rs = $GLOBALS['dbSQL']->Query($sql); if ( $rs ) { $conta=0; $rs = $GLOBALS['dbSQL']->getAll(); //print_r($rs);die; $lstEmailsQueue = array(); //------------------------------------- $continue = false; $servidores = false; $totalEmails = count($rs); $totalServidores = 0; if( $totalEmails > 0 ) { $servidores = getSMTPEmailServer($totalEmails); } if(!$servidores) { // print_r("Error al obtener los servidores...");print_r("\n"); $continue = true;// <== quitar es para test $emailInfo["data"]["smtp"]=array( // <== quitar es para test "user"=>'u' ,"pass"=>'p' ,"smtp"=>'s' ,"port"=>'0' ); $servidores["result"][0]["umbraltmp"] = 1;// <== quitar es para test } else { // print_r("-----------ok---------");print_r("\n"); // print_r($servidores);print_r("\n"); $totalServidores = count($servidores); if($totalServidores>0) { $continue = true; } } //print_r("<<<<<<<<<<<<<<<<<<<<<<<<<");die; //------------------------------------- // print_r("--------SERVIDORES ANTES-----------");print_r("\n"); // print_r($servidores);print_r("\n"); // print_r("-----------------------------------");print_r("\n"); if($continue) { /* foreach($rs as $row) { $emailId = $row["ema_numero"]; $emailInfo = decodeDataB64($row["ema_messag"]); //$emailInfo["data"]["email"] = 'juarezgustavoa@gmail.com'; setEmailServer($emailInfo,$servidores,$totalServidores); array_push($lstEmailsQueue, array(0=>$emailId, 1=>$emailInfo)); $conta++; } */ // print_r("--------SERVIDORES DESPUES-----------");print_r("\n"); // print_r($servidores);print_r("\n"); // print_r("--------LISTADO DE EMAILS-----------");print_r("\n"); //print_r($lstEmailsQueue);print_r("\n");die; //--------------------------------- // Grabar grupo de envio //--------------------------------- //saveGrupoEnvio(GRUPO_ENVIO_TIPO_EMAIL,$lstEmailsQueue) //--------------------------------- if($conta>0) { for($i=0;$iQuery($sql,true); if ( $rs ) { return true; } } return false; } function isMessagesInProgress() { $sql = " SELECT COUNT(*) as total FROM dbo.[mensajes_in_process] WHERE [msgprc_estado] IS NULL AND msgprc_type = 'EMAIL'"; $rs = $GLOBALS['dbSQL']->Query($sql); if ( $rs ) { $rs = $GLOBALS['dbSQL']->getAll(); if(intval($rs[0]["total"])>=1) { return true; // Hay un proceso activo de envio de mensajes } } return false; //No hay un preoceso activo de envio de mensajes } function openMessagesProgress() { $sql = " INSERT INTO dbo.[mensajes_in_process] (msgprc_estado,msgprc_tstamp_init,msgprc_type) VALUES (NULL,GETDATE(),'EMAIL')"; $rs = $GLOBALS['dbSQL']->Query($sql,true); if ( $rs ) { return true; } return false; } function closeMessagesProgress() { $sql = " UPDATE dbo.[mensajes_in_process] SET msgprc_estado = 1, msgprc_tstamp = GETDATE() WHERE msgprc_estado IS NULL AND msgprc_type = 'EMAIL'"; $rs = $GLOBALS['dbSQL']->Query($sql,true); if ( $rs ) { return true; } return false; } function createSesionMessages($totalMensajes,$usuario) { $p = '1234567890ADSFFSDFQAMDEPESFDGFDGDFG0985SFFSD'; $sesion = md5(randomText(6,$p).date("Y-m-d").time()); $sql = "INSERT INTO dbo.[mensajes_envio_grupo] ([menenvgr_fechaenvio] ,[menenvgr_tipo] ,[menenvgr_estado] ,[menenvgr_total] ,[menenvgr_sesion] ,[usu_codigo]) VALUES (GETDATE() ,'E' ,0 ,".$totalMensajes." ,'".$sesion."' ,".$usuario.")"; $rs = $GLOBALS['dbSQL']->Query($sql,true); if ( $rs ) { $idGrupo = $GLOBALS['dbSQL']->getLastId('mensajes_envio_grupo','menenvgr_id'); return array($idGrupo,$sesion); } return array(false,false); } function closeSesionMessages($idSesion,$totalFinal) { $sql = " UPDATE mensajes_envio_grupo SET menenvgr_estado = 1, menenvgr_total_enviados = ".$totalFinal." WHERE menenvgr_id = ".$idSesion; $rs = $GLOBALS['dbSQL']->Query($sql,true); if ( $rs ) { return true; } return false; } function saveLogJobError() { $sql = " INSERT INTO jobs (job_nombre,job_fecha,job_total,job_fecha_param) VALUES ('CUOTA EMAIL EXEDIDA',GETDATE(),0,NULL)"; $rs = $GLOBALS['dbSQL']->Query($sql); if ( !$rs ) { return false; } } function updateEmailCuotaDiaria($total) { //Si no existe una cuota diaria, crear $sql = "SELECT mencuo_numero as cuotaid FROM mensajes_cuota WHERE LEFT(CONVERT(VARCHAR,mencuo_fecha, 120), 10) = LEFT(CONVERT(VARCHAR,GETDATE(), 120), 10)"; $rs = $GLOBALS['dbSQL']->Query($sql); if ( !$rs ) { return false; } $cuotaInfo = $GLOBALS['dbSQL']->getAll(); if(count($cuotaInfo)<=0) { $sql = " INSERT INTO mensajes_cuota (mencuo_fecha,mencuo_contador) VALUES (GETDATE(),0)"; $rs = $GLOBALS['dbSQL']->Query($sql,true); if ( !$rs ) { return false; } } $sql = " UPDATE mensajes_cuota SET mencuo_contador = mencuo_contador + ".$total." WHERE LEFT(CONVERT(VARCHAR,mencuo_fecha, 120), 10) = LEFT(CONVERT(VARCHAR,GETDATE(), 120), 10)"; $rs = $GLOBALS['dbSQL']->Query($sql,true); if ( $rs ) { return true; } return false; } function validarEmailCuota($total,&$resto=0) { updateEmailCuotaDiaria(0);//CREO LA CUOTA DIARIA SI NO EXISTE //CALCULAR EL RANGO DE FECHA DEL PERIODO ACTUAL $fecha = date("Y-m-d"); $fechaIni = substr($fecha,0,4)."-".substr($fecha,5,5)."-01"; $fechaFin = false; $sql = " SELECT EOMONTH('".$fecha."') as final"; $rs = $GLOBALS['dbSQL']->Query($sql); if ( $rs ) { $fechaInfo = $GLOBALS['dbSQL']->getAll(); if(count($fechaInfo)>0) { $fechaFin = substr($fechaInfo[0]["final"],0,4)."-".substr($fechaInfo[0]["final"],5,5)."-".substr($fechaInfo[0]["final"],8,2); } } if(!$fechaFin) { return EMAIL_ERROR_CALCULAR_FECHAS; } //CONTAR LA CANTIDAD DE MENSAJES ENVIADOS OK $sql = "SELECT SUM(mencuo_contador) as total FROM mensajes_cuota WHERE LEFT(CONVERT(VARCHAR,mencuo_fecha, 120), 10) BETWEEN LEFT(CONVERT(VARCHAR,'".$fechaIni."', 120), 10) AND LEFT(CONVERT(VARCHAR,'".$fechaFin."', 120), 10)"; //print_r($sql);print_r("\n");die; $rs = $GLOBALS['dbSQL']->Query($sql); if ( !$rs ) { return EMAIL_ERROR_CALCULAR_ENVIADOS; } $cuotaInfo = $GLOBALS['dbSQL']->getAll(); if(count($cuotaInfo)>0) { $totalEnviado=$cuotaInfo[0]["total"]; } else { $totalEnviado=0; } //print_r("totalEnviado[$totalEnviado]cta[".$GLOBALS['EMAIL_CUOTA_DIARIA']."]");print_r("\n"); if($totalEnviado<=intval($GLOBALS['EMAIL_CUOTA_DIARIA'])) { if(($totalEnviado+$total)<=intval($GLOBALS['EMAIL_CUOTA_DIARIA'])) { return EMAIL_CUOTA_PERMITIDA; } else { $resto = intval($GLOBALS['EMAIL_CUOTA_DIARIA']) - intval($totalEnviado); } } return EMAIL_ERROR_CUOTA_AGOTADA; } function processEmailMessagesQueue() { //testMs(); if(!isMessagesInProgress()) { //Set in progress try { openMessagesProgress(); // ,(CASE WHEN men_token is not null AND men_tipo BETWEEN 1 AND 3 THEN (SELECT tnro.tur_numero FROM turnos as tnro WHERE tnro.tur_token = men.men_token ) ELSE '' END) as turnro // ,(CASE WHEN men_token is not null AND men_tipo BETWEEN 1 AND 3 THEN (SELECT obsp.obsp_denom FROM turnos as tpl INNER JOIN obsplan as obsp ON tpl.obsp_cod = obsp.obsp_cod AND tpl.obs_codigo = obsp.obs_codigo WHERE tur_token = men.men_token ) ELSE '' END) as turpl // ,(CASE WHEN men_token is not null AND men_tipo BETWEEN 1 AND 3 THEN (SELECT esp.esp_denom FROM turnos as tesp INNER JOIN especial as esp ON tesp.esp_codigo = esp.esp_codigo WHERE tesp.tur_token = men.men_token ) ELSE '' END) as turesp // ,'' as turnro // ,'' as turpl // ,'' as turesp //$sql = " SELECT * FROM dbo.[mensajes] WHERE [men_procesado] = 0"; $top = " TOP " . $GLOBALS['EMAIL_SEND_TOP']; $sql = " SELECT ".$top." men.men_id ,men.men_fechaenvio ,FORMAT ( men_fecha, 'dd/MM/yyyy' ) as men_fecha ,men.men_hora ,men.men_destinatario ,men.men_paciente ,men.men_medico ,men.men_obs ,men.men_texto ,men.men_procesado ,men.men_fechaproceso ,men.men_tstamp ,men.men_tipo ,men.men_asunto ,men.men_email_remitente ,men.men_nombre_remitente ,men.men_token ,'' as turnro ,'' as turpl ,'' as turesp ,mtmpl.mencust_codigo AS template FROM dbo.[mensajes] as men INNER JOIN mensajes_templates as mtmpl ON mtmpl.mencust_tipo = men.men_tipo WHERE men.men_procesado = 0"; //print_r($sql);print_r("\n");die; $rs = $GLOBALS['dbSQL']->Query($sql); if ( $rs ) { $conta=0; $rs = $GLOBALS['dbSQL']->getAll(); $lstEmailsQueue = array(); //------------------------------------- $continue = true; $servidores = false; $totalEmails = count($rs); $totalServidores = 0; $resCuota = false; $restoCuota = 0; $restoCuotaContador = 0; $flagCuotaLimitada = false; if( $totalEmails > 0 ) { $resCuota = validarEmailCuota($totalEmails,$restoCuota); //-->$servidores = getSMTPEmailServer($totalEmails); } // print_r("----validarEmailCuota---------");print_r("\n"); // print_r("resCuota[".$resCuota."]");print_r("\n"); // print_r("restoCuota[".$restoCuota."]");print_r("\n"); // print_r("--------------------------");print_r("\n"); if($resCuota!==EMAIL_CUOTA_PERMITIDA) { if($restoCuota<=0) { //Grabar log del job: especificar el error saveLogJobError(); $continue=false; } else { //Quitar Sobrantes $flagCuotaLimitada=true; $restoCuotaContador=$restoCuota; $continue=true; } } else { $continue=true; } if( $continue ) { $idsesion=''; $sesion =''; list($idsesion,$sesion) = createSesionMessages($totalEmails,$GLOBALS['USER_BOOT_SEND_MESSAGES']); foreach($rs as $row) { if( !(filter_var($row['men_destinatario'], FILTER_VALIDATE_EMAIL)) ) { //Email inválido $r = updateEmailMessagesState($row['men_id'],$idsesion,true); //TODO: Mejorar la captura de error } elseif($flagCuotaLimitada&&$restoCuotaContador<=0) { //Email sin cuota disponible $r = updateEmailMessagesState($row['men_id'],$idsesion,false,true); } else { $params = array(); $params['id'] = $row['men_id']; $params['sesion'] = $idsesion; $params['tipo'] = $row['men_tipo']; $params['email'] = $row['men_destinatario']; $params['nombre'] = encodeDataB64(htmlentities($row['men_paciente'])); $params["customer"]= $GLOBALS['WS_WHATSAPP_CUSTOMER']; $params['template']= $row['template']; switch( intval($row['men_tipo']) ) { //Turno //Cancelación Turno //Recordatotio Turno case 1: case 2: case 3: { $params['fecha'] = $row['men_fecha']; $params['hora'] = $row['men_hora']; $params['obs'] = encodeDataB64(htmlentities($row['men_obs'])); $params['med'] = encodeDataB64(htmlentities($row['men_medico'])); $params['token'] = $row['men_token']; $params['turnro'] = $row['turnro']; $params['plan'] = $row['turpl']; $params['esp'] = $row['turesp']; } break; //Resumen de turno case 4: { $hoy = Date("Y-m-d"); $datos['info'][0] = $row['men_fecha']; // date("d/m/Y",strtotime($hoy. ' + 1 days')); $datos['info'][1] = encodeDataB64($row['men_texto']); $datos['info'][2] = htmlentities($row['men_medico']); } break; //Copia Aviso a email case 5: { $datos['info'][0] = htmlentities($row['men_asunto']); $datos['info'][1] = htmlentities($row['men_texto']); $datos['info'][2] = htmlentities($row['men_nombre_remitente']); $datos['info'][3] = $row['men_fecha']; $datos['info'][4] = htmlentities($row['men_email_remitente']); } break; //Pedido de Interconsulta case 6: { $datos['info'][0] = htmlentities($row['men_nombre_remitente']); $datos['info'][1] = htmlentities($row['men_medico']); $datos['info'][2] = date("d/m/Y H:i",strtotime(str_replace(".000","",$row['men_fecha']))); $datos['info'][3] = encodeDataB64($row['men_texto']); } break; //Reclamo de estudio case 11: { /*$datos['info'][0] = htmlentities($row['men_paciente']); $datos['info'][1] = $row['men_hora']; $datos['info'][2] = encodeDataB64($row['men_texto']); $datos['info'][3] = $row['men_token']; $datos['info'][4] = $row['men_fecha'];*/ $params['nro'] = $row['men_hora']; $params['detalle'] = encodeDataB64($row['men_texto']); $params['archivo'] = $row['men_token']; $params['fecha'] = $row['men_fecha']; } break; } if( intval($params['template'])>0 ) { $conta++; //array_push($lstEmailsQueue, $datos); array_push($lstEmailsQueue, $params); } } if($flagCuotaLimitada) { $restoCuotaContador--; } } if($conta>0) { //print_r($lstEmailsQueue);print_r("\n");die; for($i=0;$iQuery($sql,true); if ( $rs ) { $sql = "DELETE FROM dbo.[email] WHERE [ema_send] IS NOT NULL AND [ema_succes] = 1"; $rsN = $GLOBALS['dbSQL']->Query($sql,true); if ( $rsN ) { return true; } } return false; } function cleanEmailMessagesSendedQueue() { $sql = " INSERT INTO dbo.[mensajes_procesados] (men_id,men_fechaenvio,men_fecha,men_hora,men_destinatario,men_paciente,men_medico,men_obs,men_texto,men_procesado,men_fechaproceso,men_tstamp,men_tipo,men_asunto,men_email_remitente,men_nombre_remitente,men_token,men_server_response,men_reprocesar,men_invalido,men_sendingblue_id,men_resultado,men_cuota) "; $sql.= " SELECT men_id,men_fechaenvio,men_fecha,men_hora,men_destinatario,men_paciente,men_medico,men_obs,men_texto,men_procesado,men_fechaproceso,men_tstamp,men_tipo,men_asunto,men_email_remitente,men_nombre_remitente,men_token,men_server_response,men_reprocesar,men_invalido,men_sendingblue_id,men_resultado,men_cuota"; $sql.= " FROM dbo.[mensajes] "; $sql.= " WHERE [men_fechaproceso] IS NOT NULL AND [men_procesado] = 1 "; $rs = $GLOBALS['dbSQL']->Query($sql,true); if ( $rs ) { $sql = "DELETE FROM dbo.[mensajes] WHERE [men_fechaproceso] IS NOT NULL AND [men_procesado] = 1"; $rsN = $GLOBALS['dbSQL']->Query($sql,true); if ( $rsN ) { return true; } } return false; } function updateEmailState($result, $id, $resInfo=false) { /* if( $result!==false && $result!==0 ) { $sql = " UPDATE dbo.[email] SET [ema_succes] = 1, [ema_send] = getdate() "; $sql.= " WHERE [ema_numero] = ".$id; } else { $sql = " UPDATE dbo.[email] SET [ema_succes] = 0, [ema_send] = NULL "; $sql.= " WHERE [ema_numero] = ".$id; } $rs = $GLOBALS['dbSQL']->Query($sql,true); if ( $rs ) { return true; } return false; */ $flagReprocesar = '0'; if(!$resInfo) { $flagReprocesar = '1'; $sql = " INSERT INTO dbo.[email_reprocesar] SELECT * FROM dbo.[email] WHERE [ema_numero] = ".$id; $rs = $GLOBALS['dbSQL']->Query($sql,true); if ( $rs ) { //Error, seguir adelante, se pierde el envio y reprocesamiento } } $sql = " UPDATE dbo.[email] SET [ema_succes] = 1, [ema_send] = getdate() [ema_server_response] = '".print_r($resInfo,true)."' [ema_reprocesar] = ".$flagReprocesar." WHERE [ema_numero] = ".$id; $rs = $GLOBALS['dbSQL']->Query($sql,true); if ( $rs ) { return true; } return false; } function updateEmailMessagesState($id,$idsesion,$flagInvalido=false,$flagCuota=false,$resInfo=false) { try { $flagReprocesar = '0'; //if(!$flagInvalido && !$resInfo) if($flagCuota) { $flagReprocesar = '1'; $sql = " INSERT INTO dbo.[mensajes_reprocesar] SELECT * FROM dbo.[mensajes] WHERE [men_id] = ".$id; $rs = $GLOBALS['dbSQL']->Query($sql,true); if ( !$rs ) { //Error, seguir adelante, se pierde el envio y reprocesamiento } } $sendingblueid = false; if(isset($resInfo["i"]["messageId"])) { $sendingblueid = str_replace("<","",$resInfo["i"]["messageId"]); $sendingblueid = str_replace(">","",$sendingblueid); } $sql = " UPDATE dbo.[mensajes] SET [men_procesado] = 1, [men_fechaproceso] = getdate(), [men_server_response] = '".print_r($resInfo,true)."' , [men_reprocesar] = ".$flagReprocesar.", [men_invalido] = ".($flagInvalido?'1':'0').", [men_sendingblue_id] = ".($sendingblueid?"'".$sendingblueid."'":'NULL').", [menenvgr_id] = '".$idsesion."', [men_resultado] = ".intval($resInfo["r"])." [men_cuota] = ".($flagCuota?'1':'0').", WHERE [men_id] = ".$id; $rs = $GLOBALS['dbSQL']->Query($sql,true); if ( $rs ) { return true; } return false; } catch (Exception $e) { //print_r("updateEmailMessagesState >>>>>> Error:".($e->__toString())); return false; } } function updateEmailAlertaState($id,$resInfo=false) { try { $sendingblueid = false; if(isset($resInfo["i"]["messageId"])) { $sendingblueid = str_replace("<","",$resInfo["i"]["messageId"]); $sendingblueid = str_replace(">","",$sendingblueid); } $sql = " UPDATE dbo.[mensajes_alerta] SET [menal_procesado] = 1, [menal_fechaproceso] = getdate(), [menal_server_response] = '".print_r($resInfo,true)."' , [menal_sendingblue_id] = ".($sendingblueid?"'".$sendingblueid."'":'NULL').", [menal_resultado] = ".intval($resInfo["r"])." WHERE [menal_numero] = ".$id; $rs = $GLOBALS['dbSQL']->Query($sql,true); if ( $rs ) { return true; } return false; } catch (Exception $e) { //print_r("updateEmailMessagesState >>>>>> Error:".($e->__toString())); return false; } } function isEmailAlertaInProgress() { $sql = " SELECT COUNT(*) as total FROM dbo.[mensajes_in_process] WHERE [msgprc_estado] IS NULL AND msgprc_type = 'EMAILALERT'"; $rs = $GLOBALS['dbSQL']->Query($sql); if ( $rs ) { $rs = $GLOBALS['dbSQL']->getAll(); if(intval($rs[0]["total"])>=1) { return true; // Hay un proceso activo de envio de mensajes } } return false; //No hay un preoceso activo de envio de mensajes } function openEmailAlertaProgress() { $sql = " INSERT INTO dbo.[mensajes_in_process] (msgprc_estado,msgprc_tstamp_init,msgprc_type) VALUES (NULL,GETDATE(),'EMAILALERT')"; $rs = $GLOBALS['dbSQL']->Query($sql,true); if ( $rs ) { return true; } return false; } function closeEmailAlertaProgress() { $sql = " UPDATE dbo.[mensajes_in_process] SET msgprc_estado = 1, msgprc_tstamp = GETDATE() WHERE msgprc_estado IS NULL AND msgprc_type = 'EMAILALERT'"; $rs = $GLOBALS['dbSQL']->Query($sql,true); if ( $rs ) { return true; } return false; } function testEmailAlertaMs() { closeEmailAlertaProgress(); $res=false; // $r=callWebServiceSendingBlueAccess($res); // print_r("------////----");print_r("\n"); // print_r(json_decode($res));die; $sql = " update dbo.[mensajes_alerta] set [menal_procesado] = 0, [menal_fechaproceso]=null, menal_server_response = '' WHERE menal_numero = 3"; $rs = $GLOBALS['dbSQL']->Query($sql,true); if ( $rs ) { return true; } return false; } function processEmailAlertaQueue() { //testEmailAlertaMs(); if(!isEmailAlertaInProgress()) { //Set in progress try { openEmailAlertaProgress(); $top = " TOP " . $GLOBALS['EMAIL_ALERTA_SEND_TOP']; $sql = " SELECT ".$top." menal_numero AS id ,t.tur_numero as turnonro ,FORMAT ( t.tur_fecha, 'dd/MM/yyyy' ) as fechaTurno ,t.tur_hora as hora ,c.cli_nombre as paciente ,c.cli_dni as documento ,m.med_nombre as medico ,e.emp_nombre as usuario ,o.obs_denom AS obs ,p.obsp_denom AS plan_ ,tur_registracion as fechaRegistracion ,men.menal_fecha as fechaRegistracionAlerta FROM mensajes_alerta as men INNER JOIN tbl_mensaje_alerta as ma ON ma.menal_codigo = men.menal_codigo INNER JOIN turnos as t ON t.tur_numero = men.menal_turno INNER JOIN clientes as c ON t.cli_codigo = c.cli_codigo INNER JOIN medicos as m ON t.med_codigo = m.med_codigo INNER JOIN empleado as e ON e.emp_codigo = t.usu_codigo INNER JOIN obrasoc as o ON o.obs_codigo = t.obs_codigo INNER JOIN obsplan as p ON p.obs_codigo = t.obs_codigo AND p.obsp_cod = t.obsp_cod WHERE men.menal_procesado = 0"; //print_r($sql);print_r("\n");die; // print_r("----------------");print_r("\n"); // print_r($params); // print_r("----------------");print_r("\n"); // die(" <<<<<"); $rs = $GLOBALS['dbSQL']->Query($sql); if ( $rs ) { $conta=0; $rs = $GLOBALS['dbSQL']->getAll(); $lstEmailsQueue = array(); //------------------------------------- $continue = true; $totalEmails = count($rs); if( $continue ) { foreach($rs as $row) { $params = array(); $params['id'] = $row['id']; $params['sesion'] = ''; $params['tipo'] = 30; //$row['men_tipo']; $params['email'] = $GLOBALS['EMAIL_ALERTA_DESTINATARIOS']; $params['paciente']= encodeDataB64(htmlentities($row['paciente'])); $params['doc'] = $row['documento']; $params['medico'] = encodeDataB64(htmlentities($row['medico'])); $params['usuario'] = encodeDataB64(htmlentities($row['usuario'])); $params['obs'] = encodeDataB64(htmlentities($row['obs'])); $params['plan'] = encodeDataB64(htmlentities($row['plan_'])); $params['alnro'] = $row['turnonro']; $params['tnro'] = $row['turnonro']; $params['fecha'] = $row['fechaTurno']; $params['hora'] = $row['hora']; $params['fturreg'] = $row['fechaRegistracion']; $params['falerta'] = $row['fechaRegistracionAlerta']; $params["customer"]= $GLOBALS['WS_WHATSAPP_CUSTOMER']; $params['template']= 9;//$row['template']; $conta++; array_push($lstEmailsQueue, $params); } if($conta>0) { //print_r($lstEmailsQueue);print_r("\n");die; for($i=0;$i","",$sendingblueid); // } $sql = " UPDATE web.cliente_alertas_tratamientos SET [cat_estado] = 1, [cat_fecha] = getdate(), [cat_resultado] = ".$resInfo." WHERE [cat_numero] = ".$id; // print_r("-----------------------");print_r("\n"); // print_r($sql);print_r("\n"); // print_r("-----------------------");print_r("\n"); $rs = $GLOBALS['dbSQL']->Query($sql,true); if ( $rs ) { return true; } return false; } catch (Exception $e) { //print_r("updateEmailMessagesState >>>>>> Error:".($e->__toString())); return false; } } function isEmailAlertaTratamientoInProgress() { $sql = " SELECT COUNT(*) as total FROM dbo.[mensajes_in_process] WHERE [msgprc_estado] IS NULL AND msgprc_type = 'EMAILALERTTRATAMIENTO'"; $rs = $GLOBALS['dbSQL']->Query($sql); if ( $rs ) { $rs = $GLOBALS['dbSQL']->getAll(); if(intval($rs[0]["total"])>=1) { return true; // Hay un proceso activo de envio de mensajes } } return false; //No hay un preoceso activo de envio de mensajes } function openEmailAlertaTratamientoProgress() { $sql = " INSERT INTO dbo.[mensajes_in_process] (msgprc_estado,msgprc_tstamp_init,msgprc_type) VALUES (NULL,GETDATE(),'EMAILALERTTRATAMIENTO')"; $rs = $GLOBALS['dbSQL']->Query($sql,true); if ( $rs ) { return true; } return false; } function closeEmailAlertaTratamientoProgress() { $sql = " UPDATE dbo.[mensajes_in_process] SET msgprc_estado = 1, msgprc_tstamp = GETDATE() WHERE msgprc_estado IS NULL AND msgprc_type = 'EMAILALERTTRATAMIENTO'"; $rs = $GLOBALS['dbSQL']->Query($sql,true); if ( $rs ) { return true; } return false; } function processEmailAlertaTratamientoQueue($flagReprocesar=true) { //testEmailAlertaMs(); if(!isEmailAlertaTratamientoInProgress()) { //Set in progress try { openEmailAlertaTratamientoProgress(); $continue=true; //------------------------------------------------------ //BUSCAR LISTADO DE ITEMS QUE TIENEN DEFINIDA UNA ALERTA //------------------------------------------------------ if($flagReprocesar) { $sql = "SELECT nom_alerta, nom_alerta_mensaje, nom_codigo, inos_cod FROM nomenclador WHERE nom_alerta IS NOT NULL AND nom_alerta_mensaje IS NOT NULL "; $rs = $GLOBALS['dbSQL']->Query($sql); if ( $rs ) { $nomenclador = $GLOBALS['dbSQL']->getAll(); if(is_array($nomenclador)&&count($nomenclador)>0) { for($i=0,$t=count($nomenclador);$i<$t;$i++) { if( trim($nomenclador[$i]["nom_alerta"])!="" && trim($nomenclador[$i]["nom_alerta_mensaje"])!="" ) { $alertaInfo = explode(";",$nomenclador[$i]["nom_alerta"]); $nombrePractica= $nomenclador[$i]["nom_alerta_mensaje"]; //DEBER TENER DEFINIDO AL MENOS LOS DIAS DE VENCIMIENTO Y AL MENOS UNA CANTIDAD DE DIAS DE ALERTA if( isset($alertaInfo[0])&&is_numeric($alertaInfo[0]) && isset($alertaInfo[1])&&is_numeric($alertaInfo[1]) ) { $vto = $alertaInfo[0]; for($k=1,$tk=(count($alertaInfo)-1);$k<$tk;$k++) //RECORRO TODOS LOS DIAS DEFINIDOS { $diasAlerta = $alertaInfo[$k]; //----------------------------------------------------------------- //BUSCAR LOS TURNOS CONFIRMADOS/NO CANCELADOS QUE TENGAN UNA ALERTA // >> DESCARTAR SI YA SE ENVIADO LA ALERTA AL CLIENTE PARA LA CANTIDAD DE DIAS //----------------------------------------------------------------- $sql = "SELECT t.tur_numero, t.nom_codigo, t.inos_cod, t.cli_codigo, c.cli_nombre, c.cli_email, t.tur_fecha FROM turnos AS t INNER JOIN clientes as c ON c.cli_codigo = t.cli_codigo WHERE t.tur_asiste = 1 AND t.nom_codigo = ".$nomenclador[$i]["nom_codigo"]." AND t.inos_cod = '".$nomenclador[$i]["inos_cod"]."' AND (DATEDIFF(day, t.tur_fecha, GETDATE())=(".($vto-$diasAlerta).")) AND NOT EXISTS ( SELECT 1 FROM web.cliente_alertas_tratamientos as tn WHERE tn.tur_numero = t.tur_numero AND tn.cat_diaalert = ".$diasAlerta." )"; // print_r("-----------------------");print_r("\n"); // print_r($sql);print_r("\n"); // print_r("-----------------------");print_r("\n"); $rs = $GLOBALS['dbSQL']->Query($sql); if ( $rs ) { $turnos = $GLOBALS['dbSQL']->getAll(); if(is_array($turnos)&&count($turnos)>0) { $items = ''; for($j=0,$tj=count($turnos);$j<$tj;$j++) { //----------------------------------------------------------------- //PREPARAR MENSAJE //----------------------------------------------------------------- $template = "({CLIID},{TURNOID},'{NOMBRE}','{EMAIL}',{MESES},{DIASALERTA},'{TRATAMIENTO}',{VALEMAIL},0,NULL,0,'{TFECHA}',GETDATE())"; $item = str_replace("{CLIID}",$turnos[$j]["cli_codigo"],$template); $item = str_replace("{TURNOID}",$turnos[$j]["tur_numero"],$item); $item = str_replace("{NOMBRE}",$turnos[$j]["cli_nombre"],$item); $item = str_replace("{EMAIL}",$turnos[$j]["cli_email"],$item); $item = str_replace("{MESES}",$vto,$item); $item = str_replace("{DIASALERTA}",$diasAlerta,$item); $item = str_replace("{TRATAMIENTO}",$nombrePractica,$item); $item = str_replace("{TFECHA}",$turnos[$j]["tur_fecha"],$item); if( !is_null($turnos[$j]["cli_email"]) && !empty($turnos[$j]["cli_email"]) && trim($turnos[$j]["cli_email"])!="" ) { $emailvalido = validarEmail($turnos[$j]["cli_email"]); } else { $emailvalido = false; } $item = str_replace("{VALEMAIL}",($emailvalido?1:0),$item); $sep=","; if($items==''){$sep='';} $items.=$sep.$item; } //----------------------------------------------------------------- //ENCOLAR MENSAJES //----------------------------------------------------------------- $sql = "INSERT INTO web.cliente_alertas_tratamientos ( cli_codigo ,tur_numero ,cli_nombre ,cli_email ,cat_meses ,cat_diaalert ,cat_praalert ,cat_validemail ,cat_estado ,cat_fecha ,cat_resultado ,cat_turfecha ,cat_fechainsert ) VALUES ".$items; // print_r("-----------------------");print_r("\n"); // print_r($sql);print_r("\n"); // print_r("-----------------------");print_r("\n"); $rs = $GLOBALS['dbSQL']->Query($sql,true); if ( $rs ) { $continue=true; } else { $continue=false; } } } } } } } } } } //------------------------------------------------------ //ENVIAR COLA DE MENSAJES DE ALERTA DE TRATAMIENTO //------------------------------------------------------ if($continue) { $top = " TOP " . $GLOBALS['EMAIL_ALERTA_SEND_TOP']; //$sql = " SELECT ".$top." cat_numero AS id $sql = " SELECT cat_numero AS id ,cli_codigo ,cli_nombre ,cli_email ,tur_numero ,CONCAT(cat_meses,' días') AS cat_meses ,cat_diaalert ,cat_praalert ,cat_estado ,cat_resultado ,cat_validemail ,cat_fecha ,cat_turfecha ,cat_fechainsert FROM web.cliente_alertas_tratamientos as men WHERE men.cat_estado = 0 AND cat_validemail = 1"; // print_r($sql);print_r("\n");die; // print_r("----------------");print_r("\n"); // print_r($params); // print_r("----------------");print_r("\n"); // die(" <<<<<"); print_r("-----------------------");print_r("\n"); print_r($sql);print_r("\n"); print_r("-----------------------");print_r("\n"); $rs = $GLOBALS['dbSQL']->Query($sql); if ( $rs ) { $conta=0; $rs = $GLOBALS['dbSQL']->getAll(); $lstEmailsQueue = array(); //------------------------------------- $continue = true; $totalEmails = count($rs); if( $continue ) { foreach($rs as $row) { $paramsEmail = array(); $paramsEmail["email"] = $row['cli_email']; $paramsEmail["cliN"] = encodeDataB64($row['cli_nombre']); $paramsEmail["praM"] = encodeDataB64($row['cat_meses']); $paramsEmail["praN"] = encodeDataB64($row['cat_praalert']); $paramsEmail["nombre"] = encodeDataB64($row['cli_nombre']); $paramsEmail["subject"] = "Recordatorio Must Estética Médica"; $paramsEmail['customer']= $GLOBALS['WS_WHATSAPP_CUSTOMER'];; $paramsEmail['template']= 19; //OBTENER DE LA BASE $paramsEmail['tipo'] = 29; //CAMBIAR A CONSTANTE $paramsEmail["fromn"] = $GLOBALS['FROMN']; $paramsEmail["from"] = $GLOBALS['FROM']; //print_r($paramsEmail);die(" <<<<<<<<< "); $result = false; $res = callWebServiceSendEmail($paramsEmail,$result); //$res=true; ($res?'1':'0'); $r = updateEmailAlertaTratamientoState($row['id'],$res); } } } } closeEmailAlertaTratamientoProgress(); } catch (Exception $e) { closeEmailAlertaTratamientoProgress(); } } else { print_r("Envio en progreso. Se cancela hilo de ejecucion"); } } function isMessagesRecordatorioTurnoInProgress() { $sql = " SELECT COUNT(*) as total FROM dbo.[mensajes_in_process] WHERE [msgprc_estado] IS NULL AND msgprc_type = 'EMAILIFERRECTUR'"; $rs = $GLOBALS['dbSQL']->Query($sql); if ( $rs ) { $rs = $GLOBALS['dbSQL']->getAll(); if(intval($rs[0]["total"])>=1) { return true; // Hay un proceso activo de envio de mensajes } } return false; //No hay un preoceso activo de envio de mensajes } function openMessagesRecordatorioTurnoProgress() { $sql = " INSERT INTO dbo.[mensajes_in_process] (msgprc_estado,msgprc_tstamp_init,msgprc_type) VALUES (NULL,GETDATE(),'EMAILIFERRECTUR')"; $rs = $GLOBALS['dbSQL']->Query($sql,true); if ( $rs ) { return true; } return false; } function closeMessagesRecordatorioTurnoProgress() { $sql = " UPDATE dbo.[mensajes_in_process] SET msgprc_estado = 1, msgprc_tstamp = GETDATE() WHERE msgprc_estado IS NULL AND msgprc_type = 'EMAILIFERRECTUR'"; $rs = $GLOBALS['dbSQL']->Query($sql,true); if ( $rs ) { return true; } return false; } function updateEmailRecordatorioTurnoMessagesState($turnonro,$resultado) { try { $sql = " UPDATE dbo.turnos SET tur_recordatorio = 1, tur_recordatorio_fecha = getdate(), tur_recordatorio_resultado = ".($resultado?1:0)." WHERE tur_numero = ".$turnonro; $rs = $GLOBALS['dbSQL']->Query($sql,true); if ( $rs ) { return true; } return false; } catch (Exception $e) { //print_r("updateEmailMessagesState >>>>>> Error:".($e->__toString())); return false; } } //function processEmailMessagesQueue() function processEmailRecordatorioTurnoMessagesQueue() { //testMs(); if(!isMessagesRecordatorioTurnoInProgress()) { //Set in progress try { openMessagesRecordatorioTurnoProgress(); $top = " TOP " . $GLOBALS['EMAIL_SEND_TOP']; $top = " TOP 2"; $fechaDesde = date("Y-m-d"); $fechaHasta = date("Y-m-d",strtotime('+1 days',strtotime($fechaDesde)));//TODO $fechaIni = date("Y-m-d 00:00:00.000",strtotime($fechaHasta)); $fechaFin = date("Y-m-d 23:59:59.000",strtotime($fechaHasta)); $fechaOrg = date("Y-m-d",strtotime($fechaHasta)); //AND tur_fecha = '".$fechaOrg."' //AND CONVERT(VARCHAR,tur_fecha,120) BETWEEN LEFT(CONVERT(VARCHAR, '".$fechaIni."', 120), 10) AND LEFT(CONVERT(VARCHAR, '".$fechaFin."', 120), 10) $sql = " SELECT ".$top." tur_numero as nro ,FORMAT ( tur_fecha, 'dd/MM/yyyy' ) as fecha ,tur_hora as hora ,c.cli_email as email ,obs.obs_denom as obrasoc ,c.cli_nombre as paciente ,t.med_codigo as medicocod ,med.med_nombre as medico FROM dbo.turnos as t LEFT JOIN dbo.clientes as c ON c.cli_codigo = t.cli_codigo LEFT JOIN dbo.medicos as med ON med.med_codigo = t.med_codigo LEFT JOIN dbo.obrasoc as obs ON obs.obs_codigo = t.obs_codigo WHERE t.cli_codigo > 1 AND ISNULL(tur_recordatorio,0) = 0 AND LEFT(CONVERT(VARCHAR, tur_fecha, 120), 10) BETWEEN LEFT(CONVERT(VARCHAR, '".$fechaIni."', 120), 10) AND LEFT(CONVERT(VARCHAR, '".$fechaFin."', 120), 10) AND c.cli_email IS NOT NULL"; //print_r($sql);print_r("\n"); closeMessagesRecordatorioTurnoProgress(); //die; $rs = $GLOBALS['dbSQL']->Query($sql); if ( $rs ) { $conta=0; $turnos = $GLOBALS['dbSQL']->getAll(); $lstEmailsQueue = array(); $continue = true; if( $continue ) { for($i=0,$t=count($turnos);$i<$t;$i++) { if( trim($turnos[$i]["email"])!="" && validarEmail($turnos[$i]["email"]) ) { $params = array(); $params['turnro'] = $turnos[$i]["nro"]; $params['sesion'] = $turnos[$i]["nro"]; $params['tipo'] = 44; //TIPO: RECORDATORIO $params['email'] = "juarezgustavoa@gmail.com";//$turnos[$i]["email"]; $params['nombre'] = encodeDataB64(htmlentities($turnos[$i]["paciente"])); $params["customer"]= $GLOBALS['WS_WHATSAPP_CUSTOMER']; $params['template']= 28; //TEMPLATE BREVO: RECORDATORIO TURNO $params['fecha'] = $turnos[$i]["fecha"]; if( strlen($turnos[$i]["hora"])<4 ) { $aux = "0" . substr($turnos[$i]["hora"],0, 1) . ":" . substr($turnos[$i]["hora"],1); } else { $aux = substr($turnos[$i]["hora"],0, 2) . ":" . substr($turnos[$i]["hora"],2); } $params['hora'] = $aux; $params['obs'] = encodeDataB64(htmlentities($turnos[$i]["obrasoc"])); $params['med'] = encodeDataB64(htmlentities($turnos[$i]["medico"])); $params['token'] = '111111'; $params['turnro'] = $turnos[$i]["nro"]; $params['plan'] = ''; $params['esp'] = ''; $paramsEmail["fromn"] = $GLOBALS['FROMN']; $paramsEmail["from"] = $GLOBALS['FROM']; print_r("turno[".$turnos[$i]["nro"]."]hora[".$params['hora']."]");print_r("\n"); $conta++; array_push($lstEmailsQueue, $params); } else { $r = updateEmailRecordatorioTurnoMessagesState($lstEmailsQueue[$i]['turnro'],false); } } if($conta>0) { //print_r($lstEmailsQueue);print_r("\n");die; for($i=0;$i $url,'uri' => 'urn:webservices', )); $resultado = $soapClient->testEmail($params); $resinfo = json_decode($resultado ,true); // print_r("-----SB KEY----");print_r("\n"); // print_r($resultado);print_r("\n"); // print_r($resinfo); // print_r("-----*************----");print_r("\n"); return true; //------------------------------------------------------------------------------ } catch ( Exception $e ) { //Error al consultar el WS print_r("Error al consultar el web service");print_r("\n"); print_r($e->__toString());print_r("\n"); return false; } } ?>