<?php

        
                require_once("xmlseclibsapos/XmlseclibsAdapter.php");
                require_once("DTE/DTE.php");
                require_once("extensions/ObjectAndXML.php");
				
			class Firma_apos{
				
				var $pkPass;
				var $fecha_resol;
				var $numero_resol;
				var $original_ruta;
				var $doc_original;
				var $tipdoc;
				var $numdoc;
				var $docenvio;
				var	$rutEmpresa;
				var $rutRepresenta;
				
				
				public function __construct() {
        
				} 
    
				public function Proce() {
				echo "rut en fee: ".$this->rutRepresenta;
			    $zona = new DateTimeZone('America/Santiago'); 
				$fch = new DateTime('', $zona);
				$fechahoy = $fch->format('Y-m-d\TH:i:s'); 
                
           
				$ORG = new DOMDocument();
                $ORG->preserveWhiteSpace = TRUE;
				$ORG->load($this->original_ruta);
				$original = $ORG->getElementsByTagName('DTE')->item(0)->C14N();

			    
				$ORG_FINAL = new DOMDocument();
                $ORG_FINAL->preserveWhiteSpace = TRUE;
				$ORG_FINAL->encoding = "ISO-8859-1";
				
				$frag = $ORG_FINAL->createDocumentFragment();
                $frag->appendXML($original);
                $ORG_FINAL->appendChild($frag);
				
				$ORG_FINAL->save('../DOC/ORIGINAL/'.$this->doc_original);
			   
                
                /********** OBTENER CAF, LLAVES PRIVADA Y PUBLICA DEL CAF **********/
                              $LCAFImport = new DOMDocument();
                $LCAFImport->formatOutput = FALSE;
                $LCAFImport->preserveWhiteSpace = FALSE;
               
				if ($this->tipdoc == 33)
					{$LCAFImport->load('../FOLIOS/Folios_factura.xml');}
				if ($this->tipdoc == 61)
					{$LCAFImport->load('../FOLIOS/Folios_nc.xml');}
				if ($this->tipdoc == 34)
					{$LCAFImport->load('../FOLIOS/Folios_factura_exenta.xml');}
				if ($this->tipdoc == 46)
					{$LCAFImport->load('../FOLIOS/Folios_factura_compra.xml');}
				if ($this->tipdoc == 52)
					{$LCAFImport->load('../FOLIOS/Folios_guia.xml');}
				if ($this->tipdoc == 56)
					{$LCAFImport->load('../FOLIOS/Folios_nd.xml');}

                $CAF = $LCAFImport->getElementsByTagName("CAF")->item(0);
                $nodecaf = $LCAFImport->getElementsByTagName("CAF")->item(0);
                $priv_key = $LCAFImport->getElementsByTagName("RSASK")->item(0)->nodeValue;
                $publickey = $LCAFImport->getElementsByTagName("RSAPUBK")->item(0)->nodeValue;

                $CAF = $LCAFImport->saveXML($CAF);
                $CAF = str_replace("I", 'Í', $CAF);
                /********** OBTENER CAF, LLAVES PRIVADA Y PUBLICA DEL CAF **********/                
                
                
                $DTE_TIMBRE = new DOMDocument();
                $DTE_TIMBRE->formatOutput = FALSE;
                $DTE_TIMBRE->preserveWhiteSpace = TRUE;
                $DTE_TIMBRE->load('../DOC/ORIGINAL/'.$this->doc_original);
                $DTE_TIMBRE->encoding = "ISO-8859-1";
                
                $import = $DTE_TIMBRE->importNode($nodecaf, true);
                $TSTED = $DTE_TIMBRE->getElementsByTagName("TSTED")->item(0);
				$FETSTED = $DTE_TIMBRE->getElementsByTagName("TSTED")->item(0)->nodeValue;
                $TSTED->parentNode->insertBefore($import, $TSTED);
                            
                $RSR = $DTE_TIMBRE->getElementsByTagName("RSR")->item(0)->nodeValue;
                $RSR = str_replace("&", '&amp;', $RSR);
                $RSR = str_replace("<", '&lt;', $RSR);
                $RSR = str_replace(">", '&gt;', $RSR);
                $ITEM1 = utf8_decode($DTE_TIMBRE->getElementsByTagName("IT1")->item(0)->nodeValue);
                $IT1 = str_replace("&", '&amp;', $ITEM1);
                $IT1 = str_replace("<", '&lt;', $IT1);
                $IT1 = str_replace(">", '&gt;', $IT1);                
                $TD = $DTE_TIMBRE->getElementsByTagName("TD")->item(0)->nodeValue;
                $FOLIO = $DTE_TIMBRE->getElementsByTagName("F")->item(0)->nodeValue;
                $RUTEMIS = $DTE_TIMBRE->getElementsByTagName("RE")->item(0)->nodeValue;
                $FECHA = $DTE_TIMBRE->getElementsByTagName("FE")->item(0)->nodeValue;
                $MONTO = $DTE_TIMBRE->getElementsByTagName("MNT")->item(0)->nodeValue;
                $RUTRECE = $DTE_TIMBRE->getElementsByTagName("RR")->item(0)->nodeValue;
				
				$CAF = str_replace("&apos;","\'",$CAF);
				$CAF = str_replace("\'", "&apos;",$CAF);
					
				
                $DD2 = "<DD><RE>".$RUTEMIS."</RE><TD>" .$TD."</TD><F>" .$FOLIO. "</F><FE>". $FECHA ."</FE><RR>" . $RUTRECE . 
                       "</RR><RSR>" . utf8_decode($RSR) . "</RSR><MNT>" . $MONTO . "</MNT><IT1>" . $IT1 ."</IT1>" . $CAF . "<TSTED>". 
                        $FETSTED ."</TSTED></DD>";
                $FRMT = $this->buildSign($DD2, $priv_key);
                $fragment = $DTE_TIMBRE->createDocumentFragment();
                $fragment->appendXML("<FRMT algoritmo=\"SHA1withRSA\">$FRMT</FRMT>\n");
                $TED = $DTE_TIMBRE->getElementsByTagName("TED")->item(0);
                $TED->appendChild($fragment);
                $key = array();
                $xmlTool = new FR3D\XmlDSig\Adapter\XmlseclibsAdapter(); 
                $pfx = file_get_contents('../firmarDTE/'. $this->rutRepresenta .'.pfx');
                openssl_pkcs12_read($pfx, $key, $this->pkPass);
                $xmlTool->setPrivateKey($key["pkey"]);
                $xmlTool->setpublickey($key["cert"]);
                $xmlTool->addTransform(FR3D\XmlDSig\Adapter\XmlseclibsAdapter::ENVELOPED);
                   
                $xmlTool->sign($DTE_TIMBRE, "DTE");  
                            
                $firmado= str_replace(".xml", "", $this->doc_original);
                $DTE_TIMBRE->save('../DOC/FIRMADO/'.$firmado.'_f.xml');

				
				//****************ciclo genera envios****************************
				
				$ciclo = 0;
				    
				
			while ($ciclo <=1)
			{
					
					
					$doc = new DOMDocument("1.0", "ISO-8859-1");
					$doc->formatOutput = FALSE;
					$doc->preserveWhiteSpace = TRUE;
						
					$fragment = $doc->createDocumentFragment(); 
					
					if ($ciclo == 0)
						{	
						$rut_recep = $RUTRECE;
						}
					else{
						$rut_recep = "60803000-K";
						}
					
					$timezone = new DateTimeZone('America/Santiago'); 
					$date = new DateTime('', $timezone);
					$fechaTimbre = $date->format('Y-m-d\TH:i:s');  
					$subtotalDTE = "";
					$caratulaXML = "<Caratula version=\"1.0\">\n<RutEmisor>".$this->rutEmpresa."</RutEmisor>\n<RutEnvia>".$this->rutRepresenta."</RutEnvia>\n";    
					$caratulaXML .="<RutReceptor>" . $rut_recep . "</RutReceptor>\n<FchResol>".$this->fecha_resol."</FchResol>\n<NroResol>".$this->numero_resol."</NroResol>\n";
					$caratulaXML .="<TmstFirmaEnv>" . $fechaTimbre . "</TmstFirmaEnv>\n";
								
					
					  $subtotalDTE .= "<SubTotDTE>\n<TpoDTE>".$this->tipdoc."</TpoDTE>\n<NroDTE>1</NroDTE>\n</SubTotDTE>\n";
					
					$iddte_doc="SetDoc";
					$caratulaXML .= $subtotalDTE . "</Caratula>\n";
					$EnvioDTE = "<EnvioDTE version=\"1.0\" xmlns=\"http://www.sii.cl/SiiDte\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.sii.cl/SiiDte EnvioDTE_v10.xsd\">\n";
					$EnvioDTE .= "<SetDTE ID=\"" . $iddte_doc . "\">\n" . $caratulaXML . "</SetDTE>\n</EnvioDTE>";
					
					$fragment->appendXML($EnvioDTE);
					
					$doc->appendChild($fragment);
					
					$SetDTE = $doc->getElementsByTagName("SetDTE")->item(0);
				   
						$Documento = new DOMDocument();
						$Documento->formatOutput = FALSE;
						$Documento->preserveWhiteSpace = TRUE;
						$pRutEmpresa   = $this->rutEmpresa;
						
						$IDDTE = "DTE-".$this->tipdoc."-".$this->numdoc;
						
						$Documento->load('../DOC/FIRMADO/'.$firmado.'_f.xml');
						$Documento->encoding = "ISO-8859-1";
						
						$NodoDTE = $Documento->getElementsByTagName("DTE")->item(0);                
						$importar = $doc->importNode($NodoDTE, true);
						$SetDTE->appendChild($importar);             
					   
					
					$DTE = $doc->getElementsByTagName('DTE');
					foreach($DTE as $DT){
						$DT->removeAttributeNS('http://www.w3.org/2000/09/xmldsig#','default');
					}    
					
					$pRutEmpresa   = $this->rutEmpresa;
					$key = array();
					$xmlTool = new FR3D\XmlDSig\Adapter\XmlseclibsAdapter();
					$pfx = file_get_contents('../firmarDTE/'. $this->rutRepresenta .'.pfx');
						openssl_pkcs12_read($pfx, $key, $this->pkPass);           
					$xmlTool->setPrivateKey($key["pkey"]);
					$xmlTool->setpublickey($key["cert"]);
					$xmlTool->addTransform(FR3D\XmlDSig\Adapter\XmlseclibsAdapter::ENVELOPED);
					$xmlTool->sign($doc, "ENVIO");            
					
					if ($ciclo == 0)
					{
						$doc->save('../DOC/ENVIO/'.$firmado.'_f_mail.xml');   
						
						$string = file_get_contents('../DOC/ENVIO/'.$firmado.'_f_mail.xml');
						$string = str_replace("'", "&apos;", $string);
						file_put_contents('../DOC/ENVIO/'.$firmado.'_f_mail.xml', $string);
					}
					else{
						$doc->save('../DOC/ENVIO/'.$firmado.'_mail.xml');   
						
						$string = file_get_contents('../DOC/ENVIO/'.$firmado.'_mail.xml');
						$string = str_replace("'", "&apos;", $string);
						file_put_contents('../DOC/ENVIO/'.$firmado.'_mail.xml', $string);
						}
			
			$ciclo++;
			}
				
				$this->docenvio = '../DOC/ENVIO/'.$firmado.'_mail.xml';
			
			
			}
			
			public function buildSign($toSign, $privkey) {
						$signature = null;
						$priv_key = $privkey;
						$pkeyid = openssl_get_privatekey($priv_key);
						openssl_sign($toSign, $signature, $priv_key, OPENSSL_ALGO_SHA1);
						openssl_free_key($pkeyid);
						$base64 = base64_encode($signature);
						return $base64;
				}
			}
			
?>

