Esempio n. 1
0
 public function GenerarXML()
 {
     $ruta_real = dirname(__FILE__);
     $PlantillaCFDI = $ruta_real . '\\CFDI_Factura.xml';
     $PlantillaCFDIXML = fopen($PlantillaCFDI, "r");
     $PlantillaXML = fread($PlantillaCFDIXML, filesize($PlantillaCFDI));
     fclose($PlantillaCFDIXML);
     $XMLCFDI = new DomDocument();
     $XMLCFDI->loadXML($PlantillaXML) or die("XML invalido");
     $c = $XMLCFDI->getElementsByTagName('Comprobante')->item(0);
     $c->setAttribute('fecha', $this->fecha);
     if ($this->folio != '') {
         $c->setAttribute('folio', $this->folio);
     }
     if ($this->serie != '') {
         $c->setAttribute('serie', $this->serie);
     }
     if ($this->formadepago != '') {
         $c->setAttribute('formaDePago', $this->formadepago);
     } else {
         throw new Exception('Es obligatorio capturar el nodo "Forma de Pago"');
     }
     if ($this->metododepago != '') {
         $c->setAttribute('metodoDePago', $this->metododepago);
     } else {
         throw new Exception('Es obligatorio capturar el nodo "Forma de Pago"');
     }
     if ($this->lugardeexpedicion != '') {
         $c->setAttribute('LugarExpedicion', $this->lugardeexpedicion);
     } else {
         throw new Exception('Es obligatorio capturar el nodo "Lugar de expedición"');
     }
     if ($this->cuentadepago != '') {
         $c->setAttribute('NumCtaPago', $this->cuentadepago);
     } else {
         $c->setAttribute('NumCtaPago', 'NO IDENTIFICADO');
     }
     if ($this->tipocomprobante != '') {
         if (in_array($this->tipocomprobante, array("ingreso", "egreso", "traslado"))) {
             $c->setAttribute('tipoDeComprobante', $this->tipocomprobante);
         } else {
             throw new Exception('El tipo de comprobante solo puede ser de cualquiera de estos tres tipos: "ingreso", "egreso", "traslado"');
         }
     } else {
         throw new Exception('Es obligatorio elegir el tipo de comprobante: ingreso, egreso, traslado');
     }
     if ($this->moneda != "") {
         $c->setAttribute('moneda', $this->moneda);
     }
     if ($this->descuento > 0) {
         $c->setAttribute('descuento', Importe($this->descuento));
     }
     if ($this->motivodescuento != "") {
         $c->setAttribute('motivoDescuento', $this->motivodescuento);
     }
     $NodoEmisor = $XMLCFDI->getElementsByTagName('Emisor')->item(0);
     $NodoEmisor->setAttribute("rfc", $this->emisor->rfc);
     $NodoEmisor->setAttribute("nombre", $this->emisor->razonsocial);
     if ($this->emisor->domicilio->calle != '' and $this->emisor->domicilio->colonia != '') {
         $NodoDomicilio_Emisor = $XMLCFDI->createElement('cfdi:DomicilioFiscal');
         if ($this->emisor->domicilio->calle != '') {
             $NodoDomicilio_Emisor->setAttribute('calle', $this->emisor->domicilio->calle);
         }
         if ($this->emisor->domicilio->numeroexterior != '') {
             $NodoDomicilio_Emisor->setAttribute('noExterior', $this->emisor->domicilio->numeroexterior);
         }
         if ($this->emisor->domicilio->numerointerior != '') {
             $NodoDomicilio_Emisor->setAttribute('noInterior', $this->emisor->domicilio->numerointerior);
         }
         if ($this->emisor->domicilio->colonia != '') {
             $NodoDomicilio_Emisor->setAttribute('colonia', $this->emisor->domicilio->colonia);
         }
         if ($this->emisor->domicilio->localidad != '') {
             $NodoDomicilio_Emisor->setAttribute('localidad', $this->emisor->domicilio->localidad);
         }
         if ($this->emisor->domicilio->municipio != '') {
             $NodoDomicilio_Emisor->setAttribute('municipio', $this->emisor->domicilio->municipio);
         }
         if ($this->emisor->domicilio->codigopostal != '') {
             $NodoDomicilio_Emisor->setAttribute('codigoPostal', $this->emisor->domicilio->codigopostal);
         }
         if ($this->emisor->domicilio->estado != '') {
             $NodoDomicilio_Emisor->setAttribute('estado', $this->emisor->domicilio->estado);
         }
         if ($this->emisor->domicilio->pais != '') {
             $NodoDomicilio_Emisor->setAttribute('pais', $this->emisor->domicilio->pais);
         }
         $NodoEmisor->appendChild($NodoDomicilio_Emisor);
     }
     if ($this->emisor->regimenfiscal != '') {
         $NodoRegimenFiscal_Emisor = $XMLCFDI->createElement('cfdi:RegimenFiscal');
         $NodoRegimenFiscal_Emisor->setAttribute('Regimen', $this->emisor->regimenfiscal);
         $NodoEmisor->appendChild($NodoRegimenFiscal_Emisor);
     } else {
         die('Debe existir un regimen fiscal para el emisor de la factura');
     }
     $NodoReceptor = $XMLCFDI->getElementsByTagName('Receptor')->item(0);
     $NodoReceptor->setAttribute("rfc", $this->receptor->rfc);
     $NodoReceptor->setAttribute("nombre", $this->receptor->razonsocial);
     if ($this->receptor->domicilio->calle != '' and $this->receptor->domicilio->colonia != '') {
         $NodoDomicilio_Receptor = $XMLCFDI->createElement('cfdi:Domicilio');
         if ($this->receptor->domicilio->calle != '') {
             $NodoDomicilio_Receptor->setAttribute('calle', $this->receptor->domicilio->calle);
         }
         if ($this->receptor->domicilio->numeroexterior != '') {
             $NodoDomicilio_Receptor->setAttribute('noExterior', $this->receptor->domicilio->numeroexterior);
         }
         if ($this->receptor->domicilio->numerointerior != '') {
             $NodoDomicilio_Receptor->setAttribute('noInterior', $this->receptor->domicilio->numerointerior);
         }
         if ($this->receptor->domicilio->colonia != '') {
             $NodoDomicilio_Receptor->setAttribute('colonia', $this->receptor->domicilio->colonia);
         }
         if ($this->receptor->domicilio->localidad != '') {
             $NodoDomicilio_Receptor->setAttribute('localidad', $this->receptor->domicilio->localidad);
         }
         if ($this->receptor->domicilio->municipio != '') {
             $NodoDomicilio_Receptor->setAttribute('municipio', $this->receptor->domicilio->municipio);
         }
         if ($this->receptor->domicilio->codigopostal != '') {
             $NodoDomicilio_Receptor->setAttribute('codigoPostal', $this->receptor->domicilio->codigopostal);
         }
         if ($this->receptor->domicilio->estado != '') {
             $NodoDomicilio_Receptor->setAttribute('estado', $this->receptor->domicilio->estado);
         }
         if ($this->receptor->domicilio->pais != '') {
             $NodoDomicilio_Receptor->setAttribute('pais', $this->receptor->domicilio->pais);
         }
         $NodoReceptor->appendChild($NodoDomicilio_Receptor);
     }
     $this->subtotal = 0;
     if (count($this->conceptos) > 0) {
         $NodoConceptos = $XMLCFDI->getElementsByTagName('Conceptos')->item(0);
         foreach ($this->conceptos as $conceptos) {
             $NodoConcepto = $XMLCFDI->createElement('cfdi:Concepto');
             if ($conceptos->cantidad > 0) {
                 $NodoConcepto->setAttribute("cantidad", $conceptos->cantidad);
             } else {
                 die('El nodo concepto debe tener una cantidad especificada');
             }
             if ($conceptos->unidad != "") {
                 $NodoConcepto->setAttribute("unidad", $conceptos->unidad);
             } else {
                 die('El nodo concepto debe tener una unidad especificada');
             }
             if ($conceptos->descripcion != "") {
                 $NodoConcepto->setAttribute("descripcion", $conceptos->descripcion);
             } else {
                 die('El nodo concepto debe tener una descripción asignada');
             }
             if ($conceptos->valorunitario > 0) {
                 $NodoConcepto->setAttribute("valorUnitario", Importe($conceptos->valorunitario));
             } else {
                 die('El nodo valor unitario debe tener asignado un importe');
             }
             $NodoConcepto->setAttribute("importe", Importe($conceptos->cantidad * $conceptos->valorunitario));
             $NodoConceptos->appendChild($NodoConcepto);
             $this->subtotal = $this->subtotal + $conceptos->cantidad * $conceptos->valorunitario;
         }
     }
     if (count($this->impuestos) > 0) {
         $TotalImpuestosRetenidos = 0;
         $TotalImpuestosTrasladados = 0;
         $NodoImpuestos = $XMLCFDI->getElementsByTagName('Impuestos')->item(0);
         foreach ($this->impuestos as $impuesto) {
             if ($impuesto->tipo == _tiRetenido) {
                 if ($XMLCFDI->getElementsByTagName('cfdi:Retenciones')->length > 0) {
                     $NodoImpuestosRetenidos = $XMLCFDI->getElementsByTagName('cfdi:Retenciones')->item(0);
                 } else {
                     $NodoImpuestosRetenidos = $XMLCFDI->createElement('cfdi:Retenciones');
                     $NodoImpuestos->appendChild($NodoImpuestosRetenidos);
                 }
                 $NodoImpuestoRetenido = $XMLCFDI->createElement('cfdi:Retencion');
                 if ($impuesto->impuesto != "") {
                     $NodoImpuestoRetenido->setAttribute('impuesto', $impuesto->impuesto);
                 } else {
                     die('El nodo impuesto retenido debe tener un valor en el atributo "impuesto"');
                 }
                 // if($impuesto->tasa <> "")	{
                 // 	$NodoImpuestoRetenido->setAttribute('tasa', Importe($impuesto->tasa));
                 // }
                 $NodoImpuestoRetenido->setAttribute('importe', Importe($impuesto->importe));
                 $NodoImpuestosRetenidos->appendChild($NodoImpuestoRetenido);
                 $TotalImpuestosRetenidos = $TotalImpuestosRetenidos + $impuesto->importe;
             }
             if ($TotalImpuestosRetenidos > 0) {
                 $NodoImpuestos->setAttribute('totalImpuestosRetenidos', Importe($TotalImpuestosRetenidos));
             }
         }
         foreach ($this->impuestos as $impuesto) {
             if ($impuesto->tipo == _tiTrasladado) {
                 if ($XMLCFDI->getElementsByTagName('cfdi:Traslados')->length > 0) {
                     $NodoImpuestosTrasladados = $XMLCFDI->getElementsByTagName('cfdi:Traslados')->item(0);
                 } else {
                     $NodoImpuestosTrasladados = $XMLCFDI->createElement('cfdi:Traslados');
                     $NodoImpuestos->appendChild($NodoImpuestosTrasladados);
                 }
                 $NodoImpuestoTrasladado = $XMLCFDI->createElement('cfdi:Traslado');
                 if ($impuesto->impuesto != "") {
                     $NodoImpuestoTrasladado->setAttribute('impuesto', $impuesto->impuesto);
                 } else {
                     die('El nodo impuesto trasladado debe tener un valor en el atributo "impuesto"');
                 }
                 if ($impuesto->tasa != "") {
                     $NodoImpuestoTrasladado->setAttribute('tasa', Importe($impuesto->tasa));
                 }
                 $NodoImpuestoTrasladado->setAttribute('importe', Importe($impuesto->importe));
                 $NodoImpuestosTrasladados->appendChild($NodoImpuestoTrasladado);
                 $TotalImpuestosTrasladados = $TotalImpuestosTrasladados + $impuesto->importe;
             }
             if ($TotalImpuestosTrasladados > 0) {
                 $NodoImpuestos->setAttribute('totalImpuestosTrasladados', Importe($TotalImpuestosTrasladados));
             }
         }
     }
     if ($this->subtotal > 0) {
         $c->setAttribute('subTotal', Importe($this->subtotal));
     }
     // $descuentosporimpuestos = ($TotalImpuestosRetenidos + $TotalImpuestosTrasladados);
     // $descuentosporimpuestos = $TotalImpuestosRetenidos;
     $atributo_total = $this->subtotal - $TotalImpuestosRetenidos + $TotalImpuestosTrasladados - $this->descuento;
     $c->setAttribute('total', $atributo_total);
     $this->FacturaXML = $XMLCFDI->saveXML();
     $XMLCFDI->normalizeDocument();
     $XMLCFDI->formatOutput = true;
     if ($this->XMLSellado) {
         // $this->SellarXML_($XMLCFDI);
         $this->SellarXML_($this->FacturaXML);
         $c = $XMLCFDI->getElementsByTagNameNS('http://www.sat.gob.mx/cfd/3', 'Comprobante')->item(0);
         if ($this->sello == '') {
             throw new Exception('Ocurrió un error al intentar colocar el sello, no se registró ninguno');
         }
         if ($this->certificado == '') {
             throw new Exception('Ocurrió un error al intentar colocar el certificado, no se registró ninguno');
         }
         if ($this->numcertificado == '') {
             throw new Exception('Ocurrió un error al intentar colocar el número de certificado, no se registró ninguno');
         }
         $c->setAttribute('sello', $this->sello);
         $c->setAttribute('certificado', $this->certificado);
         $c->setAttribute('noCertificado', $this->numcertificado);
     }
     $this->XMLNominaCFDI = $XMLCFDI->saveXML();
     return $this->XMLNominaCFDI;
 }
