
<script type="text/javascript"> 


	function inicio(){


	fechacorreos=document.getElementById("fechacorreos").value;
	

      location.href="descargar_correo.php?fechacorreos=" + fechacorreos;

	document.getElementById("form_busqueda").submit();
}	

</script>


<html>	 
	 <head>		
		<link href="../estilos/estilos.css" type="text/css" rel="stylesheet">
     </head>
		 	 
  	<body>
    
	<div id="bloquea" class="cargando" style="display:block;">
	<img style="margin-left: 5%;margin-top: 15%" alt="Espere..." src="../img/procesando.gif" />
	
	</div>        
			
	<div id="botonBusquedaAWR">					
				
				<div id="" align="center">
				  <p><img src="../img/Vista (238).png" width="256" height="256" onClick="aceptar()" border="0" onMouseOver="style.cursor=cursor" title="Salir">				  </p>
					<p><span class="fuente_gracias">DESCARGANDO CORREOS DESDE <?php echo  $_GET["fechacorreos"]; ?>  </span></p>
				</div>
				
						
	</div>	
				
				<form id="form_busqueda" name="form_busqueda" method="post" action="listar_correos_cargando.php" target="frame_rejilla">
							
							<p>
							  <input type="hidden" id="fechacorreos" name="fechacorreos" value="<?php echo  $fechacorreos ?> ">
</p>
							<p>&nbsp;</p>
							<p>&nbsp;</p>
							<p>&nbsp;                            </p>
							<iframe width="100%" height="550" id="frame_rejilla" name="frame_rejilla" frameborder="0">
                    <ilayer width="60%" height="60" id="frame_rejilla" name="frame_rejilla"></ilayer>
				    </iframe>	  
					
					
	</form>		
	</body>
</html>


<?php

include('../conexion.php'); 



error_reporting(0);
				
///////////////////   limpia el directorio del correo //////////////////////////////

$directorio = opendir("./correos/");  
while ($archivo = readdir($directorio))     
{   $nombreArch = ucwords($archivo);     
$nombreArch = str_replace("..", "Atras", $nombreArch);  

unlink("./correos/".$nombreArch);
} 

closedir($directorio);   


//////////// descarga los  nuevos correos /////////////////////////////////

set_time_limit(300000);
//$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
//$hostname = '{imap-mail.outlook.com:993/imap/ssl}INBOX';



$parametros = "SELECT * FROM web_0000 ";
       $result_parametros = $mysqli->query($parametros);
       $row_para = $result_parametros->fetch_array();
     
	  $username =  $row_para["COREMP"];         //  ruddyajm2018@gmail.com
	  $password =  $row_para["CLACOR"];         //  Rjmc0587
	  $hostname =  $row_para["SERIMAP"];        //  $hostname = '{imap.gmail.com:993/imap/ssl}INBOX'
   
   
      $servidor_correo = substr($username, -9); 
         $fechacorreos=$_GET["fechacorreos"];
         $fecini= implode("-", array_reverse(explode("-",  $fechacorreos))); 
         $fecini= str_replace("-","/",$fecini);
		 
	echo	 $fechahoy=date("Y/m/d");

