KGRKJGETMRETU895U-589TY5MIGM5JGB5SDFESFREWTGR54TY
Server : Apache/2.4.62
System : FreeBSD fbsdweb2.web.rcn.net 14.1-RELEASE FreeBSD 14.1-RELEASE releng/14.1-n267679-10e31f0946d8 GENERIC amd64
User : www ( 80)
PHP Version : 8.3.8
Disable Function : NONE
Directory :  /domains/logicswapweb/aplicaciones/admon/newsletter/fnc/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /domains/logicswapweb/aplicaciones/admon/newsletter/fnc/newsletter_.php
<?php
/********************************************************
clase Newsletter: 
			utiliza la interfas de BD para realizar 
			las necesidades propias de registro y 
			verificacion de Usuarios de el sitio web
*********************************************************/

class Newsletter extends Aplicacion{

var $fecha_actual;
var $cuenta = "[email protected]";
var $azul = "[email protected]";
var $margen = 5;//tiemp� estimado utilizado por el script para realizar tareas ajenas al envio de email
//cantidad de email que se pueden adjuntar en envio.
//en un envio solo pueden ir 29 direcciones de correo maximo entre todos to + cc + bcc = 30
var $paquete = 29;

var $sitio = "www.logicswap.com";
var $dirSetup = "/aplicaciones/admon/newsletter/";
var $subDir;
var $aplicacion = "Newsletter";
var $fileMsgAplicaciones;
var $color = "#f2f2f2";
var $templatePass = "datos.tml";
var $fileImageDefault= "defaultSite.jpg";
var $fileImgProductoNuevo="productosNuevo.jpg";
var $fileImgProductoOferta="productosPromocion.jpg";
var $fileImgProducto="productosNormal.jpg";
var $fileImgDocumento="imgDocumento.jpg";
var $fileImgEncuesta="imgEncuesta.jpg";
var $frmNewsletter="frmNewsletter.html";
var $frmBoletin="frmBoletin.html";
var $frmBoletinProducto="frmBoletinProducto.html";
var $frmLink="frmEnlace.html";
var $frmGeneral = "general";
var $codDuplicate ="1062";
var $linkDocumento="";
var $linkProducto = "";
var $linkDefault = "index.php";
var $linkDefaultLabel = "ver mas...";
var $enlaceUnsuscribe = "actRegistro.php?data=novalue&email=novalue";
var $tituloEncuesta = "Opine...";

var $tokenNone="none";
var $tokenNew="nuevo";
var $util;
/************************************************************
FUNCION: 		cliente (constructor)
DESCRIPCION: 	inicializa interfaz de conexion de DB
*************************************************************/
function Newsletter($fC="msgAplicaciones.php",$subDir="/",$dirSetup="aplicaciones/admon/newsletter/",$sitio=false){
	$this->Aplicacion();
	$this->fecha_actual = date('Y-m-d');
	$this->util=new Utileria();
	if(empty($sitio)){
		$this->sitio = $_SERVER['SERVER_NAME'];
	}else{
		$this->sitio = $sitio;
	}
	$this->fileMsgAplicaciones = "http://".$this->sitio.$subDir.$fC;
	$this->pathSite="http://".$this->sitio.$subDir;
	$this->subDir = $subDir;
	$this->dirSetup = $dirSetup;
	$this->linkDocumento=$this->sitio.$subDir."documento.php?seleccion=";
	$this->linkProducto=$this->sitio.$subDir."productoCatalogo.php?flagNews=true&idProducto=";
	$this->linkEncuesta=$this->sitio.$subDir."index.php?flagNews=true&idEncuesta=";
	$this->linkDefault=$this->sitio.$subDir."index.php";
}

/************************************************************
FUNCION: 		enviar_mail
DESCRIPCION: 	envia mail a un usuario.
*************************************************************/
 function sendMail($to, $from, $suject, $mensaje, $cc=false, $bcc=false, $desde=false)
 {	
	if(empty($desde)){
		$desde = $this->getCliente();
	}
	$header    = "From: \"".$desde."\" <".$from.">\n";
	if(!empty($cc)){
		$header .= "Cc: ".$cc."\n";
	}
	if(!empty($bcc)){
		$header   .= "Bcc: ".$bcc."\n";
	}

	$header   .= "Return-path: ".$from."\n";
	$header   .= "Errors-To: ".$this->azul."\n"; 
	$header   .= "Reply-To: ".$from."\n";	
    $header   .= "MIME-Version: 1.0\n";
    $header   .= "Content-Type: text/html; charset=iso-8859-1\n";
    $header   .= "X-Priority: 1\n";
    $header   .= "X-Mailer: PHP / ".phpversion()."\n";
  	if(mail($to, $suject, $mensaje , $header)){
		$this->setSalida(true,$this->getMensaje("[058]","confirmacion"),"sendMail($to)",$this->aplicacion);
		return true;
	}else{
		$this->setSalida(false,$this->getMensaje("[019]","error"),"sendMail($to)",$this->aplicacion);	
		return false;
	}
 }  

/*
funcion getCliente
descripcion trae el cliente en el que esta instalado el panel
*/
function getCliente(){
	$sql="select valor from parametro where nombre='cliente' and aplicacion='9999'";
	if($this->execute($sql)){
		if($this->numRows()>0){
			list($cliente)=$this->fetchRow();
			return $cliente;
		}else{
			$out=trim($this->getMensaje("[013]","confirmacion"));
			$this->setSalida(false,$out,"getCliente",$this->aplicacion);		
			return "indefinido";
		}
	}else{
		$out=trim($this->getMensaje("[008]","error"));
		$out.="\\n::".trim($this->getException());
		$this->setSalida(false,$out,"getCliente",$this->aplicacion);
		return "inconsultable";
	}
}
/*
*funcion getIdVinculoWeb()
*descripcion devuelve el id del vinculo del usuario solicitado
*			 con la aplicacion newsletter
*/
function getIdVinculoWeb($user,$id_news){
	$sql="select id from vinculo_web where usuario_web='$user' and aplicacion='$id_news'";
	if($this->execute($sql)){
		list($id)=$this->fetchRow();
		$out=trim($this->getMensaje("[092]","confirmacion"));
		$this->setSalida(false,$out,"getVinculoWeb($user,$id_news)",$this->aplicacion);
		return $id;
	}else{
		$out=trim($this->getMensaje("[026]","error"));
		$out.="\\n::".trim($this->getException());
		$this->setSalida(false,$out,"getVinculoWeb($user,$id_news)",$this->aplicacion);
		return false;
	}	
}

/*
*funcion getIdaplicacion()
*descripcion devuelve el id del vinculo del usuario solicitado
*			 con la aplicacion newsletter
*/
function getIdaplicacion($nombre){
	$sql="select id from panel_aplicacion where nombre='$nombre'";
	if($this->execute($sql)){
		list($id)=$this->fetchRow();
		$out=trim($this->getMensaje("[093]","confirmacion"));
		$this->setSalida(false,$out,"getIdaplicacion($nombre)",$this->aplicacion);
		return $id;
	}else{
		$out=trim($this->getMensaje("[012]","error"));
		$out.="\\n::".trim($this->getException());
		$this->setSalida(false,$out,"getIdaplicacion($nombre)",$this->aplicacion);
		return false;
	}	
}

/************************************************************
FUNCION: 		sendSuscripcion
DESCRIPCION: 	envia un mensaje de suscripcion al newsletter 
				con un enlace para que el usuario se active
*************************************************************/
function sendSuscripcion($email, $id, $plantilla){
	$file = @file_get_contents($plantilla);
	$site = $this->sitio;
	$cliente =$this->getCliente();
	$enlaceAc = $this->fileMsgAplicaciones."?tarea=actSubscripcion&seleccion=$id|$email&clave=13acNts";
	$enlaceEl = $this->fileMsgAplicaciones."?tarea=delSubscripcion&seleccion=$id|$email&clave=13acNts";
	if(!$file){	$this->setSalida(false,"Imposibilidad de leer formato de mensaje!", "Sitio Web"); return false;}	
	else{
		//$mensaje1 = implode("",$file);
		$mensaje1 = str_replace("[-cliente-]",$cliente,$file);
		$mensaje1 = str_replace("[-sitio-]",$site,$mensaje1);
		$mensaje1 = str_replace("[-enlaceAc-]",$enlaceAc,$mensaje1);
		$mensaje1 = str_replace("[-enlaceEl-]",$enlaceEl,$mensaje1);
		$sujeto ="Register in $site";
		$cc=false;
				//sendMail($to=email, $from, $suject, $mensaje, $cc=false, $bcc=false, $desde=false)

		if($this->sendMail($email, $this->cuenta, $sujeto, $mensaje1, $cc, false, $cliente)){
			$out=trim($this->getMensaje("[076]","confirmacion"));
			$this->setSalida(true,$out,"sendSuscripcion($email, $id, $plantilla)",$this->aplicacion);
			return true;
		}else{
			$out = $this->salida['msg'];
			$this->setSalida(false,$out,"sendSuscripcion($email, $id, $plantilla)",$this->aplicacion);
			return false;					
		}

	}
}//end eniar inm
/************************************************************
FUNCION: 		sendUnsuscripcion
DESCRIPCION: 	envia un mensaje de retiro de suscripcion al newsletter 
				con un enlace para que el usuario se elimine
*************************************************************/
function sendUnsuscripcion($email, $id, $plantilla, $login){
	$file = @file_get_contents($plantilla);
	$site = $this->sitio;
	
	$enlaceEl = $this->fileMsgAplicaciones."?tarea=actSubscripcion&seleccion=$id|$email&clave=13acNts";
	if(!$file){	$this->setSalida(false,"Imposibilidad de leer formato de mensaje!", "Sitio Web"); return false;}	
	else{
		$mensaje1 = str_replace("[-email-]",$login,$file);
		$mensaje1 = str_replace("[-sitio-]",$site,$mensaje1);
		$mensaje1 = str_replace("[-enlace-]",$enlaceEl,$mensaje1); echo $mensaje1; 
		$sujeto ="$site";
		if($this->sendMail($email, $this->cuenta, $sujeto, $mensaje1, false, false, $cliente)){
			$out=trim($this->getMensaje("[165]","confirmacion"));
			$this->setSalida(true,$out,"sendUnsuscripcion($email, $id, $plantilla)",$this->aplicacion);
			return true;
		}else{
			$out = $this->salida['msg'];
			$this->setSalida(false,$out,"sendUnsuscripcion($email, $id, $plantilla)",$this->aplicacion);
			return false;
		}
	}
}//end 
/*
*funcion actSubscripcion()
*descripcion activa un vinculo de un usuario con la aplicacion newsletter
*/
function actSubscripcion($vinc,$nApli){
	$vec=explode("|",$vinc);
	$id = $vec[0];
	$sql="update vinculo_web set estado='activo' where id='$vinc'";
	if($this->execute($sql)){
		$out=$this->getMensaje("[094]","confirmacion")." ".$vec[1];
		$this->setSalida(true,$out,"actSubscripcion($vinc)",$nApli);
		return true;
	}else{
		$out=trim($this->getMensaje("[027]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"actSubscripcion($vinc)",$nApli);
		return false;
	}
}

/*
*funcion modVinculoWeb()
*descripcion modifica un vinculo de un usuario con la aplicacion newsletter
*/
function modVinculoWeb($vinc,$est,$nApli){
	$vec=explode("|",$vinc);
	$id = $vec[0];
	$sql="update vinculo_web set estado='$est' where id='$vinc'";
	if($this->execute($sql)){
		if($est=="activo"){$nms="[094]";}
		if($est=="bloqueado"){$nms="[100]";}
		$out=$this->getMensaje($nms,"confirmacion")." ".$vec[1];
		$this->setSalida(true,$out,"modVinculoWeb($vinc,$est,$nApli)",$nApli);
		return true;
	}else{
		$out=trim($this->getMensaje("[027]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"modVinculoWeb($vinc,$est,$nApli)",$nApli);
		return false;
	}
}

/*
*funcion delSubscripcion()
*descripcion elimina un vinculo de un usuario con la aplicacion newsletter
*/
function delSubscripcion($vinc,$nApli){
	$vec=explode("|",$vinc);
	$id = $vec[0];
	//$sql="delete from vinculo_web where id='$id'";
	$sql="update vinculo_web set estado='eliminado' where id='$id'";
	if($this->delVinculoUser($vinc,$nApli)){
		if($this->execute($sql)){
			$out=$this->getMensaje("[098]","confirmacion")." ".$vec[1];
			$this->setSalida(true,$out,"delSubscripcion($vinc,$nApli)",$nApli);
			return true;
		}else{
			$out=trim($this->getMensaje("[027]","error")." ".$vec[1]);
			$out.="\\n:Desc: ".trim($this->getException());
			$this->setSalida(false,$out,"delSubscripcion($vinc,$nApli)",$nApli);
			return false;
		}
	}else{
		$out=$this->salida['msg'];
		$this->setSalida(false,$out,"delSubscripcion($vinc,$nApli)",$nApli);
		return false;	
	}
}


/*
FUNCION: 		addVinculo
DESCRIPCION: 	ingresa un v�nculo de un usuario con un tema
pre: 			el usuario existe con su direccion de email 
				al igual que el tema.
*/
function addVinculo($user,$tema,$estado="preactivo",$aplicacion=false){
	$news=explode("-",$tema);
	$idtm = $news[0];
	if(empty($aplicacion)){
		$aplicacion=$this->aplicacion;
	}
	$sql="insert into news_vinculo (vinculo,tema,estado) values ('$user','$idtm','$estado')";
	if($this->execute($sql)){
		$out=$this->getMensaje("[063]","confirmacion");
		$this->setSalida(true,$out,"addVinculo($user,$tema,$estado)",$aplicacion);
		return true;
	}else{
		$out=trim($this->getMensaje("[021]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"addVinculo($user,$tema,$estado)",$aplicacion);
		return false;
	}
}//end addVinculo
/*
*funcion: 		existVinculo
*descripcion: 	verifica que exista el vinculo entre un usuario y un tema de newsleter
*/
function existVinculo($user,$tema,$aplicacion=false){
	if(empty($aplicacion)){
		$aplicacion=$this->aplicacion;
	}
	$sql="select count(*) as cant from news_vinculo where vinculo='$user' and tema='$tema'";
	if($this->execute($sql)){
		list($cant)=$this->fetchRow();
		if($cant>0){
			$out=$this->getMensaje("[064]","confirmacion");
			$this->setSalida(true,$out,"existVinuculo($user,$tema)",$aplicacion);
			return true;
		}else{
			$out=$this->getMensaje("[065]","confirmacion");
			$this->setSalida(true,$out,"existVinuculo($user,$tema)",$aplicacion);
			return false;	
		}
	}else{
		$out=trim($this->getMensaje("[021]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"existVinuculo($user,$tema)",$aplicacion);
		return false;
	}
}//end existVinuculo

/************************************************************
FUNCION: 		modVinculo
DESCRIPCION: 	modifica el estado de un v�nculo de un usuario con un tema
pre: 			el vinculo existe. se puede hacer por id o por user-tema
*************************************************************/
function modVinculo($id=false,$user=false,$tema=false,$estado,$aplicacion=false){
	if(empty($aplicacion)){
		$aplicacion=$this->aplicacion;
	}
	$sql=NULL;
	if(!empty($id)){
		$sql="update news_vinculo set estado='$estado' where id='$id'";
	}elseif(!empty($user)&&!empty($tema)){
		$sql="update news_vinculo set estado='$estado' where vinculo='$user' and tema='$tema'";
	}
	if(!empty($sql)){	
		if($this->execute($sql)){
			$out=$this->getMensaje("[066]","confirmacion");
			$this->setSalida(true,$out,"modVinculo($id,$user,$tema,$estado)",$aplicacion);
			return true;
		}else{
			$out=trim($this->getMensaje("[021]","error"));
			$out.="\\n:Desc: ".trim($this->getException());
			$this->setSalida(false,$out,"modVinculo($id,$user,$tema,$estado)",$aplicacion);
			return false;
		}
	}else{
		$out=$this->getMensaje("[022]","confirmacion");
		$this->setSalida(false,$out,"modVinculo($id,$user,$tema,$estado)",$aplicacion);
		return false;
	}
}//end modVinculo

/*
*funcion showListTemasCol
*descripcion despliega el listado de temas disponibles
*			 para la suscripcion en el sitio.
*			 general = true o false; true escribe general si no hay mas temas
*			 col = indica el numero de columnas en que se dividira la lista de temas
*/
function showListTemasCol($alto,$ancho,$class,$general,$col,$aplicacion=false){
	
	if(empty($aplicacion)){
		$aplicacion="Newsletter";
	}
	if(empty($general)){
		$sql="select id, titulo from news_tema where id!=1";
		if($this->checkTemaGeneral(false)){
			$sintemas="";//no muestre nada si es el unico tema
		}else{
			$sintemas=$this->salida['msq']; //aviza si no esta creado el tema general y no hay nada mas
		}
		$i=1;
	}else{
		$sql="select id, titulo from news_tema where 1";
		$sintemas="No se h�n creado temas!";
		$i=0;
	}
	if($this->execute($sql)){
		$rows =$this->numRows();
		$lines = ceil($rows/$col);
		if($rows>0){//siempre estar� creado el tema general
			echo "<div id=\"temasNews\" class=\"$class\" style=\"position:relative; top:0; left:0; height:$alto; width:$ancho; overflow:auto;\">";
			echo "<table>";
			for($k=0;$k<$lines;$k++){
				echo "<tr>";
				for($m=0;$m<$col;$m++){
					if(list($id,$titulo)=$this->fetchRow()){
						echo "<td><input type=\"checkbox\" name=\"tema_$i\" id=\"tema_$i\" value=\"$id-$titulo\" ></td><td align=\"left\"><label for=\"tema_$i\" class=\"$class\">$titulo</label></td>";
						$i++;
					}
				}
				echo "</tr>";
			}
			echo "</table>";
			echo "</div>";
			$out=$this->getMensaje("[068]","confirmacion");
			$this->setSalida(true,$out,"showListTemasCol($alto,$ancho,$class,$general,$col,$aplicacion)",$aplicacion);
		}else{
			echo "<div class=\"$class\" style=\"height:$alto; width:$ancho; overflow:auto; display:inline \" align=\"center\">".$sintemas."</div>";
		}		
	}else{
		$out1=trim($this->getMensaje("[023]","error"));
		$out2=$out1."\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out2,"showListTemasCol($alto,$ancho,$class,$general,$col,$aplicacion)",$aplicacion);
		echo "<div class=\"$class\" style=\"height:$alto; width:$ancho; overflow:auto; display:inline \" align=\"center\">".$out1."</div>";
	}
	
}

/*
*function checkTemaGeneral
*descripcion verifica que la categoria general del newsletter
*			 haya sido creada
*/
function checkTemaGeneral($make=false,$aplicacion=false){
	if(empty($aplicacion)){
		$aplicacion="Newsletter";
	}
	$sql="select count(*) from news_tema where id=1";
	if($this->execute($sql)){
		list($cant)=$this->fetchRow();
		if($cant>0){
			$out=$this->getMensaje("[075]","confirmacion");
			$this->setSalida(true,$out,"checkTemaGeneral($make)",$aplicacion);
			return true;
		}elseif($make){
			$titulo="General";
			$descripcion="informaci�n general de todo lo que acontese en nuestro sitio web";
			$id=1;
			return $this->addTema($titulo,$descripcion,$id,$aplicacion);			
		}else{
			$out=$this->getMensaje("[074]","confirmacion");
			$this->setSalida(false,$out,"checkTemaGeneral($make)",$aplicacion);
			return false;			
		}
	}else{
		$out=trim($this->getMensaje("[023]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"checkTemaGeneral($make)",$aplicacion);
		return false;
	}	
}


/*
*funcion addTema
*descripcion inserta un nuevo tema para newsletter
*/

function addTema($titu,$descri,$id=NULL,$nApli){
	$descri = $this->util->parseInput2DB($descri);
	if(!empty($id)){
		$sql = "insert into news_tema values('$id','$titulo','$descripcion')";
	}else{
		$sql = "insert into news_tema (titulo,descripcion) values('$titu','$descri')";
	}

	if ($this->execute($sql)) {
		$out=$this->getMensaje("[075]","confirmacion");
		$this->setSalida(true,$out,"addTema($titu,$descri,$id,$nApli)",$nApli);
		return true;
	} else{
		$out=trim($this->getMensaje("[023]","error"));
		$nm = $this->getExceptionNum();
		$out.="\\n:Desc: ".trim($this->getException());
		if($nm==$this->codDuplicate){$out=trim($this->getMensaje("[055]","error"));}
		$this->setSalida(false,$out,"addTema($titu,$descri,$id,$nApli)",$nApli);
		return false;
	}
}

/*
*funcion modTema
*descripcion modifica un tema de newsletter
*/

function modTema($titu,$descri,$id,$nApli){
	$descri = $this->util->parseInput2DB($descri);
	$sql="update news_tema set titulo='$titu', descripcion='$descri' where id='$id'";
	if ($this->execute($sql)) {
		$out=$this->getMensaje("[087]","confirmacion");
		$this->setSalida(true,$out,"modTema($titu,$descri,$id,$nApli)",$nApli);
		return true;
	} else{
		$out=trim($this->getMensaje("[023]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"modTema($titu,$descri,$id,$nApli)",$nApli);
		return false;
	}
}

/*
*funcion delTema
*descripcion elimina un tema de newsletter
*/

function delTema($id,$nApli){
	$sql="delete from news_tema where id='$id'";
	if ($this->execute($sql)) {
		$out=$this->getMensaje("[088]","confirmacion");
		$this->setSalida(true,$out,"delTema($id,$nApli)",$nApli);
		return true;
	} else{
		$out=trim($this->getMensaje("[023]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"delTema($id,$nApli)",$nApli);
		return false;
	}
}

/*
*funcion delVinculoTema
*descripcion elimina todos los vinculos existentes de los 
*			 usuarios con el tema de newsletter
*/

function delVinculoTema($tema,$nApli,$user=false){
	if(empty($user)){
		$sql="delete from news_vinculo where tema='$tema'";
	}else{
		$sql="delete from news_vinculo where tema='$tema' and vinculo='$user'";
	}
	if ($this->execute($sql)) {
		$out=$this->getMensaje("[089]","confirmacion");
		$this->setSalida(true,$out,"delVinculoTema($tema,$nApli)",$nApli);
		return true;
	} else{
		$out=trim($this->getMensaje("[021]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"delVinculoTema($tema,$nApli)",$nApli);
		return false;
	}
}

/*
*funcion delVinculoUser
*descripcion elimina todos los vinculos existentes del 
*			 usuario con los temas de newsletter
*/

function delVinculoUser($vincW,$nApli){
	$vec=explode("|",$vincW);
	$id = $vec[0];
	$sql="delete from news_vinculo where vinculo='$id'";
	if ($this->execute($sql)) {
		$out=$this->getMensaje("[097]","confirmacion")." ".$vec[1];
		$this->setSalida(true,$out,"delVinculoUser($vincW,$nApli)",$nApli);
		return true;
	} else{
		$out=trim($this->getMensaje("[021]","error")." ".$vec[1]);
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"delVinculoUser($vincW,$nApli)",$nApli);
		return false;
	}
}

/**************************************************
funcion addPreferencias
descripcion registra las preferencias hechas de las secciones 
			seleecionadas por el usuario
*/
function addPreferencias($user,$temas,$nApli){

	$vec = explode("[|]",$temas);
	$lng = count($vec); $i =0; $fallos=""; $msf="";$hechos="\\n";
	foreach($vec as $key=>$val){
		if($this->addVinculo($user,$val,"preactivo","Sitio Web")){
			$i++;
			$hechos.=" .".$val;
		}else{
			$fallos.=" .".$val;
			$msf =$this->salida['msg']."($fallos).";
			break;
		}
	}
	if($lng==$i){
		$out=$this->getMensaje("[084]","confirmacion").$hechos;
		$this->setSalida(true,$out,"addPreferencias($user,$temas)",$nApli);
		return true;
	}else{
		$out=$msf;
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"addPreferencias($user,$temas)",$nApli);
		return false;		
	}
}

/*
funcion listarTemas
descripcion trae todos los temas disponibles
*/
function listarTemas($inicio,$limite,$class,$nApli){
	$sql="select id, titulo, descripcion from news_tema where 1 order by titulo asc limit $inicio,$limite";
	if($this->execute($sql)){
	    echo '<script>var t = new SortTable("t");t.AddColumn("ico","width=\"20\"","center","");t.AddColumn("titulo","nowrap","","");t.AddColumn("desc","nowrap","",""); t.AddColumn("Seleccion","","center","");';
		$i=1;
		$j=0;
	    if ($this->numRows()>0) {
			while(list($id,$titulo,$desc)=$this->fetchRow()){
				$imagen="<img src=\"img/temas.gif\" onClick=\"fncAccion(\'listUsuarios\',\'$id\')\">";
				
				$titulo=ucfirst(strtolower($titulo));
				if(strlen($titulo)>30){
					$titulo = substr($titulo,0,30)."...";
				}
				if(strlen($desc)>30){
					$desc= substr($desc,0,35)."...";
				}
				$desc=$this->util->parseDB2Html($desc);				
				echo "t.AddLine('$imagen','<!--$titulo--><a class=\"arial12\" onClick=\"fncAccion(\'listUsuarios\',\'$id|$titulo\')\">$titulo</a>', '<a class=\"arial12\" onClick=\"fncAccion(\'listUsuarios\',\'$id\')\">$desc</a>','<INPUT class=\"radio\" name=\"usuario_$j\" type=\"checkbox\" value=\"$id|$titulo\">');\n";
				echo "t.AddLineProperties('id=\"tr_$j\" class=\"$class\" align=\"left\" onMouseOver=\"mOvr(this,\'#faff95\',\'tr_$j\')\" onMouseOut=\"mOut(this,\'#FFFFFF\',\'tr_$j\')\"');\n"; 
				
				$j++;
        	}
			echo "t.WriteRows();";
    	} else {
			$out=trim($this->getMensaje("[086]","confirmacion"));
			echo "document.write('<TR><TD colspan=\"3\" align=\"center\" class=\"$class\"><BR>$out<BR>&nbsp;</TD></TR>');";
    	}
		echo "</script>";
		return $sql;
	}else{
		$out=trim($this->getMensaje("[023]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		echo "<TR><TD colspan=\"3\" align=\"center\" class=\"$class\"><BR>$out<BR>&nbsp;</TD></TR>";
		$this->setSalida(false,$out,"listarTemas($inicio,$limite,$nApli)",$nApli);
		return false;
	}
	
}

/*
funcion cantidadTemas
descripcion devuelve el numero de temas disponibles para el newsletter
*/
function cantidadTemas($nApli="newsletter"){
	$sql="select count(*) from news_tema where 1";
	if($this->execute($sql)){
		list($cant)=$this->fetchRow();
		$out=trim($this->getMensaje("[085]","confirmacion"));
		$this->setSalida(true,$out,"cantidadTemas($nApli)",$nApli);	
		return $cant;
	}else{
		$out=trim($this->getMensaje("[023]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"cantidadTemas($nApli)",$nApli);
		return false;
	}
}
/**
* despliega un listado de elementos
* 
* lista los elementos disponibles para adicionar como boletines ya
* sea en noticias, eventos, documentos o productos, con checkbox
* de valor de la siguiente forma "id|titulo|descripcion|url" para    
* los casos de noticias y eventos, y para el caso de producto de la forma 
* "id|nombre|descripcion|nombrecategoria|valor|referencia|estado"
*
* @param string $tipo {noticia|evento|documento|producto}
* @param integer $inicio linea inicial de la consulta
* @param integer $limite catidad maxima de elementos a listar
* @param string $nApli nombre de la aplicacion que llama la funcion
* @param string $hdTex adiciones html a las propiedades de cada linea del listado
* @param string $hdTrP adiciones html a las propiedades de la linea de cabecera de la tabla principal
* @param string $hdTextrP adiciones html a las propiedades de las celdas de la linea de cabecera de la tabla principal
* @param string $hdTextrP adiciones html a las propiedades de las celdas de la linea de cabecera de la tabla principal* 
* @param string $croll color en html para el rollOver del mose sobre el listado
*/
function listarBoletines($tipo,$inicio,$limite,$nApli,$hdTex,$hdTrP,$hdTextrP,$croll){
	if($tipo=="noticia"){
		$sql="select noticia_id, noticia_titulo, noticia_resumen, noticia_url from noticias where 1 order by noticia_titulo asc limit $inicio,$limite";
		$cmsg="[037]";
	}
	if($tipo=="evento"){
		$sql="select evento_id, evento_titulo, evento_resumen, evento_url from eventos where 1 order by evento_titulo asc limit $inicio,$limite";
		$cmsg="[038]";		
	}
	if($tipo=="documento"){
		$sql="select docu.id, docu.titulo, docu.texto, car.carpeta from documentos as docu, carpeta as car where docu.carpeta=car.id order by titulo asc limit $inicio,$limite";
		$cmsg="[040]";
	}
	if($tipo=="producto"){
		$sql="select pro.id, pro.nombre as nomp, pro.descripcion, cate.nombre as nomc, pro.valor, pro.referencia, pro.estado, pro.estado_oferta from catalogo_producto as pro, catalogo_categoria as cate where pro.estado!='no-disponible' and pro.categoria=cate.id order by pro.nombre asc limit $inicio,$limite";
		$cmsg="[039]";		
	}

	if($this->execute($sql)){
		if($tipo!="producto"){
			echo '<table width="545">
				  <tr '.$hdTrP.'>
					<td width="20" align="left" '.$hdTextrP.'>&nbsp;</td>
					<td width="418" align="center" '.$hdTextrP.'>T&iacute;tulo</td>
					<td width="91" align="center" '.$hdTextrP.'>Selecci&oacute;n</td>
				   </tr>';
			echo '<script>var t = new SortTable("t");t.AddColumn("ico","nowrap","","");
			      t.AddColumn("titulo","nowrap","",""); 
				  t.AddColumn("Seleccion","","center","");';
			$span=3;   
		}else{
			echo '<table width="545">
				  <tr '.$hdTrP.'>
					<td width="20" align="left" '.$hdTextrP.'>&nbsp;</td>
					<td width="40" align="center" '.$hdTextrP.'>Ref.</td>
					<td width="95" align="center" '.$hdTextrP.'>Nombre</td>
					<td width="200" align="center" '.$hdTextrP.'>Descripci&oacute;n</td>
					<td width="90" align="center" '.$hdTextrP.'>Categor&iacute;a</td>
					<td width="80" align="center" '.$hdTextrP.'>Valor</td>
					<td width="20" align="center" '.$hdTextrP.'>Sel.</td>
				   </tr>';
			echo '<script>var t = new SortTable("t");t.AddColumn("ico","nowrap","","");
			      t.AddColumn("referencia","nowrap","","");
				  t.AddColumn("nombre","nowrap","","");
				  t.AddColumn("descripcion","nowrap","","");
				  t.AddColumn("categoria","nowrap","","");
				  t.AddColumn("valor","nowrap","","");
				  t.AddColumn("Seleccion","","center","");';
			$span=7;
		}
		$i=1; $j=0;
	    if ($this->numRows()>0) {
			while($row=$this->fetchRow()){
			
				if($tipo=="producto"){
					$imagen="<img src=\"img/temas.gif\">";
				}
				if($tipo=="documento"){
					$imagen="<img src=\"img/temas.gif\">";
				}
				if($tipo=="noticia"){
					$imagen="<img src=\"img/temas.gif\">";
				}
				if($tipo=="evento"){
					$imagen="<img src=\"img/temas.gif\">";
				}
				if($tipo!="producto"){
					$id = $row[0]; $titulo= $row[1]; $desc= $row[2]; $ext= $row[3];
					$titulo=ucfirst(strtolower($titulo));
					if(strlen($titulo)>60){
						$titulo = substr($titulo,0,57)."...";
					}
					echo "t.AddLine('$imagen','$titulo','<INPUT name=\"usuario_$j\" type=\"checkbox\" value=\"$id|$titulo|$desc|$ext\">');\n";
					echo "t.AddLineProperties('id=\"tr_$j\" $hdTex align=\"left\" onMouseOver=\"mOvr(this,\'$croll\',\'tr_$j\')\" onMouseOut=\"mOut(this,\'#FFFFFF\',\'tr_$j\')\"');\n"; 
				}else{
					$id = $row[0]; $titulo= $row[1]; $desc= $row[2]; $cate= $row[3]; $val= $row[4]; $ref= $row[5]; $est=$row[6];
					if($row[6]=="promocion"){
						if($row[7]=="vencida"){
							$est="disponible";
							//$imagen="<img src=\"img/icoProductoDisponible.gif\">";
						}else{
							//$imagen="<img src=\"img/icoProductoOferta.gif\">";
						}
					}
					//las lineas anteriores y las siguientes, se comentan para dejar un solo icono en el listado de boletines a adicionar
					//if($row[6]=="disponible"){$imagen="<img src=\"img/icoProducto.gif\">";}
					//if($row[6]=="nuevo"){$imagen="<img src=\"img/icoProductoNuevo.gif\">";}
					
					$titulo=ucfirst(strtolower($titulo));
					if(strlen($titulo)>23){
						$titulos = substr($titulo,0,20)."...";
					}
					if(strlen($desc)>30){
						$descs = $this->util->parseDB2Html(substr($desc,0,27))."...";
					}
					echo "t.AddLine('$imagen','$ref','$titulos','$descs','$cate','$val','<INPUT class=\"radio\" name=\"usuario_$j\" type=\"checkbox\" value=\"$id|$titulo|$desc|$cate|$val|$ref|$est\">');\n";
					echo "t.AddLineProperties('id=\"tr_$j\" $hdTex align=\"left\" onMouseOver=\"mOvr(this,\'$croll\',\'tr_$j\')\" onMouseOut=\"mOut(this,\'#FFFFFF\',\'tr_$j\')\"');\n"; 
				}
				$j++;
        	}
			echo "t.WriteRows();";
    	} else {
			$out=trim($this->getMensaje("[109]","confirmacion"));
			echo "document.write('<TR><TD colspan=\"3\" align=\"center\" $hdTex><BR>$out<BR>&nbsp;</TD></TR>');";
    	}
		echo "</script>";
		echo '<tr '.$hdTrP.'>
				<td colspan="'.$span.'" '.$hdtrP.' align="center"><span '.$hdTextrP.'>Cantidad de '.ucfirst($tipo).'s : '.$this->numRows().'</span> <input type="hidden" name="valores" id="valores" value=""><input type="hidden" name="tipo" id="tipo" value="'.$tipo.'"><input type="hidden" name="tarea" id="tarea" value="addBoletin"><input type="hidden" name="seleccion" id="seleccion" value=""></td>
			</tr>
		</table>';
		return $this->numRows();
	}else{
		$out=trim($this->getMensaje($cmsg,"error"));
		$out.="\\n:Desc: ".trim($this->getException());
		echo "<TR><TD colspan=\"3\" align=\"center\" $hdTex><BR>$out<BR>&nbsp;</TD></TR>";
		$this->setSalida(false,$out,"listarBoletines($tipo,$inicio,$limite,$class,$nApli)",$nApli);
		return false;
	}
	
}

/*
funcion getTema
descripcion devuelve la informacion del tema solicitado
pre : 		el tema existe
*/
function getTema($id,$nApli){
	$sql="select * from news_tema where id='$id'";
	if($this->execute($sql)){
		$out=trim($this->getMensaje("[090]","confirmacion"));
		$this->setSalida(true,$out,"getTema($id,$nApli)",$nApli);
		return $this->fetchRow();
	}else{
		$out=trim($this->getMensaje("[023]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"getTema($id,$nApli)",$nApli);
		return false;
	}
}

/*
*funcion listarUsuariosTema
*descripcion trae todos los usuarios registrados en un tema en particular
*			 apli: id de la aplicacion relacionada con los usuarios a listar
*			 est: estado de los usuarios que se quieren listar
*/
function listarUsuariosTema($tema,$inicio,$limite,$class,$est,$find,$nApli){
	$idn = $this->getIdAplicacion("newsletter");
	
	$sql = 'select vincw.id, user.nombres, user.login, user.email, vincw.estado'
		. ' from usuario_web as user, vinculo_web as vincw, news_vinculo as vincn '
		. ' where vincw.aplicacion=\''.$idn.'\' and vincw.usuario_web=user.id and vincw.id=vincn.vinculo and vincn.tema=\''.$tema.'\' and vincw.estado=\''.$est.'\' LIMIT '.$inicio.','.$limite;		

	if($est=="todos"){
		$sql = 'select vincw.id, user.nombres, user.login, user.email, vincw.estado'
			. ' from usuario_web as user, vinculo_web as vincw, news_vinculo as vincn '
			. ' where vincw.aplicacion=\''.$idn.'\' and vincw.usuario_web=user.id and vincw.id=vincn.vinculo and vincn.tema=\''.$tema.'\' LIMIT '.$inicio.','.$limite;			
	}

	if(!empty($find)){
		$sql = 'select vincw.id, user.nombres, user.login, user.email, vincw.estado'
			. ' from usuario_web as user, vinculo_web as vincw, news_vinculo as vincn '
			. ' where vincw.aplicacion=\''.$idn.'\' and vincw.usuario_web=user.id and vincw.id=vincn.vinculo and vincn.tema=\''.$tema.'\' and ( (user.nombres like \'%'.$find.'%\') or (user.email like \'%'.$find.'%\') or (user.login like \'%'.$find.'%\') ) LIMIT '.$inicio.','.$limite;
	}

	if($this->execute($sql)){
	    echo '<script>var t = new SortTable("t");t.AddColumn("ico","width=\"20\"","center","");t.AddColumn("Nombre","nowrap","","");t.AddColumn("Login","nowrap","",""); t.AddColumn("tipo","","center",""); t.AddColumn("Seleccion","","center","");';
		$i=1;
		$j=0;
	    if ($this->numRows()>0) {
			while(list($id,$nombre,$login,$email,$estado)=$this->fetchRow()){
				if($estado=="activo"){
					$imagen="<img src=\"img/vinculotema.gif\" onClick=\"fncConsultarUsr(\'$id\')\">";
				}
				if($estado=="preactivo"){
					$imagen="<img src=\"img/newslPreactivo.gif\" onClick=\"fncConsultarUsr(\'$id\')\">";
				}
				if($estado=="bloqueado"){
					$imagen="<img src=\"img/newslBloqueado.gif\" onClick=\"fncConsultarUsr(\'$id\')\">";
				}
				
				$nombre=ucfirst(strtolower($nombre))." ".ucfirst(strtolower($apellido));
				if(strlen($nombre)>38){
					$nombre = substr($nombre,0,35)."...";
				}
				echo "t.AddLine('$imagen','<!--$nombre--><a class=\"arial12\" >$nombre </a>', '<!--$email--><a class=\"arial12\">$email</a>','$login', '<INPUT class=\"radio\" name=\"usuario_$j\" type=\"checkbox\" value=\"$id|$email\">');";
				echo "t.AddLineProperties('id=\"tr_$j\" class=\"$class\" align=\"left\" onMouseOver=\"mOvr(this,\'#faff95\',\'tr_$j\');\" onMouseOut=\"mOut(this,\'#FFFFFF\',\'tr_$j\')\"');"; 

				$j++;
        	}
			echo "t.WriteRows();";
    	} else {
			$ests = $est."s";
			if($est=="todos"){$ests ="";}
			//if(!empty($find)){$ests =$sql;}
			$out=trim($this->getMensaje("[023]","confirmacion"));
			echo "document.write('<TR><TD colspan=\"4\" align=\"center\" class=\"$class\"><BR>$out $ests<BR>&nbsp;</TD></TR>');";
    	}
		echo "</script>";
		return $sql;
	}else{
		$out=trim($this->getMensaje("[026]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		echo "<TR><TD colspan=\"4\" align=\"center\" class=\"$class\"><BR>$out<BR>&nbsp;</TD></TR>";
		$this->setSalida(false,$out,"listarUsuariosTema($tema,$inicio,$limite,$class,$est,$nApli)",$nApli);
		return false;
	}
	
}
/*
*funcion cantidadUsuarios
*descripcion devuelve el numero de usuarios en el panel diferentes de azulDigital
*/
function cantidadUsuariosTema($tm,$est,$find,$ini,$lim,$nApli){
	$idn = $this->getIdAplicacion("newsletter");
	$sql = 'select count(user.id)'
		. ' from usuario_web as user, vinculo_web as vincw, news_vinculo as vincn '
		. ' where vincw.aplicacion=\''.$idn.'\' and vincw.usuario_web=user.id and vincw.id=vincn.vinculo and vincn.tema=\''.$tm.'\' and vincw.estado=\''.$est.'\' ';		

	if($est=="todos"){
		$sql = 'select count(user.id)'
			. ' from usuario_web as user, vinculo_web as vincw, news_vinculo as vincn '
			. ' where vincw.aplicacion=\''.$idn.'\' and vincw.usuario_web=user.id and vincw.id=vincn.vinculo and vincn.tema=\''.$tm.'\' ';			
	}

	if(!empty($find)){
		$sql = 'select count(user.id)'
			. ' from usuario_web as user, vinculo_web as vincw, news_vinculo as vincn '
			. ' where vincw.aplicacion=\''.$idn.'\' and vincw.usuario_web=user.id and vincw.id=vincn.vinculo and vincn.tema=\''.$tm.'\' and ( (user.nombres like \'%'.$find.'%\') or (user.email2 like \'%'.$find.'%\') or (user.email like \'%'.$find.'%\') or (user.ciudad like \'%'.$find.'%\') or (user.pais like \'%'.$find.'%\') ) ';
	}

	if($this->execute($sql)){
		list($cant)=$this->fetchRow();
		$out=trim($this->getMensaje("[025]","confirmacion"));
		$this->setSalida(true,$out,"cantidadUsuariosTema($tm,$est,$find,$ini,$lim,$nApli)",$nApli);	
		return $cant;
	}else{
		$out=trim($this->getMensaje("[026]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"cantidadUsuariosTema($tm,$est,$find,$ini,$lim,$nApli)",$nApli);
		return false;
	}
}

/*
funcion showTemas()
descripcion coloca un select con los temas de newsletter
pre: ya hay temas registrados de newsletter
*/
function showTemas($sel=false,$head){
	$sql="select id, titulo from news_tema where 1";
	echo"<select name=\"seleccion\" $head style=\"width:100\">";
	if($this->execute($sql)){
		while(list($id,$nombre)=$this->fetchRow()){
			$nombre=ucfirst(strtolower($nombre));
			if($id==1 && empty($sel)){$sele="selected";}
			elseif(!empty($sel) && $id==$sel)
			{$sele="selected";}else{$sele="";}
			if($id==1){$nombre = strtoupper($nombre);}
			echo "<option value=\"$id|$nombre\" $sele>$nombre</option>";
		}
	}else{
		$out=trim($this->getMensaje("[023]","error"));
		echo "<option value=\"\" selected>$out</option>";
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"showTemas($sel)",$this->aplicacion);
	}
	echo"</select>";
}
/*
*funcion listarNewsletterTema
*descripcion trae todos los newsletter creados en un tema en particular
*			 tema: id del tema que se quiere listar 
*			 est: estado de los newsletter que se quieren listar
*/
function listarNewsletterTema($tema,$inicio,$limite,$class,$est,$find,$nApli){
	
	if($tema=="1"){
		if($est=="todos"){
			$sql = 'select id, titulo, fecha_ing, fecha_env, estado'
				. ' from news_newsletter'
				. ' where 1 order by id desc LIMIT '.$inicio.','.$limite;
		}else{
			$sql = 'select id, titulo, fecha_ing, fecha_env, estado'
				. ' from news_newsletter'
				. ' where estado=\''.$est.'\' order by id desc LIMIT '.$inicio.','.$limite;
		}
	}else{
		if($est=="todos"){
			$sql = 'select news.id, news.titulo, news.fecha_ing, news.fecha_env, news.estado'
				. ' from news_newsletter as news, news_condicion_tema as condicion'
				. ' where news.general_tema=\'todos\' or (condicion.newsletter=news.id and condicion.tema=\''.$tema.'\') group by news.id order by news.id desc LIMIT '.$inicio.','.$limite;
		}else{
			$sql = 'select id, titulo, fecha_ing, fecha_env, estado'
				. ' from news_newsletter'
				. ' where estado=\''.$est.'\' and (news.general_tema=\'todos\' or (condicion.newsletter=news.id and condicion.tema=\''.$tema.'\')) group by news.id order by news.id desc LIMIT '.$inicio.','.$limite;
		}		
	}

	if(!empty($find)){
		$sql = 'select id, titulo, fecha_ing, fecha_env, estado'
			. ' from news_newsletter'
			. ' where (titulo like \'%'.$find.'%\') order by id desc LIMIT '.$inicio.','.$limite;
		$est="find";
	}

	if($this->execute($sql)){
	    echo '<script>var t = new SortTable("t");t.AddColumn("ico","width=\"20\"","center","");t.AddColumn("Nombre","nowrap","",""); t.AddColumn("fecha1","","center","");t.AddColumn("fecha2","","center",""); t.AddColumn("Seleccion","","center","");';
		$i=1;
		$j=0;
	    if ($this->numRows()>0) {
			while(list($id,$titulo,$fecha_ing,$fecha_env,$estado)=$this->fetchRow()){
				if($estado=="enviado"){
					$imagen="<img src=\"img/newsletter.gif\" onClick=\"fncConsultarUsr(\'$id|$titulo\',true)\">";
				}
				if($estado=="nuevo"){
					$imagen="<img src=\"img/newsletterPendiente.gif\" onClick=\"fncConsultarUsr(\'$id|$titulo\',true)\">";
				}
				if($estado=="programado"){
					$imagen="<img src=\"img/newsletterProgramado.gif\" onClick=\"fncConsultarUsr(\'$id|$titulo\',true)\">";
				}
				
				if(strlen($titulo)>40){
					$titulo=substr($titulo,0,37)."...";
				}
				$titulo=ucfirst(strtolower($titulo));
				echo "t.AddLine('$imagen',' <!--$titulo--><a class=\"$class\" onClick=\"fncAccion(\'modNewsletter\',\'$id|$titulo\')\">$titulo </a>', '$fecha_ing','$fecha_env', '<INPUT class=\"radio\" name=\"usuario_$j\" type=\"checkbox\" value=\"$id|$titulo\">');";
				echo "t.AddLineProperties('id=\"tr_$j\" class=\"$class\" align=\"left\" onMouseOver=\"mOvr(this,\'#faff95\',\'tr_$j\');\" onMouseOut=\"mOut(this,\'#FFFFFF\',\'tr_$j\')\"');"; 

				$j++;
        	}
			echo "t.WriteRows();";
    	} else {
			$out = "";
			if($est=="todos"){$out=trim($this->getMensaje("[103]","confirmacion"));}
			if($est=="enviado"){$out=trim($this->getMensaje("[104]","confirmacion"));}
			if($est=="pendiente"){$out=trim($this->getMensaje("[105]","confirmacion"));}
			if($est=="find"){$out=trim($this->getMensaje("[106]","confirmacion"));}
			echo "document.write('<TR><TD colspan=\"5\" align=\"center\" class=\"$class\"><BR>$out<BR>&nbsp;</TD></TR>');";
    	}
		echo "</script>";
		return $this->numRows();
	}else{
		$out=trim($this->getMensaje("[028]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		//$out=htmlentities(nl2br(addslashes($out)));
		echo "<TR><TD colspan=\"4\" align=\"center\" class=\"$class\"><BR>$out<BR>&nbsp;</TD></TR>";
		$this->setSalida(false,$out,"listarNewsletterTema($tema,$inicio,$limite,$class,$est,$nApli)",$nApli);
		return false;
	}
	
}
/*
*funcion cantidadNewsletterTema
*descripcion devuelve el numero news 
*/
function cantidadNewsletterTema($tm,$est,$find,$ini,$lim,$nApli){
	if($tm=="1"){
		if($est=="todos"){
			$sql = 'select count(*)'
				. ' from news_newsletter'
				. ' where 1 ';
		}else{
			$sql = 'select count(*)'
				. ' from news_newsletter'
				. ' where estado=\''.$est.'\'';
		}
	}else{
		if($est=="todos"){
			$sql = 'select count(*)'
				. ' from news_newsletter'
				. ' where tema=\''.$tm.'\'';
		}else{
			$sql = 'select count(*)'
				. ' from news_newsletter'
				. ' where tema=\''.$tm.'\' and estado=\''.$est.'\'';
		}
	}

	if(!empty($find)){
		$sql = 'select count(*)'
			. ' from news_newsletter'
			. ' where (titulo like \'%'.$find.'%\')';
		$est="todos";
	}

	if($this->execute($sql)){
		list($cant)=$this->fetchRow();
		$out=trim($this->getMensaje("[102]","confirmacion"));
		$this->setSalida(true,$out,"cantidadNewsletterTema($tm,$est,$find,$ini,$lim,$nApli)",$nApli);
		return $cant;
	}else{
		$out=trim($this->getMensaje("[028]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"cantidadNewsletterTema($tm,$est,$find,$ini,$lim,$nApli)",$nApli);
		return false;
	}
}

/*
*funcion addNews()
*descripcion crea un newsletter nuevo en la base de datos
*/
function addNews($nApli){
	$f = date('Y-m-d');
	$sql="insert into news_newsletter (fecha_ing,estado) values ('$f','nuevo')";
	if($this->execute($sql)){
		$out=trim($this->getMensaje("[107]","confirmacion"));
		$this->setSalida(true,$out,"addNews($nApli)",$nApli);
		return true;
	}else{
		$out=trim($this->getMensaje("[028]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"addNews($nApli)",$nApli);
		return false;
	}
}
/*
*funcion modNewsletter()
*descripcion modifica newsletter en la base de datos
*/
function modNewsletter($news, $valor, $campo){
	$inf=explode("|",$news);
	if(is_string($campo)){
		$sql="update news_newsletter set {$campo}='$valor' where id='".$inf[0]."'";
	}else{
		$sql="update news_newsletter set fecha_env='".$campo['fecha_env']."', filtro_usuario='".$campo['filtro_usuario']."', filtro_tema='".$campo['filtro_tema']."', general_tema='".$campo['general_tema']."', estado='".$campo['estado']."' where id='".$inf[0]."'";
	}
	if($this->execute($sql)){
		$out=trim($this->getMensaje("[124]","confirmacion"));
		$this->setSalida(true,$out,"modNewsletter($news, $valor, $campo)","newsletter");
		return true;
	}else{
		$out=trim($this->getMensaje("[028]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"modNewsletter($news, $valor, $campo)","newsletter");
		return false;
	}
}
/*
*funcion modBoletin()
*descripcion modifica boletin en la base de datos
*/
function modBoletin($bol, $titulo, $contenido){
	//pendiente hacer el parceo
	$sql="update news_boletin set titulo='$titulo', contenido='$contenido' where id='$bol'";
	if($this->execute($sql)){
		$out=trim($this->getMensaje("[126]","confirmacion"));
		$this->setSalida(true,$out,"modBoletin($bol, $titulo, $contenido)","newsletter");
		return true;
	}else{
		$out=trim($this->getMensaje("[031]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"modBoletin($bol, $titulo, $contenido)","newsletter");
		return false;
	}
}
/*
*funcion getBoletin()
*descripcion devuelve la informacion de un boletin
*/
function getBoletin($bol){
	$sql="select * from news_boletin where id='$bol'";
	if($this->execute($sql)){
		$out=trim($this->getMensaje("[140]","confirmacion"));
		$this->setSalida(true,$out,"getBoletin($bol)","newsletter");
		return $this->fetchRow();
	}else{
		$out=trim($this->getMensaje("[031]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"getBoletin($bol)","newsletter");
		return false;
	}
}



/*
*funcion showBoletines()
*descripcion despliega los boletines de un newsletter
*/
function showBoletines($bol,$nApli,$hdTex,$hdInp){
	$sql="select * from news_boletin where newsletter='$bol'";
	$ides = array();
	$titulos=array();
	$contenidos =array();
	$referencias=array();
	$valores=array();
	$categorias=array();
	$estados=array();
	$tipos=array();
	if($this->execute($sql)){
		$i=0;
		if($this->numRows()>0){
			
			while($row = $this->fetchRow()){
				$ides[$i]=$this->util->parseDB2Input($row['id']);
				$titulos[$i]=$row['titulo'];
				$contenidos[$i]=$row['contenido'];
				$tipos[$i]=$row['tipo'];
				if($row['tipo']=="producto"){
					$referencias[$i]=$row['referencia'];
					$valores[$i]=$row['valor'];
					$categorias[$i]=$row['padre'];
					$estados[$i]=$row['estado'];
				}else{
					unset($referencias);
					unset($valores);
					unset($categorias);
					unset($estados);
				}
				$i++;
			}
			foreach($ides as $key=>$val){
				$ti = $titulos[$key];
				$co = $this->util->parseDB2Input($contenidos[$key]);
				$len = $this->parametro->getParametro("nombre", "longitud_contenido", $this->id, "newsletter");
				echo "<tr id=\"boletin_{$key}\"><td>&nbsp;</td>";
				echo "<td><table width=\"100%\" class=\"texto1\">";
				echo "<tr><td $hdTex>Titulo:<input type=\"hidden\" name=\"boletin_{$key}_id\" value=\"$val\"></td><td><input type=\"text\" name=\"boletin_{$key}_titulo\" value=\"$ti\" $hdInp style=\"width:400px\" maxlength=\"100\">*</td></tr>\n";
				if($tipos[$key]!=="encuesta"){
					echo "<tr><td $hdTex>Contenido:</td><td><textarea name=\"boletin_{$key}_contenido\" $hdInp cols=\"65\" style=\"width:400px\" onkeypress=\"javascript: return limitetxtarea(this, $len,event);\" wrap=\"PHYSICAL\">$co</textarea>*</td></tr>\n";
				}else{
					echo "<tr><td $hdTex>Contenido:</td><td $hdTex><strong>$co</strong><input type=\"hidden\" name=\"boletin_{$key}_contenido\" value=\"$co\"></td></tr>\n";
				}
				if($tipos[$key]=="producto"){
					$re = $referencias[$key];$va=$this->util->valorNumero($valores[$key]);$ca=$categorias[$key];$es=$estados[$key];
					echo "<tr><td colspan=\"2\"><table width=\"100%\" class=\"texto1\">\n";
					echo "<tr><td width=\"30%\" align=\"left\" $hdTex><strong>Valor: </strong>$va</td><td align=\"left\" $hdTex><strong>Referencia: </strong>$re</td>\n";
					echo "<td align=\"left\" $hdTex><strong>Status: </strong>$es</td></tr>\n";
					echo "<tr><td align=\"left\" colspan=\"3\" $hdTex><strong>Categoria: </strong>$ca</td></tr>\n";
					echo "</table></td></tr>\n";
				}
				$this->showEnlaces($val,$key,$tipos[$key],$hdTex,$hdInp);
				$this->showImagenes($val,$key,$tipos[$key],$hdTex,$hdInp,$ti);
				echo "<tr bgcolor=\"#eeeeee\"><td align=\"right\" colspan=\"2\" height=\"25px\"><input type=\"button\" class=\"boton5\" onClick=\"javascript: fncAccion('delBoletin','$val|$ti')\" value=\"Borrar bolet�n\" title=\"$ti\"></td></tr>\n";				
				echo "</table></td></tr>\n";
			}
		}
		return $i;
	}else{
		$out=trim($this->getMensaje("[028]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		echo "<tr><td>&nbsp;</td><td $hdTex>$out</td></tr>";
		$this->setSalida(false,$out,"showBoletines($bol,$nApli)",$nApli);
		return false;
	}
}

/*
*funcion showEnlaces($bol)
*descripcion despliega los enlaces de el boletin
*/
function showEnlaces($bolId,$bolLine,$cate,$hdTe,$hdIn){
	$sql="select * from news_enlace where boletin='$bolId'";
	if($this->execute($sql)){
		if($cate!=="producto"){
			if($this->numRows()>0){
				$i=0;$j=0;
				while($row = $this->fetchRow()){
					$id = $row['id'];
					$url = $row['url'];
					$masc = $row['mascara'];
					$j=$i+1;
					$delBoton="";					
					if($cate!=="encuesta"){
						echo "<tr><td $hdTe>$j. Enlace:<input type=\"hidden\" name=\"boletin_{$bolLine}_enlace_{$i}_id\" value=\"$id\"></td><td><input type=\"text\" value=\"http://\" $hdIn style=\"width:30px; border-right:0\" readonly><input type=\"text\" name=\"boletin_{$bolLine}_enlace_$i\" value=\"$url\" $hdIn style=\"width:370px; border-left:0\"></td></tr>\n";
						$delBoton="<input type=\"button\" onclick=\"javascript: fncAccion('delEnlace','$id')\" class=\"boton5\" title=\"link: $url\" value=\"Borrar enlace\" style=\"width:100px\">";
					}
					echo "<tr><td $hdTe>&nbsp;&nbsp;&nbsp;Etiqueta:</td><td><input type=\"text\" name=\"boletin_{$bolLine}_mascara_$i\" value=\"$masc\" $hdIn style=\"width:300px\">".$delBoton."</td></tr>\n";
					$i++;
				}
				if($i<$this->parametros['numero_enlaces'] && $cate!=="encuesta"){
					echo "<tr><td $hdTe>&nbsp;&nbsp;&nbsp;</td><td><input name=\"add$bolId\" type=\"button\" onclick=\"javascript: addEnlace('$bolId');\" value=\"Adicionar enlace\" class=\"boton1\" style=\"width:400px\"></td></tr>\n";			
				}
			}else{
				$i=0;$j=0;
				if($cate!=="encuesta"){
					while($i < $this->parametros['numero_enlaces']){
						$j=$i+1;
						echo "<tr><td $hdTe>$j. Enlace:<input type=\"hidden\" name=\"boletin_{$bolLine}_enlace_{$i}_id\" value=\"".$this->tokenNew."\"></td><td><input type=\"text\" value=\"http://\" $hdIn style=\"width:30px; border-right:0\" readonly><input type=\"text\" name=\"boletin_{$bolLine}_enlace_$i\" $hdIn style=\"width:370px; border-left:0\"></td></tr>\n";
						echo "<tr><td $hdTe>&nbsp;&nbsp;&nbsp;Etiqueta:</td><td><input type=\"text\" name=\"boletin_{$bolLine}_mascara_$i\" $hdIn style=\"width:400px\"></td></tr>\n";
						$i++;
					}
				}
			}
		}
	}else{
		$out=trim($this->getMensaje("[028]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		echo "<tr><td>&nbsp;</td><td $hdTe>$out</td></tr>\n";
		$this->setSalida(false,$out,"showEnlaces($bol,$nApli)",$nApli);
		return false;
	}
}
/*
*funcion showImagenes($bol)
*descripcion despliega los enlaces de el boletin
*/
function showImagenes($bol,$bolLine,$cate,$hdTe,$hdIn,$titulo){
		$sql="select * from news_imagen where boletin='$bol'";
		if($this->execute($sql)){
			if($this->numRows()>0){
				$i=0;
				if($cate!=="encuesta"){
					while($row = $this->fetchRow()){
						$id = $row['id'];
						$nom = $row['nombre'];
						$j = $i+1;
						echo "<tr><td $hdTe>$j. Imagen:</td><td $hdTe><a href=\"javascript: fncAccion('showImagen','$id|$nom|$titulo|$bol');\" title=\"De click Para ver la imagen\">$nom</a></td></tr>\n";
						$i++;
					}
				}
			}else{
				$i=0;$j=0;
				if($cate!=="encuesta"){
					while($i < $this->parametros['numero_imagenes']){
						$j=$i+1;
						echo "<tr><td $hdTe>$j. Imagen:<input type=\"hidden\" name=\"boletin_{$bolLine}_imagen_{$i}_id\" value=\"".$this->tokenNew."\"></td><td><input type=\"file\" name=\"boletin_{$bolLine}_imagen_$i\" onkeydown=\"this.blur()\" $hdIn style=\"width:400px\"></td></tr>\n";
						$i++;
					}
				}
			}
		}else{
			$out=trim($this->getMensaje("[028]","error"));
			$out.="\\n:Desc: ".trim($this->getException());
			echo "<tr><td>&nbsp;</td><td $hdTe>$out</td></tr>\n";
			$this->setSalida(false,$out,"showImagenes($bol,$nApli)",$nApli);
			return false;
		}
}
/*
*funcion getNewsletter
*descripcion devuelve los datos de un newsletter
*/
function getNewsletter($news){
	$sql="select * from news_newsletter where id='$news'";
	if($this->execute($sql)){
		$out=trim($this->getMensaje("[125]","confirmacion"));
		$this->setSalida(true,$out,"getNewsletter($news)","newsletter");
		return $this->fetchRow();
	}else{
		$out=trim($this->getMensaje("[028]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"getNewsletter($news)","newsletter");
		return false;
	}
}
/*
*funcion progNewsletter
*descripcion devuelve los datos de un newsletter
*/
function progNewsletter($news,$fecha){
	$sql="update news_newsletter set fecha_env='$fecha', estado='programado' where id='$news'";
	if($this->execute($sql)){
		$out=trim($this->getMensaje("[142]","confirmacion"));
		$this->setSalida(true,$out,"progNewsletter($news,$fecha)","newsletter");
		return true;
	}else{
		$out=trim($this->getMensaje("[028]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"progNewsletter($news,$fecha)","newsletter");
		return false;
	}
}
/*
*funcion existElemento()
*descripcion determina si ya hay un elemento igual al
*			 solicitado en el newsletter pedido
*/
function existElemento($news, $elm, $tp){
	$ve = explode("|",$news);
	$sql="select count(*) as cant from news_boletin where newsletter='".$ve[0]."' and id_elemento='$elm' and tipo='".$tp."'";
	if($this->execute($sql)){
		list($cant)=$this->fetchRow();
		settype( $cant, "integer");
		if($cant>0){
			$out=trim($this->getMensaje("[147]","confirmacion"));
			$this->setSalida(true,$out,"existElemento($news, $elm)","newsletter");		
			return true;
		}else{
			$out=trim($this->getMensaje("[148]","confirmacion"));
			$this->setSalida(false,$out,"existElemento($news, $elm)","newsletter");		
			return $this->tokenNone;
		}
	}else{
		$out=trim($this->getMensaje("[031]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"existElemento($news, $elm)","newsletter");
		return false;
	}
}

/*
*funcion getEncuesta
*descripcion devuelve los datos de la encuesta solicitada
*			 si no recibe parametro trae la encuesta activa del home
*			 
*/
function getEncuesta($id = false){
	if(empty($id)){
		$sql="select id_encuesta,pregunta from encuestas where estado='ACTIVA'";
	}else{
		$sql="select id_encuesta,pregunta from encuestas where id_encuesta='$id'";
	}
	
	if($this->execute($sql)){
		if($this->numRows()>0){
			$out=trim($this->getMensaje("[163]","confirmacion"));
			$this->setSalida(true,$out,"getEncuesta($id)","newsletter");
			$var= $this->fetchRow();
			$sal[0]= $var['id_encuesta'];
			$sal[1]= $var['pregunta'];
			$sal[2]= $this->tituloEncuesta;
			return $sal;
		}else{
			$out=trim($this->getMensaje("[164]","confirmacion"));
			$this->setSalida(false,$out,"getEncuesta($id)","newsletter");
			return $this->tokenNone;		
		}
	}else{
		$out=trim($this->getMensaje("[065]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"getEncuesta($id)","newsletter");
		return false;
	}
}


/*
*funcion addBoletin()
*descripcion adiciona un boletin la base de datos
*/
function addBoletin($bol,$tp,$valor){

	if($tp=="generico"){
		$sql="insert into news_boletin (newsletter,tipo) values('$bol','generico')";
	}
	if($tp=="encuesta"){
		$vec= explode("|",$valor);
		$ident = $vec[0];
		$contenido = $vec[1];
		$titulo = $vec[2];
		$sql="insert into news_boletin (newsletter,tipo,titulo,id_elemento,contenido) values('$bol','$tp','$titulo','$ident','$contenido')";
	}	
	if($tp=="noticia" || $tp=="evento" || $tp=="documento"){
		$vec= explode("|",$valor);
		$ident = $vec[0];
		$ti = $vec[1];
		$co = $vec[2];
		$sql="insert into news_boletin (newsletter,tipo,titulo,contenido,id_elemento) values('$bol','$tp','$ti','$co','$ident')";
	}
	if($tp=="producto"){
		$vec= explode("|",$valor);
		$ident = $vec[0];
		$ti = $vec[1];
		$co = $vec[2];
		$cate= $vec[3];
		$val = $vec[4]; 
		$ref = $vec[5];
		$est = $vec[6]; 
		$sql="insert into news_boletin (newsletter,tipo,titulo,contenido,id_elemento,padre,valor,referencia,estado) values('$bol','$tp','$ti','$co','$ident','$cate','$val','$ref','$est')";
	}
	
	if($this->execute($sql)){
		if($tp!="generico"){
			$ind= $this->insertId();
			$etiketa = "ver mas...";
			if($tp=="noticia" || $tp=="evento"){
				$en=$vec[3];
				$en = str_replace("http://","",$vec[3]);
			}
			if($tp=="producto"){
				$en= $this->linkProducto.$ident;
			}
			if($tp=="documento"){
				$en= $this->linkDocumento.$ident;
			}
			if($tp=="encuesta"){
				$en= $this->linkEncuesta.$ident;
				$etiketa = "Votar...";
			}
			if(!$this->addEnlace($ind,$en,$etiketa)){
				$r_enl=false;
				$m_enl=$this->salida['msg'];
			}else{
				$r_enl=true;
			}
			$name_imagen = $this->getImagen($tp,$vec[0]);
			if(!empty($name_imagen)){
				if($name_imagen!=$this->tokenNone){
					if($tp!="producto" && $tp!="documento"){
						$name_imagen = $this->copyImagen($name_imagen,$tp);
					}
				}else{
					$name_imagen = $this->fileImageDefault;
				}
				if(!empty($name_imagen)){
					if(!$this->addImagen($ind,$name_imagen)){
						$r_img=false;
						$m_img=$this->salida['msg'];
					}else{
						$r_img=true;
					}
				}else{
					$r_img=false;
					$m_img=$this->salida['msg'];					
				}
			}else{
				$r_img=false;
				$m_img=$this->salida['msg'];				
			}
			$out=$ti." ".$this->getMensaje("[114]","confirmacion");
			if(!$r_enl){$out.="\\nNOTA: ".$m_enl;}
			if(!$r_img){$out.="\\nNOTA: ".$m_img;}
			$this->setSalida(true,$out,"addBoletin($bol,$tp,$valor)","newsletter");
			return true;
		}else{
			$out=$this->getMensaje("[117]","confirmacion");
			$this->setSalida(true,$out,"addBoletin($bol,$tp,$valor)","newsletter");
			return true;
		}
	}else{
		$out=trim($this->getMensaje("[031]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"addBoletin($bol,$tp,$valor)","newsletter");
		return false;
	}
}

/*
*funcion addEnlace
*descripcion inserta un enlace para el boletin dado 
*			 bol=indice del boletin
*			 url=cadena de enlace
*/
function addEnlace($bol,$url,$masc=""){
	if(strlen($url)>5){
		$sql="insert into news_enlace (boletin,url,mascara) values('$bol','$url','$masc')";
		if($this->execute($sql)){
			$out=trim($this->getMensaje("[110]","confirmacion"));
			$this->setSalida(true,$out,"addEnlace($bol,$url)","newsletter");
			return true;
		}else{
			$out=trim($this->getMensaje("[029]","error"));
			$out.="\\n:Desc: ".trim($this->getException());
			$this->setSalida(false,$out,"addEnlace($bol,$url)","newsletter");
			return false;
		}
	}else{
		$out=trim($this->getMensaje("[127]","confirmacion"));
		$this->setSalida(true,$out,"addEnlace($bol,$url)","newsletter");
		return true;
	}
}
/*
*funcion modEnlace
*descripcion inserta un enlace para el boletin dado 
*			 id=indice del enlace
*			 url=cadena de enlace
*			 masc=etiqueta
*/
function modEnlace($id,$url,$masc=""){
	$sql="update news_enlace set url='$url', mascara='$masc' where id='$id' ";
	if($this->execute($sql)){
		$out=trim($this->getMensaje("[121]","confirmacion"));
		$this->setSalida(true,$out,"modEnlace($id,$url,$masc)","newsletter");
		return true;
	}else{
		$out=trim($this->getMensaje("[029]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"modEnlace($id,$url,$masc)","newsletter");
		return false;
	}
}
/*
*funcion delEnlace
*descripcion elimina un enlace para el boletin dado 
*			 id=indice del enlace
*/
function delEnlace($id){
	$sql="delete from news_enlace where id='$id' ";
	if($this->execute($sql)){
		$out=trim($this->getMensaje("[138]","confirmacion"));
		$this->setSalida(true,$out,"delEnlace($id)","newsletter");
		return true;
	}else{
		$out=trim($this->getMensaje("[029]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"delEnlace($id)","newsletter");
		return false;
	}
}

/*
*funcion addImagen
*descripcion inserta una imagen para el boletin dado 
*			 bol=indice del boletin
*			 nombre=cadena nombre de la imagen
*/
function addImagen($bol,$nombre){
	$sql="insert into news_imagen (boletin,nombre) values('$bol','$nombre')";
	if($this->execute($sql)){
		$out=trim($this->getMensaje("[111]","confirmacion"));
		$this->setSalida(true,$out,"addImagen($bol,$nombre)","newsletter");
		return true;
		
	}else{
		$out=trim($this->getMensaje("[030]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"addImagen($bol,$nombre)","newsletter");
		return false;
	}
}
/*
*funcion modImagen
*descripcion actualiza una imagen para el boletin dado 
*			 id=indice del boletin
*			 nombre=cadena nombre de la imagen
*/
function modImagen($id,$nombre){
	$sql="update news_imagen set nombre='$nombre' where id='$id'";
	if($this->execute($sql)){
		$out=trim($this->getMensaje("[123]","confirmacion"));
		$this->setSalida(true,$out,"modImagen($id,$nombre)","newsletter");
		return true;
	}else{
		$out=trim($this->getMensaje("[030]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"modImagen($id,$nombre)","newsletter");
		return false;
	}
}
/*
*funcion delImagen
*descripcion elimina una imagen de la DB
*			 id=indice de la imagen
*/
function delImagen($id){
	$sql="delete from news_imagen where id='$id'";
	if($this->execute($sql)){
		$out=trim($this->getMensaje("[134]","confirmacion"));
		$this->setSalida(true,$out,"delImagen($id)","newsletter");
		return true;
	}else{
		$out=trim($this->getMensaje("[030]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"delImagen($id)","newsletter");
		return false;
	}
}


/*
*funcion getImagen()
*descripcion devuelve el nombre de la imagen de el
*			 elemento solicitado
*			 tipo=[noticia,evento]
*			 id= indice del elemento solicitado
*			 pre= la imagen existe
*/
function getImagen($tipo,$id,$cate="home"){
	if($tipo=="noticia" || $tipo=="evento"){
		$sql="select imagen_url from {$tipo}_imagenes where {$tipo}_id='$id' and imagen_tipo='$cate'";
	}
	if($tipo=="producto"){
		$sql="select estado, estado_oferta from producto where id='$id'";
	}
	if($tipo=="documento"){
		$nm=$this->fileImgDocumento;
		$out=trim($this->getMensaje("[112]","confirmacion"))." ".$nm;
		$this->setSalida(true,$out,"getImagen($tipo,$id)","newsletter");
		return $nm;
	}
	if($tipo=="encuesta"){
		$nm=$this->fileImgEncuesta;
		$out=trim($this->getMensaje("[112]","confirmacion"))." ".$nm;
		$this->setSalida(true,$out,"getImagen($tipo,$id)","newsletter");
		return $nm;
	}
	
	if($this->execute($sql)){
		if($this->numRows()>0){
			if($tipo=="noticia" || $tipo=="evento"){
				list($nm)=$this->fetchRow();
			}
			if($tipo=="producto"){
				$row=$this->fetchRow();
				if($row['estado']=="promocion"){
					if($row['estado_oferta']=="vigente"){
						$nm=$this->fileImgProductoOferta;
					}else{
						$nm=$this->fileImgProducto;
					}
				}
				if($row['estado']=="nuevo"){
					$nm=$this->fileImgProductoNuevo;
				}
				if($row['estado']=="disponible"){
					$nm=$this->fileImgProducto;
				}
			}
			$out=trim($this->getMensaje("[112]","confirmacion"))." ".$nm;
			$this->setSalida(true,$out,"getImagen($tipo,$id)","newsletter");
			return $nm;
		}else{
			$out=trim($this->getMensaje("[113]","confirmacion"))." ".$tipo;
			$this->setSalida(false,$out,"getImagen($tipo,$id)","newsletter");
			return $this->tokenNone;		
		}
	}else{
		$out=trim($this->getMensaje("[032]","error"))." ".$tipo;
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"getImagen($tipo,$id)","newsletter");
		return false;
	}
}

/*
*funcion copyImagen
*descripcion copia una imagen desde noticias o eventos
*			 a la carpeta de newsletter
*			 nombre=indice del boletin
*			 tipo=tipo de imagen  
*/
function copyImagen($nombre,$tipo){
	$dirDes = "../img/boletines/";
	$dirOri = "../../".$tipo."s/";
	$nm = $this->copyFile($dirOri, $dirDes, $nombre, 250, $tipo);
	return $nm;
}

/*
*funcion: 		copyFile
*descripcion	copia un archivo de un origen a un destino,
*				lo renombra si es el caso
*/
function copyFile($ori,$des,$nom,$nlen,$tipo){
	if(strlen($des)>0 && $des[strlen($des)-1] != "/"){$des = $des.'/';}
	if(strlen($ori)>0 && $ori[strlen($ori)-1] != "/"){$ori = $ori.'/';}
	
	clearstatcache();
	if(file_exists($ori.$nom)){
		if($tipo=="noticia"||$tipo=="evento"){
			//quito "img/" del nombre del archivo
			$nomt = substr($nom,4);
		}
		$nom2 = preg_replace('/[^a-zA-Z0-9\.\$\%\'\`\-\@\{\}\~\!\#\(\)\&\_\^]/','',str_replace(array(' ','%20'),array('_','_'),$nomt));
		$i = 0;
		$nom2=strtolower($nom2);
		$bits = explode('.',$nom2);
		$ext = array_pop($bits);
		$nombre= $nom2;
		$temp = array_pop($bits);
		while(file_exists($des.$temp.($i?'_copy_'.$i:'').'.'.$ext)){
			++$i;
			$addstr =($i?'_copy_'.$i:'');
			$lenaddstr=strlen($addstr);
			$lentem=strlen($temp);
			$lenext=strlen($ext)+1;//con el punto
			$nombre = $temp.$addstr.'.'.$ext;
			if(strlen($nombre)>$nlen){
				$df = strlen($nombre)-$nlen;
				$temp = substr($temp,0,$lentem-$df-1);
				$i=0;
			}
		}
		
		if(!@copy($ori.$nom, $des.$nombre)){
			$out=$this->getMensaje("[034]","error")."\\n".$ori.$nom." to ".$des.$nombre;
			if(strtolower(get_cfg_var('track_errors'))=="on"){
				$out.="\\nDesc: ".trim($php_errormsg);
			}
			$this->setSalida(false,$out,"copyFile($ori,$des,$nom,$nlen)","newsletter");
			return false;
		}else{
			return $nombre;
		}
		
	}else{
		$out=$this->getMensaje("[033]","error")."\\n".$ori.$nom;
		$this->setSalida(false,$out,"copyFile($ori,$des,$nom,$nlen)","newsletter");
		return false;
	}
} 

/*
*function sizeAllow
*descripcion verifica si el tama�o del archivo a subir
*			 cumple con las restricciones de panel y de servidor
*/
function sizeAllow($sFile,$sMaxfile=false){
	$upload_max_filesize = ini_get('upload_max_filesize');
	$upload_max_filesize = preg_replace('/M/', '000000', $upload_max_filesize);
	if(empty($max_file)){
		$max_file=$upload_max_filesize;
	}
	if($sFile>$upload_max_filesize){
	 	$out=$this->getMensaje("[047]","error")."(".$upload_max_filesize."bytes)";
		$this->setSalida(false,$out,"sizeAllow($sFile,$sMaxfile)","newsletter");
		return false;
	}elseif($sFile>$sMaxfile){
	 	$out=$this->getMensaje("[049]","error")."(".$sMaxfile."bytes)";
		$this->setSalida(false,$out,"sizeAllow($sFile,$sMaxfile)","newsletter");
		return false;	
	}else{
		return true;
	}
}

/*
* descripcion verifica que la extencion del archivo
* 			  este e el vector de permitidas en minusculas
*			 vector: array de extensiones
*			extencion : cadena de la extension por eje: gif
*/
function checkTipeFile($vector, $extension){
	$sal = array_search( strtolower($extension) , $vector);
	if ( $sal===FALSE ) {
		$l = implode(",",$vector);
	 	$out=$this->getMensaje("[064]","error")."(".$extension.")->(".$l.")";
		$this->setSalida(false,$out,"checkTipeFile($vector, $extension)","newsletter");
		return FALSE;
	}else{	
		return TRUE;
	}
}

/*
*checkMedidas($ancho, $alto, $valores)
*descripcion valida que el alto y ancho de la imagen a subir
*			 cumpla con la configuracion de parametros
*			 para estos valores
*/
function checkMedidas($ancho, $alto, $valores){
	if(!empty($ancho) && $ancho<$valores[0]){
	 	$out=$this->getMensaje("[166]","confirmacion");
		$this->setSalida(false,$out,"checkMedidas($ancho, $alto, $valores)","newsletter");
		return false;
	}
	if(!empty($alto) && $alto<$valores[1]){
	 	$out=$this->getMensaje("[167]","confirmacion");
		$this->setSalida(false,$out,"checkMedidas($ancho, $alto, $valores)","newsletter");
		return false;
	}
	return true;
}


/*
*funcion: 		LoadFile
*descripcion	sube un archivo al serivdor y lo renombra de ser necesario
*				des=directorio donde se colocara el archivo
*				input=nombre del input tipo file del formulario donde viene el archivo
*				nlen=longitud maxima para el nombre del archivo 
*				max_file=tama�o en bytes permitido para el archivo
*/
function loadFile($des,$input,$nlen,$arrayExt = false,$max_file=false, $imgWidth=false, $imgHeight=false){
	//reviza si se permite subir archivos
	$file_upload_flag = ini_get('file_uploads');
	
	if(strlen($des)>0 && $des[strlen($des)-1] != "/"){$des = $des.'/';}
	if(!empty($file_upload_flag)){
		if( is_array($_FILES[$input])){
			$ext = explode(".",$_FILES[$input]['name']);
			$var = getimagesize($_FILES[$input]['tmp_name']);
			if( !$arrayExt || $this->checkTipeFile($arrayExt, $ext[1]) ){
				if($this->sizeAllow($_FILES[$input]['size'],$max_file)){
					if($this->checkMedidas($imgWidth,$imgHeight,$var)){
						$nom2 = preg_replace('/[^a-zA-Z0-9\.\$\%\'\`\-\@\{\}\~\!\#\(\)\&\_\^]/','',str_replace(array(' ','%20'),array('_','_'),$_FILES[$input]['name']));
						$i = 0;
						$nom2=strtolower($nom2);
						$bits = explode('.',$nom2);
						$ext = array_pop($bits);
						$nombre= $nom2;
						$temp = array_pop($bits);
						if(strlen($nombre)<=$nlen){
							while(file_exists($des.$temp.($i?'_copy_'.$i:'').'.'.$ext)){
								++$i;
								$addstr =($i?'_copy_'.$i:'');
								$lenaddstr=strlen($addstr);
								$lentem=strlen($temp);
								$lenext=strlen($ext)+1;//con el punto
								$nombre = $temp.$addstr.'.'.$ext;
								if(strlen($nombre)>$nlen){
									$df = strlen($nombre)-$nlen;
									$temp = substr($temp,0,$lentem-$df-1);
									$i=0;
								}
							}
						}else{
							$df = strlen($nombre)-$nlen;
							$temp = substr($temp,0,$lentem-$df-1);
							$nombre=$temp;
							while(file_exists($des.$temp.($i?'_copy_'.$i:'').'.'.$ext)){
								++$i;
								$addstr =($i?'_copy_'.$i:'');
								$lenaddstr=strlen($addstr);
								$lentem=strlen($temp);
								$lenext=strlen($ext)+1;//con el punto
								$nombre = $temp.$addstr.'.'.$ext;
								if(strlen($nombre)>$nlen){
									$df = strlen($nombre)-$nlen;
									$temp = substr($temp,0,$lentem-$df-1);
									$i=0;
								}
							}				
						}
						if(!@copy($_FILES[$input]['tmp_name'], $des.$nombre)){
							$out=$this->getMensaje("[034]","error")."\\n".$_FILES[$input]['tmp_name']." to ".$des.$nombre;
							if(ini_get('track_errors')){
								$out.="\\nDesc: ".trim($php_errormsg);
							}
							$this->setSalida(false,$out,"loadFile($des,$input,$nlen,$max_file)","newsletter");
							return false;
						}else{
							return $nombre;
						}
					}else{
						//medidas de la imagen
						return false;
					}
				}else{
				//tama�o del archivo 
					return false;
				}
			}else{
				//tipo de archivo 
				return false;
			}
		}else{//el archivo no esta en el formulario o esta mal construido
			$out=$this->getMensaje("[048]","error")."\\n".$ori.$nom;
			$this->setSalida(false,$out,"loadFile($des,$input,$nlen,$max_file)","newsletter");
			return false;
		}
	}else{
	//no ahi permiso de subida
		$out=$this->getMensaje("[046]","error");
		$this->setSalida(false,$out,"loadFile($des,$input,$nlen,$max_file)","newsletter");
		return false;	
	}
} 
/*
*funcion loadImagen()
*descripcion sube una imagen de un boletin al servidor
*			 renombrandola si fuera necesario
*/
function loadImagen($bole, $file){
	$dir="../img/boletines/";
	$vec[0] = "gif";
	$vec[1] = "png";
	$vec[3] = "jpg";
	$nombreDB =$this->loadFile($dir,$file,230,$vec,$this->parametros['peso_imagen'],$this->parametros['ancho_imagen'],$this->parametros['alto_imagen']);
	if(!empty($nombreDB)){
		if($this->addImagen($bole,$nombreDB)){
			return true;
		}else{
			return false;
		}
	}else{
		return false;
	}
}
/*
*function delFile
*descripcion elimina un archivo del servidor
*/
function delFile($ori,$nom){
	if($this->checkImage($nom)){
		if(file_exists($ori.$nom)){
			if(unlink($ori.$nom)){
				$out =$this->getMensaje("[128]","confirmacion").$nom;
				$this->setSalida(true,$out,"delFile($ori,$nom)","newsletter");
				return true;
			}else{
				$out =$this->getMensaje("[050]","error").$nom;
				$this->setSalida(false,$out,"delFile($ori,$nom)","newsletter");
				return false;
			}
		}else{
			$out =$this->getMensaje("[052]","error").$nom;
			$this->setSalida(false,$out,"delFile($ori,$nom)","newsletter");
			return $this->tokenNone;
		}
	}else{
		$out =$this->getMensaje("[149]","confirmacion").$nom;
		$this->setSalida(true,$out,"delFile($ori,$nom)","newsletter");
		return true;
	}
}
/*
*funcion chekImg
*descripcion reviza si la imagen no es ninguna de las predeterminas
*/
function checkImage($nombre){
	switch ($nombre){
		case $this->fileImgProductoNuevo:
			return false;
		break;
		case $this->fileImgProductoOferta:
			return false;
		break;
		case $this->fileImgProducto:
			return false;
		break;
		case $this->fileImgDocumento:
			return false;
		break;
		case $this->fileImgEncuesta:
			return false;
		break;		
		case $this->fileImageDefault:
			return false;
		break;
		default: return true;
	}
}

/*
*function delImagen
*descripcion elimina al imagen de un boletin
*/
function delImagenBoletin($bol){
	$im = $this->getImagenBoletin($bol);
	if(!empty($im)){
		$ima = $im['nombre'];
		$imaid = $im['id'];
		if($im!=$this->tokenNone){
				$dir="../img/boletines/";
				$sal=$this->delFile($dir,$ima);
				if(!empty($sal)){
					if($sal === $this->tokenNone){
						//la imagen no existia
						$ms = $this->salida['msg'];
						$r_Im =true;
					}else{
						$r_Im =false;
					}
					if($this->delImagen($imaid)){
						$out=$this->salida['msg'];
						if($r_Im){$out.="\\nNota: ".$ms;}
						$this->setSalida(true,$out,"delImagenBoletin($bol)","newsletter");
						return true;
					}else{
						return false;
					}
				}else{
					//imposible borrar la imagen
					return false;
				}
		}else{
			//el boletin no tiene imagen
			return true;
		}
	}else{
		//imposible consultar la imagen del boletin
		return false;
	}
}
/*
*funcion getImagen()
*descripcion devuelve el nombre de la imagen de un boletin
*/
function getImagenBoletin($boletin){
	$sql="select id, nombre from news_imagen where boletin='$boletin'";
	if($this->execute($sql)){
		if($this->numRows()>0){
			$row=$this->fetchRow();
			$out=trim($this->getMensaje("[130]","confirmacion"));
			$this->setSalida(true,$out,"getImagenBoletin($boletin)","newsletter");
			return $row;
		}else{
			$out=trim($this->getMensaje("[131]","confirmacion"));
			$this->setSalida(true,$out,"getImagenBoletin($boletin)","newsletter");
			return $this->tokenNone;
		}
	}else{
		$out=trim($this->getMensaje("[030]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"getImagenBoletin($boletin)","newsletter");
		return false;
	}
}
/*
*funcion delEnlace
*descripcion elimina los enlaces que tenga un boletin
*/
function delEnlaceBoletin($bol){
	$sql="delete from news_enlace where boletin='$bol'";
	if($this->execute($sql)){
		$out=trim($this->getMensaje("[132]","confirmacion"));
		$this->setSalida(true,$out,"delEnlaceBoletin($bol)","newsletter");
		return true;
	}else{
		$out=trim($this->getMensaje("[029]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"delEnlaceBoletin($bol)","newsletter");
		return false;
	}
}

/*
*funcion delBoletin
*descripcion elimina un boletin de newsletter
*			 incluyendo sus enlaces y sus imagenes
*/
function delBoletin($bol){
	//bol=id|titulo
	$vec = explode("|",$bol);
	$ind = $vec[0];
	$ti = $vec[1];
	$salIma =$this->delImagenBoletin($ind);
	if(!empty($salIma)){
		if($salIma===$this->tokenNone){
			$ms = $this->salida['msg'];
			$rIma =true;
		}else{
			$rIma = false;
		}
		$salEn = $this->delEnlaceBoletin($ind);
		if($salEn){
			$sql="delete from news_boletin where id='$bol'";
			if($this->execute($sql)){
				$out=trim($this->getMensaje("[133]","confirmacion")).$ti;
				if($rIma) $out.="\\nNota: ".$ms;
				$this->setSalida(true,$out,"delBoletin($bol)","newsletter");
				return true;
			}else{
				$out=trim($this->getMensaje("[028]","error"));
				$out.="\\n:Desc: ".trim($this->getException());
				$this->setSalida(false,$out,"delBoletin($bol)","newsletter");
				return false;
			}
		}else{
			$out=$this->getMensaje("[051]","error").$ti;
			$out.="\\nDesc: ".$this->salida['msg'];
			$this->setSalida(false,$out,"delBoletin($bol)","newsletter");
			return false;
		}
	}else{
		$out=$this->getMensaje("[051]","error").$ti;
		$out.="\\nDesc: ".$this->salida['msg'];
		$this->setSalida(false,$out,"delBoletin($bol)","newsletter");
		return false;
	}
	
}

/*
*funcion delNewsletter()
*descripcion elimina un newsletter con todos sus boletines si los tiene
*/
function delNewsletter($news){
	//news=id|asunto
	$vec = explode("|",$news);
	$ind = $vec[0];
	$ti = $vec[1];
	$sql = "select id,titulo from news_boletin where newsletter='$ind'";
	if($this->delCondicionTema($ind) && $this->delCondicionUsuario($ind)){	
		if($this->execute($sql)){
			if($this->numRows()>0){
				$ides= array();
				$titulos= array();
				$i=0;
				while($row = $this->fetchRow()){
					$ides[$i]= $row['id'];
					$titulos[$i]= $row['titulo'];
					$i++;
				}$i=0;
				foreach($ides as $key=>$val){
					if($this->delBoletin($val."|".$titulos[$key])){
						$i++;
					}else{
						break;
					}
				}
				if($i==count($ides)){
					if($this->delFiltro($ind)){
						$sql="delete from news_newsletter where id='$ind'";
						if($this->execute($sql)){
							$out=$this->getMensaje("[136]","confirmacion").$ti;
							$this->setSalida(true,$out,"delNewsletter($news)","newsletter");
							return true;					
						}else{
							$out=$this->getMensaje("[028]","error").$ti;
							$out.="\\nDesc: ".$this->getException();
							$this->setSalida(false,$out,"delNewsletter($news)","newsletter");
							return false;					
						}
					}else{
						return false;
					}
				}else{
					$out=$this->getMensaje("[053]","error").$ti;
					$out.="\\nDesc: ".$this->salida['msg'];
					$this->setSalida(false,$out,"delNewsletter($news)","newsletter");
					return false;
				}
			}else{
				$sql="delete from news_newsletter where id='$ind'";
				if($this->execute($sql)){
					$out=$this->getMensaje("[136]","confirmacion").$ti;
					$this->setSalida(true,$out,"delNewsletter($news)","newsletter");
					return true;					
				}else{
					$out=$this->getMensaje("[028]","error").$ti;
					$out.="\\nDesc: ".$this->getException();
					$this->setSalida(false,$out,"delNewsletter($news)","newsletter");
					return false;					
				}
			}
		}else{
			$out=trim($this->getMensaje("[028]","error"));
			$out.="\\n:Desc: ".trim($this->getException());
			$this->setSalida(false,$out,"delNewsletter($news)","newsletter");
			return false;
		}
	}else{
		return false;
	}
}

/*
*funcion delFiltro()
*/
function delFiltro($news){
	$sql="delete from news_condicion_usuario where newsletter='$news'";
	if($this->execute($sql)){
		$sql="delete from news_condicion_tema where newsletter='$news'";
		if($this->execute($sql)){
			$out=trim($this->getMensaje("[146]","confirmacion"));
			$this->setSalida(true,$out,"delFiltro($news)","newsletter");
			return true;
		}else{
			$out=trim($this->getMensaje("[057]","error"));
			$out.="\\n:Desc: ".trim($this->getException())."en delFiltro($news)";
			$this->setSalida(false,$out,"delFiltro($news)","newsletter");
			return false;
		}
	}else{
		$out=trim($this->getMensaje("[058]","error"));
		$out.="\\n:Desc: ".trim($this->getException())."en delFiltro($news)";
		$this->setSalida(false,$out,"delFiltro($news)","newsletter");
		return false;
	}
}


/*
*funcion getElementParent
*descripcion devuelve datos del padre del elemento solicitado
*			tipo=[categoria|carpeta]
*pre : 		la categoria o carpeta existe
*/
function getElementParent($id,$tipo){
	if (tipo=="categoria"){
		$sql="select nombre,descripcion,permiso from catalogo_categoria where id='$id'";
	}
	if (tipo=="carpeta"){
		$sql="select nombre,permiso from carpeta where id='$id'";
	}	
	if($this->execute($sql)){
		$out=trim($this->getMensaje("[116]","confirmacion"));
		$this->setSalida(true,$out," getElementParent($id,$tipo)","newsletter");
		return $this->fetchRow();
	}else{
		$out=trim($this->getMensaje("[036]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out," getElementParent($id,$tipo)","newsletter");
		return false;
	}
}
/*
*function getPlantilla
*descripcion devuelve la carpeta de la plantilla
*/
function getPlantilla($id){
	$sql="select carpeta from news_plantilla where id='$id'";
	if($this->execute($sql)){
		if($this->numRows()>0){
			list($fr)=$this->fetchRow();
			return $fr."/";
		}else{
			$out=trim($this->getMensaje("[144]","confirmacion"));
			$this->setSalida(true,$out,"getPlantilla($id)","newsletter");
			$this->frmGeneral."/";
		}
	}else{
		$out=trim($this->getMensaje("[056]","error"));
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"getPlantilla($id)","newsletter");
		return false;
	}
}


/*
*funcion preNewsletter()
*descrpcion devuelve una cadena con el newsletter a visualizar
*/
function preNewsletter($news,$origen){
	$sql="select * from news_newsletter where id ='$news'";
	if($this->execute($sql)){
		if($this->numRows()>0){
			$row = $this->fetchRow();
			$tml = $this->getPlantilla($row['plantilla']);
			$forma = $origen.$tml.$this->frmNewsletter;
			$fnews= (file_exists($forma))?file_get_contents($forma):NULL;
			if(!empty($fnews)){
				$date = $this->util->fecha(NULL);
				$bol = $this->preBoletin($news,$origen.$tml);//genero boletines de contenido
				if(empty($bol)){$bol=$this->salida['msg'];}
				if($bol==$this->tokenNone){$bol=$this->getMensaje("[118]","confirmacion");}
				$site= "http://".$this->sitio.$this->subDir.$this->dirSetup."plantillas/".$tml;
				$cadena = str_replace("[-fecha-]",$date,$fnews);
				$cadena = str_replace("[-titulo-]",$row[4],$cadena);
				$cadena = str_replace("[-boletines-]",$bol,$cadena);
				$cadena = str_replace("[-site-]",$site,$cadena);
				$cadena = str_replace("[-link_unsuscribe-]",$this->pathSite.$this->enlaceUnsuscribe,$cadena);
				$cadena = str_replace("[-administrador-]",$this->cuenta,$cadena);
				$cadena = str_replace("[-link_administrador-]","mailto:".$this->cuenta,$cadena);
				return $cadena;
			}else{
				$out=$this->getMensaje("[041]","error")."\\n".$forma;
				$this->setSalida(false,$out,"preNewsletter($news)","newsletter");
				return false;
			}				
		}else{
			return $this->tokenNone;
		}
	}else{
		$out=$this->getMensaje("[028]","error");
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"preNewsletter($news)","newsletter");
		return false;		
	}
}
/*
*funcion preboletin($news)
*descrpcion devuelve una cadena con el boletin a visualizar
*/
function preBoletin($news,$rt){
	$sql="select * from news_boletin where newsletter='$news'";
	if($this->execute($sql)){
		if($this->numRows()>0){
			$rbol = array(); $j=0; $row="";
			while($row=$this->fetchRow()){
				////print_r($row);
				$rbol[$j]=$this->util->implode_by_key($row,"[-|-]");
				$j++;
			}
			$strBol="";
			$site= "http://".$this->sitio.$this->subDir.$this->dirSetup.$rt;
			foreach($rbol as $key=>$val){
				$vec=explode("[-|-]",$val);
				if($vec[2]=="producto"){
					$fbol = (file_exists($rt.$this->frmBoletinProducto))?file_get_contents($rt.$this->frmBoletinProducto):NULL;
					$cms = $rt.$this->frmBoletinProducto;
				}else{
					$fbol = (file_exists($rt.$this->frmBoletin))?file_get_contents($rt.$this->frmBoletin):NULL;
					$cms = $rt.$this->frmBoletin;
				}
				if(!empty($fbol)){
					$image = $this->preImage($vec[0],"horizontal",$rt);
					$enlace = $this->preLink($vec[0],"horizontal",$rt);
					if(empty($image)){$image=$this->salida['msg'];}
					if($image==$this->tokenNone){$image="http://".$this->sitio.$this->subDir.$this->dirSetup."img/boletines/".$this->fileImageDefault;}
					if(empty($enlace)){$enlace=$this->salida['msg'];}
					if($enlace==$this->tokenNone){$enlace="";}					
					//$cadena = implode("",$fbol);
					$cadena = str_replace("[-titulo-]",$vec[3],$fbol);
					$cadena = str_replace("[-contenido-]",$this->util->parseDB2Html($vec[4]),$cadena);
					$cadena = str_replace("[-imagen-]",$image,$cadena);
					$cadena = str_replace("[-enlace-]",$enlace,$cadena);
					$cadena = str_replace("[-site-]",$site,$cadena);
					if($vec[2]=="producto"){
						$cadena = str_replace("[-valor-]",$this->util->valorNumero($vec[7]),$cadena);
						$cadena = str_replace("[-referencia-]",$vec[8],$cadena);
						$cadena = str_replace("[-categoria-]",$vec[6],$cadena);
					}
					if($key==0){
						$strBol=$cadena;
					}else{
						$strBol.=$cadena;
					}
				}else{
					$out=$this->getMensaje("[042]","error")."\\n".$cms;
					$this->setSalida(false,$out,"preBoletin($news)","newsletter");
					return false;
				}
			}//endfor
			return $strBol;
		}else{
			return $this->tokenNone;
		}
	}else{
		$out=$this->getMensaje("[031]","error");
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"preBoletin($news)","newsletter");
		return false;		
	}
}
/*
*funcion prelink($bol)
*descripcion devuelve una cadena con los enlaces a visualizar
*			 bol=id del boletin
*			 show=horizontal|vertical
*/
function prelink($bol,$show,$rta){
	$sql="select * from news_enlace where boletin='$bol'";
	if($this->execute($sql)){
		if($this->numRows()>0){
			$links="";$i=0;
			$flink= (file_exists($rta.$this->frmLink))?file_get_contents($rta.$this->frmLink):NULL;
			if(!empty($flink)){
				while($row = $this->fetchRow()){
					//$cadena = implode("",$flink);
					if(strlen($row['mascara'])==0){
						$mascara= $row['url'];
					}else{
						$mascara=$row['mascara'];
					}
					$cadena = str_replace("[-enlace-]","http://".$row['url'],$flink);
					$cadena = str_replace("[-label-]",$mascara,$cadena);
					if($show=="horizontal"){
						if($i==0){$links.=$cadena;}
						else{$links.=", ".$cadena;}
					}
					if($show=="vertical"){
						if($i==0){$links.=$cadena;}
						else{$links.="<br>".$cadena;}
					}
					$i++;	
				}
				return $links;
			}else{
				$out=$this->getMensaje("[043]","error");
				$this->setSalida(false,$out,"preLink($bol)","newsletter");
				return false;
			}
		}else{
			$out=$this->getMensaje("[152]","confirmacion");
			$this->setSalida(false,$out,"preLink($bol)","newsletter");
			$flink= (file_exists($rta.$this->frmLink))?file_get_contents($rta.$this->frmLink):NULL;
			$cadena = str_replace("[-enlace-]","http://".$this->linkDefault,$flink);
			$cadena = str_replace("[-label-]",$this->linkDefaultLabel,$cadena);
			return $cadena;
		}
	}else{
		$out=$this->getMensaje("[029]","error");
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"preLink($bol)","newsletter");
		return false;		
	}
}

/*
*funcion preImage($bol)
*descripcion recupera la imagen de un boletin
*			 bol=id del boletin
*			 show=horizontal|vertical
*/
function preImage($bol,$show,$rta){//rta no se esta utilizando en esta version
	$sql="select nombre from news_imagen where boletin='$bol'";
	if($this->execute($sql)){
		if($this->numRows()>0){
			$pt = "http://".$this->sitio.$this->subDir.$this->dirSetup."img/boletines/";
			$sal=""; $k=0;
			if($this->parametros['numero_imagenes']>1){// por si cambia a varias imagenes. lo ideal es con una plantilla al igual que los enlaces. pero queda para otra version
				while(list($nombre)=$this->fetchRow()){
					if($show=="vertical"){
						if($k==0){
							$sal="<img src=\"$pt{$nombre}\">";
						}else{
							$sal.="<br><img src=\"$pt{$nombre}\">";
						}
					}
					if($show=="horizontal"){
						if($k==0){
							$sal="<img src=\"$pt{$nombre}\">";
						}else{
							$sal.=" <img src=\"$pt{$nombre}\">";
						}
					}
					$k++;
				}
				return $sal;
			}elseif($this->parametros['numero_imagenes']==1){
				list($nombre)=$this->fetchRow();
				//$sal="<img src=\"$pt{$nombre}\">"; // por si cambia a varias imagenes. lo ideal es con una plantilla al igual que los enlaces. pero queda para otra version
				$sal=$pt.$nombre;
				return $sal;
			}else{
				$out=$this->getMensaje("[044]","error");
				$this->setSalida(false,$out,"preImage($bol,$show)","newsletter");
				return false;					
			}
		}else{
			$out=$this->getMensaje("[153]","confirmacion");
			$this->setSalida(false,$out,"preImage($bol,$show)","newsletter");
			return $this->tokenNone;
		}
	}else{
		$out=$this->getMensaje("[030]","error");
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"preImage($bol,$show)","newsletter");
		return false;		
	}
}
/*
*funcion cantboletines
*descripcion devuelve el numero de boletines que tiene el newsletter
*/
function cantBoletines($news){
	$sql="select count(*) from news_boletin where newsletter='$news'";
	if($this->execute($sql)){
		list($cant)=$this->fetchRow();
		return $cant;
	}else{
		$out=$this->getMensaje("[031]","error");
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"cantBoletines($news)","newsletter");
		return false;
	}
}

/*
*function listPlantillas
*descripcion coloca un select con las plantillas disponibles
*/
function listPlantillas($name, $hd, $sel=false){
	$sql="select * from news_plantilla where 1";
	echo "<select name=\"$name\" $hd>";
	if($this->execute($sql)){
		if($this->numRows()>0){
			while($row = $this->fetchRow()){
				if($row['id']==$sel){$selected="selected";}else{$selected="";}
				echo "<option value=\"".$row['id']."\" $selected>".ucfirst($row['carpeta'])."</option>";
			}
		}else{
			$out=$this->getMensaje("[143]","confirmacion");
			echo "<option>$out</option>";
		}
	}else{
		$out=$this->getMensaje("[056]","error");
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"listPlantillas($sel)","newsletter");
		echo "<option>$out</option>";
	}
	echo "</select>";
}

/*
*function addCondicionTema()
*descripcion adiciona una condicion de tema para el filtro de envio de newsletter
*/
function addCondicionTema($news, $tm){
	$sql="insert into news_condicion_tema (newsletter,tema) values ('$news','$tm')";
	if($this->execute($sql)){
		$out=$this->getMensaje("[145]","confirmacion");
		$this->setSalida(true,$out,"addCondicionTema($news, $tm)","newsletter");
		return true;
	}else{
		$out=$this->getMensaje("[057]","error");
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"addCondicionTema($news, $tm)","newsletter");
		return false;
	}
}
/*
*function delCondicionTema()
*descripcion elimina las condiciones de temas para el filtro de envio de newsletter
*			 correspondiente a el newsletter
*/
function delCondicionTema($news){
	$sql="delete from news_condicion_tema where newsletter='$news'";
	if($this->execute($sql)){
		$out=$this->getMensaje("[154]","confirmacion");
		$this->setSalida(true,$out,"delCondicionTema($news)","newsletter");
		return true;
	}else{
		$out=$this->getMensaje("[057]","error");
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"delCondicionTema($news)","newsletter");
		return false;
	}
}


/*
*function addCondicionUsuario()
*descripcion adiciona una condicion de usuario para el filtro de envio de newsletter
*/
function addCondicionUsuario($news, $cp, $cd, $val){
	$sql="insert into news_condicion_usuario (newsletter,campo,condicion,valor) values ('$news','$cp','$cd','$val')";
	if($this->execute($sql)){
		$out=$this->getMensaje("[145]","confirmacion");
		$this->setSalida(true,$out,"addCondicionUsuario($news, $cp, $cd, $val)","newsletter");
		return true;
	}else{
		$out=$this->getMensaje("[058]","error");
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"addCondicionUsuario($news, $cp, $cd, $val)","newsletter");
		return false;
	}
}
/*
*function delCondicionUsuario()
*descripcion adiciona una condicion de usuario para el filtro de envio de newsletter
*/
function delCondicionUsuario($news){
	$sql="delete from news_condicion_usuario where newsletter='$news'";
	if($this->execute($sql)){
		$out=$this->getMensaje("[155]","confirmacion");
		$this->setSalida(true,$out,"delCondicionUsuario($news)","newsletter");
		return true;
	}else{
		$out=$this->getMensaje("[058]","error");
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"delCondicionUsuario($news)","newsletter");
		return false;
	}
}

/*
*function calcFecha
*descripcion entrega una fecha dado una edad y un tipo
*/
function getCalcFecha($ed){
	$an = date("Y");
	$me = 1;//date("m"); para que sea desde enero
	$di = 1;//date("d"); para que sea desde el 1 de enero
	$anoN = $an - $ed;
	return $anoN."-01-01";//date( "Y-m-d", mktime(1,1,1,$me,$di,$anoN) ); no recibe fechas antes de 1970
}

/*
*funcion makeQuery
*descripcion devuelve el query para la consulta de los usuarios a los que 
*			 ira dirigido el newsletter
*/
function makeQuery($news){
	$idA =$this->id;
	$inf=$this->getNewsletter($news);
	$aliasUser = "user";
	$aliasNews = "vnews";
	$sql= "SELECT distinct(user.email), count(vnews.vinculo) as cant FROM usuario_web AS $aliasUser, vinculo_web AS vweb, news_vinculo AS $aliasNews WHERE ";
	$strPpal = " vweb.estado='activo' AND vweb.aplicacion=$idA AND vweb.usuario_web=user.id AND vweb.id=vnews.vinculo";
	$strFinal = " GROUP BY vnews.vinculo ";
	$strConjuncion =" AND ";
	if(is_array($inf)){
		$condUser = $this->makeCondUsuario($news,$inf['filtro_usuario'],$aliasUser);
		if(empty($condUser)){return false;}//sale por error formando condiciones de usuario
		$condTema = $this->makeCondTema($news,$inf['filtro_tema'],$inf['general_tema'],$aliasNews);		
		if( empty($condTema)){return false;} //sale por error formando condiciones de temas

		if($condUser==$this->tokenNone){
			$sql.=$strPpal;
		}else{
			$sql.=$condUser." AND ".$strPpal;
		}
		if( ($inf['general_tema']=="alguno" || $inf['general_tema']=="ninguno" || $inf['general_tema']=="todos") && $inf['filtro_tema']=="disyuncion" ){
			if($condTema!=$this->tokenNone){
				$sql.=" AND ".$condTema;
			}
			return $sql.$strFinal;
		}
		if( ($inf['general_tema']=="alguno" || $inf['general_tema']=="ninguno" || $inf['general_tema']=="todos") && $inf['filtro_tema']=="conjuncion" ){
			if($condTema!=$this->tokenNone){
				$sql.=$strConjuncion.$condTema;
			}
			return $sql.$strFinal;
		}

	}else{
		return false;
	}
}

function makeCondUsuario($newsU,$filtro,$prefijo){
	$prefijo = (!empty($prefijo))?$prefijo.".":NULL;
	$sql = "select campo,condicion,valor from news_condicion_usuario where newsletter='$newsU'";
	if($this->execute($sql)){
		if($this->numRows()>0){
			$op=NULL;
			if($filtro=="conjuncion"){$op=" AND ";}
			if($filtro=="disyuncion"){$op=" OR ";}
			if(!empty($op)){
				$sal="";
				while(list($campo,$cond,$val)=$this->fetchRow()){
					$sal.=$prefijo.$campo.$cond."'".$val."'".$op;
				}
				$sal=substr($sal,0,strlen($sal)-strlen($op));
				return "(".$sal.")";
			}else{
				$out=$this->getMensaje("[059]","error");
				$this->setSalida(false,$out,"makeCondUsuario($newsU,$filtro)","newsletter");
				return false;
			}
		}else{
			$out=$this->getMensaje("[156]","confirmacion");
			$this->setSalida(false,$out,"makeCondUsuario($newsU,$filtro)","newsletter");
			return $this->tokenNone;
		}
	}else{
		$out=$this->getMensaje("[058]","error");
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"makeCondUsuario($newsU,$filtro)","newsletter");
		return false;
	}	
}
/*
*funcion makeCondTema()
*descripcion realiza la creacion de la parte de la consulta que hace
*			 el filtrado por tema
*			 $news= id del newsletter
*			 $filtro=[disyuncion,conjuncion]
*			 $general= [alguno,ninguno,todos]
*			 $prefijo= cadena que precede al nombre de la columna en la consulta.
*			 pre: prefijo no puede ser cadena vacia.
*/

function makeCondTema($newsT,$filtro,$general,$prefijo){
	$prefijo = (!empty($prefijo))?$prefijo.".":NULL;
	$sql="No hay consulta!";
	$op=NULL;
	if( $general=="alguno"){
		$sql = "select tema from news_condicion_tema where newsletter='$newsT'";
		$op=" OR ";
	}
	if( $general=="ninguno" ){
		$sql = "select distinct(tema) as temas from news_vinculo where 1";
		$op=" OR ";
	}
	if( $general=="todos" ){
		$sql = "select id from news_tema where 1";
		$op=" OR ";
	}
	if($this->execute($sql)){
		if($this->numRows()>0){
			if(!empty($op)){
				$sal="";
				while(list($tm)=$this->fetchRow()){
					$sal.=$prefijo."tema='".$tm."'".$op;
				}
				$sal=substr($sal,0,strlen($sal)-strlen($op));
				return "(".$sal.")";
			}else{
				$out=$this->getMensaje("[059]","error");
				$this->setSalida(false,$out,"makeCondTema($newsT,$filtro,$general,$prefijo)","newsletter");
				return false;
			}
		}else{
			return $this->tokenNone;
		}
	}else{
		$out=$this->getMensaje("[057]","error");
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"makeCondTema($newsT,$filtro,$general,$prefijo)","newsletter");
		return false;
	}
}

/*
*funcion cantidadTemasVinculados()
*descripcion devuelve la cantidad de temas qeu tienen por lo menos un vinculo en el newsletter
*			 es decir, que por lo menos haya un usuario suscrito en �l.
*/

function cantidadTemasVinculados(){
	$sql = "select distinct(tema) as temas from news_vinculo where 1";
	if($this->execute($sql)){
		return $this->numRows();
	}else{
		$out=$this->getMensaje("[057]","error");
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"cantidadTemasVinculados()","newsletter");
		return false;
	}
}

/*
*funcion cantidadCondicionesTema()
*descripcion devuelve la cantidad de temas seleccionados
*			 como restricciones para el envio del newsletter solicitado
*/
function cantidadCondicionesTema($news){
	$sql="select count(*) as cant from news_condicion_tema where newsletter='$news'";
	if($this->execute($sql)){
		list($cant)=$this->fetchRow();
		return $cant;
	}else{
		$out=$this->getMensaje("[057]","error");
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"cantidadCondicionesTema($news)","newsletter");
		return false;
	}
}
/*
*funcion cantidadUsuariosEnvio()
*descripcion devuelve un arreglo con los valores de usuarios que recoge la consulta
*			 $sql=consulta arrojada por el makeQuery()
*			 $filtro = [conjuncion , disyuncion]
*			 $cantidad = total de temas a los que el filtro aplica
*			 arreglo[0] contiene el valor del total de usuarios de la consulta.
*			 arreglo[1] contiene el valor del total de usuarios a los que aplica el filtro
*/
function cantidadUsuariosEnvio($sql,$filtro,$cantidad){
	if($this->execute($sql)){
		$arreglo[0]=$this->NumRows();
		$lv=0;
		if($filtro=="conjuncion"){
			if(!empty($cantidad)){
				while(list($email,$cant)=$this->fetchRow()){
					if($cant==$cantidad){
						$lv++;
					}
				}
			}else{
				$out = $this->getMensaje("[061]","error");
				$this->setSalida(false,$out,"cantidadUsuariosEnvio($sql,$filtro,$cantidad)","newsletter");
				return false;
			}
		}else{
			$lv=$this->numRows();
		}
		$arreglo[1]=$lv;
		return $arreglo;
	}else{
		$out=$this->getMensaje("[060]","error");
		$out.="\\n:Desc: ".trim($this->getException());
		$this->setSalida(false,$out,"cantidadUsuariosEnvio($sql,$filtro,$cantidad)","newsletter");
		return false;
	}
}

/*
*funcion arrayTemas
*descripcion devuelve un arreglo con todos los temas que se encuentran
*			 registrados en el newsletter
*			 esta funcion se utiliza para el llenado de la base de datos temporal de pruebas
*/
function arrayTemas(){
	$sql="select id, titulo from news_tema where 1 order by id asc";
	$ides = array();
	//$titulos = array();
	$this->execute($sql);
	$i=0;
	while(list($id,$titulo)=$this->fetchRow()){
		$ides[$i]['id'] = $id;
		$ides[$i]['titulo'] = $titulo;
		$i++;
	}
	return $ides;
}

/*
*funcion getPreferences
*descripcion devuelve una cadena con temas aleatorios seleccionados del conjunto
*			 esta funcion se utiliza para el llenado de la base de datos temporal de pruebas
*			 $vector = arreglo que devuelve arrayTemas
*			 $cant = cantidad de temas que debe seleccionar de el vector
*			 pre: cant nunca es mayor que que la cantidad de elementos del vector
*/
function getPreferences($vector, $cant){
	mt_srand((double)microtime()*1000000);
	$min = 0; $max=count($vector);
	$i=0; $sal="1|General[|]";
	$hechos=array();
	$hechos[]=0;
	while($i<$cant){
		$j= mt_rand($min,$max-1);
		while(array_search($j,$hechos)!==FALSE){
			$j= mt_rand($min,$max-1);
		}
		$hechos[]=$j;
		$sal.= $vector[$j]['id']."-".$vector[$j]['titulo']."[|]";
		$i++;
	}
	$leng = strlen($sal);
	return substr($sal,0,$leng-3);
}

/*
*funcion getPreferencesAll
*descripcion devuelve una cadena con todos los temas seleccionados del conjunto
*			 esta funcion se utiliza para el llenado de la base de datos apartir de los usuarios existentes
*			 $vector = arreglo que devuelve arrayTemas
*			 pre: cant nunca es mayor que que la cantidad de elementos del vector
*/
function getPreferencesAll($vector){
	$max=count($vector);
	$i=0; $sal="1|General[|]";
	$hechos=array();
	while($i<$max){
		$sal.= $vector[$i]['id']."-".$vector[$i]['titulo']."[|]";
		$i++;
	}
	$leng = strlen($sal);
	return substr($sal,0,$leng-3);
}


/*
*funcion getConfiguracionEnvio()
*descripcion devuelve un arreglo con los valores necesarios para el envio
*			 del newsletter 
*			 query=consulta generada por makeQuery()
*			 $msg=cadena generada por preNewsletter()
*			 titulo= titulo o asunto del newsletter 
*			 numeroTemas = cantidad de temas que filtran el envio (news_condicion_tema para el newsletter a enviar)
*			 filtro = filtro_tema del newsletter a enviar [conjuncion,disyuncion]
*/
function getConfiguracionEnvio($query,$msg,$titulo,$numeroTemas,$filtro){
	$arreglo=array();
	$valores = $this->cantidadUsuariosEnvio($query,$filtro,$numeroTemas);
	if(!is_array($valores)){
		return false;
	}else{
		$arreglo['totalGeneral']=(int)$valores[0];
		$arreglo['totalNetoFiltro']=(int)$valores[1];
	
		$time1 =microtime();
		if(!$this->sendMail($this->cuenta, $this->cuenta, $titulo, $msg,false,false, false)){
			return false;
		}
		$time2 =microtime();
		$ve = $this->util->getDiference($time1,$time2,"<br>");
		$tiempoEmail = ceil((double)$ve[1]);//tiempo estimado para enviar un email
		$tiempoDisponible = (int)ini_get("max_execution_time");//tiempo disponible por el servidor para el script
		$tiempoDisponible = $tiempoDisponible - $this->margen;
		$arreglo['envios']=ceil((int)$arreglo['totalNetoFiltro'] / $this->paquete);//cantidad de envios necesarios para cumplir con todo
		$arreglo['cantidadEnviosPorIntervalo'] = floor($tiempoDisponible/$tiempoEmail);//envios posibles a realizar en cada ejecucion si sobrepasar el tiempo disponible para el script
		$arreglo['cantidadIntervalos'] = ceil((int)$arreglo['envios']/(int)$arreglo['cantidadEnviosPorIntervalo']);
		return $arreglo;
	}
}
/*
*funcion sendNewsletter()
*descripcion envia el newsletter por intervalo
*
*/
function sendNewsletter($query,$msg,$cantGeneral,$cantFiltroNeto,$cantHechos,$cantRecorridos,$etapa,$cantTemasFiltro,$filtro,$cantEnviosPermitida,$titulo){
	$enviados=0;
	$arreglo=array();
	while($enviados<$cantEnviosPermitida){
		$query2=$query." limit $cantRecorridos,$cantGeneral";
		if($this->execute($query2)){
			$i=0;$bcc="";
			while($i<$this->paquete){
				if($cantHechos<$cantFiltroNeto){
					if($cantRecorridos<$cantGeneral){
						if(list($email,$cant)=$this->fetchRow()){
							if($filtro=="conjuncion"){
								if($cant==$cantTemasFiltro){
									$bcc.=$email.",";
									$cantHechos++;
								}
							}else{
								$bcc.=$email.",";
								$cantHechos++;
							}
							$cantRecorridos++;
						}else{
							$out=$this->getMensaje("[062]","error");
							$this->setSalida(false,$out,"sendNewsletter($query,false,$cantGeneral,$cantFiltroNeto,$cantHechos,$cantRecorridos,$etapa,$cantTemasFiltro,$filtro,$cantEnviosPermitida)","newsletter");
							return false;						
						}
					}else{ 
						if($cantHechos<$cantFiltroNeto){
							$out=$this->getMensaje("[062]","error");
							$this->setSalida(false,$out,"sendNewsletter($query,false,$cantGeneral,$cantFiltroNeto,$cantHechos,$cantRecorridos,$etapa,$cantTemasFiltro,$filtro,$cantEnviosPermitida)","newsletter");
							return false;
						}else{
							$i=$this->paquete;
						}
					}
				}else{
					$i=$this->paquete;
					$enviados=$cantEnviosPermitida;
				}
				$i++;
			}//end while paquete
			$bcc=substr($bcc,0,strlen($bcc)-1);
			if($this->sendMail($this->cuenta, $this->cuenta, $titulo, $msg,false,$bcc, false)){
				$enviados++;
			}else{
				return false;
			}
		}else{
			$out=$this->getMensaje("[060]","error");
			$out.="\\n:Desc: ".trim($this->getException());
			$this->setSalida(false,$out,"sendNewsletter($query,false,$cantGeneral,$cantFiltroNeto,$cantHechos,$cantRecorridos,$etapa,$cantTemasFiltro,$filtro,$cantEnviosPermitida)","newsletter");
			return false;
		}
	}//end while enviados
	if( ($enviados==$cantEnviosPermitida) || ($cantHechos==$cantFiltroNeto) ){
		$arreglo['hechos']=$cantHechos;
		$arreglo['recorridos']=$cantRecorridos;
		$arreglo['intervalo']=$etapa+1;
		return $arreglo;
	}
}

/*
*funcion sendNewsletterProg()
*descripcion envia el newsletter programado
*
*/
function sendNewsletterProg($query,$msg,$cantGeneral,$cantFiltroNeto,$cantHechos,$cantRecorridos,$etapa,$cantTemasFiltro,$filtro,$cantEnviosPermitida,$titulo){
	$enviados=0;
	$arreglo=array();
	while($enviados<$cantEnviosPermitida){
		$query2=$query." limit $cantRecorridos,$cantGeneral";
		if($this->execute($query2)){
			$i=0;$bcc="";
			while($i<$this->paquete){
				if($cantHechos<$cantFiltroNeto){
					if($cantRecorridos<$cantGeneral){
						if(list($email,$cant)=$this->fetchRow()){
							if($filtro=="conjuncion"){
								if($cant==$cantTemasFiltro){
									$bcc.=$email.",";
									$cantHechos++;
								}
							}else{
								$bcc.=$email.",";
								$cantHechos++;
							}
							$cantRecorridos++;
						}else{
							$out=$this->getMensaje("[062]","error");
							$this->setSalida(false,$out,"sendNewsletter($query,false,$cantGeneral,$cantFiltroNeto,$cantHechos,$cantRecorridos,$etapa,$cantTemasFiltro,$filtro,$cantEnviosPermitida)","newsletter");
							return false;						
						}
					}else{ 
						if($cantHechos<$cantFiltroNeto){
							$out=$this->getMensaje("[062]","error");
							$this->setSalida(false,$out,"sendNewsletter($query,false,$cantGeneral,$cantFiltroNeto,$cantHechos,$cantRecorridos,$etapa,$cantTemasFiltro,$filtro,$cantEnviosPermitida)","newsletter");
							return false;
						}else{
							$i=$this->paquete;
						}
					}
				}else{
					$i=$this->paquete;
					$enviados=$cantEnviosPermitida;
				}
				$i++;
			}//end while paquete
			$bcc=substr($bcc,0,strlen($bcc)-1);
			if($this->sendMail($this->cuenta, $this->cuenta, $titulo, $msg,false,$bcc, false)){
				$enviados++;
			}else{
				return false;
			}
		}else{
			$out=$this->getMensaje("[060]","error");
			$out.="\\n:Desc: ".trim($this->getException());
			$this->setSalida(false,$out,"sendNewsletter($query,false,$cantGeneral,$cantFiltroNeto,$cantHechos,$cantRecorridos,$etapa,$cantTemasFiltro,$filtro,$cantEnviosPermitida)","newsletter");
			return false;
		}
	}//end while enviados
	if( ($enviados==$cantEnviosPermitida) || ($cantHechos==$cantFiltroNeto) ){
		$arreglo['hechos']=$cantHechos;
		$arreglo['recorridos']=$cantRecorridos;
		$arreglo['intervalo']=$etapa+1;
		return $arreglo;
	}
}



}//end class cliente
?>

Anon7 - 2021