
<?php

include('../conexion.php'); 
				
///////////////////   limpia el directorio del correo //////////////////////////////
$directorio = opendir("./pdf/");  
while ($archivo = readdir($directorio))     
{   $nombreArch = ucwords($archivo);     
$nombreArch = str_replace("..", "Atras", $nombreArch);  

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

closedir($directorio);   
  

//////////// descarga los  nuevos softcomcr_grupo_corporativo_jms /////////////////////////////////

set_time_limit(3000);
//$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); 
		
         $fechainicio=$_GET["fechainicio"];
         $fecini= implode("-", array_reverse(explode("-",  $fechainicio))); 
         $fecini= str_replace("-","/",$fecini);
		 
		 $fechafin=$_GET["fechafin"];
		 $fecfin= implode("-", array_reverse(explode("-",  $fechafin))); 
         $fecfin= str_replace("-","/",$fecfin);


//resto 1 día		 
echo $fecini = date("Y/m/d",strtotime($fecini."- 1 days"));		 
echo "<br>";

	 
//sumo 1 día


echo $fechahoy = date("Y/m/d",strtotime($fecfin."+ 1 days")); 
echo "<br>";


//	$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;

	
	$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;
	
	

	
	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 ] );

    }
	
	function getAttachments($message_id, $parts,$client) {
		
		$mnsPath = expandHomeDirectory(__DIR__ . '/pdf/');
		$attachments = [];
		foreach ($parts as $part) {
			if (!empty($part->body->attachmentId)) {
				$attachment = $client->users_messages_attachments->get('me', $message_id, $part->body->attachmentId);
				$attachments[] = [
					'filename' => $part->filename,
					'mimeType' => $part->mimeType,
					'data'     => strtr($attachment->data, '-_', '+/')
				];
				
				$decode = base64_decode(str_replace(array('-', '_'), array('+', '/'), $attachment->data));
				$res = file_put_contents($mnsPath.$part->filename,$decode);
										
			} else if (!empty($part->parts)) {
				$attachments = array_merge($attachments, getAttachments($message_id, $part->parts,$client));
			}
		}
		return $attachments;
	}
	
	function pArray($array){
		echo '<pre>';
		var_dump($array);
		echo '</pre>';
	}

    // Get the API client and construct the service object.
   
    $messages = $service->users_messages->listUsersMessages($userId, $opt_param);
	$files = [];
    foreach ($messages as $message_thread) {
            $message = $service->users_messages->get($userId, $message_thread['id']);			
            $message_parts = $message->getPayload()->getParts();
			
			$attachments = getAttachments($message_thread['id'],$message_parts,$service);
			
			$files = array_merge($files,$attachments);

			$messageDetails = $message->getPayload();
			
			foreach ($messageDetails['parts'] as $key => $value) {
				if (!isset($value['body']['data'])) {
				  array_push($files, $value['partId']);
			  }
			}
	}      
	
       if(isset($_GET['messageId']) && $_GET['part_id']) {
			$attachment = getAttachment($_GET['messageId'], $_GET['part_id'], $userId);
			$content_type = "";
			foreach ($attachment['data']['headers'] as $key => $value) 
				if($value->name == 'Content-Type') $content_type = $value->value; 
					header($value->name.':'.$value->value);
			
			$content_type_val = current(explode("/",$content_type));
			$media_types = ["video", "image", "application","text/xml","application/xml"];
			if(in_array($content_type_val, $media_types ))
				echo base64_to_jpeg($attachment['data']['data'], $content_type); // Only for Image files
			 else 
			  echo base64_decode($attachment['data']['data']); // Other than Image Files
		}
		
	 
	 
	 
	} 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("./pdf/" . $email_number . "-" . $filename, "w+");
					
		
				
				
                fwrite($fp, $attachment['attachment']);
                fclose($fp);
            }

        }

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

    
}
}



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


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



}  else {

unlink("./softcomcr_grupo_corporativo_jms/".$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 == "pdf"){  // para guardar solo los xml
			
				$fp=fopen("./pdf/".$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 
  


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


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



}  else {

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



?>

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

</script>