//	$opt_param['q'] = "after:2022/03/01 before:2022/03/24";
	 
	 if ($servidor_correo == "gmail.com" )   {    // SI EL SERVIDOR DE CORREO ES GMAIL
	 
	 
	 
	 	//dar acceso https://console.cloud.google.com/
	
	//hacer funcion de index.php en localhost con redirect de code
	//Si hay token
	//dar acceso
	//revocar token
	//tareas
	
	//este ejemplo realiza todo el proceso de una vez, pero si desea realizar algo mas especificio
	//https://developers.google.com/gmail/api/quickstart/php
	
	require_once __DIR__ . '/vendor/autoload.php';
	
	function getClient(){
		$client = new Google_Client();
		$client->setApplicationName('GmailBox');
		$client->setScopes([Google_Service_Gmail::MAIL_GOOGLE_COM]);
		$client->setAuthConfig( __DIR__.'/client_secret.json');
		$client->setAccessType('offline');
		
		$credentialsPath = expandHomeDirectory(__DIR__ . '/token.json');
		if(isset($_GET['code'])){
			$authCode = trim($_GET['code']);		
			$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
			if (!file_exists(dirname($credentialsPath))) {
				mkdir(dirname($credentialsPath), 0700, true);
			}
			file_put_contents($credentialsPath, json_encode($accessToken));
			printf("Credentials saved to %s\n", $credentialsPath);
		}
		
		if (file_exists($credentialsPath)) {
			$accessToken = json_decode(file_get_contents($credentialsPath), true);
		} else {
			//$client->setRedirectUri('http://softcomcr.com/wccr');
			$authUrl = $client->createAuthUrl();
			echo '<a href="'.$authUrl.'">Dar acceso</a><br>';
			die;
		}
		
		$client->setAccessToken($accessToken);
		if ($client->isAccessTokenExpired()) {
			$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
			file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
		}
		return $client;
	}

/**
 * Expands the home directory alias '~' to the full path.
 * @param string $path the path to expand.
 * @return string the expanded path.
 */
function expandHomeDirectory($path)
{
    $homeDirectory = getenv('HOME');
    if (empty($homeDirectory)) {
        $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
    }
    return str_replace('~', realpath($homeDirectory), $path);
}

$userId = $username;

	/************************/
	function getAttachment($messageId, $partId, $userId)
    {
        try {
            $client = getClient();
            $gmail = new Google_Service_Gmail($client);
            $message = $gmail->users_messages->get($userId, $messageId);
            $message_payload_details = $message->getPayload()->getParts();
            $attachmentDetails = array();
            $attachmentDetails['attachmentId'] = $message_payload_details[$partId]['body']['attachmentId'];
            $attachmentDetails['headers'] = $message_payload_details[$partId]['headers'];
            $attachment = $gmail->users_messages_attachments->get($userId, $messageId, $attachmentDetails['attachmentId']);
            $attachmentDetails['data'] = $attachment->data;
            return ['status' => true, 'data' => $attachmentDetails];
        } catch (\Google_Service_Exception $e) {
            return ['status' => false, 'message' => $e->getMessage()];
        }
    }
/*
    function base64_to_jpeg($base64_string, $content_type) {
        $find = ["_","-"]; $replace = ["/","+"];
        $base64_string = str_replace($find,$replace,$base64_string);
        $url_str = 'data:'.$content_type.','.$base64_string;
        $base64_string = "url(".$url_str.")";
        $data = explode(',', $base64_string);
        return base64_decode( $data[ 1 ] );
    }
	*/
	
	$client = getClient();
    $service = new Google_Service_Gmail($client);
    $opt_param = array();
    $opt_param['labelIds'] =  'INBOX';
    $opt_param['maxResults'] = 3000;
	$opt_param['q'] = "after:".$fecini." before:".$fechahoy;
	
    $messages = $service->users_messages->listUsersMessages($userId, $opt_param);
	$files = array();
     
	$mnsPath = expandHomeDirectory(__DIR__ . '/correos/');
	echo 'Cantidad: '.count($messages).'<br>';
	
	$nosonxmls = '';
    
	foreach ($messages as $message_thread) {
		$message = $service->users_messages->get($userId, $message_thread['id']);
		$message_parts = $message->getPayload()->getParts();
		
		
		if(count($message_parts)>0)
			if (array_key_exists(1,$message_parts))				
				$attachId = $message_parts[1]['body']['attachmentId'];
			
		
		if(!is_null($attachId)){			
			$attach = $service->users_messages_attachments->get($userId, $message['id'], $attachId);
			foreach ($message_parts as $key => $value) {
				if ( isset($value->body->attachmentId) && !isset($value->body->data)) {
					$messageId = $message['id'];
					$partId = $value['partId'];				
					$message_payload_details = $message->getPayload()->getParts();
					$attachmentDetails = array();
					$attachmentDetails['attachmentId'] = $message_payload_details[$partId]['body']['attachmentId'];
					$attachmentDetails['headers'] = $message_payload_details[$partId]['headers'];
					$attachment = $service->users_messages_attachments->get($userId, $messageId, $attachmentDetails['attachmentId']);
					$attachmentDetails['data'] = $attachment->data;
					$attachment = ['status' => true, 'data' => $attachmentDetails];
					
					$content_type = "";
					foreach ($attachment['data']['headers'] as $key => $values) {
						if($values->name == 'Content-Type'){ 
							$content_type_val = current(explode("/",$values->value));							
							echo 'Adjunto del tipo: '.$values->value.' / '.$content_type_val.'<br>';
							if(
								str_contains($values->value,'text/xml') ||
								str_contains($values->value,'application/xml')	||							
								str_contains($values->value,'application/octet-stream')		||
								
								str_contains($values->value,'txt/Xml')					
								){
									/*
									$findme   = 'name=';
									$pos = strpos($values->value, $findme);
									$endPos = strrpos($values->value, '"');									
									$findme   = 'xm';
									$pos = strpos($values->value, $findme) + 1; 
									$endPos = strrpos($values->value, '"'); 
									$nameAttach = substr($values->value, $pos, -1); // devuelve "el nombre del archivo"
									*/
									
									
									$finalName = str_replace('application/xml; name="','',$values->value);
									$finalName = str_replace('"','',$finalName);
									$finalName = str_replace('text/xml; name=','',$finalName);
									$finalName = str_replace('application/octet-stream; name=','',$finalName);
									$finalName = str_replace('application/xml','',$finalName);
									$finalName = str_replace('text/xml','',$finalName);
									$finalName = str_replace('txt/Xml; name=','',$finalName);
									
									echo 'Nombre final del archivo : '.$finalName. '<br><hr><br>';
										$decode = base64_decode(str_replace(array('-', '_'), array('+', '/'), $attachment['data']['data']));
									if($finalName != '')
										file_put_contents($mnsPath.$finalName,$decode);
									else
										file_put_contents($mnsPath.'gn_'.date('Ymdhis').'xml',$decode);
										
									
								}else{
									$nosonxmls .= $values->value.'<br>';	
								}
						}	
					}
				}
			}
		}
		
					
	}

		echo '<br><hr><h3>Archivos adjuntos que no son xml</h3><br>';
		echo $nosonxmls;

	 
	 
	 
	} else  {     //  SI EL SERVIDOR DE CORREO NO ES GMAIL 
	 
	 
$max_emails = 30000;



	   
/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());