Esempio n. 2
0
 public static function html($var, $array = null, $default = '')
 {
     $var = (string) self::getVal($var, $array, $default);
     //$var = Filter::utf8($var);
     if (!preg_match('/\\S/', $var)) {
         return $default;
     }
     // corrige les </li>&#13;
     $var = preg_replace('#>[\\r\\n]+#m', '>', $var);
     //ignore error
     libxml_use_internal_errors(true);
     $dom = new \DomDocument('1.0', 'UTF-8');
     $dom->recover = true;
     // this is the trick
     $var = '<div>' . $var . '</div>';
     try {
         // hack to preserve UTF-8 characters
         //http://stackoverflow.com/questions/3548880/php-dom-utf-8-problem
         $dom->loadHTML('<?xml encoding="UTF-8">' . $var);
         // hack fix utf-8
         $dom->encoding = 'UTF-8';
     } catch (\Exception $e) {
     }
     if (!function_exists('filterHtmlCleanChild')) {
         function filterHtmlCleanChild(DOMElement $p, $removeTag, $removeAttr)
         {
             if ($p->hasChildNodes()) {
                 foreach ($p->childNodes as $c) {
                     // on delete ce fils
                     if (in_array($c->nodeName, $removeTag)) {
                         $p->removeChild($c);
                     } elseif ($c->nodeType == XML_ELEMENT_NODE) {
                         filterHtmlCleanChild($c, $removeTag, $removeAttr);
                     }
                 }
             }
             foreach ($removeAttr as $ra) {
                 $p->removeAttribute($ra);
                 /** 		 	test
                          if ( $ra == 'onkeydown' ) {
                          if ( $va = $p->getAttribute('onkeydown') ) {
                          $p->removeAttribute($ra);
                          $rgx = '#*media\{id:([0-9]*)\}*#';
                          preg_match($rgx, $va, $m);
                          $r = array();
                          if ( isset($m[1]) ) { $p->setAttribute($ra,"media{id:".$m[1]."}"); }
                          }
                         */
             }
             return $p;
         }
     }
     $removeAttr = array('onclick', 'ondblclick', 'onkeydown', 'onkeypress', 'onkeyup', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onunload');
     $removeTag = array('script');
     foreach ($dom->childNodes as $p) {
         if ($p->nodeType == XML_PI_NODE) {
             $dom->removeChild($p);
         } elseif ($p->hasChildNodes()) {
             filterHtmlCleanChild($p, $removeTag, $removeAttr);
         }
     }
     $dom->normalizeDocument();
     $r = $dom->saveXML($dom->childNodes->item(1)->childNodes->item(0)->childNodes->item(0), LIBXML_NOEMPTYTAG);
     $r = preg_replace('#^<div>#', '', $r);
     $var = preg_replace('#</div>$#', '', $r);
     // fix certain navigateur compte 2 <br> pour <br></br>, et n'accepte pas les <iframe />
     $var = preg_replace('#<br></br>#', '<br />', $var);
     return self::setVal($var, $default);
 }
 /**
  * Génère le XML d'une fonction pour le jeu de test.
  * Elle diffère de la fonction generateXMLForPHP dans la mesure où 
  * generateXMLFromTestSet n'utilise que des tableaux pour la fonction.
  * 
  * @param type $ei_fonction
  * @param EiProfil $profile
  * @return type
  */
 public function generateXMLFromTestSet($ei_fonction, EiProfil $profile)
 {
     $prefix = MyFunction::getPrefixPath();
     // On définit le document.
     $dom = new DomDocument("1.0", "utf-8");
     $dom->formatOutput = true;
     //Génération de l'url du xsl associé à la fonction
     $user = $dom->createElement('user');
     //$user->setAttribute("xsl", $urlxsl);
     $dom->appendChild($user);
     $nom_balise_fonction = $dom->createElement('fonction-' . $ei_fonction['function_id'] . '_' . $ei_fonction['function_ref']);
     $nom_balise_fonction->setAttribute("name", $ei_fonction['name']);
     $user->appendChild($nom_balise_fonction);
     //paramètre de la fonction
     foreach ($ei_fonction['params'] as $p => $param) {
         $nom_balise_param = $dom->createElement($param['name']);
         $param_value = $dom->createTextNode($param['valeur']);
         $nom_balise_param->appendChild($param_value);
         $nom_balise_fonction->appendChild($nom_balise_param);
     }
     //paramètres de profil
     foreach ($profile->getParams() as $param) {
         $nom_balise_param = $dom->createElement($param->getStringName());
         $param_value = $dom->createTextNode($param->getValue());
         $nom_balise_param->appendChild($param_value);
         $nom_balise_fonction->appendChild($nom_balise_param);
     }
     $dom->normalizeDocument();
     // renvoie du fichier XML sous forme de chaine de caractères.
     return $dom->saveXML();
 }
 /**
  * Appends data into the XML tree of a Data Source
  * @param $wrapper
  * @param $data
  */
 public function appendFormattedElement(&$wrapper, $data)
 {
     if (!is_array($data) || empty($data) || empty($data['url'])) {
         return;
     }
     // If cache has expired refresh the data array from parsing the API XML
     /*if ((time() - $data['last_updated']) > ($this->_fields['refresh'] * 60)) {
     			$data = VimeoHelper::updateClipInfo($data['clip_id'], $this->_fields['id'], $wrapper->getAttribute('id'), $this->Database);
     		}*/
     // store a pointer to the driver
     // @todo: use the `driver` column
     $driver = ServiceDispatcher::getServiceDriver($data['url']);
     if ($driver == null) {
         throw new Exception('Unable to find driver for url: `' . $data['url'] . '`');
     }
     $apiFormat = $driver->getAPIFormat();
     $parser = ServiceParser::getServiceParser($apiFormat);
     if ($parser == null) {
         throw new Exception('Unable to find parser for format: `' . $apiFormat . '`');
     }
     // root for all values
     $field = new XMLElement($this->get('element_name'));
     $field->setAttributeArray(array('id' => $data['res_id']));
     $title = new XMLElement('title', General::sanitize($data['title']));
     $title->setAttribute('handle', Lang::createHandle($data['title']));
     $field->appendChild($title);
     $field->appendChild(new XMLElement('url', General::sanitize($data['url'])));
     $field->appendChild(new XMLElement('thumbnail', General::sanitize($data['thumbnail_url'])));
     $field->appendChild(new XMLElement('driver', General::sanitize($data['driver'])));
     $protocols = new XMLElement('protocols');
     if ($driver->supportsSSL()) {
         $protocols->appendChild(new XMLElement('item', 'https'));
     }
     $protocols->appendChild(new XMLElement('item', 'http'));
     $field->appendChild($protocols);
     // oembed data
     $xml = new DomDocument('1.0', 'utf-8');
     $errorFlag = false;
     // use our parser in order to get the xml string
     $xml_data = $parser->createXML($data['oembed_xml'], $driver, $data['url'], $errorFlag);
     // if we can successfully load the XML data into the
     // DOM object while ignoring errors (@)
     if (!$errorFlag && @$xml->loadXML($xml_data)) {
         $xml->preserveWhiteSpace = true;
         $xml->formatOutput = true;
         $xml->normalizeDocument();
         $root_name = $driver->getRootTagName();
         // get the root node
         $xml_root = $xml->getElementsByTagName($root_name)->item(0);
         // if we've found a root node
         if (!empty($xml_root)) {
             // save it as a string
             $xml = $xml->saveXML($xml_root);
             // replace the 'root' element with 'oembed'
             if ($root_name != 'oembed') {
                 $xml = preg_replace('/^<' . $root_name . '>/', '<oembed>', $xml);
                 $xml = preg_replace('/<\\/' . $root_name . '>/', '</oembed>', $xml);
             }
             // set it as the 'value' of the field
             // BEWARE: it will be just a string, since the
             // value we set is xml. It's just a hack to pass
             // the value from the DOMDocument object to the XMLElement
             $field->setValue($xml, false);
         } else {
             $errorFlag = true;
         }
     } else {
         $errorFlag = true;
     }
     if ($errorFlag) {
         // loading the xml string into the DOMDocument did not work
         // so we will add a errors message into the result
         $error = new XMLElement('error');
         $error->setValue(__('Error while loading the xml into the document'));
         $field->appendChild($error);
     }
     $wrapper->appendChild($field);
 }