/* grab emails */

$originalDate= implode("-", array_reverse(explode("-", $fechacorreos))); 


echo $newDate = date("d M Y", strtotime($originalDate));

$emails = imap_search ( $inbox, "SINCE \"$newDate\"");

$max_emails = 30000;

/* if emails are returned, cycle through each... */
if($emails) {

    $count = 1;

    /* begin output var */
    $output = '';

    /* put the newest emails on top */
    rsort($emails);

    /* for every email... */
    foreach($emails as $email_number) {

        /* get information specific to this email */
        $overview = imap_fetch_overview($inbox,$email_number,0);
        $message = imap_fetchbody($inbox,$email_number,1.1);
        $structure = imap_fetchstructure($inbox,$email_number);
		
  


  $attachments = array();

$filename_en_mismo_correo="";
$archivos= 0; 
        /* if any attachments found... */
        if(isset($structure->parts) && count($structure->parts)) 
        {
            for($i = 0; $i < count($structure->parts); $i++) 
            {
                $attachments[$i] = array(
                    'is_attachment' => false,
                    'filename' => '',
                    'name' => '',
                    'attachment' => ''
                );
				


                if($structure->parts[$i]->ifdparameters) 
                {
                    foreach($structure->parts[$i]->dparameters as $object) 
                    {
			
                        if(strtolower($object->attribute) == 'filename') 
                        {
                       $attachments[$i]['is_attachment'] = true;
                    

                        }
                    }
                }

                if($structure->parts[$i]->ifparameters) 
                {
                    foreach($structure->parts[$i]->parameters as $object) 
                    {
                        if(strtolower($object->attribute) == 'name') 
                        {
                            $attachments[$i]['is_attachment'] = true;
                            $attachments[$i]['name'] = $object->value;
	
                        }
                    }
                }

                if($attachments[$i]['is_attachment']) 
                {

                    $attachments[$i]['attachment'] = imap_fetchbody($inbox, $email_number, $i+1);
				
                    /* 3 = BASE64 encoding */
                    if($structure->parts[$i]->encoding == 3) 
                    { 
                        $attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
											 
                    }
                    /* 4 = QUOTED-PRINTABLE encoding */
                    elseif($structure->parts[$i]->encoding == 4) 
                    { 
                        $attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
									
		
						
                    }
                }
            }
        }

        /* iterate through each attachment and save it */
        foreach($attachments as $attachment)
        {
            if($attachment['is_attachment'] == 1)
            {
			
            $filename = $attachment['name'];
                if(empty($filename)) $filename = $attachment['filename'];
				
		
                if(empty($filename)) $filename = time() . ".dat";

                /* prefix the email number to the filename in case two emails
                 * have the attachment with the same file name.
                 */
				 

   
				
				    // imprime de quien viene el correo y lo limpia de caracteres especiales						
                    $salida = $overview[0]->from;		// $salida.= 'Tema: '.$overview[0]->subject;
				    $salida = str_replace(' ', '_',  $salida);
				    $salida = str_replace('.', '',  $salida);
					$salida = str_replace('"', '',  $salida);
					//$salida = str_replace('<@>', '',  $salida);
					$salida = str_replace('<', '',  $salida);
					$salida = str_replace('>', '',  $salida);
					$salida = str_replace('ú', 'u',  $salida);
					$salida = str_replace('é', 'e',  $salida);
					$salida = str_replace('á', 'a',  $salida);
					$salida = str_replace('ó', 'o',  $salida);
					$salida = str_replace('í', 'i',  $salida);
					$salida = str_replace('ñ', 'n',  $salida);
					$salida = str_replace('Ñ', 'n',  $salida);
					$salida = str_replace('-', '',  $salida);
					
					$archivos= $archivos + 1; 

				//echo $filename=  "Comprobante_Electronico_".$salida.".xml";
				$filename=  "Comprobante_Electronico_".$archivos.".xml";
	
				
				    $fp = fopen("./correos/" . $email_number . "-" . $filename, "w+");
					
		
				
				
                fwrite($fp, $attachment['attachment']);
                fclose($fp);
            }

        }

        if($count++ >= $max_emails) break;

    
}
}



$directorio = opendir("./correos/");  
while ($archivo = readdir($directorio))     
{   $nombreArch = ucwords($archivo);     
$nombreArch = str_replace("..", "Atras", $nombreArch);  


if (strtolower(substr($nombreArch, -3) == "xml"   ))
{



}  else {

unlink("./correos/".$nombreArch);
} 
} 
closedir($directorio);   








  /* try to connect */
$link = imap_open($hostname,$username,$password) or die('No se Conecto al Correo: ' . imap_last_error());
//$emails = imap_search ( $link, 'SINCE 01-Aug-2021'); // cambiar fecha solo para pruebas
$emails = imap_search ( $link, 'SINCE "'.$newDate.'"');  // usar este
 
	 
if($emails) {	 
	 rsort($emails);
	 
	 foreach($emails as $msgid) {
//buscar la estructura del mensaje
$s=imap_fetchstructure($link,$msgid);

//mira si hay partes
if (count($s->parts)>0){
foreach ($s->parts as $partno=>$partarr){
    //analizar partes del correo electrónico parsepart
    analizar_parte($partarr,$partno+1);
    }
}

//for not multipart messages
else{
    //get body of message
    $text=imap_body($link,$msgid);
    //decode if quoted-printable
    if ($s->encoding==4) $text=quoted_printable_decode($text);
    //OPTIONAL PROCESSING
    if (strtoupper($s->subtype)=='PLAIN') $text=$text;
    if (strtoupper($s->subtype)=='HTML') $text=$text;
   
    $partsarray['not multipart'][text]=array('type'=>$s->subtype,'string'=>$text);
}

}

}

//print_r($partsarray); // mostrar el contenido



function analizar_parte($p,$i){
    global $link,$msgid,$partsarray;
    //dónde escribir archivos adjuntos a:
	//$filestore = 'descargas';

    //buscar parte
    $parte=imap_fetchbody($link,$msgid,$i);
    //si el tipo no es texto
    if ($p->type!=0){
        //DECODE PART       
        //decode if base64
        if ($p->encoding==3)$parte=base64_decode($parte);
        //decode if quoted printable
        if ($p->encoding==4)$parte=quoted_printable_decode($parte);
        //no need to decode binary or 8bit!
       
        //obtener el nombre del archivo adjunto si está presente
        $filename='';
        // si hay algún dparameters presente en esta parte
        if (count($p->dparameters)>0){
            foreach ($p->dparameters as $dparam){
                if ((strtoupper($dparam->attribute)=='NAME') ||(strtoupper($dparam->attribute)=='FILENAME')) $filename=$dparam->value;
                }
            }
        //si no se encuentra ningún nombre de archivo
        if ($filename==''){
            // si hay algún parámetro presente en esta parte
            if (count($p->parameters)>0){
                foreach ($p->parameters as $param){
                    if ((strtoupper($param->attribute)=='NAME') ||(strtoupper($param->attribute)=='FILENAME')) $filename=$param->value;
                    }
                }
            }
        
			//escribir el archivo y establecer la variable en la matriz 
        if ($filename!=''){
           // $partsarray[$i][attachment] = array('filename'=>$filename,'binary'=>$parte);   //  quitar comentario para guardar en el arreglo si quiero ver lo que se imprime
		    $extencion = substr($filename, -3);    // devuelve "f"
			
			if ($extencion == "xml"){  // para guardar solo los xml
			
				$fp=fopen("./correos/".$filename,"w+");
				fwrite($fp,$parte);
				fclose($fp);
				
			}
			
			
            }
    //end if type!=0       
    }
   
    //if part is text
    else if($p->type==0){
        //decode text
        //if QUOTED-PRINTABLE
        if ($p->encoding==4) $parte=quoted_printable_decode($parte);
        //if base 64
        if ($p->encoding==3) $parte=base64_decode($parte);
       
        //PROCESAMIENTO OPCIONAL, p. Ej. nl2br para texto sin formato
        //si es texto sin formato

        if (strtoupper($p->subtype)=='PLAIN')1;
        //if HTML
        else if (strtoupper($p->subtype)=='HTML')1;
        $partsarray[$i][text] = array('type'=>$p->subtype,'string'=>$parte);
    }
   
    //si las subpartes ... recurren a la función y las analizan también.
    if (count($p->parts)>0){
        foreach ($p->parts as $pno=>$parr){
            analizar_parte($parr,($i.'.'.($pno+1)));           
            }
        }
return;
}
 
 
 }  // cierra que no es GMAIL 
  
  ?>

<script type="text/javascript"> 
window.location="listar_correos.php"; 

</script>



	   

	
