repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
LibreDTE/libredte-lib | lib/Sii/Dte/PDF/Dte.php | Dte.agregarTimbre | protected function agregarTimbre($timbre, $x_timbre = 10, $x = 10, $y = 190, $w = 70, $font_size = 8)
{
$y = (!$this->papelContinuo and !$this->timbre_pie) ? $this->x_fin_datos : $y;
if ($timbre!==null) {
$style = [
'border' => false,
'padding' => 0,
'hpadding' => 0,
'vpadding' => 0,
'module_width' => 1, // width of a single module in points
'module_height' => 1, // height of a single module in points
'fgcolor' => [0,0,0],
'bgcolor' => false, // [255,255,255]
'position' => $this->papelContinuo ? 'C' : 'S',
];
$ecl = version_compare(phpversion(), '7.0.0', '<') ? -1 : $this->ecl;
$this->write2DBarcode($timbre, 'PDF417,,'.$ecl, $x_timbre, $y, $w, 0, $style, 'B');
$this->setFont('', 'B', $font_size);
$this->Texto('Timbre Electrónico SII', $x, null, 'C', $w);
$this->Ln();
$this->Texto('Resolución '.$this->resolucion['NroResol'].' de '.explode('-', $this->resolucion['FchResol'])[0], $x, null, 'C', $w);
$this->Ln();
if ($w>=60) {
$this->Texto('Verifique documento: '.$this->web_verificacion, $x, null, 'C', $w);
} else {
$this->Texto('Verifique documento:', $x, null, 'C', $w);
$this->Ln();
$this->Texto($this->web_verificacion, $x, null, 'C', $w);
}
}
} | php | protected function agregarTimbre($timbre, $x_timbre = 10, $x = 10, $y = 190, $w = 70, $font_size = 8)
{
$y = (!$this->papelContinuo and !$this->timbre_pie) ? $this->x_fin_datos : $y;
if ($timbre!==null) {
$style = [
'border' => false,
'padding' => 0,
'hpadding' => 0,
'vpadding' => 0,
'module_width' => 1, // width of a single module in points
'module_height' => 1, // height of a single module in points
'fgcolor' => [0,0,0],
'bgcolor' => false, // [255,255,255]
'position' => $this->papelContinuo ? 'C' : 'S',
];
$ecl = version_compare(phpversion(), '7.0.0', '<') ? -1 : $this->ecl;
$this->write2DBarcode($timbre, 'PDF417,,'.$ecl, $x_timbre, $y, $w, 0, $style, 'B');
$this->setFont('', 'B', $font_size);
$this->Texto('Timbre Electrónico SII', $x, null, 'C', $w);
$this->Ln();
$this->Texto('Resolución '.$this->resolucion['NroResol'].' de '.explode('-', $this->resolucion['FchResol'])[0], $x, null, 'C', $w);
$this->Ln();
if ($w>=60) {
$this->Texto('Verifique documento: '.$this->web_verificacion, $x, null, 'C', $w);
} else {
$this->Texto('Verifique documento:', $x, null, 'C', $w);
$this->Ln();
$this->Texto($this->web_verificacion, $x, null, 'C', $w);
}
}
} | [
"protected",
"function",
"agregarTimbre",
"(",
"$",
"timbre",
",",
"$",
"x_timbre",
"=",
"10",
",",
"$",
"x",
"=",
"10",
",",
"$",
"y",
"=",
"190",
",",
"$",
"w",
"=",
"70",
",",
"$",
"font_size",
"=",
"8",
")",
"{",
"$",
"y",
"=",
"(",
"!",
... | Método que agrega el timbre de la factura
- Se imprime en el tamaño mínimo: 2x5 cms
- En el lado de abajo con margen izquierdo mínimo de 2 cms
@param timbre String con los datos del timbre
@param x Posición horizontal de inicio en el PDF
@param y Posición vertical de inicio en el PDF
@param w Ancho del timbre
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2018-04-12 | [
"Método",
"que",
"agrega",
"el",
"timbre",
"de",
"la",
"factura",
"-",
"Se",
"imprime",
"en",
"el",
"tamaño",
"mínimo",
":",
"2x5",
"cms",
"-",
"En",
"el",
"lado",
"de",
"abajo",
"con",
"margen",
"izquierdo",
"mínimo",
"de",
"2",
"cms"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte/PDF/Dte.php#L1116-L1146 |
LibreDTE/libredte-lib | lib/Sii/Dte/PDF/Dte.php | Dte.agregarAcuseRecibo | protected function agregarAcuseRecibo($x = 83, $y = 190, $w = 60, $h = 40)
{
$y = (!$this->papelContinuo and !$this->timbre_pie) ? $this->x_fin_datos : $y;
$this->SetTextColorArray([0,0,0]);
$this->Rect($x, $y, $w, $h, 'D', ['all' => ['width' => 0.1, 'color' => [0, 0, 0]]]);
$this->setFont('', 'B', 10);
$this->Texto('Acuse de recibo', $x, $y+1, 'C', $w);
$this->setFont('', 'B', 8);
$this->Texto('Nombre', $x+2, $this->y+8);
$this->Texto('_________________________', $x+18);
$this->Texto('RUN', $x+2, $this->y+6);
$this->Texto('_________________________', $x+18);
$this->Texto('Fecha', $x+2, $this->y+6);
$this->Texto('_________________________', $x+18);
$this->Texto('Recinto', $x+2, $this->y+6);
$this->Texto('_________________________', $x+18);
$this->Texto('Firma', $x+2, $this->y+8);
$this->Texto('_________________________', $x+18);
$this->setFont('', 'B', 7);
$this->MultiTexto('El acuse de recibo que se declara en este acto, de acuerdo a lo dispuesto en la letra b) del Art. 4°, y la letra c) del Art. 5° de la Ley 19.983, acredita que la entrega de mercaderías o servicio (s) prestado (s) ha (n) sido recibido (s).'."\n", $x, $this->y+6, 'J', $w);
} | php | protected function agregarAcuseRecibo($x = 83, $y = 190, $w = 60, $h = 40)
{
$y = (!$this->papelContinuo and !$this->timbre_pie) ? $this->x_fin_datos : $y;
$this->SetTextColorArray([0,0,0]);
$this->Rect($x, $y, $w, $h, 'D', ['all' => ['width' => 0.1, 'color' => [0, 0, 0]]]);
$this->setFont('', 'B', 10);
$this->Texto('Acuse de recibo', $x, $y+1, 'C', $w);
$this->setFont('', 'B', 8);
$this->Texto('Nombre', $x+2, $this->y+8);
$this->Texto('_________________________', $x+18);
$this->Texto('RUN', $x+2, $this->y+6);
$this->Texto('_________________________', $x+18);
$this->Texto('Fecha', $x+2, $this->y+6);
$this->Texto('_________________________', $x+18);
$this->Texto('Recinto', $x+2, $this->y+6);
$this->Texto('_________________________', $x+18);
$this->Texto('Firma', $x+2, $this->y+8);
$this->Texto('_________________________', $x+18);
$this->setFont('', 'B', 7);
$this->MultiTexto('El acuse de recibo que se declara en este acto, de acuerdo a lo dispuesto en la letra b) del Art. 4°, y la letra c) del Art. 5° de la Ley 19.983, acredita que la entrega de mercaderías o servicio (s) prestado (s) ha (n) sido recibido (s).'."\n", $x, $this->y+6, 'J', $w);
} | [
"protected",
"function",
"agregarAcuseRecibo",
"(",
"$",
"x",
"=",
"83",
",",
"$",
"y",
"=",
"190",
",",
"$",
"w",
"=",
"60",
",",
"$",
"h",
"=",
"40",
")",
"{",
"$",
"y",
"=",
"(",
"!",
"$",
"this",
"->",
"papelContinuo",
"and",
"!",
"$",
"t... | Método que agrega el acuse de rebido
@param x Posición horizontal de inicio en el PDF
@param y Posición vertical de inicio en el PDF
@param w Ancho del acuse de recibo
@param h Alto del acuse de recibo
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2018-04-13 | [
"Método",
"que",
"agrega",
"el",
"acuse",
"de",
"rebido"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte/PDF/Dte.php#L1157-L1177 |
LibreDTE/libredte-lib | lib/Sii/Dte/PDF/Dte.php | Dte.agregarAcuseReciboContinuo | protected function agregarAcuseReciboContinuo($x = 3, $y = null, $w = 68, $h = 40)
{
$this->SetTextColorArray([0,0,0]);
$this->Rect($x, $y, $w, $h, 'D', ['all' => ['width' => 0.1, 'color' => [0, 0, 0]]]);
$style = array('width' => 0.2,'color' => array(0, 0, 0));
$this->Line($x, $y+22, $w+3, $y+22, $style);
//$this->setFont('', 'B', 10);
//$this->Texto('Acuse de recibo', $x, $y+1, 'C', $w);
$this->setFont('', 'B', 6);
$this->Texto('Nombre', $x+2, $this->y+8);
$this->Texto('_____________________________________________', $x+12);
$this->Texto('RUN', $x+2, $this->y+6);
$this->Texto('________________', $x+12);
$this->Texto('Firma', $x+32, $this->y+0.5);
$this->Texto('___________________', $x+42.5);
$this->Texto('Fecha', $x+2, $this->y+6);
$this->Texto('________________', $x+12);
$this->Texto('Recinto', $x+32, $this->y+0.5);
$this->Texto('___________________', $x+42.5);
$this->setFont('', 'B', 5);
$this->MultiTexto('El acuse de recibo que se declara en este acto, de acuerdo a lo dispuesto en la letra b) del Art. 4°, y la letra c) del Art. 5° de la Ley 19.983, acredita que la entrega de mercaderías o servicio (s) prestado (s) ha (n) sido recibido (s).'."\n", $x+2, $this->y+8, 'J', $w-3);
} | php | protected function agregarAcuseReciboContinuo($x = 3, $y = null, $w = 68, $h = 40)
{
$this->SetTextColorArray([0,0,0]);
$this->Rect($x, $y, $w, $h, 'D', ['all' => ['width' => 0.1, 'color' => [0, 0, 0]]]);
$style = array('width' => 0.2,'color' => array(0, 0, 0));
$this->Line($x, $y+22, $w+3, $y+22, $style);
//$this->setFont('', 'B', 10);
//$this->Texto('Acuse de recibo', $x, $y+1, 'C', $w);
$this->setFont('', 'B', 6);
$this->Texto('Nombre', $x+2, $this->y+8);
$this->Texto('_____________________________________________', $x+12);
$this->Texto('RUN', $x+2, $this->y+6);
$this->Texto('________________', $x+12);
$this->Texto('Firma', $x+32, $this->y+0.5);
$this->Texto('___________________', $x+42.5);
$this->Texto('Fecha', $x+2, $this->y+6);
$this->Texto('________________', $x+12);
$this->Texto('Recinto', $x+32, $this->y+0.5);
$this->Texto('___________________', $x+42.5);
$this->setFont('', 'B', 5);
$this->MultiTexto('El acuse de recibo que se declara en este acto, de acuerdo a lo dispuesto en la letra b) del Art. 4°, y la letra c) del Art. 5° de la Ley 19.983, acredita que la entrega de mercaderías o servicio (s) prestado (s) ha (n) sido recibido (s).'."\n", $x+2, $this->y+8, 'J', $w-3);
} | [
"protected",
"function",
"agregarAcuseReciboContinuo",
"(",
"$",
"x",
"=",
"3",
",",
"$",
"y",
"=",
"null",
",",
"$",
"w",
"=",
"68",
",",
"$",
"h",
"=",
"40",
")",
"{",
"$",
"this",
"->",
"SetTextColorArray",
"(",
"[",
"0",
",",
"0",
",",
"0",
... | Método que agrega el acuse de rebido
@param x Posición horizontal de inicio en el PDF
@param y Posición vertical de inicio en el PDF
@param w Ancho del acuse de recibo
@param h Alto del acuse de recibo
@author Pablo Reyes (https://github.com/pabloxp)
@version 2015-11-17 | [
"Método",
"que",
"agrega",
"el",
"acuse",
"de",
"rebido"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte/PDF/Dte.php#L1188-L1210 |
LibreDTE/libredte-lib | lib/Sii/Dte/PDF/Dte.php | Dte.agregarLeyendaDestino | protected function agregarLeyendaDestino($tipo, $y = 190, $font_size = 10)
{
$y = (!$this->papelContinuo and !$this->timbre_pie and $this->x_fin_datos<=$y) ? $this->x_fin_datos : $y;
$y += 48;
$this->setFont('', 'B', $font_size);
$this->Texto('CEDIBLE'.($tipo==52?' CON SU FACTURA':''), null, $y, 'R');
} | php | protected function agregarLeyendaDestino($tipo, $y = 190, $font_size = 10)
{
$y = (!$this->papelContinuo and !$this->timbre_pie and $this->x_fin_datos<=$y) ? $this->x_fin_datos : $y;
$y += 48;
$this->setFont('', 'B', $font_size);
$this->Texto('CEDIBLE'.($tipo==52?' CON SU FACTURA':''), null, $y, 'R');
} | [
"protected",
"function",
"agregarLeyendaDestino",
"(",
"$",
"tipo",
",",
"$",
"y",
"=",
"190",
",",
"$",
"font_size",
"=",
"10",
")",
"{",
"$",
"y",
"=",
"(",
"!",
"$",
"this",
"->",
"papelContinuo",
"and",
"!",
"$",
"this",
"->",
"timbre_pie",
"and"... | Método que agrega la leyenda de destino
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2018-09-10 | [
"Método",
"que",
"agrega",
"la",
"leyenda",
"de",
"destino"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte/PDF/Dte.php#L1217-L1223 |
LibreDTE/libredte-lib | lib/Sii/Dte/PDF/Dte.php | Dte.agregarLeyendaDestinoContinuo | protected function agregarLeyendaDestinoContinuo($tipo)
{
$this->setFont('', 'B', 8);
$this->Texto('CEDIBLE'.($tipo==52?' CON SU FACTURA':''), null, $this->y+6, 'R');
} | php | protected function agregarLeyendaDestinoContinuo($tipo)
{
$this->setFont('', 'B', 8);
$this->Texto('CEDIBLE'.($tipo==52?' CON SU FACTURA':''), null, $this->y+6, 'R');
} | [
"protected",
"function",
"agregarLeyendaDestinoContinuo",
"(",
"$",
"tipo",
")",
"{",
"$",
"this",
"->",
"setFont",
"(",
"''",
",",
"'B'",
",",
"8",
")",
";",
"$",
"this",
"->",
"Texto",
"(",
"'CEDIBLE'",
".",
"(",
"$",
"tipo",
"==",
"52",
"?",
"' CO... | Método que agrega la leyenda de destino
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-10-05 | [
"Método",
"que",
"agrega",
"la",
"leyenda",
"de",
"destino"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Dte/PDF/Dte.php#L1230-L1234 |
LibreDTE/libredte-lib | lib/I18n.php | I18n.translate | public static function translate($string, $domain = 'master')
{
if (!isset(self::$locales[self::$idioma]) or !function_exists('gettext')) {
return $string;
}
$locale = self::$locales[self::$idioma];
putenv("LANG=".$locale);
setlocale(LC_MESSAGES, $locale);
bindtextdomain($domain, dirname(dirname(__FILE__)).'/locale');
textdomain($domain);
bind_textdomain_codeset($domain, 'UTF-8');
return gettext($string);
} | php | public static function translate($string, $domain = 'master')
{
if (!isset(self::$locales[self::$idioma]) or !function_exists('gettext')) {
return $string;
}
$locale = self::$locales[self::$idioma];
putenv("LANG=".$locale);
setlocale(LC_MESSAGES, $locale);
bindtextdomain($domain, dirname(dirname(__FILE__)).'/locale');
textdomain($domain);
bind_textdomain_codeset($domain, 'UTF-8');
return gettext($string);
} | [
"public",
"static",
"function",
"translate",
"(",
"$",
"string",
",",
"$",
"domain",
"=",
"'master'",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"locales",
"[",
"self",
"::",
"$",
"idioma",
"]",
")",
"or",
"!",
"function_exists",
"(",... | Método que realiza la traducción de un string a otro idioma.
Plantilla para archivo master.po (para locale en_US.utf8):
msgid ""
msgstr ""
"Project-Id-Version: proyecto en_US master\n"
"PO-Revision-Date: 2014-03-02 11:37-0300\n"
"Last-Translator: Nombre del traductor <traductor@example.com>\n"
"Language-Team: English\n"
"Language: en_US\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
msgid "Buscar"
msgstr "Search"
Guardar la plantilla en locale/en_US.utf8/LC_MESSAGES/master.po
Luego ejecutar:
$ msgfmt master.po -o master.mo
En caso que se esté creando desde un archivo pot se debe crear el archivo po con:
$ msginit --locale=en_US.utf8 --input=master.pot
Lo anterior creará el archivo en_US.po y luego se usa msgfmt con este archivo
La locale que se esté utilizando debe existir en el sistema, verificar con:
$ locale -a
En caso que no exista editar /etc/locale.gen para agregarla y luego ejecutar:
# locale-gen
Cuando se crean o modifican los directorios en locale se debe reiniciar
el servicio Apache (¿?)
@param string Texto que se desea traducir
@param domain Dominio que se desea utilizar para la traducción
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-09-17 | [
"Método",
"que",
"realiza",
"la",
"traducción",
"de",
"un",
"string",
"a",
"otro",
"idioma",
"."
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/I18n.php#L96-L108 |
LibreDTE/libredte-lib | lib/Sii/LibroCompraVenta.php | LibroCompraVenta.getID | public function getID()
{
if ($this->datos===null) {
$this->datos = $this->toArray();
}
return !empty($this->datos['LibroCompraVenta']['EnvioLibro']['@attributes']['ID']) ? $this->datos['LibroCompraVenta']['EnvioLibro']['@attributes']['ID'] : false;
} | php | public function getID()
{
if ($this->datos===null) {
$this->datos = $this->toArray();
}
return !empty($this->datos['LibroCompraVenta']['EnvioLibro']['@attributes']['ID']) ? $this->datos['LibroCompraVenta']['EnvioLibro']['@attributes']['ID'] : false;
} | [
"public",
"function",
"getID",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"datos",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"datos",
"=",
"$",
"this",
"->",
"toArray",
"(",
")",
";",
"}",
"return",
"!",
"empty",
"(",
"$",
"this",
"->",
"da... | Método que permite obtener el ID del libro
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-07-28 | [
"Método",
"que",
"permite",
"obtener",
"el",
"ID",
"del",
"libro"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/LibroCompraVenta.php#L88-L94 |
LibreDTE/libredte-lib | lib/Sii/LibroCompraVenta.php | LibroCompraVenta.normalizarDetalle | private function normalizarDetalle(array &$detalle)
{
// agregar nodos (esto para mantener orden del XML)
$detalle = array_merge([
'TpoDoc' => false,
'Emisor' => false,
'IndFactCompra' => false,
'NroDoc' => false,
'Anulado' => false,
'Operacion' => false,
'TpoImp' => 1,
'TasaImp' => false,
'NumInt' => false,
'IndServicio' => false,
'IndSinCosto' => false,
'FchDoc' => false,
'CdgSIISucur' => false,
'RUTDoc' => false,
'RznSoc' => false,
'Extranjero' => false,
'TpoDocRef' => false,
'FolioDocRef' => false,
'MntExe' => false,
'MntNeto' => false,
'MntIVA' => false,
'MntActivoFijo' => false,
'MntIVAActivoFijo' => false,
'IVANoRec' => false,
'IVAUsoComun' => false,
'IVAFueraPlazo' => false,
'IVAPropio' => false,
'IVATerceros' => false,
'Ley18211' => false,
'OtrosImp' => false,
'MntSinCred' => false,
'IVARetTotal' => false,
'IVARetParcial' => false,
'CredEC' => false,
'DepEnvase' => false,
'Liquidaciones' => false,
'MntTotal' => false,
'IVANoRetenido' => false,
'MntNoFact' => false,
'MntPeriodo' => false,
'PsjNac' => false,
'PsjInt' => false,
'TabPuros' => false,
'TabCigarrillos' => false,
'TabElaborado' => false,
'ImpVehiculo' => false,
], $detalle);
// si el caso está anulado se genera sólo lo mínimo pedido por el SII
if (!empty($detalle['Anulado']) and $detalle['Anulado']=='A') {
$detalle = [
'TpoDoc' => $detalle['TpoDoc'],
'NroDoc' => $detalle['NroDoc'],
'Anulado' => $detalle['Anulado']
];
return;
}
// largo campos
if ($detalle['RznSoc']) {
$detalle['RznSoc'] = mb_substr($detalle['RznSoc'], 0, 50);
}
// calcular valores que no se hayan entregado
if (isset($detalle['FctProp'])) {
if ($detalle['IVAUsoComun']===false)
$detalle['IVAUsoComun'] = round($detalle['MntNeto'] * ($detalle['TasaImp']/100));
} else if (!$detalle['MntIVA'] and !is_array($detalle['IVANoRec']) and $detalle['TasaImp'] and $detalle['MntNeto']) {
$detalle['MntIVA'] = round($detalle['MntNeto'] * ($detalle['TasaImp']/100));
}
// si el monto total es 0 pero no se asigno neto ni exento se coloca
if ($detalle['MntExe']===false and $detalle['MntNeto']===false and $detalle['MntTotal']===0) {
$detalle['MntNeto'] = 0;
}
// colocar montos que falten en 0 si es solo exento y no neto
if ($detalle['MntNeto']===false and $detalle['MntExe']) {
$detalle['TasaImp'] = \sasco\LibreDTE\Sii::getIVA();
$detalle['MntNeto'] = 0;
$detalle['MntIVA'] = 0;
}
// normalizar IVA no recuperable
if (!empty($detalle['IVANoRec'])) {
if (!isset($detalle['IVANoRec'][0]))
$detalle['IVANoRec'] = [$detalle['IVANoRec']];
// si son múltiples iva no recuperable se arma arreglo real
if (strpos($detalle['IVANoRec'][0]['CodIVANoRec'], ',')) {
$CodIVANoRec = explode(',', $detalle['IVANoRec'][0]['CodIVANoRec']);
$MntIVANoRec = explode(',', $detalle['IVANoRec'][0]['MntIVANoRec']);
$detalle['IVANoRec'] = [];
$n_inr = count($CodIVANoRec);
for ($i=0; $i<$n_inr; $i++) {
$detalle['IVANoRec'][] = [
'CodIVANoRec' => $CodIVANoRec[$i],
'MntIVANoRec' => $MntIVANoRec[$i],
];
}
}
}
// normalizar otros impuestos
if (!empty($detalle['OtrosImp'])) {
if (!isset($detalle['OtrosImp'][0]))
$detalle['OtrosImp'] = [$detalle['OtrosImp']];
// si son múltiples impuestos se arma arreglo real
if (strpos($detalle['OtrosImp'][0]['CodImp'], ',')) {
$CodImp = explode(',', $detalle['OtrosImp'][0]['CodImp']);
$TasaImp = explode(',', $detalle['OtrosImp'][0]['TasaImp']);
$MntImp = explode(',', $detalle['OtrosImp'][0]['MntImp']);
$detalle['OtrosImp'] = [];
$n_impuestos = count($CodImp);
for ($i=0; $i<$n_impuestos; $i++) {
$detalle['OtrosImp'][] = [
'CodImp' => $CodImp[$i],
'TasaImp' => !empty($TasaImp[$i]) ? $TasaImp[$i] : false,
'MntImp' => $MntImp[$i],
];
}
}
// calcular y agregar IVA no retenido si corresponde
$retenido = ImpuestosAdicionales::getRetenido($detalle['OtrosImp']);
if ($retenido) {
// si el iva retenido es total
if ($retenido == $detalle['MntIVA']) {
$detalle['IVARetTotal'] = $retenido;
}
// si el iva retenido es parcial
else {
$detalle['IVARetParcial'] = $retenido;
$detalle['IVANoRetenido'] = $detalle['MntIVA'] - $retenido;
}
}
}
// calcular monto total si no se especificó
if ($detalle['MntTotal']===false) {
// calcular monto total inicial
$detalle['MntTotal'] = $detalle['MntExe'] + $detalle['MntNeto'] + (int)$detalle['MntIVA'];
// agregar iva no recuperable al monto total
if (!empty($detalle['IVANoRec'])) {
foreach ($detalle['IVANoRec'] as $IVANoRec) {
$detalle['MntTotal'] += $IVANoRec['MntIVANoRec'];
}
}
// agregar iva de uso común al monto total
if (isset($detalle['FctProp'])) {
$detalle['MntTotal'] += $detalle['IVAUsoComun'];
}
// descontar del total la retención total de IVA
if (!empty($detalle['OtrosImp'])) {
foreach ($detalle['OtrosImp'] as $OtrosImp) {
if (ImpuestosAdicionales::getTipo($OtrosImp['CodImp'])=='R') {
$detalle['MntTotal'] -= $OtrosImp['MntImp'];
}
}
}
// agregar otro montos e impuestos al total
$detalle['MntTotal'] += (int)$detalle['MntSinCred'] + (int)$detalle['TabPuros'] + (int)$detalle['TabCigarrillos'] + (int)$detalle['TabElaborado'] + (int)$detalle['ImpVehiculo'];
}
// si no hay no hay monto neto, no se crean campos para IVA
if ($detalle['MntNeto']===false) {
$detalle['MntNeto'] = $detalle['TasaImp'] = $detalle['MntIVA'] = false;
}
// si el código de sucursal no existe se pone a falso, esto básicamente
// porque algunos sistemas podrían usar 0 cuando no hay CdgSIISucur
if (!$detalle['CdgSIISucur']) {
$detalle['CdgSIISucur'] = false;
}
} | php | private function normalizarDetalle(array &$detalle)
{
// agregar nodos (esto para mantener orden del XML)
$detalle = array_merge([
'TpoDoc' => false,
'Emisor' => false,
'IndFactCompra' => false,
'NroDoc' => false,
'Anulado' => false,
'Operacion' => false,
'TpoImp' => 1,
'TasaImp' => false,
'NumInt' => false,
'IndServicio' => false,
'IndSinCosto' => false,
'FchDoc' => false,
'CdgSIISucur' => false,
'RUTDoc' => false,
'RznSoc' => false,
'Extranjero' => false,
'TpoDocRef' => false,
'FolioDocRef' => false,
'MntExe' => false,
'MntNeto' => false,
'MntIVA' => false,
'MntActivoFijo' => false,
'MntIVAActivoFijo' => false,
'IVANoRec' => false,
'IVAUsoComun' => false,
'IVAFueraPlazo' => false,
'IVAPropio' => false,
'IVATerceros' => false,
'Ley18211' => false,
'OtrosImp' => false,
'MntSinCred' => false,
'IVARetTotal' => false,
'IVARetParcial' => false,
'CredEC' => false,
'DepEnvase' => false,
'Liquidaciones' => false,
'MntTotal' => false,
'IVANoRetenido' => false,
'MntNoFact' => false,
'MntPeriodo' => false,
'PsjNac' => false,
'PsjInt' => false,
'TabPuros' => false,
'TabCigarrillos' => false,
'TabElaborado' => false,
'ImpVehiculo' => false,
], $detalle);
// si el caso está anulado se genera sólo lo mínimo pedido por el SII
if (!empty($detalle['Anulado']) and $detalle['Anulado']=='A') {
$detalle = [
'TpoDoc' => $detalle['TpoDoc'],
'NroDoc' => $detalle['NroDoc'],
'Anulado' => $detalle['Anulado']
];
return;
}
// largo campos
if ($detalle['RznSoc']) {
$detalle['RznSoc'] = mb_substr($detalle['RznSoc'], 0, 50);
}
// calcular valores que no se hayan entregado
if (isset($detalle['FctProp'])) {
if ($detalle['IVAUsoComun']===false)
$detalle['IVAUsoComun'] = round($detalle['MntNeto'] * ($detalle['TasaImp']/100));
} else if (!$detalle['MntIVA'] and !is_array($detalle['IVANoRec']) and $detalle['TasaImp'] and $detalle['MntNeto']) {
$detalle['MntIVA'] = round($detalle['MntNeto'] * ($detalle['TasaImp']/100));
}
// si el monto total es 0 pero no se asigno neto ni exento se coloca
if ($detalle['MntExe']===false and $detalle['MntNeto']===false and $detalle['MntTotal']===0) {
$detalle['MntNeto'] = 0;
}
// colocar montos que falten en 0 si es solo exento y no neto
if ($detalle['MntNeto']===false and $detalle['MntExe']) {
$detalle['TasaImp'] = \sasco\LibreDTE\Sii::getIVA();
$detalle['MntNeto'] = 0;
$detalle['MntIVA'] = 0;
}
// normalizar IVA no recuperable
if (!empty($detalle['IVANoRec'])) {
if (!isset($detalle['IVANoRec'][0]))
$detalle['IVANoRec'] = [$detalle['IVANoRec']];
// si son múltiples iva no recuperable se arma arreglo real
if (strpos($detalle['IVANoRec'][0]['CodIVANoRec'], ',')) {
$CodIVANoRec = explode(',', $detalle['IVANoRec'][0]['CodIVANoRec']);
$MntIVANoRec = explode(',', $detalle['IVANoRec'][0]['MntIVANoRec']);
$detalle['IVANoRec'] = [];
$n_inr = count($CodIVANoRec);
for ($i=0; $i<$n_inr; $i++) {
$detalle['IVANoRec'][] = [
'CodIVANoRec' => $CodIVANoRec[$i],
'MntIVANoRec' => $MntIVANoRec[$i],
];
}
}
}
// normalizar otros impuestos
if (!empty($detalle['OtrosImp'])) {
if (!isset($detalle['OtrosImp'][0]))
$detalle['OtrosImp'] = [$detalle['OtrosImp']];
// si son múltiples impuestos se arma arreglo real
if (strpos($detalle['OtrosImp'][0]['CodImp'], ',')) {
$CodImp = explode(',', $detalle['OtrosImp'][0]['CodImp']);
$TasaImp = explode(',', $detalle['OtrosImp'][0]['TasaImp']);
$MntImp = explode(',', $detalle['OtrosImp'][0]['MntImp']);
$detalle['OtrosImp'] = [];
$n_impuestos = count($CodImp);
for ($i=0; $i<$n_impuestos; $i++) {
$detalle['OtrosImp'][] = [
'CodImp' => $CodImp[$i],
'TasaImp' => !empty($TasaImp[$i]) ? $TasaImp[$i] : false,
'MntImp' => $MntImp[$i],
];
}
}
// calcular y agregar IVA no retenido si corresponde
$retenido = ImpuestosAdicionales::getRetenido($detalle['OtrosImp']);
if ($retenido) {
// si el iva retenido es total
if ($retenido == $detalle['MntIVA']) {
$detalle['IVARetTotal'] = $retenido;
}
// si el iva retenido es parcial
else {
$detalle['IVARetParcial'] = $retenido;
$detalle['IVANoRetenido'] = $detalle['MntIVA'] - $retenido;
}
}
}
// calcular monto total si no se especificó
if ($detalle['MntTotal']===false) {
// calcular monto total inicial
$detalle['MntTotal'] = $detalle['MntExe'] + $detalle['MntNeto'] + (int)$detalle['MntIVA'];
// agregar iva no recuperable al monto total
if (!empty($detalle['IVANoRec'])) {
foreach ($detalle['IVANoRec'] as $IVANoRec) {
$detalle['MntTotal'] += $IVANoRec['MntIVANoRec'];
}
}
// agregar iva de uso común al monto total
if (isset($detalle['FctProp'])) {
$detalle['MntTotal'] += $detalle['IVAUsoComun'];
}
// descontar del total la retención total de IVA
if (!empty($detalle['OtrosImp'])) {
foreach ($detalle['OtrosImp'] as $OtrosImp) {
if (ImpuestosAdicionales::getTipo($OtrosImp['CodImp'])=='R') {
$detalle['MntTotal'] -= $OtrosImp['MntImp'];
}
}
}
// agregar otro montos e impuestos al total
$detalle['MntTotal'] += (int)$detalle['MntSinCred'] + (int)$detalle['TabPuros'] + (int)$detalle['TabCigarrillos'] + (int)$detalle['TabElaborado'] + (int)$detalle['ImpVehiculo'];
}
// si no hay no hay monto neto, no se crean campos para IVA
if ($detalle['MntNeto']===false) {
$detalle['MntNeto'] = $detalle['TasaImp'] = $detalle['MntIVA'] = false;
}
// si el código de sucursal no existe se pone a falso, esto básicamente
// porque algunos sistemas podrían usar 0 cuando no hay CdgSIISucur
if (!$detalle['CdgSIISucur']) {
$detalle['CdgSIISucur'] = false;
}
} | [
"private",
"function",
"normalizarDetalle",
"(",
"array",
"&",
"$",
"detalle",
")",
"{",
"// agregar nodos (esto para mantener orden del XML)",
"$",
"detalle",
"=",
"array_merge",
"(",
"[",
"'TpoDoc'",
"=>",
"false",
",",
"'Emisor'",
"=>",
"false",
",",
"'IndFactCom... | Método que normaliza un detalle del libro de compra o venta
@param detalle Arreglo con el resumen del DTE que se desea agregar
@return Arreglo con el detalle normalizado
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2018-01-26 | [
"Método",
"que",
"normaliza",
"un",
"detalle",
"del",
"libro",
"de",
"compra",
"o",
"venta"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/LibroCompraVenta.php#L120-L286 |
LibreDTE/libredte-lib | lib/Sii/LibroCompraVenta.php | LibroCompraVenta.agregarVentasCSV | public function agregarVentasCSV($archivo, $separador = ';')
{
$data = \sasco\LibreDTE\CSV::read($archivo);
$n_data = count($data);
$detalles = [];
for ($i=1; $i<$n_data; $i++) {
// detalle genérico
$detalle = [
'TpoDoc' => $data[$i][0],
'NroDoc' => $data[$i][1],
'RUTDoc' => !empty($data[$i][2]) ? $data[$i][2] : false,
'TasaImp' => !empty($data[$i][3]) ? $data[$i][3] : false,
'RznSoc' => !empty($data[$i][4]) ? $data[$i][4] : false,
'FchDoc' => !empty($data[$i][5]) ? $data[$i][5] : false,
'Anulado' => !empty($data[$i][6]) ? 'A' : false,
'MntExe' => !empty($data[$i][7]) ? $data[$i][7] : false,
'MntNeto' => !empty($data[$i][8]) ? $data[$i][8] : false,
'MntIVA' => !empty($data[$i][9]) ? $data[$i][9] : 0,
'IVAFueraPlazo' => !empty($data[$i][10]) ? $data[$i][10] : false,
'IVAPropio' => !empty($data[$i][14]) ? $data[$i][14] : false,
'IVATerceros' => !empty($data[$i][15]) ? $data[$i][15] : false,
'IVARetTotal' => !empty($data[$i][16]) ? $data[$i][16] : false,
'IVARetParcial' => !empty($data[$i][17]) ? $data[$i][17] : false,
'IVANoRetenido' => !empty($data[$i][18]) ? $data[$i][18] : false,
'Ley18211' => !empty($data[$i][19]) ? $data[$i][19] : false,
'CredEC' => !empty($data[$i][20]) ? $data[$i][20] : false,
'TpoDocRef' => !empty($data[$i][21]) ? $data[$i][21] : false,
'FolioDocRef' => !empty($data[$i][22]) ? $data[$i][22] : false,
'DepEnvase' => !empty($data[$i][23]) ? $data[$i][23] : false,
'MntNoFact' => !empty($data[$i][24]) ? $data[$i][24] : false,
'MntPeriodo' => !empty($data[$i][25]) ? $data[$i][25] : false,
'PsjNac' => !empty($data[$i][26]) ? $data[$i][26] : false,
'PsjInt' => !empty($data[$i][27]) ? $data[$i][27] : false,
'IndServicio' => !empty($data[$i][30]) ? $data[$i][30] : false,
'IndSinCosto' => !empty($data[$i][31]) ? $data[$i][31] : false,
'CdgSIISucur' => !empty($data[$i][36]) ? $data[$i][36] : false,
'NumInt' => !empty($data[$i][37]) ? $data[$i][37] : false,
'Emisor' => !empty($data[$i][38]) ? 1 : false,
];
// agregar código y monto de otros impuestos
if (!empty($data[$i][11])) {
$detalle['OtrosImp'] = [
'CodImp' => $data[$i][11],
'TasaImp' => !empty($data[$i][12]) ? $data[$i][12] : false,
'MntImp' => !empty($data[$i][13]) ? $data[$i][13] : round($detalle['MntNeto'] * ($data[$i][12]/100)),
];
}
// agregar datos extranjeros
if (!empty($data[$i][28]) or !empty($data[$i][29])) {
$detalle['Extranjero'] = [
'NumId' => !empty($data[$i][28]) ? $data[$i][28] : false,
'Nacionalidad' => !empty($data[$i][29]) ? $data[$i][29] : false,
];
}
// agregar datos de liquidaciones
if (!empty($data[$i][32])) {
$detalle['Liquidaciones'] = [
'RutEmisor' => $data[$i][32],
'ValComNeto' => !empty($data[$i][33]) ? $data[$i][33] : false,
'ValComExe' => !empty($data[$i][34]) ? $data[$i][34] : false,
'ValComIVA' => !empty($data[$i][35]) ? $data[$i][35] : false,
];
}
// si hay monto total se agrega
if (!empty($data[$i][39])) {
$detalle['MntTotal'] = $data[$i][39];
}
// agregar a los detalles
$this->agregar($detalle);
}
} | php | public function agregarVentasCSV($archivo, $separador = ';')
{
$data = \sasco\LibreDTE\CSV::read($archivo);
$n_data = count($data);
$detalles = [];
for ($i=1; $i<$n_data; $i++) {
// detalle genérico
$detalle = [
'TpoDoc' => $data[$i][0],
'NroDoc' => $data[$i][1],
'RUTDoc' => !empty($data[$i][2]) ? $data[$i][2] : false,
'TasaImp' => !empty($data[$i][3]) ? $data[$i][3] : false,
'RznSoc' => !empty($data[$i][4]) ? $data[$i][4] : false,
'FchDoc' => !empty($data[$i][5]) ? $data[$i][5] : false,
'Anulado' => !empty($data[$i][6]) ? 'A' : false,
'MntExe' => !empty($data[$i][7]) ? $data[$i][7] : false,
'MntNeto' => !empty($data[$i][8]) ? $data[$i][8] : false,
'MntIVA' => !empty($data[$i][9]) ? $data[$i][9] : 0,
'IVAFueraPlazo' => !empty($data[$i][10]) ? $data[$i][10] : false,
'IVAPropio' => !empty($data[$i][14]) ? $data[$i][14] : false,
'IVATerceros' => !empty($data[$i][15]) ? $data[$i][15] : false,
'IVARetTotal' => !empty($data[$i][16]) ? $data[$i][16] : false,
'IVARetParcial' => !empty($data[$i][17]) ? $data[$i][17] : false,
'IVANoRetenido' => !empty($data[$i][18]) ? $data[$i][18] : false,
'Ley18211' => !empty($data[$i][19]) ? $data[$i][19] : false,
'CredEC' => !empty($data[$i][20]) ? $data[$i][20] : false,
'TpoDocRef' => !empty($data[$i][21]) ? $data[$i][21] : false,
'FolioDocRef' => !empty($data[$i][22]) ? $data[$i][22] : false,
'DepEnvase' => !empty($data[$i][23]) ? $data[$i][23] : false,
'MntNoFact' => !empty($data[$i][24]) ? $data[$i][24] : false,
'MntPeriodo' => !empty($data[$i][25]) ? $data[$i][25] : false,
'PsjNac' => !empty($data[$i][26]) ? $data[$i][26] : false,
'PsjInt' => !empty($data[$i][27]) ? $data[$i][27] : false,
'IndServicio' => !empty($data[$i][30]) ? $data[$i][30] : false,
'IndSinCosto' => !empty($data[$i][31]) ? $data[$i][31] : false,
'CdgSIISucur' => !empty($data[$i][36]) ? $data[$i][36] : false,
'NumInt' => !empty($data[$i][37]) ? $data[$i][37] : false,
'Emisor' => !empty($data[$i][38]) ? 1 : false,
];
// agregar código y monto de otros impuestos
if (!empty($data[$i][11])) {
$detalle['OtrosImp'] = [
'CodImp' => $data[$i][11],
'TasaImp' => !empty($data[$i][12]) ? $data[$i][12] : false,
'MntImp' => !empty($data[$i][13]) ? $data[$i][13] : round($detalle['MntNeto'] * ($data[$i][12]/100)),
];
}
// agregar datos extranjeros
if (!empty($data[$i][28]) or !empty($data[$i][29])) {
$detalle['Extranjero'] = [
'NumId' => !empty($data[$i][28]) ? $data[$i][28] : false,
'Nacionalidad' => !empty($data[$i][29]) ? $data[$i][29] : false,
];
}
// agregar datos de liquidaciones
if (!empty($data[$i][32])) {
$detalle['Liquidaciones'] = [
'RutEmisor' => $data[$i][32],
'ValComNeto' => !empty($data[$i][33]) ? $data[$i][33] : false,
'ValComExe' => !empty($data[$i][34]) ? $data[$i][34] : false,
'ValComIVA' => !empty($data[$i][35]) ? $data[$i][35] : false,
];
}
// si hay monto total se agrega
if (!empty($data[$i][39])) {
$detalle['MntTotal'] = $data[$i][39];
}
// agregar a los detalles
$this->agregar($detalle);
}
} | [
"public",
"function",
"agregarVentasCSV",
"(",
"$",
"archivo",
",",
"$",
"separador",
"=",
"';'",
")",
"{",
"$",
"data",
"=",
"\\",
"sasco",
"\\",
"LibreDTE",
"\\",
"CSV",
"::",
"read",
"(",
"$",
"archivo",
")",
";",
"$",
"n_data",
"=",
"count",
"(",... | Método que agrega el detalle del libro de ventas a partir de un archivo
CSV.
Formato del archivo (desde la columna A):
0: TpoDoc
1: NroDoc
2: RUTDoc
3: TasaImp
4: RznSoc (opcional)
5: FchDoc
6: Anulado (opcional, 'A' sólo para folios anulados, no anulados con NC o ND)
7: MntExe (opcional)
8: MntNeto (opcional)
9: MntIVA (calculable)
10: IVAFueraPlazo
OtrosImp (opcional):
11: CodImp
12: TasaImp
13: MntImp (calculable)
14: IVAPropio
15: IVATerceros
16: IVARetTotal
17: IVARetParcial
18: IVANoRetenido
19: Ley18211
20: CredEC
21: TpoDocRef
22: FolioDocRef
23: DepEnvase
24: MntNoFact
25: MntPeriodo
26: PsjNac
27: PsjInt
Extranjero (sólo DTE de exportación):
28: NumId
29: Nacionalidad
30: IndServicio (=1 servicios periodicos domiciliarios, =2 otros servicios periodicos, =3 servicios no periodicos)
31: IndSinCosto
Liquidaciones (opcional):
32: RutEmisor
33: ValComNeto
34: ValComExe
35: ValComIVA
36: CdgSIISucur (opcional)
37: NumInt
38: Emisor
39: MntTotal (calculable)
@param archivo Ruta al archivo que se desea cargar
@param separador Separador de campos del archivo CSV
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-09-06 | [
"Método",
"que",
"agrega",
"el",
"detalle",
"del",
"libro",
"de",
"ventas",
"a",
"partir",
"de",
"un",
"archivo",
"CSV",
"."
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/LibroCompraVenta.php#L449-L519 |
LibreDTE/libredte-lib | lib/Sii/LibroCompraVenta.php | LibroCompraVenta.setCaratula | public function setCaratula(array $caratula)
{
$this->caratula = array_merge([
'RutEmisorLibro' => false,
'RutEnvia' => isset($this->Firma) ? $this->Firma->getID() : false,
'PeriodoTributario' => date('Y-m'),
'FchResol' => false,
'NroResol' => false,
'TipoOperacion' => 'VENTA',
'TipoLibro' => 'MENSUAL',
'TipoEnvio' => 'TOTAL',
'FolioNotificacion' => false,
], $caratula);
if ($this->caratula['TipoEnvio']=='ESPECIAL')
$this->caratula['FolioNotificacion'] = null;
$this->id = 'LibreDTE_LIBRO_'.$this->caratula['TipoOperacion'].'_'.str_replace('-', '', $this->caratula['RutEmisorLibro']).'_'.str_replace('-', '', $this->caratula['PeriodoTributario']).'_'.date('U');
} | php | public function setCaratula(array $caratula)
{
$this->caratula = array_merge([
'RutEmisorLibro' => false,
'RutEnvia' => isset($this->Firma) ? $this->Firma->getID() : false,
'PeriodoTributario' => date('Y-m'),
'FchResol' => false,
'NroResol' => false,
'TipoOperacion' => 'VENTA',
'TipoLibro' => 'MENSUAL',
'TipoEnvio' => 'TOTAL',
'FolioNotificacion' => false,
], $caratula);
if ($this->caratula['TipoEnvio']=='ESPECIAL')
$this->caratula['FolioNotificacion'] = null;
$this->id = 'LibreDTE_LIBRO_'.$this->caratula['TipoOperacion'].'_'.str_replace('-', '', $this->caratula['RutEmisorLibro']).'_'.str_replace('-', '', $this->caratula['PeriodoTributario']).'_'.date('U');
} | [
"public",
"function",
"setCaratula",
"(",
"array",
"$",
"caratula",
")",
"{",
"$",
"this",
"->",
"caratula",
"=",
"array_merge",
"(",
"[",
"'RutEmisorLibro'",
"=>",
"false",
",",
"'RutEnvia'",
"=>",
"isset",
"(",
"$",
"this",
"->",
"Firma",
")",
"?",
"$"... | Método para asignar la caratula
@param caratula Arreglo con datos del envío: RutEnvia, FchResol y NroResol
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-08-06 | [
"Método",
"para",
"asignar",
"la",
"caratula"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/LibroCompraVenta.php#L527-L543 |
LibreDTE/libredte-lib | lib/Sii/LibroCompraVenta.php | LibroCompraVenta.generar | public function generar($incluirDetalle = true)
{
// si ya se había generado se entrega directamente
if ($this->xml_data)
return $this->xml_data;
// generar totales de DTE y sus montos
$TotalesPeriodo = $this->getResumen();
$ResumenPeriodo = $TotalesPeriodo ? ['TotalesPeriodo'=>$TotalesPeriodo] : false;
// generar XML del envío
$xmlEnvio = (new \sasco\LibreDTE\XML())->generate([
'LibroCompraVenta' => [
'@attributes' => [
'xmlns' => 'http://www.sii.cl/SiiDte',
'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
'xsi:schemaLocation' => $this->simplificado ? 'http://www.sii.cl/SiiDte LibroCVS_v10.xsd' : 'http://www.sii.cl/SiiDte LibroCV_v10.xsd',
'version' => '1.0',
],
'EnvioLibro' => [
'@attributes' => [
'ID' => $this->id,
],
'Caratula' => $this->caratula,
'ResumenPeriodo' => $ResumenPeriodo,
'Detalle' => $incluirDetalle ? $this->getDetalle() : false,
'TmstFirma' => date('Y-m-d\TH:i:s'),
],
]
])->saveXML();
// firmar XML del envío y entregar
$this->xml_data = (!$this->simplificado and $this->Firma) ? $this->Firma->signXML($xmlEnvio, '#'.$this->id, 'EnvioLibro', true) : $xmlEnvio;
return $this->xml_data;
} | php | public function generar($incluirDetalle = true)
{
// si ya se había generado se entrega directamente
if ($this->xml_data)
return $this->xml_data;
// generar totales de DTE y sus montos
$TotalesPeriodo = $this->getResumen();
$ResumenPeriodo = $TotalesPeriodo ? ['TotalesPeriodo'=>$TotalesPeriodo] : false;
// generar XML del envío
$xmlEnvio = (new \sasco\LibreDTE\XML())->generate([
'LibroCompraVenta' => [
'@attributes' => [
'xmlns' => 'http://www.sii.cl/SiiDte',
'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
'xsi:schemaLocation' => $this->simplificado ? 'http://www.sii.cl/SiiDte LibroCVS_v10.xsd' : 'http://www.sii.cl/SiiDte LibroCV_v10.xsd',
'version' => '1.0',
],
'EnvioLibro' => [
'@attributes' => [
'ID' => $this->id,
],
'Caratula' => $this->caratula,
'ResumenPeriodo' => $ResumenPeriodo,
'Detalle' => $incluirDetalle ? $this->getDetalle() : false,
'TmstFirma' => date('Y-m-d\TH:i:s'),
],
]
])->saveXML();
// firmar XML del envío y entregar
$this->xml_data = (!$this->simplificado and $this->Firma) ? $this->Firma->signXML($xmlEnvio, '#'.$this->id, 'EnvioLibro', true) : $xmlEnvio;
return $this->xml_data;
} | [
"public",
"function",
"generar",
"(",
"$",
"incluirDetalle",
"=",
"true",
")",
"{",
"// si ya se había generado se entrega directamente",
"if",
"(",
"$",
"this",
"->",
"xml_data",
")",
"return",
"$",
"this",
"->",
"xml_data",
";",
"// generar totales de DTE y sus mont... | Método que genera el XML del libro IECV para el envío al SII
@param incluirDetalle =true no se incluirá el detalle de los DTEs (sólo se usará para calcular totales)
@return XML con el envio del libro de compra y venta firmado o =false si no se pudo generar o firmar el envío
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-02-12 | [
"Método",
"que",
"genera",
"el",
"XML",
"del",
"libro",
"IECV",
"para",
"el",
"envío",
"al",
"SII"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/LibroCompraVenta.php#L552-L583 |
LibreDTE/libredte-lib | lib/Sii/LibroCompraVenta.php | LibroCompraVenta.setResumen | public function setResumen($resumen)
{
// verificar que se haya pasado el tipo de documento y total como mínimo
foreach ($resumen as $tipo) {
if (!isset($tipo['TpoDoc']) or !isset($tipo['TotDoc'])) {
return false;
}
}
// asignar resumen
$this->resumen = [];
foreach ($resumen as $tipo) {
$this->resumen[$tipo['TpoDoc']] = $tipo;
}
} | php | public function setResumen($resumen)
{
// verificar que se haya pasado el tipo de documento y total como mínimo
foreach ($resumen as $tipo) {
if (!isset($tipo['TpoDoc']) or !isset($tipo['TotDoc'])) {
return false;
}
}
// asignar resumen
$this->resumen = [];
foreach ($resumen as $tipo) {
$this->resumen[$tipo['TpoDoc']] = $tipo;
}
} | [
"public",
"function",
"setResumen",
"(",
"$",
"resumen",
")",
"{",
"// verificar que se haya pasado el tipo de documento y total como mínimo",
"foreach",
"(",
"$",
"resumen",
"as",
"$",
"tipo",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"tipo",
"[",
"'TpoDoc'",
... | Método que permite agregar sólo resumen al libro (sin detalle), esto para
poder agregar, por ejemplo, el resumen de las boletas en papel sin tener
que agregar la totalidad al detalle
@param resumen Arreglo con índice el DTE y valor arreglo con el resumen de ese DTE
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-02-12 | [
"Método",
"que",
"permite",
"agregar",
"sólo",
"resumen",
"al",
"libro",
"(",
"sin",
"detalle",
")",
"esto",
"para",
"poder",
"agregar",
"por",
"ejemplo",
"el",
"resumen",
"de",
"las",
"boletas",
"en",
"papel",
"sin",
"tener",
"que",
"agregar",
"la",
"tota... | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/LibroCompraVenta.php#L593-L606 |
LibreDTE/libredte-lib | lib/Sii/LibroCompraVenta.php | LibroCompraVenta.getResumen | public function getResumen()
{
$totales = [];
// agregar resumen de detalles
foreach ($this->detalles as &$d) {
if (!isset($totales[$d['TpoDoc']])) {
$totales[$d['TpoDoc']] = array_merge($this->total_default, ['TpoDoc'=>$d['TpoDoc']]);
}
// contabilizar cantidad de documentos y montos (exento, neto, iva y total)
$totales[$d['TpoDoc']]['TotDoc']++;
$totales[$d['TpoDoc']]['TotMntExe'] += $d['MntExe'];
$totales[$d['TpoDoc']]['TotMntNeto'] += $d['MntNeto'];
if (!empty($d['MntIVA'])) {
$totales[$d['TpoDoc']]['TotMntIVA'] += $d['MntIVA'];
}
$totales[$d['TpoDoc']]['TotMntTotal'] += $d['MntTotal'];
// contabilizar documentos anulados
if (!empty($d['Anulado']) and $d['Anulado']=='A') {
$totales[$d['TpoDoc']]['TotAnulado']++;
}
// si hay activo fijo se contabiliza
if (!empty($d['MntActivoFijo'])) {
$totales[$d['TpoDoc']]['TotMntActivoFijo'] += $d['MntActivoFijo'];
}
if (!empty($d['MntIVAActivoFijo'])) {
$totales[$d['TpoDoc']]['TotMntIVAActivoFijo'] += $d['MntIVAActivoFijo'];
}
// si hay iva no recuperable se contabiliza
if (!empty($d['IVANoRec'])) {
foreach ($d['IVANoRec'] as $IVANoRec) {
if (!isset($totales[$d['TpoDoc']]['TotIVANoRec'][$IVANoRec['CodIVANoRec']])) {
$totales[$d['TpoDoc']]['TotIVANoRec'][$IVANoRec['CodIVANoRec']] = [
'CodIVANoRec' => $IVANoRec['CodIVANoRec'],
'TotOpIVANoRec' => 0,
'TotMntIVANoRec' => 0,
];
}
$totales[$d['TpoDoc']]['TotIVANoRec'][$IVANoRec['CodIVANoRec']]['TotOpIVANoRec']++;
$totales[$d['TpoDoc']]['TotIVANoRec'][$IVANoRec['CodIVANoRec']]['TotMntIVANoRec'] += $IVANoRec['MntIVANoRec'];
}
}
// si hay IVA de uso común se contabiliza
if (!empty($d['FctProp'])) {
$totales[$d['TpoDoc']]['TotIVAUsoComun'] += $d['IVAUsoComun'];
$totales[$d['TpoDoc']]['FctProp'] = $d['FctProp']/100;
$totales[$d['TpoDoc']]['TotCredIVAUsoComun'] += round($d['IVAUsoComun'] * ($d['FctProp']/100));
unset($d['FctProp']); // se quita el factor de proporcionalidad del detalle ya que no es parte del XML
}
// contabilizar IVA fuera de plazo
if (!empty($d['IVAFueraPlazo'])) {
$totales[$d['TpoDoc']]['TotIVAFueraPlazo'] += $d['IVAFueraPlazo'];
}
// si hay otro tipo de impuesto se contabiliza
if (!empty($d['OtrosImp'])) {
foreach ($d['OtrosImp'] as $OtrosImp) {
if (!isset($totales[$d['TpoDoc']]['TotOtrosImp'][$OtrosImp['CodImp']])) {
$totales[$d['TpoDoc']]['TotOtrosImp'][$OtrosImp['CodImp']] = [
'CodImp' => $OtrosImp['CodImp'],
'TotMntImp' => 0,
];
}
$totales[$d['TpoDoc']]['TotOtrosImp'][$OtrosImp['CodImp']]['TotMntImp'] += $OtrosImp['MntImp'];
}
}
// contabilizar impuesto sin derecho a crédito
if (!empty($d['MntSinCred'])) {
$totales[$d['TpoDoc']]['TotImpSinCredito'] += $d['MntSinCred'];
}
// contabilidad IVA retenido total
if (!empty($d['IVARetTotal'])) {
$totales[$d['TpoDoc']]['TotIVARetTotal'] += $d['IVARetTotal'];
}
// contabilizar IVA retenido parcial
if (!empty($d['IVARetParcial'])) {
$totales[$d['TpoDoc']]['TotIVARetParcial'] += $d['IVARetParcial'];
}
// contabilizar IVA no retenido
if (!empty($d['IVANoRetenido'])) {
$totales[$d['TpoDoc']]['TotIVANoRetenido'] += $d['IVANoRetenido'];
}
// contabilidar impuesto vehículos
if (!empty($d['ImpVehiculo'])) {
$totales[$d['TpoDoc']]['TotImpVehiculo'] += $d['ImpVehiculo'];
}
}
// agregar resumenes pasados que no se hayan generado por los detalles
foreach ($this->resumen as $tipo => $resumen) {
if (!isset($totales[$tipo])) {
$totales[$tipo] = array_merge($this->total_default, $resumen);
}
}
// entregar resumen
ksort($totales);
return $totales;
} | php | public function getResumen()
{
$totales = [];
// agregar resumen de detalles
foreach ($this->detalles as &$d) {
if (!isset($totales[$d['TpoDoc']])) {
$totales[$d['TpoDoc']] = array_merge($this->total_default, ['TpoDoc'=>$d['TpoDoc']]);
}
// contabilizar cantidad de documentos y montos (exento, neto, iva y total)
$totales[$d['TpoDoc']]['TotDoc']++;
$totales[$d['TpoDoc']]['TotMntExe'] += $d['MntExe'];
$totales[$d['TpoDoc']]['TotMntNeto'] += $d['MntNeto'];
if (!empty($d['MntIVA'])) {
$totales[$d['TpoDoc']]['TotMntIVA'] += $d['MntIVA'];
}
$totales[$d['TpoDoc']]['TotMntTotal'] += $d['MntTotal'];
// contabilizar documentos anulados
if (!empty($d['Anulado']) and $d['Anulado']=='A') {
$totales[$d['TpoDoc']]['TotAnulado']++;
}
// si hay activo fijo se contabiliza
if (!empty($d['MntActivoFijo'])) {
$totales[$d['TpoDoc']]['TotMntActivoFijo'] += $d['MntActivoFijo'];
}
if (!empty($d['MntIVAActivoFijo'])) {
$totales[$d['TpoDoc']]['TotMntIVAActivoFijo'] += $d['MntIVAActivoFijo'];
}
// si hay iva no recuperable se contabiliza
if (!empty($d['IVANoRec'])) {
foreach ($d['IVANoRec'] as $IVANoRec) {
if (!isset($totales[$d['TpoDoc']]['TotIVANoRec'][$IVANoRec['CodIVANoRec']])) {
$totales[$d['TpoDoc']]['TotIVANoRec'][$IVANoRec['CodIVANoRec']] = [
'CodIVANoRec' => $IVANoRec['CodIVANoRec'],
'TotOpIVANoRec' => 0,
'TotMntIVANoRec' => 0,
];
}
$totales[$d['TpoDoc']]['TotIVANoRec'][$IVANoRec['CodIVANoRec']]['TotOpIVANoRec']++;
$totales[$d['TpoDoc']]['TotIVANoRec'][$IVANoRec['CodIVANoRec']]['TotMntIVANoRec'] += $IVANoRec['MntIVANoRec'];
}
}
// si hay IVA de uso común se contabiliza
if (!empty($d['FctProp'])) {
$totales[$d['TpoDoc']]['TotIVAUsoComun'] += $d['IVAUsoComun'];
$totales[$d['TpoDoc']]['FctProp'] = $d['FctProp']/100;
$totales[$d['TpoDoc']]['TotCredIVAUsoComun'] += round($d['IVAUsoComun'] * ($d['FctProp']/100));
unset($d['FctProp']); // se quita el factor de proporcionalidad del detalle ya que no es parte del XML
}
// contabilizar IVA fuera de plazo
if (!empty($d['IVAFueraPlazo'])) {
$totales[$d['TpoDoc']]['TotIVAFueraPlazo'] += $d['IVAFueraPlazo'];
}
// si hay otro tipo de impuesto se contabiliza
if (!empty($d['OtrosImp'])) {
foreach ($d['OtrosImp'] as $OtrosImp) {
if (!isset($totales[$d['TpoDoc']]['TotOtrosImp'][$OtrosImp['CodImp']])) {
$totales[$d['TpoDoc']]['TotOtrosImp'][$OtrosImp['CodImp']] = [
'CodImp' => $OtrosImp['CodImp'],
'TotMntImp' => 0,
];
}
$totales[$d['TpoDoc']]['TotOtrosImp'][$OtrosImp['CodImp']]['TotMntImp'] += $OtrosImp['MntImp'];
}
}
// contabilizar impuesto sin derecho a crédito
if (!empty($d['MntSinCred'])) {
$totales[$d['TpoDoc']]['TotImpSinCredito'] += $d['MntSinCred'];
}
// contabilidad IVA retenido total
if (!empty($d['IVARetTotal'])) {
$totales[$d['TpoDoc']]['TotIVARetTotal'] += $d['IVARetTotal'];
}
// contabilizar IVA retenido parcial
if (!empty($d['IVARetParcial'])) {
$totales[$d['TpoDoc']]['TotIVARetParcial'] += $d['IVARetParcial'];
}
// contabilizar IVA no retenido
if (!empty($d['IVANoRetenido'])) {
$totales[$d['TpoDoc']]['TotIVANoRetenido'] += $d['IVANoRetenido'];
}
// contabilidar impuesto vehículos
if (!empty($d['ImpVehiculo'])) {
$totales[$d['TpoDoc']]['TotImpVehiculo'] += $d['ImpVehiculo'];
}
}
// agregar resumenes pasados que no se hayan generado por los detalles
foreach ($this->resumen as $tipo => $resumen) {
if (!isset($totales[$tipo])) {
$totales[$tipo] = array_merge($this->total_default, $resumen);
}
}
// entregar resumen
ksort($totales);
return $totales;
} | [
"public",
"function",
"getResumen",
"(",
")",
"{",
"$",
"totales",
"=",
"[",
"]",
";",
"// agregar resumen de detalles",
"foreach",
"(",
"$",
"this",
"->",
"detalles",
"as",
"&",
"$",
"d",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"totales",
"[",
... | Método que obtiene los datos para generar los tags TotalesPeriodo
@return Arreglo con los datos para generar los tags TotalesPeriodo
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-11-27 | [
"Método",
"que",
"obtiene",
"los",
"datos",
"para",
"generar",
"los",
"tags",
"TotalesPeriodo"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/LibroCompraVenta.php#L614-L708 |
LibreDTE/libredte-lib | lib/Sii/LibroCompraVenta.php | LibroCompraVenta.getResumenManual | public function getResumenManual()
{
$manual = [];
if (isset($this->toArray()['LibroCompraVenta']['EnvioLibro']['ResumenPeriodo']['TotalesPeriodo'])) {
$totales = $this->toArray()['LibroCompraVenta']['EnvioLibro']['ResumenPeriodo']['TotalesPeriodo'];
if (!isset($totales[0]))
$totales = [$totales];
foreach ($totales as $total) {
if (isset($total['TpoDoc']) and in_array($total['TpoDoc'], [35, 38, 48])) {
$manual[$total['TpoDoc']] = array_merge($this->total_default, $total);
}
}
}
return $manual;
} | php | public function getResumenManual()
{
$manual = [];
if (isset($this->toArray()['LibroCompraVenta']['EnvioLibro']['ResumenPeriodo']['TotalesPeriodo'])) {
$totales = $this->toArray()['LibroCompraVenta']['EnvioLibro']['ResumenPeriodo']['TotalesPeriodo'];
if (!isset($totales[0]))
$totales = [$totales];
foreach ($totales as $total) {
if (isset($total['TpoDoc']) and in_array($total['TpoDoc'], [35, 38, 48])) {
$manual[$total['TpoDoc']] = array_merge($this->total_default, $total);
}
}
}
return $manual;
} | [
"public",
"function",
"getResumenManual",
"(",
")",
"{",
"$",
"manual",
"=",
"[",
"]",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"toArray",
"(",
")",
"[",
"'LibroCompraVenta'",
"]",
"[",
"'EnvioLibro'",
"]",
"[",
"'ResumenPeriodo'",
"]",
"[",
"'... | Método que entrega el resumen manual, de los totales registrados en el
XML del libro
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-10-12 | [
"Método",
"que",
"entrega",
"el",
"resumen",
"manual",
"de",
"los",
"totales",
"registrados",
"en",
"el",
"XML",
"del",
"libro"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/LibroCompraVenta.php#L716-L730 |
LibreDTE/libredte-lib | lib/Sii/LibroCompraVenta.php | LibroCompraVenta.getDetalle | public function getDetalle()
{
if ($this->caratula['TipoOperacion']=='VENTA') {
$omitir = [35, 38, 39, 41, 105, 500, 501, 919, 920, 922, 924];
$detalles = [];
foreach ($this->detalles as $d) {
if (!in_array($d['TpoDoc'], $omitir)) {
$detalles[] = $d;
}
}
return $detalles;
}
return $this->detalles;
} | php | public function getDetalle()
{
if ($this->caratula['TipoOperacion']=='VENTA') {
$omitir = [35, 38, 39, 41, 105, 500, 501, 919, 920, 922, 924];
$detalles = [];
foreach ($this->detalles as $d) {
if (!in_array($d['TpoDoc'], $omitir)) {
$detalles[] = $d;
}
}
return $detalles;
}
return $this->detalles;
} | [
"public",
"function",
"getDetalle",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"caratula",
"[",
"'TipoOperacion'",
"]",
"==",
"'VENTA'",
")",
"{",
"$",
"omitir",
"=",
"[",
"35",
",",
"38",
",",
"39",
",",
"41",
",",
"105",
",",
"500",
",",
"501... | Método que entrega el detalle a incluir en XML, en el libro de ventas no
se incluyen ciertos documentos (como boletas), por eso se usa este método
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-02-12 | [
"Método",
"que",
"entrega",
"el",
"detalle",
"a",
"incluir",
"en",
"XML",
"en",
"el",
"libro",
"de",
"ventas",
"no",
"se",
"incluyen",
"ciertos",
"documentos",
"(",
"como",
"boletas",
")",
"por",
"eso",
"se",
"usa",
"este",
"método"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/LibroCompraVenta.php#L759-L772 |
LibreDTE/libredte-lib | lib/Sii/LibroCompraVenta.php | LibroCompraVenta.getCompras | public function getCompras()
{
$detalle = [];
foreach ($this->detalles as $d) {
// armar iva no recuperable
$iva_no_recuperable_codigo = [];
$iva_no_recuperable_monto = [];
foreach ((array)$d['IVANoRec'] as $inr) {
$iva_no_recuperable_codigo[] = $inr['CodIVANoRec'];
$iva_no_recuperable_monto[] = $inr['MntIVANoRec'];
}
// armar impuestos adicionales
$impuesto_adicional_codigo = [];
$impuesto_adicional_tasa = [];
$impuesto_adicional_monto = [];
foreach ((array)$d['OtrosImp'] as $ia) {
$impuesto_adicional_codigo[] = $ia['CodImp'];
$impuesto_adicional_tasa[] = $ia['TasaImp'];
$impuesto_adicional_monto[] = $ia['MntImp'];
}
// armar detalle
$detalle[] = [
(int)$d['TpoDoc'],
(int)$d['NroDoc'],
$d['RUTDoc'],
(int)$d['TasaImp'],
$d['RznSoc'],
$d['TpoImp']!==false ? $d['TpoImp'] : 1,
$d['FchDoc'],
$d['Anulado']!==false ? $d['Anulado'] : null,
$d['MntExe']!==false ? $d['MntExe'] : null,
$d['MntNeto']!==false ? $d['MntNeto'] : null,
(int)$d['MntIVA'],
$iva_no_recuperable_codigo ? implode(',', $iva_no_recuperable_codigo) : null,
$iva_no_recuperable_monto ? implode(',', $iva_no_recuperable_monto) : null,
$d['IVAUsoComun']!==false ? $d['IVAUsoComun'] : null,
$impuesto_adicional_codigo ? implode(',', $impuesto_adicional_codigo) : null,
$impuesto_adicional_tasa ? implode(',', $impuesto_adicional_tasa) : null,
$impuesto_adicional_monto ? implode(',', $impuesto_adicional_monto) : null,
$d['MntSinCred']!==false ? $d['MntSinCred'] : null,
$d['MntActivoFijo']!==false ? $d['MntActivoFijo'] : null,
$d['MntIVAActivoFijo']!==false ? $d['MntIVAActivoFijo'] : null,
$d['IVANoRetenido']!==false ? $d['IVANoRetenido'] : null,
$d['TabPuros']!==false ? $d['TabPuros'] : null,
$d['TabCigarrillos']!==false ? $d['TabCigarrillos'] : null,
$d['TabElaborado']!==false ? $d['TabElaborado'] : null,
$d['ImpVehiculo']!==false ? $d['ImpVehiculo'] : null,
$d['CdgSIISucur']!==false ? $d['CdgSIISucur'] : null,
$d['NumInt']!==false ? $d['NumInt'] : null,
$d['Emisor']!==false ? $d['Emisor'] : null,
$d['MntTotal']!==false ? $d['MntTotal'] : null,
(isset($d['FctProp']) and $d['FctProp']!==false) ? $d['FctProp'] : null,
];
}
return $detalle;
} | php | public function getCompras()
{
$detalle = [];
foreach ($this->detalles as $d) {
// armar iva no recuperable
$iva_no_recuperable_codigo = [];
$iva_no_recuperable_monto = [];
foreach ((array)$d['IVANoRec'] as $inr) {
$iva_no_recuperable_codigo[] = $inr['CodIVANoRec'];
$iva_no_recuperable_monto[] = $inr['MntIVANoRec'];
}
// armar impuestos adicionales
$impuesto_adicional_codigo = [];
$impuesto_adicional_tasa = [];
$impuesto_adicional_monto = [];
foreach ((array)$d['OtrosImp'] as $ia) {
$impuesto_adicional_codigo[] = $ia['CodImp'];
$impuesto_adicional_tasa[] = $ia['TasaImp'];
$impuesto_adicional_monto[] = $ia['MntImp'];
}
// armar detalle
$detalle[] = [
(int)$d['TpoDoc'],
(int)$d['NroDoc'],
$d['RUTDoc'],
(int)$d['TasaImp'],
$d['RznSoc'],
$d['TpoImp']!==false ? $d['TpoImp'] : 1,
$d['FchDoc'],
$d['Anulado']!==false ? $d['Anulado'] : null,
$d['MntExe']!==false ? $d['MntExe'] : null,
$d['MntNeto']!==false ? $d['MntNeto'] : null,
(int)$d['MntIVA'],
$iva_no_recuperable_codigo ? implode(',', $iva_no_recuperable_codigo) : null,
$iva_no_recuperable_monto ? implode(',', $iva_no_recuperable_monto) : null,
$d['IVAUsoComun']!==false ? $d['IVAUsoComun'] : null,
$impuesto_adicional_codigo ? implode(',', $impuesto_adicional_codigo) : null,
$impuesto_adicional_tasa ? implode(',', $impuesto_adicional_tasa) : null,
$impuesto_adicional_monto ? implode(',', $impuesto_adicional_monto) : null,
$d['MntSinCred']!==false ? $d['MntSinCred'] : null,
$d['MntActivoFijo']!==false ? $d['MntActivoFijo'] : null,
$d['MntIVAActivoFijo']!==false ? $d['MntIVAActivoFijo'] : null,
$d['IVANoRetenido']!==false ? $d['IVANoRetenido'] : null,
$d['TabPuros']!==false ? $d['TabPuros'] : null,
$d['TabCigarrillos']!==false ? $d['TabCigarrillos'] : null,
$d['TabElaborado']!==false ? $d['TabElaborado'] : null,
$d['ImpVehiculo']!==false ? $d['ImpVehiculo'] : null,
$d['CdgSIISucur']!==false ? $d['CdgSIISucur'] : null,
$d['NumInt']!==false ? $d['NumInt'] : null,
$d['Emisor']!==false ? $d['Emisor'] : null,
$d['MntTotal']!==false ? $d['MntTotal'] : null,
(isset($d['FctProp']) and $d['FctProp']!==false) ? $d['FctProp'] : null,
];
}
return $detalle;
} | [
"public",
"function",
"getCompras",
"(",
")",
"{",
"$",
"detalle",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"detalles",
"as",
"$",
"d",
")",
"{",
"// armar iva no recuperable",
"$",
"iva_no_recuperable_codigo",
"=",
"[",
"]",
";",
"$",
"iva... | Método que obtiene los datos de las compras en el formato que se usa en
el archivo CSV
@return Arreglo con los datos de las compras
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-10-06 | [
"Método",
"que",
"obtiene",
"los",
"datos",
"de",
"las",
"compras",
"en",
"el",
"formato",
"que",
"se",
"usa",
"en",
"el",
"archivo",
"CSV"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/LibroCompraVenta.php#L781-L836 |
LibreDTE/libredte-lib | lib/Sii/ConsumoFolio.php | ConsumoFolio.setCaratula | public function setCaratula(array $caratula)
{
$this->caratula = array_merge([
'@attributes' => [
'version' => '1.0',
],
'RutEmisor' => false,
'RutEnvia' => isset($this->Firma) ? $this->Firma->getID() : false,
'FchResol' => false,
'NroResol' => false,
'FchInicio' => $this->getFechaEmisionInicial(),
'FchFinal' => $this->getFechaEmisionFinal(),
'Correlativo' => false,
'SecEnvio' => 1,
'TmstFirmaEnv' => date('Y-m-d\TH:i:s'),
], $caratula);
$this->id = 'LibreDTE_CONSUMO_FOLIO_'.str_replace('-', '', $this->caratula['RutEmisor']).'_'.str_replace('-', '', $this->caratula['FchInicio']).'_'.date('U');
} | php | public function setCaratula(array $caratula)
{
$this->caratula = array_merge([
'@attributes' => [
'version' => '1.0',
],
'RutEmisor' => false,
'RutEnvia' => isset($this->Firma) ? $this->Firma->getID() : false,
'FchResol' => false,
'NroResol' => false,
'FchInicio' => $this->getFechaEmisionInicial(),
'FchFinal' => $this->getFechaEmisionFinal(),
'Correlativo' => false,
'SecEnvio' => 1,
'TmstFirmaEnv' => date('Y-m-d\TH:i:s'),
], $caratula);
$this->id = 'LibreDTE_CONSUMO_FOLIO_'.str_replace('-', '', $this->caratula['RutEmisor']).'_'.str_replace('-', '', $this->caratula['FchInicio']).'_'.date('U');
} | [
"public",
"function",
"setCaratula",
"(",
"array",
"$",
"caratula",
")",
"{",
"$",
"this",
"->",
"caratula",
"=",
"array_merge",
"(",
"[",
"'@attributes'",
"=>",
"[",
"'version'",
"=>",
"'1.0'",
",",
"]",
",",
"'RutEmisor'",
"=>",
"false",
",",
"'RutEnvia'... | Método para asignar la caratula
@param caratula Arreglo con datos del envío: RutEnvia, FchResol y NroResol, etc
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-08-06 | [
"Método",
"para",
"asignar",
"la",
"caratula"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/ConsumoFolio.php#L65-L82 |
LibreDTE/libredte-lib | lib/Sii/ConsumoFolio.php | ConsumoFolio.generar | public function generar()
{
// si ya se había generado se entrega directamente
if ($this->xml_data)
return $this->xml_data;
// generar XML del envío
$xmlEnvio = (new \sasco\LibreDTE\XML())->generate([
'ConsumoFolios' => [
'@attributes' => [
'xmlns' => 'http://www.sii.cl/SiiDte',
'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
'xsi:schemaLocation' => 'http://www.sii.cl/SiiDte ConsumoFolio_v10.xsd',
'version' => '1.0',
],
'DocumentoConsumoFolios' => [
'@attributes' => [
'ID' => $this->id,
],
'Caratula' => $this->caratula,
'Resumen' => $this->getResumen(),
],
]
])->saveXML();
// firmar XML del envío y entregar
$this->xml_data = $this->Firma ? $this->Firma->signXML($xmlEnvio, '#'.$this->id, 'DocumentoConsumoFolios', true) : $xmlEnvio;
return $this->xml_data;
} | php | public function generar()
{
// si ya se había generado se entrega directamente
if ($this->xml_data)
return $this->xml_data;
// generar XML del envío
$xmlEnvio = (new \sasco\LibreDTE\XML())->generate([
'ConsumoFolios' => [
'@attributes' => [
'xmlns' => 'http://www.sii.cl/SiiDte',
'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
'xsi:schemaLocation' => 'http://www.sii.cl/SiiDte ConsumoFolio_v10.xsd',
'version' => '1.0',
],
'DocumentoConsumoFolios' => [
'@attributes' => [
'ID' => $this->id,
],
'Caratula' => $this->caratula,
'Resumen' => $this->getResumen(),
],
]
])->saveXML();
// firmar XML del envío y entregar
$this->xml_data = $this->Firma ? $this->Firma->signXML($xmlEnvio, '#'.$this->id, 'DocumentoConsumoFolios', true) : $xmlEnvio;
return $this->xml_data;
} | [
"public",
"function",
"generar",
"(",
")",
"{",
"// si ya se había generado se entrega directamente",
"if",
"(",
"$",
"this",
"->",
"xml_data",
")",
"return",
"$",
"this",
"->",
"xml_data",
";",
"// generar XML del envío",
"$",
"xmlEnvio",
"=",
"(",
"new",
"\\",
... | Método que genera el XML del consumo de folios para el envío al SII
@return XML con el envio del consumo de folios firmado o =false si no se pudo generar o firmar el envío
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-12-13 | [
"Método",
"que",
"genera",
"el",
"XML",
"del",
"consumo",
"de",
"folios",
"para",
"el",
"envío",
"al",
"SII"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/ConsumoFolio.php#L90-L116 |
LibreDTE/libredte-lib | lib/Sii/ConsumoFolio.php | ConsumoFolio.getFechaEmisionInicial | public function getFechaEmisionInicial()
{
$fecha = '9999-12-31';
foreach ($this->detalles as &$d) {
if ($d['FchDoc'] < $fecha)
$fecha = $d['FchDoc'];
}
return $fecha;
} | php | public function getFechaEmisionInicial()
{
$fecha = '9999-12-31';
foreach ($this->detalles as &$d) {
if ($d['FchDoc'] < $fecha)
$fecha = $d['FchDoc'];
}
return $fecha;
} | [
"public",
"function",
"getFechaEmisionInicial",
"(",
")",
"{",
"$",
"fecha",
"=",
"'9999-12-31'",
";",
"foreach",
"(",
"$",
"this",
"->",
"detalles",
"as",
"&",
"$",
"d",
")",
"{",
"if",
"(",
"$",
"d",
"[",
"'FchDoc'",
"]",
"<",
"$",
"fecha",
")",
... | Método que entrega la fecha del primer documento que se está reportando
@return Fecha del primer documento que se está reportando
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-12-13 | [
"Método",
"que",
"entrega",
"la",
"fecha",
"del",
"primer",
"documento",
"que",
"se",
"está",
"reportando"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/ConsumoFolio.php#L124-L132 |
LibreDTE/libredte-lib | lib/Sii/ConsumoFolio.php | ConsumoFolio.getFechaEmisionFinal | public function getFechaEmisionFinal()
{
$fecha = '0000-01-01';
foreach ($this->detalles as &$d) {
if ($d['FchDoc'] > $fecha)
$fecha = $d['FchDoc'];
}
return $fecha;
} | php | public function getFechaEmisionFinal()
{
$fecha = '0000-01-01';
foreach ($this->detalles as &$d) {
if ($d['FchDoc'] > $fecha)
$fecha = $d['FchDoc'];
}
return $fecha;
} | [
"public",
"function",
"getFechaEmisionFinal",
"(",
")",
"{",
"$",
"fecha",
"=",
"'0000-01-01'",
";",
"foreach",
"(",
"$",
"this",
"->",
"detalles",
"as",
"&",
"$",
"d",
")",
"{",
"if",
"(",
"$",
"d",
"[",
"'FchDoc'",
"]",
">",
"$",
"fecha",
")",
"$... | Método que entrega la fecha del último documento que se está reportando
@return Fecha del último documento que se está reportando
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-12-13 | [
"Método",
"que",
"entrega",
"la",
"fecha",
"del",
"último",
"documento",
"que",
"se",
"está",
"reportando"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/ConsumoFolio.php#L140-L148 |
LibreDTE/libredte-lib | lib/Sii/ConsumoFolio.php | ConsumoFolio.getResumen | private function getResumen()
{
// si hay detalles generar resumen
$Resumen = [];
$RangoUtilizados = [];
//$RangoAnulados = [];
foreach ($this->detalles as &$d) {
// si no existe el tipo de documento se utiliza
if (!isset($Resumen[$d['TpoDoc']])) {
$key = array_search($d['TpoDoc'], $this->documentos);
if ($key!==false) {
unset($this->documentos[$key]);
}
$Resumen[$d['TpoDoc']] = [
'TipoDocumento' => $d['TpoDoc'],
'MntNeto' => false,
'MntIva' => false,
'TasaIVA' => $d['TasaImp'] ? $d['TasaImp'] : false,
'MntExento' => false,
'MntTotal' => 0,
'FoliosEmitidos' => 0,
'FoliosAnulados' => 0,
'FoliosUtilizados' => false,
'RangoUtilizados' => false,
//'RangoAnulados' => false,
];
$RangoUtilizados[$d['TpoDoc']] = [];
//$RangoAnulados[$d['TpoDoc']] = [];
}
// ir agregando al resumen cada detalle
if ($d['MntNeto']) {
$Resumen[$d['TpoDoc']]['MntNeto'] += $d['MntNeto'];
$Resumen[$d['TpoDoc']]['MntIva'] += $d['MntIVA'];
}
if ($d['MntExe']) {
$Resumen[$d['TpoDoc']]['MntExento'] += $d['MntExe'];
}
$Resumen[$d['TpoDoc']]['MntTotal'] += $d['MntTotal'];
$Resumen[$d['TpoDoc']]['FoliosEmitidos']++;
// ir guardando folios emitidos para luego crear rangos
$RangoUtilizados[$d['TpoDoc']][] = $d['NroDoc'];
}
// ajustes post agregar detalles
foreach ($Resumen as &$r) {
// obtener folios utilizados = emitidos + anulados
$r['FoliosUtilizados'] = $r['FoliosEmitidos'] + $r['FoliosAnulados'];
$r['RangoUtilizados'] = $this->getRangos($RangoUtilizados[$r['TipoDocumento']]);
}
// completar con los resumenes que no se colocaron
foreach ($this->documentos as $tipo) {
$Resumen[$tipo] = [
'TipoDocumento' => $tipo,
'MntTotal' => 0,
'FoliosEmitidos' => 0,
'FoliosAnulados' => 0,
'FoliosUtilizados' => 0,
];
}
// entregar resumen
return $Resumen;
} | php | private function getResumen()
{
// si hay detalles generar resumen
$Resumen = [];
$RangoUtilizados = [];
//$RangoAnulados = [];
foreach ($this->detalles as &$d) {
// si no existe el tipo de documento se utiliza
if (!isset($Resumen[$d['TpoDoc']])) {
$key = array_search($d['TpoDoc'], $this->documentos);
if ($key!==false) {
unset($this->documentos[$key]);
}
$Resumen[$d['TpoDoc']] = [
'TipoDocumento' => $d['TpoDoc'],
'MntNeto' => false,
'MntIva' => false,
'TasaIVA' => $d['TasaImp'] ? $d['TasaImp'] : false,
'MntExento' => false,
'MntTotal' => 0,
'FoliosEmitidos' => 0,
'FoliosAnulados' => 0,
'FoliosUtilizados' => false,
'RangoUtilizados' => false,
//'RangoAnulados' => false,
];
$RangoUtilizados[$d['TpoDoc']] = [];
//$RangoAnulados[$d['TpoDoc']] = [];
}
// ir agregando al resumen cada detalle
if ($d['MntNeto']) {
$Resumen[$d['TpoDoc']]['MntNeto'] += $d['MntNeto'];
$Resumen[$d['TpoDoc']]['MntIva'] += $d['MntIVA'];
}
if ($d['MntExe']) {
$Resumen[$d['TpoDoc']]['MntExento'] += $d['MntExe'];
}
$Resumen[$d['TpoDoc']]['MntTotal'] += $d['MntTotal'];
$Resumen[$d['TpoDoc']]['FoliosEmitidos']++;
// ir guardando folios emitidos para luego crear rangos
$RangoUtilizados[$d['TpoDoc']][] = $d['NroDoc'];
}
// ajustes post agregar detalles
foreach ($Resumen as &$r) {
// obtener folios utilizados = emitidos + anulados
$r['FoliosUtilizados'] = $r['FoliosEmitidos'] + $r['FoliosAnulados'];
$r['RangoUtilizados'] = $this->getRangos($RangoUtilizados[$r['TipoDocumento']]);
}
// completar con los resumenes que no se colocaron
foreach ($this->documentos as $tipo) {
$Resumen[$tipo] = [
'TipoDocumento' => $tipo,
'MntTotal' => 0,
'FoliosEmitidos' => 0,
'FoliosAnulados' => 0,
'FoliosUtilizados' => 0,
];
}
// entregar resumen
return $Resumen;
} | [
"private",
"function",
"getResumen",
"(",
")",
"{",
"// si hay detalles generar resumen",
"$",
"Resumen",
"=",
"[",
"]",
";",
"$",
"RangoUtilizados",
"=",
"[",
"]",
";",
"//$RangoAnulados = [];",
"foreach",
"(",
"$",
"this",
"->",
"detalles",
"as",
"&",
"$",
... | Método que obtiene los datos para generar los tags de Resumen del
consumo de folios
@return Arreglo con los datos para generar los tags Resumen
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-02-14 | [
"Método",
"que",
"obtiene",
"los",
"datos",
"para",
"generar",
"los",
"tags",
"de",
"Resumen",
"del",
"consumo",
"de",
"folios"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/ConsumoFolio.php#L157-L217 |
LibreDTE/libredte-lib | lib/Sii/ConsumoFolio.php | ConsumoFolio.getRangos | private function getRangos($folios)
{
// crear auxiliar con los folios separados por rangos
sort($folios);
$aux = [];
$inicial = $folios[0];
$i = $inicial;
foreach($folios as $f) {
if ($i!=$f) {
$inicial = $f;
$i = $inicial;
}
$aux[$inicial][] = $f;
$i++;
}
// crear rangos
$rangos = [];
foreach ($aux as $folios) {
$rangos[] = [
'Inicial' => $folios[0],
'Final' => $folios[count($folios)-1],
];
}
return $rangos;
} | php | private function getRangos($folios)
{
// crear auxiliar con los folios separados por rangos
sort($folios);
$aux = [];
$inicial = $folios[0];
$i = $inicial;
foreach($folios as $f) {
if ($i!=$f) {
$inicial = $f;
$i = $inicial;
}
$aux[$inicial][] = $f;
$i++;
}
// crear rangos
$rangos = [];
foreach ($aux as $folios) {
$rangos[] = [
'Inicial' => $folios[0],
'Final' => $folios[count($folios)-1],
];
}
return $rangos;
} | [
"private",
"function",
"getRangos",
"(",
"$",
"folios",
")",
"{",
"// crear auxiliar con los folios separados por rangos",
"sort",
"(",
"$",
"folios",
")",
";",
"$",
"aux",
"=",
"[",
"]",
";",
"$",
"inicial",
"=",
"$",
"folios",
"[",
"0",
"]",
";",
"$",
... | Método que determina los rangos de los folios para el resumen del consumo
de folios
@param folios Arreglo con los folios que se deben generar sus rangos
@return Arreglo con cada uno de los rangos de folios
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-12-13 | [
"Método",
"que",
"determina",
"los",
"rangos",
"de",
"los",
"folios",
"para",
"el",
"resumen",
"del",
"consumo",
"de",
"folios"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/ConsumoFolio.php#L227-L251 |
LibreDTE/libredte-lib | lib/Chile.php | Chile.getCiudad | public static function getCiudad($comuna)
{
if (!$comuna)
return false;
$comuna = mb_strtoupper($comuna, 'UTF-8');
return isset(self::$ciudades[$comuna]) ? self::$ciudades[$comuna] : false;
} | php | public static function getCiudad($comuna)
{
if (!$comuna)
return false;
$comuna = mb_strtoupper($comuna, 'UTF-8');
return isset(self::$ciudades[$comuna]) ? self::$ciudades[$comuna] : false;
} | [
"public",
"static",
"function",
"getCiudad",
"(",
"$",
"comuna",
")",
"{",
"if",
"(",
"!",
"$",
"comuna",
")",
"return",
"false",
";",
"$",
"comuna",
"=",
"mb_strtoupper",
"(",
"$",
"comuna",
",",
"'UTF-8'",
")",
";",
"return",
"isset",
"(",
"self",
... | Método que entrega la dirección regional según la comuna que se esté
consultando
@param comuna de la sucursal del emior o bien código de la sucursal del SII
@return Dirección regional del SII
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-08-12 | [
"Método",
"que",
"entrega",
"la",
"dirección",
"regional",
"según",
"la",
"comuna",
"que",
"se",
"esté",
"consultando"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Chile.php#L54-L60 |
LibreDTE/libredte-lib | lib/XML.php | XML.generate | public function generate(array $data, array $namespace = null, \DOMElement &$parent = null)
{
if ($parent===null) {
$parent = &$this;
}
foreach ($data as $key => $value) {
if ($key=='@attributes') {
if ($value!==false) {
foreach ($value as $attr => $val) {
if ($val!==false) {
$parent->setAttribute($attr, $val);
}
}
}
} else if ($key=='@value') {
$parent->nodeValue = $this->sanitize($value);
} else {
if (is_array($value)) {
if (!empty($value)) {
$keys = array_keys($value);
if (!is_int($keys[0])) {
$value = [$value];
}
foreach ($value as $value2) {
if ($namespace) {
$Node = $this->createElementNS($namespace[0], $namespace[1].':'.$key);
} else {
$Node = $this->createElement($key);
}
$parent->appendChild($Node);
$this->generate($value2, $namespace, $Node);
}
}
} else {
if (is_object($value) and $value instanceof \DOMElement) {
$Node = $this->importNode($value, true);
$parent->appendChild($Node);
} else {
if ($value!==false) {
if ($namespace) {
$Node = $this->createElementNS($namespace[0], $namespace[1].':'.$key, $this->iso2utf($this->sanitize($value)));
} else {
$Node = $this->createElement($key, $this->iso2utf($this->sanitize($value)));
}
$parent->appendChild($Node);
}
}
}
}
}
return $this;
} | php | public function generate(array $data, array $namespace = null, \DOMElement &$parent = null)
{
if ($parent===null) {
$parent = &$this;
}
foreach ($data as $key => $value) {
if ($key=='@attributes') {
if ($value!==false) {
foreach ($value as $attr => $val) {
if ($val!==false) {
$parent->setAttribute($attr, $val);
}
}
}
} else if ($key=='@value') {
$parent->nodeValue = $this->sanitize($value);
} else {
if (is_array($value)) {
if (!empty($value)) {
$keys = array_keys($value);
if (!is_int($keys[0])) {
$value = [$value];
}
foreach ($value as $value2) {
if ($namespace) {
$Node = $this->createElementNS($namespace[0], $namespace[1].':'.$key);
} else {
$Node = $this->createElement($key);
}
$parent->appendChild($Node);
$this->generate($value2, $namespace, $Node);
}
}
} else {
if (is_object($value) and $value instanceof \DOMElement) {
$Node = $this->importNode($value, true);
$parent->appendChild($Node);
} else {
if ($value!==false) {
if ($namespace) {
$Node = $this->createElementNS($namespace[0], $namespace[1].':'.$key, $this->iso2utf($this->sanitize($value)));
} else {
$Node = $this->createElement($key, $this->iso2utf($this->sanitize($value)));
}
$parent->appendChild($Node);
}
}
}
}
}
return $this;
} | [
"public",
"function",
"generate",
"(",
"array",
"$",
"data",
",",
"array",
"$",
"namespace",
"=",
"null",
",",
"\\",
"DOMElement",
"&",
"$",
"parent",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"parent",
"===",
"null",
")",
"{",
"$",
"parent",
"=",
"&"... | Método que genera nodos XML a partir de un arreglo
@param data Arreglo con los datos que se usarán para generar XML
@param namespace Arreglo con el espacio de nombres para el XML que se generará (URI y prefijo)
@param parent DOMElement padre para los elementos, o =null para que sea la raíz
@return Objeto \sasco\LibreDTE\XML
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-10-22 | [
"Método",
"que",
"genera",
"nodos",
"XML",
"a",
"partir",
"de",
"un",
"arreglo"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/XML.php#L60-L111 |
LibreDTE/libredte-lib | lib/XML.php | XML.sanitize | private function sanitize($txt)
{
// si no se paso un texto o bien es un número no se hace nada
if (!$txt or is_numeric($txt))
return $txt;
// convertir "predefined entities" de XML
$txt = str_replace(
['&', '&', '<', '<', '>', '>', '"', '"', ''', '''],
['&', '&', '<', '<', '>', '>', '"', '"', '\'', '\''],
$txt
);
$txt = str_replace('&', '&', $txt);
/*$txt = str_replace(
['&', '"', '\''],
['&', '"', '''],
$txt
);*/
// entregar texto sanitizado
return $txt;
} | php | private function sanitize($txt)
{
// si no se paso un texto o bien es un número no se hace nada
if (!$txt or is_numeric($txt))
return $txt;
// convertir "predefined entities" de XML
$txt = str_replace(
['&', '&', '<', '<', '>', '>', '"', '"', ''', '''],
['&', '&', '<', '<', '>', '>', '"', '"', '\'', '\''],
$txt
);
$txt = str_replace('&', '&', $txt);
/*$txt = str_replace(
['&', '"', '\''],
['&', '"', '''],
$txt
);*/
// entregar texto sanitizado
return $txt;
} | [
"private",
"function",
"sanitize",
"(",
"$",
"txt",
")",
"{",
"// si no se paso un texto o bien es un número no se hace nada",
"if",
"(",
"!",
"$",
"txt",
"or",
"is_numeric",
"(",
"$",
"txt",
")",
")",
"return",
"$",
"txt",
";",
"// convertir \"predefined entities\"... | Método que sanitiza los valores que son asignados a los tags del XML
@param txt String que que se asignará como valor al nodo XML
@return String sanitizado
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-09-02 | [
"Método",
"que",
"sanitiza",
"los",
"valores",
"que",
"son",
"asignados",
"a",
"los",
"tags",
"del",
"XML"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/XML.php#L120-L139 |
LibreDTE/libredte-lib | lib/XML.php | XML.loadXML | public function loadXML($source, $options = null)
{
return $source ? parent::loadXML($this->iso2utf($source), $options) : false;
} | php | public function loadXML($source, $options = null)
{
return $source ? parent::loadXML($this->iso2utf($source), $options) : false;
} | [
"public",
"function",
"loadXML",
"(",
"$",
"source",
",",
"$",
"options",
"=",
"null",
")",
"{",
"return",
"$",
"source",
"?",
"parent",
"::",
"loadXML",
"(",
"$",
"this",
"->",
"iso2utf",
"(",
"$",
"source",
")",
",",
"$",
"options",
")",
":",
"fa... | Método que carga un string XML en el Objeto
@param source String con el documento XML a cargar
@param options Opciones para la carga del XML
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-11-21 | [
"Método",
"que",
"carga",
"un",
"string",
"XML",
"en",
"el",
"Objeto"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/XML.php#L148-L151 |
LibreDTE/libredte-lib | lib/XML.php | XML.getFlattened | public function getFlattened($xpath = null)
{
if ($xpath) {
$node = $this->xpath($xpath)->item(0);
if (!$node)
return false;
$xml = $this->utf2iso($node->C14N());
$xml = $this->fixEntities($xml);
} else {
$xml = $this->C14N();
}
$xml = preg_replace("/\>\n\s+\</", '><', $xml);
$xml = preg_replace("/\>\n\t+\</", '><', $xml);
$xml = preg_replace("/\>\n+\</", '><', $xml);
return trim($xml);
} | php | public function getFlattened($xpath = null)
{
if ($xpath) {
$node = $this->xpath($xpath)->item(0);
if (!$node)
return false;
$xml = $this->utf2iso($node->C14N());
$xml = $this->fixEntities($xml);
} else {
$xml = $this->C14N();
}
$xml = preg_replace("/\>\n\s+\</", '><', $xml);
$xml = preg_replace("/\>\n\t+\</", '><', $xml);
$xml = preg_replace("/\>\n+\</", '><', $xml);
return trim($xml);
} | [
"public",
"function",
"getFlattened",
"(",
"$",
"xpath",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"xpath",
")",
"{",
"$",
"node",
"=",
"$",
"this",
"->",
"xpath",
"(",
"$",
"xpath",
")",
"->",
"item",
"(",
"0",
")",
";",
"if",
"(",
"!",
"$",
"n... | Método que entrega el código XML aplanado y con la codificación que
corresponde
@param xpath XPath para consulta al XML y extraer sólo una parte
@return String con código XML aplanado
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-01-20 | [
"Método",
"que",
"entrega",
"el",
"código",
"XML",
"aplanado",
"y",
"con",
"la",
"codificación",
"que",
"corresponde"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/XML.php#L173-L188 |
LibreDTE/libredte-lib | lib/XML.php | XML.toArray | public function toArray(\DOMElement $dom = null, array &$array = null, $arregloNodos = false)
{
// determinar valores de parámetros
if (!$dom)
$dom = $this->documentElement;
if (!$dom)
return false;
if ($array===null)
$array = [$dom->tagName => null];
// agregar atributos del nodo
if ($dom->hasAttributes()) {
$array[$dom->tagName]['@attributes'] = [];
foreach ($dom->attributes as $attribute) {
$array[$dom->tagName]['@attributes'][$attribute->name] = $attribute->value;
}
}
// agregar nodos hijos
if ($dom->hasChildNodes()) {
foreach($dom->childNodes as $child) {
if ($child instanceof \DOMText) {
$textContent = trim($child->textContent);
if ($textContent!="") {
if ($dom->childNodes->length==1 and empty($array[$dom->tagName])) {
$array[$dom->tagName] = $textContent;
} else
$array[$dom->tagName]['@value'] = $textContent;
}
}
else if ($child instanceof \DOMElement) {
$nodos_gemelos = $this->countTwins($dom, $child->tagName);
if ($nodos_gemelos==1) {
if ($arregloNodos)
$this->toArray($child, $array);
else
$this->toArray($child, $array[$dom->tagName]);
}
// crear arreglo con nodos hijos que tienen el mismo nombre de tag
else {
if (!isset($array[$dom->tagName][$child->tagName]))
$array[$dom->tagName][$child->tagName] = [];
$siguiente = count($array[$dom->tagName][$child->tagName]);
$array[$dom->tagName][$child->tagName][$siguiente] = [];
$this->toArray($child, $array[$dom->tagName][$child->tagName][$siguiente], true);
}
}
}
}
// entregar arreglo
return $array;
} | php | public function toArray(\DOMElement $dom = null, array &$array = null, $arregloNodos = false)
{
// determinar valores de parámetros
if (!$dom)
$dom = $this->documentElement;
if (!$dom)
return false;
if ($array===null)
$array = [$dom->tagName => null];
// agregar atributos del nodo
if ($dom->hasAttributes()) {
$array[$dom->tagName]['@attributes'] = [];
foreach ($dom->attributes as $attribute) {
$array[$dom->tagName]['@attributes'][$attribute->name] = $attribute->value;
}
}
// agregar nodos hijos
if ($dom->hasChildNodes()) {
foreach($dom->childNodes as $child) {
if ($child instanceof \DOMText) {
$textContent = trim($child->textContent);
if ($textContent!="") {
if ($dom->childNodes->length==1 and empty($array[$dom->tagName])) {
$array[$dom->tagName] = $textContent;
} else
$array[$dom->tagName]['@value'] = $textContent;
}
}
else if ($child instanceof \DOMElement) {
$nodos_gemelos = $this->countTwins($dom, $child->tagName);
if ($nodos_gemelos==1) {
if ($arregloNodos)
$this->toArray($child, $array);
else
$this->toArray($child, $array[$dom->tagName]);
}
// crear arreglo con nodos hijos que tienen el mismo nombre de tag
else {
if (!isset($array[$dom->tagName][$child->tagName]))
$array[$dom->tagName][$child->tagName] = [];
$siguiente = count($array[$dom->tagName][$child->tagName]);
$array[$dom->tagName][$child->tagName][$siguiente] = [];
$this->toArray($child, $array[$dom->tagName][$child->tagName][$siguiente], true);
}
}
}
}
// entregar arreglo
return $array;
} | [
"public",
"function",
"toArray",
"(",
"\\",
"DOMElement",
"$",
"dom",
"=",
"null",
",",
"array",
"&",
"$",
"array",
"=",
"null",
",",
"$",
"arregloNodos",
"=",
"false",
")",
"{",
"// determinar valores de parámetros",
"if",
"(",
"!",
"$",
"dom",
")",
"$"... | Método que convierte el XML a un arreglo
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-06-11 | [
"Método",
"que",
"convierte",
"el",
"XML",
"a",
"un",
"arreglo"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/XML.php#L222-L271 |
LibreDTE/libredte-lib | lib/XML.php | XML.countTwins | private function countTwins(\DOMElement $dom, $tagName)
{
$twins = 0;
foreach ($dom->childNodes as $child) {
if ($child instanceof \DOMElement and $child->tagName==$tagName)
$twins++;
}
return $twins;
} | php | private function countTwins(\DOMElement $dom, $tagName)
{
$twins = 0;
foreach ($dom->childNodes as $child) {
if ($child instanceof \DOMElement and $child->tagName==$tagName)
$twins++;
}
return $twins;
} | [
"private",
"function",
"countTwins",
"(",
"\\",
"DOMElement",
"$",
"dom",
",",
"$",
"tagName",
")",
"{",
"$",
"twins",
"=",
"0",
";",
"foreach",
"(",
"$",
"dom",
"->",
"childNodes",
"as",
"$",
"child",
")",
"{",
"if",
"(",
"$",
"child",
"instanceof",... | Método que cuenta los nodos con el mismo nombre hijos deun DOMElement
No sirve usar: $dom->getElementsByTagName($tagName)->length ya que esto
entrega todos los nodos con el nombre, sean hijos, nietos, etc.
@return Cantidad de nodos hijos con el mismo nombre en el DOMElement
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-09-07 | [
"Método",
"que",
"cuenta",
"los",
"nodos",
"con",
"el",
"mismo",
"nombre",
"hijos",
"deun",
"DOMElement",
"No",
"sirve",
"usar",
":",
"$dom",
"-",
">",
"getElementsByTagName",
"(",
"$tagName",
")",
"-",
">",
"length",
"ya",
"que",
"esto",
"entrega",
"todos... | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/XML.php#L281-L289 |
LibreDTE/libredte-lib | lib/XML.php | XML.getSchema | public function getSchema()
{
$schemaLocation = $this->documentElement->getAttribute('xsi:schemaLocation');
if (!$schemaLocation or strpos($schemaLocation, ' ')===false)
return false;
list($uri, $xsd) = explode(' ', $schemaLocation);
return $xsd;
} | php | public function getSchema()
{
$schemaLocation = $this->documentElement->getAttribute('xsi:schemaLocation');
if (!$schemaLocation or strpos($schemaLocation, ' ')===false)
return false;
list($uri, $xsd) = explode(' ', $schemaLocation);
return $xsd;
} | [
"public",
"function",
"getSchema",
"(",
")",
"{",
"$",
"schemaLocation",
"=",
"$",
"this",
"->",
"documentElement",
"->",
"getAttribute",
"(",
"'xsi:schemaLocation'",
")",
";",
"if",
"(",
"!",
"$",
"schemaLocation",
"or",
"strpos",
"(",
"$",
"schemaLocation",
... | Método que entrega el nombre del archivo del schema del XML
@return Nombre del schema o bien =false si no se encontró
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-12-14 | [
"Método",
"que",
"entrega",
"el",
"nombre",
"del",
"archivo",
"del",
"schema",
"del",
"XML"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/XML.php#L321-L328 |
LibreDTE/libredte-lib | lib/XML.php | XML.saveXML | public function saveXML(\DOMNode $node = null, $options = null)
{
$xml = parent::saveXML($node, $options);
$xml = $this->fixEntities($xml);
return $xml;
} | php | public function saveXML(\DOMNode $node = null, $options = null)
{
$xml = parent::saveXML($node, $options);
$xml = $this->fixEntities($xml);
return $xml;
} | [
"public",
"function",
"saveXML",
"(",
"\\",
"DOMNode",
"$",
"node",
"=",
"null",
",",
"$",
"options",
"=",
"null",
")",
"{",
"$",
"xml",
"=",
"parent",
"::",
"saveXML",
"(",
"$",
"node",
",",
"$",
"options",
")",
";",
"$",
"xml",
"=",
"$",
"this"... | Wrapper para saveXML() y corregir entities
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-01-20 | [
"Wrapper",
"para",
"saveXML",
"()",
"y",
"corregir",
"entities"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/XML.php#L335-L340 |
LibreDTE/libredte-lib | lib/XML.php | XML.C14N | public function C14N($exclusive = null, $with_comments = null, array $xpath = null, array $ns_prefixes = null)
{
$xml = parent::C14N($exclusive, $with_comments, $xpath, $ns_prefixes);
$xml = $this->fixEntities($xml);
return $xml;
} | php | public function C14N($exclusive = null, $with_comments = null, array $xpath = null, array $ns_prefixes = null)
{
$xml = parent::C14N($exclusive, $with_comments, $xpath, $ns_prefixes);
$xml = $this->fixEntities($xml);
return $xml;
} | [
"public",
"function",
"C14N",
"(",
"$",
"exclusive",
"=",
"null",
",",
"$",
"with_comments",
"=",
"null",
",",
"array",
"$",
"xpath",
"=",
"null",
",",
"array",
"$",
"ns_prefixes",
"=",
"null",
")",
"{",
"$",
"xml",
"=",
"parent",
"::",
"C14N",
"(",
... | Wrapper para C14N() y corregir entities
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-01-20 | [
"Wrapper",
"para",
"C14N",
"()",
"y",
"corregir",
"entities"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/XML.php#L347-L352 |
LibreDTE/libredte-lib | lib/XML.php | XML.fixEntities | private function fixEntities($xml)
{
$newXML = '';
$n_letras = strlen($xml);
$convertir = false;
for ($i=0; $i<$n_letras; ++$i) {
if ($xml[$i]=='>')
$convertir = true;
if ($xml[$i]=='<')
$convertir = false;
if ($convertir) {
$l = $xml[$i]=='\'' ? ''' : ($xml[$i]=='"' ? '"' : $xml[$i]);
} else {
$l = $xml[$i];
}
$newXML .= $l;
}
return $newXML;
} | php | private function fixEntities($xml)
{
$newXML = '';
$n_letras = strlen($xml);
$convertir = false;
for ($i=0; $i<$n_letras; ++$i) {
if ($xml[$i]=='>')
$convertir = true;
if ($xml[$i]=='<')
$convertir = false;
if ($convertir) {
$l = $xml[$i]=='\'' ? ''' : ($xml[$i]=='"' ? '"' : $xml[$i]);
} else {
$l = $xml[$i];
}
$newXML .= $l;
}
return $newXML;
} | [
"private",
"function",
"fixEntities",
"(",
"$",
"xml",
")",
"{",
"$",
"newXML",
"=",
"''",
";",
"$",
"n_letras",
"=",
"strlen",
"(",
"$",
"xml",
")",
";",
"$",
"convertir",
"=",
"false",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
... | Método que corrige las entities ' (') y " (") ya que el SII no
respeta el estándar y las requiere convertidas
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-01-20 | [
"Método",
"que",
"corrige",
"las",
"entities",
"(",
"&apos",
";",
")",
"y",
"(",
""",
";",
")",
"ya",
"que",
"el",
"SII",
"no",
"respeta",
"el",
"estándar",
"y",
"las",
"requiere",
"convertidas"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/XML.php#L360-L378 |
LibreDTE/libredte-lib | lib/Log.php | Log.write | public static function write($code, $msg = null, $severity = LOG_ERR)
{
// si no existe la bitácora para la gravedad se crea
if (!isset(self::$bitacora[$severity]))
self::$bitacora[$severity] = [];
// si el código es un string se copia a msg
if (is_string($code)) {
$msg = $code;
$code = -1; // código de error genérico
}
// crear mensaje
$LogMsg = new LogMsg($code, $msg);
// agregar datos de quien llamó al método
if (self::$backtrace) {
$trace = debug_backtrace(!DEBUG_BACKTRACE_PROVIDE_OBJECT and !DEBUG_BACKTRACE_IGNORE_ARGS, 2);
$LogMsg->file = $trace[0]['file'];
$LogMsg->line = $trace[0]['line'];
$LogMsg->function = $trace[1]['function'];
$LogMsg->class = $trace[1]['class'];
$LogMsg->type = $trace[1]['type'];
$LogMsg->args = $trace[1]['args'];
}
// agregar mensaje a la bitácora
array_push(self::$bitacora[$severity], $LogMsg);
} | php | public static function write($code, $msg = null, $severity = LOG_ERR)
{
// si no existe la bitácora para la gravedad se crea
if (!isset(self::$bitacora[$severity]))
self::$bitacora[$severity] = [];
// si el código es un string se copia a msg
if (is_string($code)) {
$msg = $code;
$code = -1; // código de error genérico
}
// crear mensaje
$LogMsg = new LogMsg($code, $msg);
// agregar datos de quien llamó al método
if (self::$backtrace) {
$trace = debug_backtrace(!DEBUG_BACKTRACE_PROVIDE_OBJECT and !DEBUG_BACKTRACE_IGNORE_ARGS, 2);
$LogMsg->file = $trace[0]['file'];
$LogMsg->line = $trace[0]['line'];
$LogMsg->function = $trace[1]['function'];
$LogMsg->class = $trace[1]['class'];
$LogMsg->type = $trace[1]['type'];
$LogMsg->args = $trace[1]['args'];
}
// agregar mensaje a la bitácora
array_push(self::$bitacora[$severity], $LogMsg);
} | [
"public",
"static",
"function",
"write",
"(",
"$",
"code",
",",
"$",
"msg",
"=",
"null",
",",
"$",
"severity",
"=",
"LOG_ERR",
")",
"{",
"// si no existe la bitácora para la gravedad se crea",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"bitacora",
"[",... | Método que escribe un mensaje en la bitácora
@param code Código del mensaje que se desea escribir
@param msg Mensaje que se desea escribir
@param severity Gravedad del mensaje, por defecto LOG_ERR (puede ser cualquiera de las constantes PHP de syslog)
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-09-16 | [
"Método",
"que",
"escribe",
"un",
"mensaje",
"en",
"la",
"bitácora"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Log.php#L65-L89 |
LibreDTE/libredte-lib | lib/Log.php | Log.read | public static function read($severity = LOG_ERR)
{
if (!isset(self::$bitacora[$severity]))
return false;
return array_pop(self::$bitacora[$severity]);
} | php | public static function read($severity = LOG_ERR)
{
if (!isset(self::$bitacora[$severity]))
return false;
return array_pop(self::$bitacora[$severity]);
} | [
"public",
"static",
"function",
"read",
"(",
"$",
"severity",
"=",
"LOG_ERR",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"bitacora",
"[",
"$",
"severity",
"]",
")",
")",
"return",
"false",
";",
"return",
"array_pop",
"(",
"self",
"::"... | Método que recupera un mensaje de la bitácora y lo borra de la misma
@param severity Gravedad del mensaje, por defecto LOG_ERR (puede ser cualquiera de las constantes PHP de syslog)
@return Mensaje de la bitácora
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-09-14 | [
"Método",
"que",
"recupera",
"un",
"mensaje",
"de",
"la",
"bitácora",
"y",
"lo",
"borra",
"de",
"la",
"misma"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Log.php#L98-L103 |
LibreDTE/libredte-lib | lib/Log.php | Log.readAll | public static function readAll($severity = LOG_ERR, $new_first = true)
{
if (!isset(self::$bitacora[$severity]))
return [];
$bitacora = self::$bitacora[$severity];
if ($new_first)
krsort($bitacora);
self::$bitacora[$severity] = [];
return $bitacora;
} | php | public static function readAll($severity = LOG_ERR, $new_first = true)
{
if (!isset(self::$bitacora[$severity]))
return [];
$bitacora = self::$bitacora[$severity];
if ($new_first)
krsort($bitacora);
self::$bitacora[$severity] = [];
return $bitacora;
} | [
"public",
"static",
"function",
"readAll",
"(",
"$",
"severity",
"=",
"LOG_ERR",
",",
"$",
"new_first",
"=",
"true",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"bitacora",
"[",
"$",
"severity",
"]",
")",
")",
"return",
"[",
"]",
";"... | Método que recupera todos los mensajes de la bitácora y los borra de la misma
@param severity Gravedad del mensaje, por defecto LOG_ERR (puede ser cualquiera de las constantes PHP de syslog)
@param new_first =true ordenará los mensajes de la bitácora en orden descendente
@return Arreglo con toos los mensaje de la bitácora
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-09-14 | [
"Método",
"que",
"recupera",
"todos",
"los",
"mensajes",
"de",
"la",
"bitácora",
"y",
"los",
"borra",
"de",
"la",
"misma"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Log.php#L113-L122 |
LibreDTE/libredte-lib | lib/Sii/Certificacion/SetPruebas.php | SetPruebas.getJSON | public static function getJSON($archivo, array $folios = [], $separador = '==============')
{
$documentos = [];
$casos = self::parse($archivo, $separador);
$referencias = [];
foreach ($casos as $caso) {
// determinar tipo documento y folio
$TipoDTE = self::$tipos[$caso['documento']];
if (!isset($folios[$TipoDTE]))
$folios[$TipoDTE] = 1;
$Folio = $folios[$TipoDTE];
// crear encabezado del documento
$documento = [
'Encabezado' => [
'IdDoc' => [
'TipoDTE' => $TipoDTE,
'Folio' => $Folio
]
],
];
// si es guía de despacho se agrega indicador de traslado
if ($TipoDTE==52) {
if (isset($caso['traslado_por'])) {
$documento['Encabezado']['IdDoc']['TipoDespacho'] = self::$TipoDespachos[$caso['traslado_por']];
}
if (isset($caso['motivo'])) {
$documento['Encabezado']['IdDoc']['IndTraslado'] = self::$IndTraslados[$caso['motivo']];
}
}
// si es documento de exportación se agregan datos específicos para exportación
else if (in_array($TipoDTE, [110, 111, 112])) {
// si hay datos de exportación se agrega información de receptor más aduana
if (isset($caso['exportacion'])) {
// forma de pago
if (!empty($caso['exportacion']['FORMA DE PAGO EXPORTACION'])) {
$documento['Encabezado']['IdDoc']['FmaPagExp'] = self::$formas_pago_exportacion[$caso['exportacion']['FORMA DE PAGO EXPORTACION']];
unset($caso['exportacion']['FORMA DE PAGO EXPORTACION']);
}
// datos del receptor
if (!empty($caso['exportacion']['NACIONALIDAD'])) {
$documento['Encabezado']['Receptor']['Extranjero'] = [
'Nacionalidad' => \sasco\LibreDTE\Sii\Aduana::getCodigo(
self::$Aduana['PAIS RECEPTOR Y PAIS DESTINO'],
$caso['exportacion']['NACIONALIDAD']
),
];
unset($caso['exportacion']['NACIONALIDAD']);
}
// datos de la aduana
$documento['Encabezado']['Transporte']['Aduana'] = [];
foreach ($caso['exportacion'] as $var => $val) {
if (isset(self::$Aduana[$var])) {
$tag = self::$Aduana[$var];
$valor = \sasco\LibreDTE\Sii\Aduana::getCodigo($tag, $val);
$documento['Encabezado']['Transporte']['Aduana'][$tag] = $valor;
unset($caso['exportacion'][$var]);
}
}
if (!empty($documento['Encabezado']['Transporte']['Aduana']['CodPaisRecep'])) {
$documento['Encabezado']['Transporte']['Aduana']['CodPaisDestin'] = $documento['Encabezado']['Transporte']['Aduana']['CodPaisRecep'];
}
// si existe tipo de bultos entonces se crea
if (!empty($documento['Encabezado']['Transporte']['Aduana']['TipoBultos'])) {
$documento['Encabezado']['Transporte']['Aduana']['TipoBultos'] = [
'CodTpoBultos' => $documento['Encabezado']['Transporte']['Aduana']['TipoBultos'],
'CantBultos' => $documento['Encabezado']['Transporte']['Aduana']['TotBultos'],
'Marcas' => md5($documento['Encabezado']['Transporte']['Aduana']['TipoBultos'].$documento['Encabezado']['Transporte']['Aduana']['TotBultos']),
];
// si el bulto es contenedor entonces se colocan datos extras
if ($documento['Encabezado']['Transporte']['Aduana']['TipoBultos']['CodTpoBultos']==75) {
$documento['Encabezado']['Transporte']['Aduana']['TipoBultos']['IdContainer'] = 'ABC123';
$documento['Encabezado']['Transporte']['Aduana']['TipoBultos']['Sello'] = '10973348-2';
$documento['Encabezado']['Transporte']['Aduana']['TipoBultos']['EmisorSello'] = 'Sellos de Chile';
}
}
if (empty($documento['Encabezado']['Transporte']['Aduana'])) {
unset($documento['Encabezado']['Transporte']);
}
// agregar moneda a los totales
if (!empty($caso['exportacion']['MONEDA DE LA OPERACION'])) {
$documento['Encabezado']['Totales']['TpoMoneda'] = $caso['exportacion']['MONEDA DE LA OPERACION'];
unset($caso['exportacion']['MONEDA DE LA OPERACION']);
}
}
// agregar indicador de servicio
if (isset($caso['detalle'])) {
foreach ($caso['detalle'] as $item) {
if ($item['ITEM']=='ASESORIAS Y PROYECTOS PROFESIONALES') {
$documento['Encabezado']['IdDoc']['IndServicio'] = 3;
break;
} else if ($item['ITEM']=='ALOJAMIENTO HABITACIONES') {
$documento['Encabezado']['IdDoc']['IndServicio'] = 4;
break;
}
}
}
// agregar tipo de cambio para colocar el valor en CLP
$documento['Encabezado']['OtraMoneda'] = [
'TpoMoneda' => 'PESO CL',
'TpoCambio' => 500,
];
}
// agregar detalle del documento si fue pasado explícitamente
if (isset($caso['detalle'])) {
$documento['Detalle'] = [];
foreach ($caso['detalle'] as $item) {
// generar detalle del item
$detalle = [];
foreach ($item as $col => $val) {
$col = self::$item_cols[$col];
// procesar cada valor de acuerdo al nombre de la columna
if (in_array($col, ['DescuentoPct', 'RecargoPct']))
$detalle[$col] = substr($val, 0, -1);
else
$detalle[$col] = utf8_encode($val); // se convierte de ISO-8859-1 a UTF-8
}
// si el item es EXENTO se agrega campo que lo indica
if (strpos($detalle['NmbItem'], 'EXENTO'))
$detalle['IndExe'] = 1;
// si hay una referencia se completa con los campos del
// detalle de la referencia que no estén en este detalle
if (!empty($caso['referencia'])) {
// buscar el caso y copiar sus columnas que no estén
$detalle_r = $documentos[$caso['referencia']['caso']]['Detalle'];
$n_detalle_r = count($detalle_r);
for ($i=0; $i<$n_detalle_r; $i++) {
if ($detalle_r[$i]['NmbItem']==$detalle['NmbItem']) {
foreach ($detalle_r[$i] as $attr => $val) {
if (!isset($detalle[$attr]))
$detalle[$attr] = $val;
}
}
}
// si la referencia es a una factura exenta y existe un
// precio entonces se marca como exento el item
if ($documentos[$caso['referencia']['caso']]['Encabezado']['IdDoc']['TipoDTE']==34 and isset($detalle['PrcItem'])) {
$detalle['IndExe'] = 1;
}
}
// si es factura de compra se agrega código de retención
if ($TipoDTE==46) {
if (strpos($detalle['NmbItem'], 'PPA')) {
$detalle['CdgItem'] = 3900;
$detalle['Retenedor'] = true;
$detalle['CodImpAdic'] = 39;
} else {
$detalle['CodImpAdic'] = 15;
}
}
// agregar detalle del item a los detalles
$documento['Detalle'][] = $detalle;
}
}
// si no fue pasado explícitamente aun puede haber detalle: el de
// otro caso que se esté referenciando
else if (!empty($caso['referencia'])) {
$referencia = self::getReferencia($caso['referencia']['razon']);
// copiar todos los detalles
if ($referencia['detalle']==1) {
$documento['Detalle'] = $documentos[$caso['referencia']['caso']]['Detalle'];
}
// copiar sólo el nombre del primer item
else if ($referencia['detalle']==2) {
$documento['Detalle'] = [
[
'NmbItem' => $documentos[$caso['referencia']['caso']]['Detalle'][0]['NmbItem'],
]
];
}
}
// si es documento de exportación y es referencia, se copian los datos de transporte
if (in_array($TipoDTE, [111, 112]) and !empty($caso['referencia'])) {
$documento['Encabezado']['Transporte'] = $documentos[$caso['referencia']['caso']]['Encabezado']['Transporte'];
}
// agregar descuento del documento
$documento['DscRcgGlobal'] = [];
if (!empty($caso['descuento'])) {
$documento['DscRcgGlobal'][] = [
'TpoMov' => 'D',
'TpoValor' => '%',
'ValorDR' => substr($caso['descuento'], 0, -1),
];
}
// agregar recargo total clausula
if (!empty($caso['recargo-total-clausula'])) {
$documento['DscRcgGlobal'][] = [
'TpoMov' => 'R',
'TpoValor' => '$',
'ValorDR' => round((substr($caso['recargo-total-clausula'], 0, -1)/100) * $documento['Encabezado']['Transporte']['Aduana']['TotClauVenta'], 2),
];
}
// agregar recargo por flete y/o seguro, se agrega sólo en factura
// ya que las notas de crédito y débito de los SETs no consideran
// estos recargos
if ($documento['Encabezado']['IdDoc']['TipoDTE']==110) {
foreach (['MntFlete', 'MntSeguro'] as $recargo_aduana) {
if (!empty($documento['Encabezado']['Transporte']['Aduana'][$recargo_aduana])) {
$documento['DscRcgGlobal'][] = [
'TpoMov' => 'R',
'TpoValor' => '$',
'ValorDR' => $documento['Encabezado']['Transporte']['Aduana'][$recargo_aduana],
];
}
}
}
// agregar recargo del documento
if (!empty($caso['recargo'])) {
$documento['DscRcgGlobal'][] = [
'TpoMov' => 'R',
'TpoValor' => '%',
'ValorDR' => substr($caso['recargo'], 0, -1),
];
}
if (empty($documento['DscRcgGlobal']))
unset($documento['DscRcgGlobal']);
// agregar descuento del documento de la referencia
else if (!empty($caso['referencia'])) {
$referencia = self::getReferencia($caso['referencia']['razon']);
if ($referencia['codigo']===1 and isset($documentos[$caso['referencia']['caso']]['DscRcgGlobal'])) {
$documento['DscRcgGlobal'] = $documentos[$caso['referencia']['caso']]['DscRcgGlobal'];
}
}
// agregar referencia obligatoria
$documento['Referencia'] = [];
$documento['Referencia'][] = [
'TpoDocRef' => 'SET',
'FolioRef' => $folios[$TipoDTE],
'RazonRef' => 'CASO '.$caso['caso'],
];
// agregar referencias del caso
if (!empty($caso['referencia'])) {
$referencia = self::getReferencia($caso['referencia']['razon']);
// agregar referencia
$documento['Referencia'][] = [
'TpoDocRef' => $documentos[$caso['referencia']['caso']]['Encabezado']['IdDoc']['TipoDTE'],
'FolioRef' => $documentos[$caso['referencia']['caso']]['Encabezado']['IdDoc']['Folio'],
'CodRef' => $referencia['codigo'],
'RazonRef' => $caso['referencia']['razon'],
];
// si la referencia es corrige giro se asigna automáticamente la corrección
if (isset($documento['Referencia'][1]['RazonRef']) and strpos($documento['Referencia'][1]['RazonRef'], 'CORRIGE GIRO')===0) {
$documento['Detalle'][0]['NmbItem'] = 'DONDE DICE Servicios integrales de informática DEBE DECIR Informática';
}
// agregar totales
$documento['Encabezado']['Totales'] = $referencia['Totales'];
// agregar tasa de IVA si corresponde
if (isset($documento['Encabezado']['Totales']['TasaIVA']))
$documento['Encabezado']['Totales']['TasaIVA'] = \sasco\LibreDTE\Sii::getIVA();
// si el documento referenciado es factura exenta y hay MntExe
if (isset($documento['Encabezado']['Totales']['MntExe'])) {
if ($documentos[$caso['referencia']['caso']]['Encabezado']['IdDoc']['TipoDTE']==34)
$documento['Encabezado']['Totales']['MntExe'] = 0;
else
unset($documento['Encabezado']['Totales']['MntExe']);
}
// si es documento de exportación se resetean los totales y se copia el tipo de moneda si no existe
if (in_array($documento['Encabezado']['IdDoc']['TipoDTE'], [111, 112])) {
if (!empty($documento['Encabezado']['Totales']['TpoMoneda'])) {
$documento['Encabezado']['Totales'] = ['TpoMoneda'=>$documento['Encabezado']['Totales']['TpoMoneda']];
} else {
$documento['Encabezado']['Totales'] = ['TpoMoneda'=>$documentos[$caso['referencia']['caso']]['Encabezado']['Totales']['TpoMoneda']];
}
}
}
// agregar referencia de exportación si existe
if (!empty($caso['exportacion']['REFERENCIA'])) {
if (!is_array($caso['exportacion']['REFERENCIA']))
$caso['exportacion']['REFERENCIA'] = [$caso['exportacion']['REFERENCIA']];
foreach ($caso['exportacion']['REFERENCIA'] as $ref) {
$documento['Referencia'][] = [
'TpoDocRef' => self::$referencias_exportacion[$ref],
'FolioRef' => substr(md5($ref), 0, 18),
];
}
unset($caso['exportacion']['REFERENCIA']);
}
// si es servicio de hotelería se crea referencia para el pasaporte
if (isset($documento['Encabezado']['IdDoc']['IndServicio']) and $documento['Encabezado']['IdDoc']['IndServicio']==4) {
$documento['Referencia'][] = [
'TpoDocRef' => 813,
'FolioRef' => 'E12345',
];
}
// si hay Totales pero no hay valores en los detalles entonces se cambia a sólo Totales de MntTotal = 0
if (isset($documento['Encabezado']['Totales'])) {
$hayValor = false;
foreach ($documento['Detalle'] as $d) {
if (!empty($d['PrcItem']))
$hayValor = true;
}
if (!$hayValor) {
if (isset($documento['Encabezado']['Totales']['MntExe']))
$documento['Encabezado']['Totales'] = ['MntExe'=>0];
else
$documento['Encabezado']['Totales'] = [];
$documento['Encabezado']['Totales']['MntTotal'] = 0;
}
}
// agregar documento a los documentos
$documentos[$caso['caso']] = $documento;
// pasar al siguiente folio de este tipo;
$folios[$TipoDTE]++;
}
// pasar de índice "número de caso" a índice numérico, o sea
// pasar de diccionario o hash a arreglo antes convertir a JSON
$aux = $documentos;
$documentos = [];
foreach ($aux as $d) {
$documentos[] = $d;
}
// retornar documentos
return json_encode($documentos, JSON_PRETTY_PRINT);
} | php | public static function getJSON($archivo, array $folios = [], $separador = '==============')
{
$documentos = [];
$casos = self::parse($archivo, $separador);
$referencias = [];
foreach ($casos as $caso) {
// determinar tipo documento y folio
$TipoDTE = self::$tipos[$caso['documento']];
if (!isset($folios[$TipoDTE]))
$folios[$TipoDTE] = 1;
$Folio = $folios[$TipoDTE];
// crear encabezado del documento
$documento = [
'Encabezado' => [
'IdDoc' => [
'TipoDTE' => $TipoDTE,
'Folio' => $Folio
]
],
];
// si es guía de despacho se agrega indicador de traslado
if ($TipoDTE==52) {
if (isset($caso['traslado_por'])) {
$documento['Encabezado']['IdDoc']['TipoDespacho'] = self::$TipoDespachos[$caso['traslado_por']];
}
if (isset($caso['motivo'])) {
$documento['Encabezado']['IdDoc']['IndTraslado'] = self::$IndTraslados[$caso['motivo']];
}
}
// si es documento de exportación se agregan datos específicos para exportación
else if (in_array($TipoDTE, [110, 111, 112])) {
// si hay datos de exportación se agrega información de receptor más aduana
if (isset($caso['exportacion'])) {
// forma de pago
if (!empty($caso['exportacion']['FORMA DE PAGO EXPORTACION'])) {
$documento['Encabezado']['IdDoc']['FmaPagExp'] = self::$formas_pago_exportacion[$caso['exportacion']['FORMA DE PAGO EXPORTACION']];
unset($caso['exportacion']['FORMA DE PAGO EXPORTACION']);
}
// datos del receptor
if (!empty($caso['exportacion']['NACIONALIDAD'])) {
$documento['Encabezado']['Receptor']['Extranjero'] = [
'Nacionalidad' => \sasco\LibreDTE\Sii\Aduana::getCodigo(
self::$Aduana['PAIS RECEPTOR Y PAIS DESTINO'],
$caso['exportacion']['NACIONALIDAD']
),
];
unset($caso['exportacion']['NACIONALIDAD']);
}
// datos de la aduana
$documento['Encabezado']['Transporte']['Aduana'] = [];
foreach ($caso['exportacion'] as $var => $val) {
if (isset(self::$Aduana[$var])) {
$tag = self::$Aduana[$var];
$valor = \sasco\LibreDTE\Sii\Aduana::getCodigo($tag, $val);
$documento['Encabezado']['Transporte']['Aduana'][$tag] = $valor;
unset($caso['exportacion'][$var]);
}
}
if (!empty($documento['Encabezado']['Transporte']['Aduana']['CodPaisRecep'])) {
$documento['Encabezado']['Transporte']['Aduana']['CodPaisDestin'] = $documento['Encabezado']['Transporte']['Aduana']['CodPaisRecep'];
}
// si existe tipo de bultos entonces se crea
if (!empty($documento['Encabezado']['Transporte']['Aduana']['TipoBultos'])) {
$documento['Encabezado']['Transporte']['Aduana']['TipoBultos'] = [
'CodTpoBultos' => $documento['Encabezado']['Transporte']['Aduana']['TipoBultos'],
'CantBultos' => $documento['Encabezado']['Transporte']['Aduana']['TotBultos'],
'Marcas' => md5($documento['Encabezado']['Transporte']['Aduana']['TipoBultos'].$documento['Encabezado']['Transporte']['Aduana']['TotBultos']),
];
// si el bulto es contenedor entonces se colocan datos extras
if ($documento['Encabezado']['Transporte']['Aduana']['TipoBultos']['CodTpoBultos']==75) {
$documento['Encabezado']['Transporte']['Aduana']['TipoBultos']['IdContainer'] = 'ABC123';
$documento['Encabezado']['Transporte']['Aduana']['TipoBultos']['Sello'] = '10973348-2';
$documento['Encabezado']['Transporte']['Aduana']['TipoBultos']['EmisorSello'] = 'Sellos de Chile';
}
}
if (empty($documento['Encabezado']['Transporte']['Aduana'])) {
unset($documento['Encabezado']['Transporte']);
}
// agregar moneda a los totales
if (!empty($caso['exportacion']['MONEDA DE LA OPERACION'])) {
$documento['Encabezado']['Totales']['TpoMoneda'] = $caso['exportacion']['MONEDA DE LA OPERACION'];
unset($caso['exportacion']['MONEDA DE LA OPERACION']);
}
}
// agregar indicador de servicio
if (isset($caso['detalle'])) {
foreach ($caso['detalle'] as $item) {
if ($item['ITEM']=='ASESORIAS Y PROYECTOS PROFESIONALES') {
$documento['Encabezado']['IdDoc']['IndServicio'] = 3;
break;
} else if ($item['ITEM']=='ALOJAMIENTO HABITACIONES') {
$documento['Encabezado']['IdDoc']['IndServicio'] = 4;
break;
}
}
}
// agregar tipo de cambio para colocar el valor en CLP
$documento['Encabezado']['OtraMoneda'] = [
'TpoMoneda' => 'PESO CL',
'TpoCambio' => 500,
];
}
// agregar detalle del documento si fue pasado explícitamente
if (isset($caso['detalle'])) {
$documento['Detalle'] = [];
foreach ($caso['detalle'] as $item) {
// generar detalle del item
$detalle = [];
foreach ($item as $col => $val) {
$col = self::$item_cols[$col];
// procesar cada valor de acuerdo al nombre de la columna
if (in_array($col, ['DescuentoPct', 'RecargoPct']))
$detalle[$col] = substr($val, 0, -1);
else
$detalle[$col] = utf8_encode($val); // se convierte de ISO-8859-1 a UTF-8
}
// si el item es EXENTO se agrega campo que lo indica
if (strpos($detalle['NmbItem'], 'EXENTO'))
$detalle['IndExe'] = 1;
// si hay una referencia se completa con los campos del
// detalle de la referencia que no estén en este detalle
if (!empty($caso['referencia'])) {
// buscar el caso y copiar sus columnas que no estén
$detalle_r = $documentos[$caso['referencia']['caso']]['Detalle'];
$n_detalle_r = count($detalle_r);
for ($i=0; $i<$n_detalle_r; $i++) {
if ($detalle_r[$i]['NmbItem']==$detalle['NmbItem']) {
foreach ($detalle_r[$i] as $attr => $val) {
if (!isset($detalle[$attr]))
$detalle[$attr] = $val;
}
}
}
// si la referencia es a una factura exenta y existe un
// precio entonces se marca como exento el item
if ($documentos[$caso['referencia']['caso']]['Encabezado']['IdDoc']['TipoDTE']==34 and isset($detalle['PrcItem'])) {
$detalle['IndExe'] = 1;
}
}
// si es factura de compra se agrega código de retención
if ($TipoDTE==46) {
if (strpos($detalle['NmbItem'], 'PPA')) {
$detalle['CdgItem'] = 3900;
$detalle['Retenedor'] = true;
$detalle['CodImpAdic'] = 39;
} else {
$detalle['CodImpAdic'] = 15;
}
}
// agregar detalle del item a los detalles
$documento['Detalle'][] = $detalle;
}
}
// si no fue pasado explícitamente aun puede haber detalle: el de
// otro caso que se esté referenciando
else if (!empty($caso['referencia'])) {
$referencia = self::getReferencia($caso['referencia']['razon']);
// copiar todos los detalles
if ($referencia['detalle']==1) {
$documento['Detalle'] = $documentos[$caso['referencia']['caso']]['Detalle'];
}
// copiar sólo el nombre del primer item
else if ($referencia['detalle']==2) {
$documento['Detalle'] = [
[
'NmbItem' => $documentos[$caso['referencia']['caso']]['Detalle'][0]['NmbItem'],
]
];
}
}
// si es documento de exportación y es referencia, se copian los datos de transporte
if (in_array($TipoDTE, [111, 112]) and !empty($caso['referencia'])) {
$documento['Encabezado']['Transporte'] = $documentos[$caso['referencia']['caso']]['Encabezado']['Transporte'];
}
// agregar descuento del documento
$documento['DscRcgGlobal'] = [];
if (!empty($caso['descuento'])) {
$documento['DscRcgGlobal'][] = [
'TpoMov' => 'D',
'TpoValor' => '%',
'ValorDR' => substr($caso['descuento'], 0, -1),
];
}
// agregar recargo total clausula
if (!empty($caso['recargo-total-clausula'])) {
$documento['DscRcgGlobal'][] = [
'TpoMov' => 'R',
'TpoValor' => '$',
'ValorDR' => round((substr($caso['recargo-total-clausula'], 0, -1)/100) * $documento['Encabezado']['Transporte']['Aduana']['TotClauVenta'], 2),
];
}
// agregar recargo por flete y/o seguro, se agrega sólo en factura
// ya que las notas de crédito y débito de los SETs no consideran
// estos recargos
if ($documento['Encabezado']['IdDoc']['TipoDTE']==110) {
foreach (['MntFlete', 'MntSeguro'] as $recargo_aduana) {
if (!empty($documento['Encabezado']['Transporte']['Aduana'][$recargo_aduana])) {
$documento['DscRcgGlobal'][] = [
'TpoMov' => 'R',
'TpoValor' => '$',
'ValorDR' => $documento['Encabezado']['Transporte']['Aduana'][$recargo_aduana],
];
}
}
}
// agregar recargo del documento
if (!empty($caso['recargo'])) {
$documento['DscRcgGlobal'][] = [
'TpoMov' => 'R',
'TpoValor' => '%',
'ValorDR' => substr($caso['recargo'], 0, -1),
];
}
if (empty($documento['DscRcgGlobal']))
unset($documento['DscRcgGlobal']);
// agregar descuento del documento de la referencia
else if (!empty($caso['referencia'])) {
$referencia = self::getReferencia($caso['referencia']['razon']);
if ($referencia['codigo']===1 and isset($documentos[$caso['referencia']['caso']]['DscRcgGlobal'])) {
$documento['DscRcgGlobal'] = $documentos[$caso['referencia']['caso']]['DscRcgGlobal'];
}
}
// agregar referencia obligatoria
$documento['Referencia'] = [];
$documento['Referencia'][] = [
'TpoDocRef' => 'SET',
'FolioRef' => $folios[$TipoDTE],
'RazonRef' => 'CASO '.$caso['caso'],
];
// agregar referencias del caso
if (!empty($caso['referencia'])) {
$referencia = self::getReferencia($caso['referencia']['razon']);
// agregar referencia
$documento['Referencia'][] = [
'TpoDocRef' => $documentos[$caso['referencia']['caso']]['Encabezado']['IdDoc']['TipoDTE'],
'FolioRef' => $documentos[$caso['referencia']['caso']]['Encabezado']['IdDoc']['Folio'],
'CodRef' => $referencia['codigo'],
'RazonRef' => $caso['referencia']['razon'],
];
// si la referencia es corrige giro se asigna automáticamente la corrección
if (isset($documento['Referencia'][1]['RazonRef']) and strpos($documento['Referencia'][1]['RazonRef'], 'CORRIGE GIRO')===0) {
$documento['Detalle'][0]['NmbItem'] = 'DONDE DICE Servicios integrales de informática DEBE DECIR Informática';
}
// agregar totales
$documento['Encabezado']['Totales'] = $referencia['Totales'];
// agregar tasa de IVA si corresponde
if (isset($documento['Encabezado']['Totales']['TasaIVA']))
$documento['Encabezado']['Totales']['TasaIVA'] = \sasco\LibreDTE\Sii::getIVA();
// si el documento referenciado es factura exenta y hay MntExe
if (isset($documento['Encabezado']['Totales']['MntExe'])) {
if ($documentos[$caso['referencia']['caso']]['Encabezado']['IdDoc']['TipoDTE']==34)
$documento['Encabezado']['Totales']['MntExe'] = 0;
else
unset($documento['Encabezado']['Totales']['MntExe']);
}
// si es documento de exportación se resetean los totales y se copia el tipo de moneda si no existe
if (in_array($documento['Encabezado']['IdDoc']['TipoDTE'], [111, 112])) {
if (!empty($documento['Encabezado']['Totales']['TpoMoneda'])) {
$documento['Encabezado']['Totales'] = ['TpoMoneda'=>$documento['Encabezado']['Totales']['TpoMoneda']];
} else {
$documento['Encabezado']['Totales'] = ['TpoMoneda'=>$documentos[$caso['referencia']['caso']]['Encabezado']['Totales']['TpoMoneda']];
}
}
}
// agregar referencia de exportación si existe
if (!empty($caso['exportacion']['REFERENCIA'])) {
if (!is_array($caso['exportacion']['REFERENCIA']))
$caso['exportacion']['REFERENCIA'] = [$caso['exportacion']['REFERENCIA']];
foreach ($caso['exportacion']['REFERENCIA'] as $ref) {
$documento['Referencia'][] = [
'TpoDocRef' => self::$referencias_exportacion[$ref],
'FolioRef' => substr(md5($ref), 0, 18),
];
}
unset($caso['exportacion']['REFERENCIA']);
}
// si es servicio de hotelería se crea referencia para el pasaporte
if (isset($documento['Encabezado']['IdDoc']['IndServicio']) and $documento['Encabezado']['IdDoc']['IndServicio']==4) {
$documento['Referencia'][] = [
'TpoDocRef' => 813,
'FolioRef' => 'E12345',
];
}
// si hay Totales pero no hay valores en los detalles entonces se cambia a sólo Totales de MntTotal = 0
if (isset($documento['Encabezado']['Totales'])) {
$hayValor = false;
foreach ($documento['Detalle'] as $d) {
if (!empty($d['PrcItem']))
$hayValor = true;
}
if (!$hayValor) {
if (isset($documento['Encabezado']['Totales']['MntExe']))
$documento['Encabezado']['Totales'] = ['MntExe'=>0];
else
$documento['Encabezado']['Totales'] = [];
$documento['Encabezado']['Totales']['MntTotal'] = 0;
}
}
// agregar documento a los documentos
$documentos[$caso['caso']] = $documento;
// pasar al siguiente folio de este tipo;
$folios[$TipoDTE]++;
}
// pasar de índice "número de caso" a índice numérico, o sea
// pasar de diccionario o hash a arreglo antes convertir a JSON
$aux = $documentos;
$documentos = [];
foreach ($aux as $d) {
$documentos[] = $d;
}
// retornar documentos
return json_encode($documentos, JSON_PRETTY_PRINT);
} | [
"public",
"static",
"function",
"getJSON",
"(",
"$",
"archivo",
",",
"array",
"$",
"folios",
"=",
"[",
"]",
",",
"$",
"separador",
"=",
"'=============='",
")",
"{",
"$",
"documentos",
"=",
"[",
"]",
";",
"$",
"casos",
"=",
"self",
"::",
"parse",
"("... | Método que procesa el arreglo con los datos del set de pruebas y crea el
arreglo json con los documentos listos para ser pasados a la clase Dte
@param archivo Contenido del archivo del set de set de pruebas
@param separador usado en el archivo para los casos (son los "=" debajo del título del caso)
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-11-04 | [
"Método",
"que",
"procesa",
"el",
"arreglo",
"con",
"los",
"datos",
"del",
"set",
"de",
"pruebas",
"y",
"crea",
"el",
"arreglo",
"json",
"con",
"los",
"documentos",
"listos",
"para",
"ser",
"pasados",
"a",
"la",
"clase",
"Dte"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Certificacion/SetPruebas.php#L149-L461 |
LibreDTE/libredte-lib | lib/Sii/Certificacion/SetPruebas.php | SetPruebas.parse | private static function parse($archivo, $separador)
{
// obtener cada caso en un arreglo con su título
$casos = explode($separador, $archivo);
$separador_len = strlen($separador);
$n_casos = count($casos);
for ($i=1; $i<$n_casos; $i++) {
$caso = trim($casos[$i]);
$caso_anterior = trim($casos[$i-1]);
$caso_titulo = substr($caso_anterior, -$separador_len);
$casos[$i] = $caso_titulo."\n".$caso;
$casos[$i-1] = trim(str_replace($caso_titulo, '', $caso_anterior));
}
array_shift($casos);
// casos
$set_pruebas = [];
foreach ($casos as $caso) {
$lineas = array_map('trim', explode("\n", $caso));
$datos = [];
// obtener número de caso
$aux = explode(' ', $lineas[0]);
$datos['caso'] = array_pop($aux);
// obtener tipo de documento
$aux = explode("\t", $lineas[1]);
$datos['documento'] = array_pop($aux);
// procesar datos antes de detalle si es guía de despacho
if ($datos['documento']=='GUIA DE DESPACHO') {
$aux = explode("\t", $lineas[2]);
$datos['motivo'] = array_pop($aux);
// si hay contenido en línea 4 entonces hay TRASLADO POR
if (!empty($lineas[3])) {
$aux = explode("\t", $lineas[3]);
$datos['traslado_por'] = array_pop($aux);
$linea_titulos_detalles = 5;
} else {
$linea_titulos_detalles = 4;
}
}
// si no es guía de despacho entonces obtener referencia si existe
// (si hay línea 3 con contenido entonces hay una referencia)
else {
if (!empty($lineas[2])) {
$aux = explode("\t", $lineas[2]);
$referencia = array_pop($aux);
$aux = explode(' ', $referencia);
$caso_referencia = array_pop($aux);
$aux = explode("\t", $lineas[3]);
$razon = array_pop($aux);
$datos['referencia'] = [
'caso' => $caso_referencia,
'razon' => $razon,
];
$linea_titulos_detalles = 5;
} else {
$linea_titulos_detalles = 3;
}
}
// sólo continuar si hay más líneas, ya que serán detalles
if (isset($lineas[$linea_titulos_detalles])) {
// extraer titulos de detalles
$titulos = array_slice(array_filter(explode("\t", $lineas[$linea_titulos_detalles])), 0);
// extraer detalles
$datos['detalle'] = [];
$i = $linea_titulos_detalles + 1;
while (!empty($lineas[$i])) {
$item = array_slice(array_filter(explode("\t", $lineas[$i])), 0);
$n_item = count($item);
$detalle = [];
foreach ($titulos as $key => $titulo) {
$detalle[$titulo] = trim($item[$key]);
}
$datos['detalle'][] = $detalle;
$i++;
}
// sólo continuar si hay más líneas, será, por ej, el descuento global
if (isset($lineas[$i])) {
$n_lineas = count($lineas);
for ($i=$i; $i<$n_lineas; $i++) {
// si la línea está vacía se omite
if (!$lineas[$i])
continue;
// si hay descuento global se guarda
if (strpos($lineas[$i], 'DESCUENTO GLOBAL ITEMES AFECTOS')===0) {
$aux = explode("\t", $lineas[$i]);
$datos['descuento'] = trim(array_pop($aux));
}
// si es factura de exportación las líneas podrían ser los datos de la factura
if ($datos['documento']=='FACTURA DE EXPORTACION ELECTRONICA') {
// recargo en item formato %VAL TIPO
if ($lineas[$i][0]=='%') {
if (strpos($lineas[$i], 'RECARGO EN LA LINEA DE ITEM')) {
$recargo = +substr($lineas[$i], 1, strpos($lineas[$i], ' ')-1);
foreach ($datos['detalle'] as &$d) {
$d['RECARGO ITEM'] = $recargo.'%';
}
}
}
// datos de exportación formato VAR:VAL
else {
$aux = explode(':', $lineas[$i]);
$val = trim(array_pop($aux));
//$var = strtolower(str_replace(' ', '_', trim(array_pop($aux), " \t\n\r\0\x0B(*)")));
$var = trim(array_pop($aux));
// comisión en extranjero, recargo global
if ($var=='COMISIONES EN EL EXTRANJERO (RECARGOS GLOBALES)') {
if (strpos($val, 'DEL TOTAL DE LA CLAUSULA')) {
$datos['recargo-total-clausula'] = substr($val, 0, strpos($val, '%')+1);
}
}
// descuento en alguna línea de detalle
else if (strpos($var, 'DESCUENTO LINEA #')===0) {
$linea = (int)substr($var, strpos($var, '#')+1);
$datos['detalle'][$linea-1]['DESCUENTO ITEM'] = $val;
}
// agregar a los datos de aduanas
else {
if (!isset($datos['exportacion']))
$datos['exportacion'] = [];
if (!isset($datos['exportacion'][$var])) {
$datos['exportacion'][$var] = $val;
} else {
if (!is_array($datos['exportacion'][$var]))
$datos['exportacion'][$var] = [$datos['exportacion'][$var]];
$datos['exportacion'][$var][] = $val;
}
}
}
}
}
}
}
$set_pruebas[$datos['caso']] = $datos;
}
// entregar datos set de prueba
return $set_pruebas;
} | php | private static function parse($archivo, $separador)
{
// obtener cada caso en un arreglo con su título
$casos = explode($separador, $archivo);
$separador_len = strlen($separador);
$n_casos = count($casos);
for ($i=1; $i<$n_casos; $i++) {
$caso = trim($casos[$i]);
$caso_anterior = trim($casos[$i-1]);
$caso_titulo = substr($caso_anterior, -$separador_len);
$casos[$i] = $caso_titulo."\n".$caso;
$casos[$i-1] = trim(str_replace($caso_titulo, '', $caso_anterior));
}
array_shift($casos);
// casos
$set_pruebas = [];
foreach ($casos as $caso) {
$lineas = array_map('trim', explode("\n", $caso));
$datos = [];
// obtener número de caso
$aux = explode(' ', $lineas[0]);
$datos['caso'] = array_pop($aux);
// obtener tipo de documento
$aux = explode("\t", $lineas[1]);
$datos['documento'] = array_pop($aux);
// procesar datos antes de detalle si es guía de despacho
if ($datos['documento']=='GUIA DE DESPACHO') {
$aux = explode("\t", $lineas[2]);
$datos['motivo'] = array_pop($aux);
// si hay contenido en línea 4 entonces hay TRASLADO POR
if (!empty($lineas[3])) {
$aux = explode("\t", $lineas[3]);
$datos['traslado_por'] = array_pop($aux);
$linea_titulos_detalles = 5;
} else {
$linea_titulos_detalles = 4;
}
}
// si no es guía de despacho entonces obtener referencia si existe
// (si hay línea 3 con contenido entonces hay una referencia)
else {
if (!empty($lineas[2])) {
$aux = explode("\t", $lineas[2]);
$referencia = array_pop($aux);
$aux = explode(' ', $referencia);
$caso_referencia = array_pop($aux);
$aux = explode("\t", $lineas[3]);
$razon = array_pop($aux);
$datos['referencia'] = [
'caso' => $caso_referencia,
'razon' => $razon,
];
$linea_titulos_detalles = 5;
} else {
$linea_titulos_detalles = 3;
}
}
// sólo continuar si hay más líneas, ya que serán detalles
if (isset($lineas[$linea_titulos_detalles])) {
// extraer titulos de detalles
$titulos = array_slice(array_filter(explode("\t", $lineas[$linea_titulos_detalles])), 0);
// extraer detalles
$datos['detalle'] = [];
$i = $linea_titulos_detalles + 1;
while (!empty($lineas[$i])) {
$item = array_slice(array_filter(explode("\t", $lineas[$i])), 0);
$n_item = count($item);
$detalle = [];
foreach ($titulos as $key => $titulo) {
$detalle[$titulo] = trim($item[$key]);
}
$datos['detalle'][] = $detalle;
$i++;
}
// sólo continuar si hay más líneas, será, por ej, el descuento global
if (isset($lineas[$i])) {
$n_lineas = count($lineas);
for ($i=$i; $i<$n_lineas; $i++) {
// si la línea está vacía se omite
if (!$lineas[$i])
continue;
// si hay descuento global se guarda
if (strpos($lineas[$i], 'DESCUENTO GLOBAL ITEMES AFECTOS')===0) {
$aux = explode("\t", $lineas[$i]);
$datos['descuento'] = trim(array_pop($aux));
}
// si es factura de exportación las líneas podrían ser los datos de la factura
if ($datos['documento']=='FACTURA DE EXPORTACION ELECTRONICA') {
// recargo en item formato %VAL TIPO
if ($lineas[$i][0]=='%') {
if (strpos($lineas[$i], 'RECARGO EN LA LINEA DE ITEM')) {
$recargo = +substr($lineas[$i], 1, strpos($lineas[$i], ' ')-1);
foreach ($datos['detalle'] as &$d) {
$d['RECARGO ITEM'] = $recargo.'%';
}
}
}
// datos de exportación formato VAR:VAL
else {
$aux = explode(':', $lineas[$i]);
$val = trim(array_pop($aux));
//$var = strtolower(str_replace(' ', '_', trim(array_pop($aux), " \t\n\r\0\x0B(*)")));
$var = trim(array_pop($aux));
// comisión en extranjero, recargo global
if ($var=='COMISIONES EN EL EXTRANJERO (RECARGOS GLOBALES)') {
if (strpos($val, 'DEL TOTAL DE LA CLAUSULA')) {
$datos['recargo-total-clausula'] = substr($val, 0, strpos($val, '%')+1);
}
}
// descuento en alguna línea de detalle
else if (strpos($var, 'DESCUENTO LINEA #')===0) {
$linea = (int)substr($var, strpos($var, '#')+1);
$datos['detalle'][$linea-1]['DESCUENTO ITEM'] = $val;
}
// agregar a los datos de aduanas
else {
if (!isset($datos['exportacion']))
$datos['exportacion'] = [];
if (!isset($datos['exportacion'][$var])) {
$datos['exportacion'][$var] = $val;
} else {
if (!is_array($datos['exportacion'][$var]))
$datos['exportacion'][$var] = [$datos['exportacion'][$var]];
$datos['exportacion'][$var][] = $val;
}
}
}
}
}
}
}
$set_pruebas[$datos['caso']] = $datos;
}
// entregar datos set de prueba
return $set_pruebas;
} | [
"private",
"static",
"function",
"parse",
"(",
"$",
"archivo",
",",
"$",
"separador",
")",
"{",
"// obtener cada caso en un arreglo con su título",
"$",
"casos",
"=",
"explode",
"(",
"$",
"separador",
",",
"$",
"archivo",
")",
";",
"$",
"separador_len",
"=",
"... | Método que procesa el contenido de la archivo y entrega un arreglo con
cada uno de los casos procesados (tipo de documento, referencias, detalle
y otros, como descuentos globales)
@param archivo Contenido del archivo del set de set de pruebas
@param separador usado en el archivo para los casos (son los "=" debajo del título del caso)
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-04-04 | [
"Método",
"que",
"procesa",
"el",
"contenido",
"de",
"la",
"archivo",
"y",
"entrega",
"un",
"arreglo",
"con",
"cada",
"uno",
"de",
"los",
"casos",
"procesados",
"(",
"tipo",
"de",
"documento",
"referencias",
"detalle",
"y",
"otros",
"como",
"descuentos",
"gl... | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Certificacion/SetPruebas.php#L472-L607 |
LibreDTE/libredte-lib | lib/Sii/Certificacion/SetPruebas.php | SetPruebas.getReferencia | private static function getReferencia($razon)
{
list($razon, $null) = explode(' ', $razon, 2);
return self::$referencias[strtoupper(trim($razon))];
} | php | private static function getReferencia($razon)
{
list($razon, $null) = explode(' ', $razon, 2);
return self::$referencias[strtoupper(trim($razon))];
} | [
"private",
"static",
"function",
"getReferencia",
"(",
"$",
"razon",
")",
"{",
"list",
"(",
"$",
"razon",
",",
"$",
"null",
")",
"=",
"explode",
"(",
"' '",
",",
"$",
"razon",
",",
"2",
")",
";",
"return",
"self",
"::",
"$",
"referencias",
"[",
"st... | Método que recupera los datos para crear la referencia del documento
@param razon Raón de la referencia con texto al inicio: ANULA, DEVOLUCON O CORRIGE
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-09-13 | [
"Método",
"que",
"recupera",
"los",
"datos",
"para",
"crear",
"la",
"referencia",
"del",
"documento"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Certificacion/SetPruebas.php#L615-L619 |
LibreDTE/libredte-lib | bin/share/Command.php | Command.args_get | private function args_get()
{
$default = [];
foreach ($this->config['args'] as $arg => $info) {
if (isset($info['default']))
$default[str_replace(':', '', $arg)] = $info['default'];
}
$this->args = array_merge(
$default, getopt('h', array_keys($this->config['args']))
);
} | php | private function args_get()
{
$default = [];
foreach ($this->config['args'] as $arg => $info) {
if (isset($info['default']))
$default[str_replace(':', '', $arg)] = $info['default'];
}
$this->args = array_merge(
$default, getopt('h', array_keys($this->config['args']))
);
} | [
"private",
"function",
"args_get",
"(",
")",
"{",
"$",
"default",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"config",
"[",
"'args'",
"]",
"as",
"$",
"arg",
"=>",
"$",
"info",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"info",
"[",
"'d... | Método que recupera los argumentos pasados al comando
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-12-15 | [
"Método",
"que",
"recupera",
"los",
"argumentos",
"pasados",
"al",
"comando"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/bin/share/Command.php#L55-L65 |
LibreDTE/libredte-lib | bin/share/Command.php | Command.usemode | protected function usemode()
{
echo 'Opciones del comando:',"\n";
foreach ($this->config['args'] as $arg => $info) {
printf(" --%s\n %s\n", str_replace(':', '', $arg), $info['description']);
}
} | php | protected function usemode()
{
echo 'Opciones del comando:',"\n";
foreach ($this->config['args'] as $arg => $info) {
printf(" --%s\n %s\n", str_replace(':', '', $arg), $info['description']);
}
} | [
"protected",
"function",
"usemode",
"(",
")",
"{",
"echo",
"'Opciones del comando:'",
",",
"\"\\n\"",
";",
"foreach",
"(",
"$",
"this",
"->",
"config",
"[",
"'args'",
"]",
"as",
"$",
"arg",
"=>",
"$",
"info",
")",
"{",
"printf",
"(",
"\" --%s\\n %s\\n\... | Método que muestra el modo de uso del comando
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-07-06 | [
"Método",
"que",
"muestra",
"el",
"modo",
"de",
"uso",
"del",
"comando"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/bin/share/Command.php#L94-L100 |
LibreDTE/libredte-lib | lib/Sii/ImpuestosAdicionales.php | ImpuestosAdicionales.getTipo | public static function getTipo($codigo)
{
if (isset(self::$impuestos[$codigo]))
return self::$impuestos[$codigo]['tipo'];
return false;
} | php | public static function getTipo($codigo)
{
if (isset(self::$impuestos[$codigo]))
return self::$impuestos[$codigo]['tipo'];
return false;
} | [
"public",
"static",
"function",
"getTipo",
"(",
"$",
"codigo",
")",
"{",
"if",
"(",
"isset",
"(",
"self",
"::",
"$",
"impuestos",
"[",
"$",
"codigo",
"]",
")",
")",
"return",
"self",
"::",
"$",
"impuestos",
"[",
"$",
"codigo",
"]",
"[",
"'tipo'",
"... | Indica si el impuesto es adicional o retención
@return A: adicional, R: retención y =false no se pudo determinar
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-03-03 | [
"Indica",
"si",
"el",
"impuesto",
"es",
"adicional",
"o",
"retención"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/ImpuestosAdicionales.php#L168-L173 |
LibreDTE/libredte-lib | lib/Sii/ImpuestosAdicionales.php | ImpuestosAdicionales.getGlosa | public static function getGlosa($codigo)
{
if (isset(self::$impuestos[$codigo]))
return self::$impuestos[$codigo]['glosa'];
return 'Impto. cód. '.$codigo;
} | php | public static function getGlosa($codigo)
{
if (isset(self::$impuestos[$codigo]))
return self::$impuestos[$codigo]['glosa'];
return 'Impto. cód. '.$codigo;
} | [
"public",
"static",
"function",
"getGlosa",
"(",
"$",
"codigo",
")",
"{",
"if",
"(",
"isset",
"(",
"self",
"::",
"$",
"impuestos",
"[",
"$",
"codigo",
"]",
")",
")",
"return",
"self",
"::",
"$",
"impuestos",
"[",
"$",
"codigo",
"]",
"[",
"'glosa'",
... | Entrega la glosa del impuesto adicional
@return Glosa del impuesto o glosa estándar si no se encontró una
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-03-03 | [
"Entrega",
"la",
"glosa",
"del",
"impuesto",
"adicional"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/ImpuestosAdicionales.php#L181-L186 |
LibreDTE/libredte-lib | lib/Sii/ImpuestosAdicionales.php | ImpuestosAdicionales.getTasa | public static function getTasa($codigo)
{
if (isset(self::$impuestos[$codigo]['tasa']))
return self::$impuestos[$codigo]['tasa'];
return false;
} | php | public static function getTasa($codigo)
{
if (isset(self::$impuestos[$codigo]['tasa']))
return self::$impuestos[$codigo]['tasa'];
return false;
} | [
"public",
"static",
"function",
"getTasa",
"(",
"$",
"codigo",
")",
"{",
"if",
"(",
"isset",
"(",
"self",
"::",
"$",
"impuestos",
"[",
"$",
"codigo",
"]",
"[",
"'tasa'",
"]",
")",
")",
"return",
"self",
"::",
"$",
"impuestos",
"[",
"$",
"codigo",
"... | Entrega la pasa del impuesto adicional
@return Tasa del impuesto o =false si no se pudo determinar
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-03-19 | [
"Entrega",
"la",
"pasa",
"del",
"impuesto",
"adicional"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/ImpuestosAdicionales.php#L194-L199 |
LibreDTE/libredte-lib | lib/Sii/ImpuestosAdicionales.php | ImpuestosAdicionales.getRetenido | public static function getRetenido($OtrosImp)
{
$retenido = 0;
foreach ($OtrosImp as $Imp) {
if (self::getTipo($Imp['CodImp'])=='R') {
$retenido += $Imp['MntImp'];
}
}
return $retenido;
} | php | public static function getRetenido($OtrosImp)
{
$retenido = 0;
foreach ($OtrosImp as $Imp) {
if (self::getTipo($Imp['CodImp'])=='R') {
$retenido += $Imp['MntImp'];
}
}
return $retenido;
} | [
"public",
"static",
"function",
"getRetenido",
"(",
"$",
"OtrosImp",
")",
"{",
"$",
"retenido",
"=",
"0",
";",
"foreach",
"(",
"$",
"OtrosImp",
"as",
"$",
"Imp",
")",
"{",
"if",
"(",
"self",
"::",
"getTipo",
"(",
"$",
"Imp",
"[",
"'CodImp'",
"]",
"... | Método que entrega el monto de impuesto retenido a partir de la
información del tag OtrosImp del DTE
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-03-03 | [
"Método",
"que",
"entrega",
"el",
"monto",
"de",
"impuesto",
"retenido",
"a",
"partir",
"de",
"la",
"información",
"del",
"tag",
"OtrosImp",
"del",
"DTE"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/ImpuestosAdicionales.php#L207-L216 |
LibreDTE/libredte-lib | lib/Sii/Aduana.php | Aduana.getGlosa | public static function getGlosa($tag)
{
if (!isset(self::$tablas[$tag]))
return false;
return is_array(self::$tablas[$tag]) ? self::$tablas[$tag]['glosa'] : self::$tablas[$tag];
} | php | public static function getGlosa($tag)
{
if (!isset(self::$tablas[$tag]))
return false;
return is_array(self::$tablas[$tag]) ? self::$tablas[$tag]['glosa'] : self::$tablas[$tag];
} | [
"public",
"static",
"function",
"getGlosa",
"(",
"$",
"tag",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"tablas",
"[",
"$",
"tag",
"]",
")",
")",
"return",
"false",
";",
"return",
"is_array",
"(",
"self",
"::",
"$",
"tablas",
"[",
... | Entrega la glosa para el campo en la tabla
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-04-05 | [
"Entrega",
"la",
"glosa",
"para",
"el",
"campo",
"en",
"la",
"tabla"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Aduana.php#L814-L819 |
LibreDTE/libredte-lib | lib/Sii/Aduana.php | Aduana.getValor | public static function getValor($tag, $codigo)
{
if (!isset(self::$tablas[$tag]))
return false;
if (!is_array(self::$tablas[$tag]))
return $codigo;
$tabla = isset(self::$tablas[$tag]['valor']) ? self::$tablas[$tag]['valor'] : self::$tablas[self::$tablas[$tag]['tabla']];
if ($tag=='TipoBultos') {
$valor = isset($tabla[$codigo['CodTpoBultos']]) ? $tabla[$codigo['CodTpoBultos']] : $codigo['CodTpoBultos'];
$valor = $codigo['CantBultos'].' '.$valor;
if (!empty($codigo['IdContainer'])) {
$valor .= ' ('.$codigo['IdContainer'].' / '.$codigo['Sello'].' / '.$codigo['EmisorSello'].')';
} else if (!empty($codigo['Marcas'])) {
$valor .= ' ('.$codigo['Marcas'].')';
}
} else {
$valor = isset($tabla[$codigo]) ? $tabla[$codigo] : $codigo;
}
return $valor;
} | php | public static function getValor($tag, $codigo)
{
if (!isset(self::$tablas[$tag]))
return false;
if (!is_array(self::$tablas[$tag]))
return $codigo;
$tabla = isset(self::$tablas[$tag]['valor']) ? self::$tablas[$tag]['valor'] : self::$tablas[self::$tablas[$tag]['tabla']];
if ($tag=='TipoBultos') {
$valor = isset($tabla[$codigo['CodTpoBultos']]) ? $tabla[$codigo['CodTpoBultos']] : $codigo['CodTpoBultos'];
$valor = $codigo['CantBultos'].' '.$valor;
if (!empty($codigo['IdContainer'])) {
$valor .= ' ('.$codigo['IdContainer'].' / '.$codigo['Sello'].' / '.$codigo['EmisorSello'].')';
} else if (!empty($codigo['Marcas'])) {
$valor .= ' ('.$codigo['Marcas'].')';
}
} else {
$valor = isset($tabla[$codigo]) ? $tabla[$codigo] : $codigo;
}
return $valor;
} | [
"public",
"static",
"function",
"getValor",
"(",
"$",
"tag",
",",
"$",
"codigo",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"tablas",
"[",
"$",
"tag",
"]",
")",
")",
"return",
"false",
";",
"if",
"(",
"!",
"is_array",
"(",
"self",... | Entrega el valor traducido a partir de la tabla
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-07-27 | [
"Entrega",
"el",
"valor",
"traducido",
"a",
"partir",
"de",
"la",
"tabla"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Aduana.php#L826-L845 |
LibreDTE/libredte-lib | lib/Sii/Aduana.php | Aduana.getCodigo | public static function getCodigo($tag, $valor)
{
if (self::$tablasInvertidas===null) {
self::$tablasInvertidas = self::getTablasInvertidas();
}
$valor = strtoupper($valor);
return isset(self::$tablasInvertidas[$tag][$valor]) ? self::$tablasInvertidas[$tag][$valor] : $valor;
} | php | public static function getCodigo($tag, $valor)
{
if (self::$tablasInvertidas===null) {
self::$tablasInvertidas = self::getTablasInvertidas();
}
$valor = strtoupper($valor);
return isset(self::$tablasInvertidas[$tag][$valor]) ? self::$tablasInvertidas[$tag][$valor] : $valor;
} | [
"public",
"static",
"function",
"getCodigo",
"(",
"$",
"tag",
",",
"$",
"valor",
")",
"{",
"if",
"(",
"self",
"::",
"$",
"tablasInvertidas",
"===",
"null",
")",
"{",
"self",
"::",
"$",
"tablasInvertidas",
"=",
"self",
"::",
"getTablasInvertidas",
"(",
")... | Método que entrega a partir de su valor (texto) el código que corresponde
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-07-26 | [
"Método",
"que",
"entrega",
"a",
"partir",
"de",
"su",
"valor",
"(",
"texto",
")",
"el",
"código",
"que",
"corresponde"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Aduana.php#L852-L859 |
LibreDTE/libredte-lib | lib/Sii/Aduana.php | Aduana.getTablasInvertidas | private static function getTablasInvertidas()
{
self::$tablasInvertidas = [];
foreach (self::$tablas as $tag => $info) {
if (is_string($info) or (!isset($info['valor']) and !isset($info['tabla'])))
continue;
$tabla = isset($info['valor']) ? $info['valor'] : self::$tablas[$info['tabla']];
foreach ($tabla as &$val) {
$val = str_replace(
['Á', 'É', 'Í', 'Ó', 'Ú', 'Ñ', 'á', 'é', 'í', 'ó', 'ú', 'ñ'],
['A', 'E', 'I', 'O', 'U', 'N', 'a', 'e', 'i', 'o', 'u', 'n'],
$val
);
$val = strtoupper($val);
}
self::$tablasInvertidas[$tag] = array_flip($tabla);
}
return self::$tablasInvertidas;
} | php | private static function getTablasInvertidas()
{
self::$tablasInvertidas = [];
foreach (self::$tablas as $tag => $info) {
if (is_string($info) or (!isset($info['valor']) and !isset($info['tabla'])))
continue;
$tabla = isset($info['valor']) ? $info['valor'] : self::$tablas[$info['tabla']];
foreach ($tabla as &$val) {
$val = str_replace(
['Á', 'É', 'Í', 'Ó', 'Ú', 'Ñ', 'á', 'é', 'í', 'ó', 'ú', 'ñ'],
['A', 'E', 'I', 'O', 'U', 'N', 'a', 'e', 'i', 'o', 'u', 'n'],
$val
);
$val = strtoupper($val);
}
self::$tablasInvertidas[$tag] = array_flip($tabla);
}
return self::$tablasInvertidas;
} | [
"private",
"static",
"function",
"getTablasInvertidas",
"(",
")",
"{",
"self",
"::",
"$",
"tablasInvertidas",
"=",
"[",
"]",
";",
"foreach",
"(",
"self",
"::",
"$",
"tablas",
"as",
"$",
"tag",
"=>",
"$",
"info",
")",
"{",
"if",
"(",
"is_string",
"(",
... | Método que crea las tablas invertidas en memoria para poder hacer más
rápidas las búsquedas.
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-07-06 | [
"Método",
"que",
"crea",
"las",
"tablas",
"invertidas",
"en",
"memoria",
"para",
"poder",
"hacer",
"más",
"rápidas",
"las",
"búsquedas",
"."
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Aduana.php#L867-L885 |
LibreDTE/libredte-lib | lib/Sii/Aduana.php | Aduana.getNacionalidad | public static function getNacionalidad($codigo)
{
return isset(self::$tablas['paises'][$codigo]) ? self::$tablas['paises'][$codigo] : $codigo;
} | php | public static function getNacionalidad($codigo)
{
return isset(self::$tablas['paises'][$codigo]) ? self::$tablas['paises'][$codigo] : $codigo;
} | [
"public",
"static",
"function",
"getNacionalidad",
"(",
"$",
"codigo",
")",
"{",
"return",
"isset",
"(",
"self",
"::",
"$",
"tablas",
"[",
"'paises'",
"]",
"[",
"$",
"codigo",
"]",
")",
"?",
"self",
"::",
"$",
"tablas",
"[",
"'paises'",
"]",
"[",
"$"... | Método que entrega la glosa de la nacionalidad a partir de su código
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-07-29 | [
"Método",
"que",
"entrega",
"la",
"glosa",
"de",
"la",
"nacionalidad",
"a",
"partir",
"de",
"su",
"código"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Aduana.php#L902-L905 |
LibreDTE/libredte-lib | lib/Sii/Autenticacion.php | Autenticacion.getSeed | private static function getSeed()
{
$xml = \sasco\LibreDTE\Sii::request('CrSeed', 'getSeed');
if ($xml===false or (string)$xml->xpath('/SII:RESPUESTA/SII:RESP_HDR/ESTADO')[0]!=='00') {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::AUTH_ERROR_SEMILLA,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::AUTH_ERROR_SEMILLA)
);
return false;
}
return (string)$xml->xpath('/SII:RESPUESTA/SII:RESP_BODY/SEMILLA')[0];
} | php | private static function getSeed()
{
$xml = \sasco\LibreDTE\Sii::request('CrSeed', 'getSeed');
if ($xml===false or (string)$xml->xpath('/SII:RESPUESTA/SII:RESP_HDR/ESTADO')[0]!=='00') {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::AUTH_ERROR_SEMILLA,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::AUTH_ERROR_SEMILLA)
);
return false;
}
return (string)$xml->xpath('/SII:RESPUESTA/SII:RESP_BODY/SEMILLA')[0];
} | [
"private",
"static",
"function",
"getSeed",
"(",
")",
"{",
"$",
"xml",
"=",
"\\",
"sasco",
"\\",
"LibreDTE",
"\\",
"Sii",
"::",
"request",
"(",
"'CrSeed'",
",",
"'getSeed'",
")",
";",
"if",
"(",
"$",
"xml",
"===",
"false",
"or",
"(",
"string",
")",
... | Método para solicitar la semilla para la autenticación automática.
Nota: la semilla tiene una validez de 2 minutos.
WSDL producción: https://palena.sii.cl/DTEWS/CrSeed.jws?WSDL
WSDL certificación: https://maullin.sii.cl/DTEWS/CrSeed.jws?WSDL
@return Semilla obtenida desde SII
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-09-17 | [
"Método",
"para",
"solicitar",
"la",
"semilla",
"para",
"la",
"autenticación",
"automática",
".",
"Nota",
":",
"la",
"semilla",
"tiene",
"una",
"validez",
"de",
"2",
"minutos",
"."
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Autenticacion.php#L64-L75 |
LibreDTE/libredte-lib | lib/Sii/Autenticacion.php | Autenticacion.getTokenRequest | private static function getTokenRequest($seed, $Firma = [])
{
if (is_array($Firma))
$Firma = new \sasco\LibreDTE\FirmaElectronica($Firma);
$seedSigned = $Firma->signXML(
(new \sasco\LibreDTE\XML())->generate([
'getToken' => [
'item' => [
'Semilla' => $seed
]
]
])->saveXML()
);
if (!$seedSigned) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::AUTH_ERROR_FIRMA_SOLICITUD_TOKEN,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::AUTH_ERROR_FIRMA_SOLICITUD_TOKEN)
);
return false;
}
return $seedSigned;
} | php | private static function getTokenRequest($seed, $Firma = [])
{
if (is_array($Firma))
$Firma = new \sasco\LibreDTE\FirmaElectronica($Firma);
$seedSigned = $Firma->signXML(
(new \sasco\LibreDTE\XML())->generate([
'getToken' => [
'item' => [
'Semilla' => $seed
]
]
])->saveXML()
);
if (!$seedSigned) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::AUTH_ERROR_FIRMA_SOLICITUD_TOKEN,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::AUTH_ERROR_FIRMA_SOLICITUD_TOKEN)
);
return false;
}
return $seedSigned;
} | [
"private",
"static",
"function",
"getTokenRequest",
"(",
"$",
"seed",
",",
"$",
"Firma",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"Firma",
")",
")",
"$",
"Firma",
"=",
"new",
"\\",
"sasco",
"\\",
"LibreDTE",
"\\",
"FirmaElectronica",
... | Método que firma una semilla previamente obtenida
@param seed Semilla obtenida desde SII
@param Firma objeto de la Firma electrónica o arreglo con configuración de la misma
@return Solicitud de token con la semilla incorporada y firmada
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-09-17 | [
"Método",
"que",
"firma",
"una",
"semilla",
"previamente",
"obtenida"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Autenticacion.php#L85-L106 |
LibreDTE/libredte-lib | lib/Sii/Autenticacion.php | Autenticacion.getToken | public static function getToken($Firma = [])
{
if (!$Firma) return false;
$semilla = self::getSeed();
if (!$semilla) return false;
$requestFirmado = self::getTokenRequest($semilla, $Firma);
if (!$requestFirmado) return false;
$xml = \sasco\LibreDTE\Sii::request('GetTokenFromSeed', 'getToken', $requestFirmado);
if ($xml===false or (string)$xml->xpath('/SII:RESPUESTA/SII:RESP_HDR/ESTADO')[0]!=='00') {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::AUTH_ERROR_TOKEN,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::AUTH_ERROR_TOKEN)
);
return false;
}
return (string)$xml->xpath('/SII:RESPUESTA/SII:RESP_BODY/TOKEN')[0];
} | php | public static function getToken($Firma = [])
{
if (!$Firma) return false;
$semilla = self::getSeed();
if (!$semilla) return false;
$requestFirmado = self::getTokenRequest($semilla, $Firma);
if (!$requestFirmado) return false;
$xml = \sasco\LibreDTE\Sii::request('GetTokenFromSeed', 'getToken', $requestFirmado);
if ($xml===false or (string)$xml->xpath('/SII:RESPUESTA/SII:RESP_HDR/ESTADO')[0]!=='00') {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::AUTH_ERROR_TOKEN,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::AUTH_ERROR_TOKEN)
);
return false;
}
return (string)$xml->xpath('/SII:RESPUESTA/SII:RESP_BODY/TOKEN')[0];
} | [
"public",
"static",
"function",
"getToken",
"(",
"$",
"Firma",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"$",
"Firma",
")",
"return",
"false",
";",
"$",
"semilla",
"=",
"self",
"::",
"getSeed",
"(",
")",
";",
"if",
"(",
"!",
"$",
"semilla",
")",
... | Método para obtener el token de la sesión a través de una semilla
previamente firmada
WSDL producción: https://palena.sii.cl/DTEWS/GetTokenFromSeed.jws?WSDL
WSDL certificación: https://maullin.sii.cl/DTEWS/GetTokenFromSeed.jws?WSDL
@param Firma objeto de la Firma electrónica o arreglo con configuración de la misma
@return Token para autenticación en SII o =false si no se pudo obtener
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-11-03 | [
"Método",
"para",
"obtener",
"el",
"token",
"de",
"la",
"sesión",
"a",
"través",
"de",
"una",
"semilla",
"previamente",
"firmada"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Autenticacion.php#L120-L136 |
LibreDTE/libredte-lib | lib/Sii/Factoring/Cesion.php | Cesion.setCedente | public function setCedente(array $cedente = [])
{
$this->datos['Cesion']['DocumentoCesion']['Cedente'] = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
'RUT' => $this->Encabezado['Emisor']['RUTEmisor'],
'RazonSocial' => $this->Encabezado['Emisor']['RznSoc'],
'Direccion' => $this->Encabezado['Emisor']['DirOrigen'].', '.$this->Encabezado['Emisor']['CmnaOrigen'],
'eMail' => !empty($this->Encabezado['Emisor']['CorreoEmisor']) ? $this->Encabezado['Emisor']['CorreoEmisor'] : false,
'RUTAutorizado' => [
'RUT' => false,
'Nombre' => false,
],
'DeclaracionJurada' => false,
], $cedente);
if (!$this->datos['Cesion']['DocumentoCesion']['Cedente']['DeclaracionJurada']) {
$this->datos['Cesion']['DocumentoCesion']['Cedente']['DeclaracionJurada'] = mb_substr(str_replace(
[
'{usuario_nombre}',
'{usuario_run}',
'{emisor_razon_social}',
'{emisor_rut}',
'{cesionario_razon_social}',
'{cesionario_rut}',
'{receptor_razon_social}',
'{receptor_rut}',
],
[
$this->datos['Cesion']['DocumentoCesion']['Cedente']['RUTAutorizado']['Nombre'],
$this->datos['Cesion']['DocumentoCesion']['Cedente']['RUTAutorizado']['RUT'],
$this->datos['Cesion']['DocumentoCesion']['Cedente']['RazonSocial'],
$this->datos['Cesion']['DocumentoCesion']['Cedente']['RUT'],
$this->datos['Cesion']['DocumentoCesion']['Cesionario']['RazonSocial'],
$this->datos['Cesion']['DocumentoCesion']['Cesionario']['RUT'],
$this->Encabezado['Receptor']['RznSocRecep'],
$this->Encabezado['Receptor']['RUTRecep'],
],
$this->declaracion
), 0, 512);
}
} | php | public function setCedente(array $cedente = [])
{
$this->datos['Cesion']['DocumentoCesion']['Cedente'] = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
'RUT' => $this->Encabezado['Emisor']['RUTEmisor'],
'RazonSocial' => $this->Encabezado['Emisor']['RznSoc'],
'Direccion' => $this->Encabezado['Emisor']['DirOrigen'].', '.$this->Encabezado['Emisor']['CmnaOrigen'],
'eMail' => !empty($this->Encabezado['Emisor']['CorreoEmisor']) ? $this->Encabezado['Emisor']['CorreoEmisor'] : false,
'RUTAutorizado' => [
'RUT' => false,
'Nombre' => false,
],
'DeclaracionJurada' => false,
], $cedente);
if (!$this->datos['Cesion']['DocumentoCesion']['Cedente']['DeclaracionJurada']) {
$this->datos['Cesion']['DocumentoCesion']['Cedente']['DeclaracionJurada'] = mb_substr(str_replace(
[
'{usuario_nombre}',
'{usuario_run}',
'{emisor_razon_social}',
'{emisor_rut}',
'{cesionario_razon_social}',
'{cesionario_rut}',
'{receptor_razon_social}',
'{receptor_rut}',
],
[
$this->datos['Cesion']['DocumentoCesion']['Cedente']['RUTAutorizado']['Nombre'],
$this->datos['Cesion']['DocumentoCesion']['Cedente']['RUTAutorizado']['RUT'],
$this->datos['Cesion']['DocumentoCesion']['Cedente']['RazonSocial'],
$this->datos['Cesion']['DocumentoCesion']['Cedente']['RUT'],
$this->datos['Cesion']['DocumentoCesion']['Cesionario']['RazonSocial'],
$this->datos['Cesion']['DocumentoCesion']['Cesionario']['RUT'],
$this->Encabezado['Receptor']['RznSocRecep'],
$this->Encabezado['Receptor']['RUTRecep'],
],
$this->declaracion
), 0, 512);
}
} | [
"public",
"function",
"setCedente",
"(",
"array",
"$",
"cedente",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"datos",
"[",
"'Cesion'",
"]",
"[",
"'DocumentoCesion'",
"]",
"[",
"'Cedente'",
"]",
"=",
"\\",
"sasco",
"\\",
"LibreDTE",
"\\",
"Arreglo",
":... | Método que agrega los datos del cedente
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-07-24 | [
"Método",
"que",
"agrega",
"los",
"datos",
"del",
"cedente"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Factoring/Cesion.php#L106-L144 |
LibreDTE/libredte-lib | lib/Sii/Factoring/Cesion.php | Cesion.setDatos | public function setDatos(array $datos)
{
if (!empty($datos['MontoCesion'])) {
$this->datos['Cesion']['DocumentoCesion']['MontoCesion'] = $datos['MontoCesion'];
}
if (!empty($datos['UltimoVencimiento'])) {
$this->datos['Cesion']['DocumentoCesion']['UltimoVencimiento'] = $datos['UltimoVencimiento'];
}
if (!empty($datos['OtrasCondiciones'])) {
$this->datos['Cesion']['DocumentoCesion']['OtrasCondiciones'] = $datos['OtrasCondiciones'];
}
if (!empty($datos['eMailDeudor'])) {
$this->datos['Cesion']['DocumentoCesion']['eMailDeudor'] = $datos['eMailDeudor'];
}
} | php | public function setDatos(array $datos)
{
if (!empty($datos['MontoCesion'])) {
$this->datos['Cesion']['DocumentoCesion']['MontoCesion'] = $datos['MontoCesion'];
}
if (!empty($datos['UltimoVencimiento'])) {
$this->datos['Cesion']['DocumentoCesion']['UltimoVencimiento'] = $datos['UltimoVencimiento'];
}
if (!empty($datos['OtrasCondiciones'])) {
$this->datos['Cesion']['DocumentoCesion']['OtrasCondiciones'] = $datos['OtrasCondiciones'];
}
if (!empty($datos['eMailDeudor'])) {
$this->datos['Cesion']['DocumentoCesion']['eMailDeudor'] = $datos['eMailDeudor'];
}
} | [
"public",
"function",
"setDatos",
"(",
"array",
"$",
"datos",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"datos",
"[",
"'MontoCesion'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"datos",
"[",
"'Cesion'",
"]",
"[",
"'DocumentoCesion'",
"]",
"[",
"'Mont... | Método que asigna otros datos de la cesión. Su uso es opcional, ya que de no ser llamado
se usará el monto total del documento y su fecha de emisión o pago si existe
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-12-10 | [
"Método",
"que",
"asigna",
"otros",
"datos",
"de",
"la",
"cesión",
".",
"Su",
"uso",
"es",
"opcional",
"ya",
"que",
"de",
"no",
"ser",
"llamado",
"se",
"usará",
"el",
"monto",
"total",
"del",
"documento",
"y",
"su",
"fecha",
"de",
"emisión",
"o",
"pago... | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Factoring/Cesion.php#L162-L176 |
LibreDTE/libredte-lib | lib/Sii/Factoring/Cesion.php | Cesion.firmar | public function firmar(\sasco\LibreDTE\FirmaElectronica $Firma)
{
$xml_unsigned = (new \sasco\LibreDTE\XML())->generate($this->datos)->saveXML();
$xml = $Firma->signXML($xml_unsigned, '#LibreDTE_Cesion', 'DocumentoCesion');
if (!$xml) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::DTE_ERROR_FIRMA,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::DTE_ERROR_FIRMA, '#LibreDTE_Cesion')
);
return false;
}
$this->xml = new \sasco\LibreDTE\XML();
if (!$this->xml->loadXML($xml) or !$this->schemaValidate())
return false;
return true;
} | php | public function firmar(\sasco\LibreDTE\FirmaElectronica $Firma)
{
$xml_unsigned = (new \sasco\LibreDTE\XML())->generate($this->datos)->saveXML();
$xml = $Firma->signXML($xml_unsigned, '#LibreDTE_Cesion', 'DocumentoCesion');
if (!$xml) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::DTE_ERROR_FIRMA,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::DTE_ERROR_FIRMA, '#LibreDTE_Cesion')
);
return false;
}
$this->xml = new \sasco\LibreDTE\XML();
if (!$this->xml->loadXML($xml) or !$this->schemaValidate())
return false;
return true;
} | [
"public",
"function",
"firmar",
"(",
"\\",
"sasco",
"\\",
"LibreDTE",
"\\",
"FirmaElectronica",
"$",
"Firma",
")",
"{",
"$",
"xml_unsigned",
"=",
"(",
"new",
"\\",
"sasco",
"\\",
"LibreDTE",
"\\",
"XML",
"(",
")",
")",
"->",
"generate",
"(",
"$",
"this... | Método que realiza la firma de cesión
@param Firma objeto que representa la Firma Electrónca
@return =true si el DTE pudo ser fimado o =false si no se pudo firmar
@author Adonias Vasquez (adonias.vasquez[at]epys.cl)
@version 2016-08-10 | [
"Método",
"que",
"realiza",
"la",
"firma",
"de",
"cesión"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/Factoring/Cesion.php#L185-L200 |
LibreDTE/libredte-lib | lib/Sii/RegistroCompraVenta.php | RegistroCompraVenta.ingresarAceptacionReclamoDoc | public function ingresarAceptacionReclamoDoc($rut, $dv, $dte, $folio, $accion)
{
// ingresar acción al DTE
$r = $this->request('ingresarAceptacionReclamoDoc', [
'rutEmisor' => $rut,
'dvEmisor' => $dv,
'tipoDoc' => $dte,
'folio' => $folio,
'accionDoc' => $accion,
]);
// si no se pudo recuperar error
if ($r===false) {
return false;
}
// entregar resultado del ingreso
return [
'codigo' => $r->codResp,
'glosa' => $r->descResp,
];
} | php | public function ingresarAceptacionReclamoDoc($rut, $dv, $dte, $folio, $accion)
{
// ingresar acción al DTE
$r = $this->request('ingresarAceptacionReclamoDoc', [
'rutEmisor' => $rut,
'dvEmisor' => $dv,
'tipoDoc' => $dte,
'folio' => $folio,
'accionDoc' => $accion,
]);
// si no se pudo recuperar error
if ($r===false) {
return false;
}
// entregar resultado del ingreso
return [
'codigo' => $r->codResp,
'glosa' => $r->descResp,
];
} | [
"public",
"function",
"ingresarAceptacionReclamoDoc",
"(",
"$",
"rut",
",",
"$",
"dv",
",",
"$",
"dte",
",",
"$",
"folio",
",",
"$",
"accion",
")",
"{",
"// ingresar acción al DTE",
"$",
"r",
"=",
"$",
"this",
"->",
"request",
"(",
"'ingresarAceptacionReclam... | Método que ingresa una acción al registro de compr/venta en el SII
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-08-29 | [
"Método",
"que",
"ingresa",
"una",
"acción",
"al",
"registro",
"de",
"compr",
"/",
"venta",
"en",
"el",
"SII"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/RegistroCompraVenta.php#L91-L110 |
LibreDTE/libredte-lib | lib/Sii/RegistroCompraVenta.php | RegistroCompraVenta.listarEventosHistDoc | public function listarEventosHistDoc($rut, $dv, $dte, $folio)
{
// consultar eventos del DTE
$r = $this->request('listarEventosHistDoc', [
'rutEmisor' => $rut,
'dvEmisor' => $dv,
'tipoDoc' => $dte,
'folio' => $folio,
]);
// si no se pudo recuperar error
if ($r===false) {
return false;
}
// si hubo error informar
if (!in_array($r->codResp, [8, 15, 16])) {
throw new \Exception($r->descResp);
}
// entregar eventos del DTE
$eventos = [];
if (!empty($r->listaEventosDoc)) {
if (!is_array($r->listaEventosDoc)) {
$r->listaEventosDoc = [$r->listaEventosDoc];
}
foreach ($r->listaEventosDoc as $evento) {
$eventos[] = [
'codigo' => $evento->codEvento,
'glosa' => $evento->descEvento,
'responsable' => $evento->rutResponsable.'-'.$evento->dvResponsable,
'fecha' => $evento->fechaEvento,
];
}
}
return $eventos;
} | php | public function listarEventosHistDoc($rut, $dv, $dte, $folio)
{
// consultar eventos del DTE
$r = $this->request('listarEventosHistDoc', [
'rutEmisor' => $rut,
'dvEmisor' => $dv,
'tipoDoc' => $dte,
'folio' => $folio,
]);
// si no se pudo recuperar error
if ($r===false) {
return false;
}
// si hubo error informar
if (!in_array($r->codResp, [8, 15, 16])) {
throw new \Exception($r->descResp);
}
// entregar eventos del DTE
$eventos = [];
if (!empty($r->listaEventosDoc)) {
if (!is_array($r->listaEventosDoc)) {
$r->listaEventosDoc = [$r->listaEventosDoc];
}
foreach ($r->listaEventosDoc as $evento) {
$eventos[] = [
'codigo' => $evento->codEvento,
'glosa' => $evento->descEvento,
'responsable' => $evento->rutResponsable.'-'.$evento->dvResponsable,
'fecha' => $evento->fechaEvento,
];
}
}
return $eventos;
} | [
"public",
"function",
"listarEventosHistDoc",
"(",
"$",
"rut",
",",
"$",
"dv",
",",
"$",
"dte",
",",
"$",
"folio",
")",
"{",
"// consultar eventos del DTE",
"$",
"r",
"=",
"$",
"this",
"->",
"request",
"(",
"'listarEventosHistDoc'",
",",
"[",
"'rutEmisor'",
... | Método que entrega los eventos asociados a un DTE
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-08-28 | [
"Método",
"que",
"entrega",
"los",
"eventos",
"asociados",
"a",
"un",
"DTE"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/RegistroCompraVenta.php#L117-L150 |
LibreDTE/libredte-lib | lib/Sii/RegistroCompraVenta.php | RegistroCompraVenta.consultarDocDteCedible | public function consultarDocDteCedible($rut, $dv, $dte, $folio)
{
// consultar eventos del DTE
$r = $this->request('consultarDocDteCedible', [
'rutEmisor' => $rut,
'dvEmisor' => $dv,
'tipoDoc' => $dte,
'folio' => $folio,
]);
// si no se pudo recuperar error
if ($r===false) {
return false;
}
// entregar información de cesión para el DTE
return [
'codigo' => $r->codResp,
'glosa' => $r->descResp,
];
} | php | public function consultarDocDteCedible($rut, $dv, $dte, $folio)
{
// consultar eventos del DTE
$r = $this->request('consultarDocDteCedible', [
'rutEmisor' => $rut,
'dvEmisor' => $dv,
'tipoDoc' => $dte,
'folio' => $folio,
]);
// si no se pudo recuperar error
if ($r===false) {
return false;
}
// entregar información de cesión para el DTE
return [
'codigo' => $r->codResp,
'glosa' => $r->descResp,
];
} | [
"public",
"function",
"consultarDocDteCedible",
"(",
"$",
"rut",
",",
"$",
"dv",
",",
"$",
"dte",
",",
"$",
"folio",
")",
"{",
"// consultar eventos del DTE",
"$",
"r",
"=",
"$",
"this",
"->",
"request",
"(",
"'consultarDocDteCedible'",
",",
"[",
"'rutEmisor... | Entrega información de cesión para el DTE, si es posible o no cederlo
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-08-28 | [
"Entrega",
"información",
"de",
"cesión",
"para",
"el",
"DTE",
"si",
"es",
"posible",
"o",
"no",
"cederlo"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/RegistroCompraVenta.php#L157-L175 |
LibreDTE/libredte-lib | lib/Sii/RegistroCompraVenta.php | RegistroCompraVenta.request | private function request($request, $args, $retry = 10)
{
if (!\sasco\LibreDTE\Sii::getVerificarSSL()) {
if (\sasco\LibreDTE\Sii::getAmbiente()==\sasco\LibreDTE\Sii::PRODUCCION) {
$msg = \sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::ENVIO_SSL_SIN_VERIFICAR);
\sasco\LibreDTE\Log::write(\sasco\LibreDTE\Estado::ENVIO_SSL_SIN_VERIFICAR, $msg, LOG_WARNING);
}
$options = ['stream_context' => stream_context_create([
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
]
])];
} else {
$options = [];
}
try {
$wsdl = self::$wsdl[\sasco\LibreDTE\Sii::getAmbiente()];
$soap = new \SoapClient($wsdl, $options);
$soap->__setCookie('TOKEN', $this->token);
} catch (\Exception $e) {
$msg = $e->getMessage();
if (isset($e->getTrace()[0]['args'][1]) and is_string($e->getTrace()[0]['args'][1])) {
$msg .= ': '.$e->getTrace()[0]['args'][1];
}
\sasco\LibreDTE\Log::write(\sasco\LibreDTE\Estado::REQUEST_ERROR_SOAP, \sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::REQUEST_ERROR_SOAP, $msg));
return false;
}
for ($i=0; $i<$retry; $i++) {
try {
$body = call_user_func_array([$soap, $request], $args);
break;
} catch (\Exception $e) {
$msg = $e->getMessage();
if (isset($e->getTrace()[0]['args'][1]) and is_string($e->getTrace()[0]['args'][1])) {
$msg .= ': '.$e->getTrace()[0]['args'][1];
}
\sasco\LibreDTE\Log::write(\sasco\LibreDTE\Estado::REQUEST_ERROR_SOAP, \sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::REQUEST_ERROR_SOAP, $msg));
$body = null;
}
}
if ($body===null) {
\sasco\LibreDTE\Log::write(\sasco\LibreDTE\Estado::REQUEST_ERROR_BODY, \sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::REQUEST_ERROR_BODY, $wsdl, $retry));
return false;
}
return $body;
} | php | private function request($request, $args, $retry = 10)
{
if (!\sasco\LibreDTE\Sii::getVerificarSSL()) {
if (\sasco\LibreDTE\Sii::getAmbiente()==\sasco\LibreDTE\Sii::PRODUCCION) {
$msg = \sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::ENVIO_SSL_SIN_VERIFICAR);
\sasco\LibreDTE\Log::write(\sasco\LibreDTE\Estado::ENVIO_SSL_SIN_VERIFICAR, $msg, LOG_WARNING);
}
$options = ['stream_context' => stream_context_create([
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
]
])];
} else {
$options = [];
}
try {
$wsdl = self::$wsdl[\sasco\LibreDTE\Sii::getAmbiente()];
$soap = new \SoapClient($wsdl, $options);
$soap->__setCookie('TOKEN', $this->token);
} catch (\Exception $e) {
$msg = $e->getMessage();
if (isset($e->getTrace()[0]['args'][1]) and is_string($e->getTrace()[0]['args'][1])) {
$msg .= ': '.$e->getTrace()[0]['args'][1];
}
\sasco\LibreDTE\Log::write(\sasco\LibreDTE\Estado::REQUEST_ERROR_SOAP, \sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::REQUEST_ERROR_SOAP, $msg));
return false;
}
for ($i=0; $i<$retry; $i++) {
try {
$body = call_user_func_array([$soap, $request], $args);
break;
} catch (\Exception $e) {
$msg = $e->getMessage();
if (isset($e->getTrace()[0]['args'][1]) and is_string($e->getTrace()[0]['args'][1])) {
$msg .= ': '.$e->getTrace()[0]['args'][1];
}
\sasco\LibreDTE\Log::write(\sasco\LibreDTE\Estado::REQUEST_ERROR_SOAP, \sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::REQUEST_ERROR_SOAP, $msg));
$body = null;
}
}
if ($body===null) {
\sasco\LibreDTE\Log::write(\sasco\LibreDTE\Estado::REQUEST_ERROR_BODY, \sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::REQUEST_ERROR_BODY, $wsdl, $retry));
return false;
}
return $body;
} | [
"private",
"function",
"request",
"(",
"$",
"request",
",",
"$",
"args",
",",
"$",
"retry",
"=",
"10",
")",
"{",
"if",
"(",
"!",
"\\",
"sasco",
"\\",
"LibreDTE",
"\\",
"Sii",
"::",
"getVerificarSSL",
"(",
")",
")",
"{",
"if",
"(",
"\\",
"sasco",
... | Método para realizar una solicitud al servicio web del SII
@param request Nombre de la función que se ejecutará en el servicio web
@param args Argumentos que se pasarán al servicio web
@param retry Intentos que se realizarán como máximo para obtener respuesta
@return Objeto o String con la respuesta (depende servicio web)
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-08-28 | [
"Método",
"para",
"realizar",
"una",
"solicitud",
"al",
"servicio",
"web",
"del",
"SII"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/RegistroCompraVenta.php#L210-L257 |
LibreDTE/libredte-lib | lib/Sii/EnvioRecibos.php | EnvioRecibos.agregar | public function agregar(array $datos)
{
$this->recibos[] = [
'@attributes' => [
'version' => '1.0',
],
'DocumentoRecibo' => array_merge([
'@attributes' => [
'ID' => 'LibreDTE_T'.$datos['TipoDoc'].'F'.$datos['Folio'],
],
'TipoDoc' => false,
'Folio' => false,
'FchEmis' => false,
'RUTEmisor' => false,
'RUTRecep' => false,
'MntTotal' => false,
'Recinto' => false,
'RutFirma' => false,
'Declaracion' => 'El acuse de recibo que se declara en este acto, de acuerdo a lo dispuesto en la letra b) del Art. 4, y la letra c) del Art. 5 de la Ley 19.983, acredita que la entrega de mercaderias o servicio(s) prestado(s) ha(n) sido recibido(s).',
'TmstFirmaRecibo' => date('Y-m-d\TH:i:s'),
], $datos)
];
return true;
} | php | public function agregar(array $datos)
{
$this->recibos[] = [
'@attributes' => [
'version' => '1.0',
],
'DocumentoRecibo' => array_merge([
'@attributes' => [
'ID' => 'LibreDTE_T'.$datos['TipoDoc'].'F'.$datos['Folio'],
],
'TipoDoc' => false,
'Folio' => false,
'FchEmis' => false,
'RUTEmisor' => false,
'RUTRecep' => false,
'MntTotal' => false,
'Recinto' => false,
'RutFirma' => false,
'Declaracion' => 'El acuse de recibo que se declara en este acto, de acuerdo a lo dispuesto en la letra b) del Art. 4, y la letra c) del Art. 5 de la Ley 19.983, acredita que la entrega de mercaderias o servicio(s) prestado(s) ha(n) sido recibido(s).',
'TmstFirmaRecibo' => date('Y-m-d\TH:i:s'),
], $datos)
];
return true;
} | [
"public",
"function",
"agregar",
"(",
"array",
"$",
"datos",
")",
"{",
"$",
"this",
"->",
"recibos",
"[",
"]",
"=",
"[",
"'@attributes'",
"=>",
"[",
"'version'",
"=>",
"'1.0'",
",",
"]",
",",
"'DocumentoRecibo'",
"=>",
"array_merge",
"(",
"[",
"'@attribu... | Método que agrega un recibo
@param datos Arreglo con los datos del recibo
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-08-06 | [
"Método",
"que",
"agrega",
"un",
"recibo"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/EnvioRecibos.php#L43-L66 |
LibreDTE/libredte-lib | lib/Sii/EnvioRecibos.php | EnvioRecibos.setCaratula | public function setCaratula(array $caratula)
{
$this->caratula = array_merge([
'@attributes' => [
'version' => '1.0'
],
'RutResponde' => false,
'RutRecibe' => false,
'NmbContacto' => false,
'FonoContacto' => false,
'MailContacto' => false,
'TmstFirmaEnv' => date('Y-m-d\TH:i:s'),
], $caratula);
if ($this->caratula['NmbContacto']) {
$this->caratula['NmbContacto'] = mb_substr($this->caratula['NmbContacto'], 0, 40);
}
$this->id = 'SetDteRecibidos';
} | php | public function setCaratula(array $caratula)
{
$this->caratula = array_merge([
'@attributes' => [
'version' => '1.0'
],
'RutResponde' => false,
'RutRecibe' => false,
'NmbContacto' => false,
'FonoContacto' => false,
'MailContacto' => false,
'TmstFirmaEnv' => date('Y-m-d\TH:i:s'),
], $caratula);
if ($this->caratula['NmbContacto']) {
$this->caratula['NmbContacto'] = mb_substr($this->caratula['NmbContacto'], 0, 40);
}
$this->id = 'SetDteRecibidos';
} | [
"public",
"function",
"setCaratula",
"(",
"array",
"$",
"caratula",
")",
"{",
"$",
"this",
"->",
"caratula",
"=",
"array_merge",
"(",
"[",
"'@attributes'",
"=>",
"[",
"'version'",
"=>",
"'1.0'",
"]",
",",
"'RutResponde'",
"=>",
"false",
",",
"'RutRecibe'",
... | Método para asignar la caratula
@param caratula Arreglo con datos del envío: RutEnvia, FchResol y NroResol
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2018-01-23 | [
"Método",
"para",
"asignar",
"la",
"caratula"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/EnvioRecibos.php#L74-L91 |
LibreDTE/libredte-lib | lib/Sii/EnvioRecibos.php | EnvioRecibos.generar | public function generar()
{
// si ya se había generado se entrega directamente
if ($this->xml_data)
return $this->xml_data;
// si no hay respuestas para generar entregar falso
if (!isset($this->recibos[0])) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::ENVIORECIBOS_FALTA_RECIBO,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::ENVIORECIBOS_FALTA_RECIBO)
);
return false;
}
// si no hay carátula error
if (!$this->caratula) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::ENVIORECIBOS_FALTA_CARATULA,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::ENVIORECIBOS_FALTA_CARATULA)
);
return false;
}
// crear arreglo de lo que se enviará
$xmlEnvio = (new \sasco\LibreDTE\XML())->generate([
'EnvioRecibos' => [
'@attributes' => [
'xmlns' => 'http://www.sii.cl/SiiDte',
'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
'xsi:schemaLocation' => 'http://www.sii.cl/SiiDte EnvioRecibos_v10.xsd',
'version' => '1.0',
],
'SetRecibos' => [
'@attributes' => [
'ID' => 'LibreDTE_SetDteRecibidos'
],
'Caratula' => $this->caratula,
'Recibo' => null,
]
]
])->saveXML();
// generar cada recibo y firmar
$Recibos = [];
foreach ($this->recibos as &$recibo) {
$recibo_xml = new \sasco\LibreDTE\XML();
$recibo_xml->generate(['Recibo'=>$recibo]);
$recibo_firmado = $this->Firma ? $this->Firma->signXML($recibo_xml->saveXML(), '#'.$recibo['DocumentoRecibo']['@attributes']['ID'], 'DocumentoRecibo', true) : $recibo_xml->saveXML();
$Recibos[] = trim(str_replace('<?xml version="1.0" encoding="ISO-8859-1"?>', '', $recibo_firmado));
}
// firmar XML del envío y entregar
$xml = str_replace('<Recibo/>', implode("\n", $Recibos), $xmlEnvio);
$this->xml_data = $this->Firma ? $this->Firma->signXML($xml, '#LibreDTE_SetDteRecibidos', 'SetRecibos', true) : $xml;
return $this->xml_data;
} | php | public function generar()
{
// si ya se había generado se entrega directamente
if ($this->xml_data)
return $this->xml_data;
// si no hay respuestas para generar entregar falso
if (!isset($this->recibos[0])) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::ENVIORECIBOS_FALTA_RECIBO,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::ENVIORECIBOS_FALTA_RECIBO)
);
return false;
}
// si no hay carátula error
if (!$this->caratula) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::ENVIORECIBOS_FALTA_CARATULA,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::ENVIORECIBOS_FALTA_CARATULA)
);
return false;
}
// crear arreglo de lo que se enviará
$xmlEnvio = (new \sasco\LibreDTE\XML())->generate([
'EnvioRecibos' => [
'@attributes' => [
'xmlns' => 'http://www.sii.cl/SiiDte',
'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
'xsi:schemaLocation' => 'http://www.sii.cl/SiiDte EnvioRecibos_v10.xsd',
'version' => '1.0',
],
'SetRecibos' => [
'@attributes' => [
'ID' => 'LibreDTE_SetDteRecibidos'
],
'Caratula' => $this->caratula,
'Recibo' => null,
]
]
])->saveXML();
// generar cada recibo y firmar
$Recibos = [];
foreach ($this->recibos as &$recibo) {
$recibo_xml = new \sasco\LibreDTE\XML();
$recibo_xml->generate(['Recibo'=>$recibo]);
$recibo_firmado = $this->Firma ? $this->Firma->signXML($recibo_xml->saveXML(), '#'.$recibo['DocumentoRecibo']['@attributes']['ID'], 'DocumentoRecibo', true) : $recibo_xml->saveXML();
$Recibos[] = trim(str_replace('<?xml version="1.0" encoding="ISO-8859-1"?>', '', $recibo_firmado));
}
// firmar XML del envío y entregar
$xml = str_replace('<Recibo/>', implode("\n", $Recibos), $xmlEnvio);
$this->xml_data = $this->Firma ? $this->Firma->signXML($xml, '#LibreDTE_SetDteRecibidos', 'SetRecibos', true) : $xml;
return $this->xml_data;
} | [
"public",
"function",
"generar",
"(",
")",
"{",
"// si ya se había generado se entrega directamente",
"if",
"(",
"$",
"this",
"->",
"xml_data",
")",
"return",
"$",
"this",
"->",
"xml_data",
";",
"// si no hay respuestas para generar entregar falso",
"if",
"(",
"!",
"i... | Método que genera el XML para el envío de la respuesta al SII
@param caratula Arreglo con la carátula de la respuesta
@param Firma Objeto con la firma electrónica
@return XML con la respuesta firmada o =false si no se pudo generar o firmar la respuesta
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-08-06 | [
"Método",
"que",
"genera",
"el",
"XML",
"para",
"el",
"envío",
"de",
"la",
"respuesta",
"al",
"SII"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/EnvioRecibos.php#L101-L152 |
LibreDTE/libredte-lib | lib/Sii/EnvioRecibos.php | EnvioRecibos.getRecibos | public function getRecibos()
{
// si no hay recibos se deben crear
if (!$this->recibos) {
// si no está creado el arrelgo con los datos error
if (!$this->arreglo) {
return false;
}
// crear recibos a partir del arreglo
$Recibos = $this->arreglo['EnvioRecibos']['SetRecibos']['Recibo'];
if (!isset($Recibos[0]))
$Recibos = [$Recibos];
foreach ($Recibos as $Recibo) {
$this->recibos[] = $Recibo;
}
}
// entregar recibos
return $this->recibos;
} | php | public function getRecibos()
{
// si no hay recibos se deben crear
if (!$this->recibos) {
// si no está creado el arrelgo con los datos error
if (!$this->arreglo) {
return false;
}
// crear recibos a partir del arreglo
$Recibos = $this->arreglo['EnvioRecibos']['SetRecibos']['Recibo'];
if (!isset($Recibos[0]))
$Recibos = [$Recibos];
foreach ($Recibos as $Recibo) {
$this->recibos[] = $Recibo;
}
}
// entregar recibos
return $this->recibos;
} | [
"public",
"function",
"getRecibos",
"(",
")",
"{",
"// si no hay recibos se deben crear",
"if",
"(",
"!",
"$",
"this",
"->",
"recibos",
")",
"{",
"// si no está creado el arrelgo con los datos error",
"if",
"(",
"!",
"$",
"this",
"->",
"arreglo",
")",
"{",
"return... | Método que entrega un arreglo con los recibos del XML
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-12-22 | [
"Método",
"que",
"entrega",
"un",
"arreglo",
"con",
"los",
"recibos",
"del",
"XML"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/EnvioRecibos.php#L169-L187 |
LibreDTE/libredte-lib | lib/CSV.php | CSV.read | public static function read($archivo, $separador = ';', $delimitadortexto = '"')
{
if (($handle = fopen($archivo, 'r')) !== FALSE) {
$data = array();
$i = 0;
while (($row = fgetcsv($handle, 0, $separador, $delimitadortexto)) !== FALSE) {
$j = 0;
foreach ($row as &$col) {
$data[$i][$j++] = $col;
}
++$i;
}
fclose($handle);
}
return $data;
} | php | public static function read($archivo, $separador = ';', $delimitadortexto = '"')
{
if (($handle = fopen($archivo, 'r')) !== FALSE) {
$data = array();
$i = 0;
while (($row = fgetcsv($handle, 0, $separador, $delimitadortexto)) !== FALSE) {
$j = 0;
foreach ($row as &$col) {
$data[$i][$j++] = $col;
}
++$i;
}
fclose($handle);
}
return $data;
} | [
"public",
"static",
"function",
"read",
"(",
"$",
"archivo",
",",
"$",
"separador",
"=",
"';'",
",",
"$",
"delimitadortexto",
"=",
"'\"'",
")",
"{",
"if",
"(",
"(",
"$",
"handle",
"=",
"fopen",
"(",
"$",
"archivo",
",",
"'r'",
")",
")",
"!==",
"FAL... | Lee un archivo CSV
@param archivo archivo a leer (ejemplo índice tmp_name de un arreglo $_FILES)
@param separador separador a utilizar para diferenciar entre una columna u otra
@param delimitadortexto Delimitador del texto para "rodear" cada campo del CSV
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-09-17 | [
"Lee",
"un",
"archivo",
"CSV"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/CSV.php#L47-L62 |
LibreDTE/libredte-lib | lib/CSV.php | CSV.generate | public static function generate(array $data, $archivo, $separador = ';', $delimitadortexto = '"')
{
ob_clean();
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename='.$archivo.'.csv');
header('Pragma: no-cache');
header('Expires: 0');
foreach($data as &$row) {
foreach($row as &$col) {
$col = $delimitadortexto.rtrim(str_replace('<br />', ', ', strip_tags($col, '<br>')), " \t\n\r\0\x0B,").$delimitadortexto;
}
echo implode($separador, $row),"\r\n";
unset($row);
}
unset($data);
exit(0);
} | php | public static function generate(array $data, $archivo, $separador = ';', $delimitadortexto = '"')
{
ob_clean();
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename='.$archivo.'.csv');
header('Pragma: no-cache');
header('Expires: 0');
foreach($data as &$row) {
foreach($row as &$col) {
$col = $delimitadortexto.rtrim(str_replace('<br />', ', ', strip_tags($col, '<br>')), " \t\n\r\0\x0B,").$delimitadortexto;
}
echo implode($separador, $row),"\r\n";
unset($row);
}
unset($data);
exit(0);
} | [
"public",
"static",
"function",
"generate",
"(",
"array",
"$",
"data",
",",
"$",
"archivo",
",",
"$",
"separador",
"=",
"';'",
",",
"$",
"delimitadortexto",
"=",
"'\"'",
")",
"{",
"ob_clean",
"(",
")",
";",
"header",
"(",
"'Content-type: text/csv'",
")",
... | Crea un archivo CSV a partir de un arreglo
@param data Arreglo utilizado para generar la planilla
@param archivo Nombre del archivo sin extensión (sin .csv)
@param separador separador a utilizar para diferenciar entre una columna u otra
@param delimitadortexto Delimitador del texto para "rodear" cada campo del CSV
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-09-17 | [
"Crea",
"un",
"archivo",
"CSV",
"a",
"partir",
"de",
"un",
"arreglo"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/CSV.php#L73-L89 |
LibreDTE/libredte-lib | lib/CSV.php | CSV.save | public static function save(array $data, $archivo, $separador = ';', $delimitadortexto = '"')
{
$fd = fopen($archivo, 'w');
foreach($data as &$row) {
foreach($row as &$col) {
$col = $delimitadortexto.rtrim(str_replace('<br />', ', ', strip_tags($col, '<br>')), " \t\n\r\0\x0B,").$delimitadortexto;
}
fwrite($fd, implode($separador, $row)."\r\n");
unset($row);
}
fclose($fd);
} | php | public static function save(array $data, $archivo, $separador = ';', $delimitadortexto = '"')
{
$fd = fopen($archivo, 'w');
foreach($data as &$row) {
foreach($row as &$col) {
$col = $delimitadortexto.rtrim(str_replace('<br />', ', ', strip_tags($col, '<br>')), " \t\n\r\0\x0B,").$delimitadortexto;
}
fwrite($fd, implode($separador, $row)."\r\n");
unset($row);
}
fclose($fd);
} | [
"public",
"static",
"function",
"save",
"(",
"array",
"$",
"data",
",",
"$",
"archivo",
",",
"$",
"separador",
"=",
"';'",
",",
"$",
"delimitadortexto",
"=",
"'\"'",
")",
"{",
"$",
"fd",
"=",
"fopen",
"(",
"$",
"archivo",
",",
"'w'",
")",
";",
"for... | Crea un archivo CSV a partir de un arreglo guardándolo en el sistema de archivos
@param data Arreglo utilizado para generar la planilla
@param archivo Nombre del archivo que se debe generar
@param separador separador a utilizar para diferenciar entre una columna u otra
@param delimitadortexto Delimitador del texto para "rodear" cada campo del CSV
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-09-17 | [
"Crea",
"un",
"archivo",
"CSV",
"a",
"partir",
"de",
"un",
"arreglo",
"guardándolo",
"en",
"el",
"sistema",
"de",
"archivos"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/CSV.php#L100-L111 |
LibreDTE/libredte-lib | lib/Sii/EnvioDte.php | EnvioDte.agregar | public function agregar(Dte $DTE)
{
// determinar el tipo del envío (DTE o boleta)
if ($this->tipo === null) {
$this->tipo = (int)$DTE->esBoleta();
}
// validar que el tipo de documento sea del tipo que se espera
else if ((int)$DTE->esBoleta() != $this->tipo) {
return false;
}
//
if (isset($this->dtes[$this->config['DTE_max'][$this->tipo]-1])) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::ENVIODTE_DTE_MAX,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::ENVIODTE_DTE_MAX, $this->config['DTE_max'][$this->tipo])
);
return false;
}
$this->dtes[] = $DTE;
return true;
} | php | public function agregar(Dte $DTE)
{
// determinar el tipo del envío (DTE o boleta)
if ($this->tipo === null) {
$this->tipo = (int)$DTE->esBoleta();
}
// validar que el tipo de documento sea del tipo que se espera
else if ((int)$DTE->esBoleta() != $this->tipo) {
return false;
}
//
if (isset($this->dtes[$this->config['DTE_max'][$this->tipo]-1])) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::ENVIODTE_DTE_MAX,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::ENVIODTE_DTE_MAX, $this->config['DTE_max'][$this->tipo])
);
return false;
}
$this->dtes[] = $DTE;
return true;
} | [
"public",
"function",
"agregar",
"(",
"Dte",
"$",
"DTE",
")",
"{",
"// determinar el tipo del envío (DTE o boleta)",
"if",
"(",
"$",
"this",
"->",
"tipo",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"tipo",
"=",
"(",
"int",
")",
"$",
"DTE",
"->",
"esBole... | Método que agrega un DTE al listado que se enviará
@param DTE Objeto del DTE
@return =true si se pudo agregar el DTE o =false si no se agregó por exceder el límite de un envío
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-12-11 | [
"Método",
"que",
"agrega",
"un",
"DTE",
"al",
"listado",
"que",
"se",
"enviará"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/EnvioDte.php#L50-L70 |
LibreDTE/libredte-lib | lib/Sii/EnvioDte.php | EnvioDte.setCaratula | public function setCaratula(array $caratula)
{
// si no hay DTEs para generar entregar falso
if (!isset($this->dtes[0])) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::ENVIODTE_FALTA_DTE,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::ENVIODTE_FALTA_DTE)
);
return false;
}
// si se agregaron demasiados DTE error
$SubTotDTE = $this->getSubTotDTE();
if (isset($SubTotDTE[$this->config['SubTotDTE_max'][$this->tipo]])) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::ENVIODTE_TIPO_DTE_MAX,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::ENVIODTE_TIPO_DTE_MAX, $this->config['SubTotDTE_max'][$this->tipo])
);
return false;
}
// generar caratula
$this->caratula = array_merge([
'@attributes' => [
'version' => '1.0'
],
'RutEmisor' => $this->dtes[0]->getEmisor(),
'RutEnvia' => isset($this->Firma) ? $this->Firma->getID() : false,
'RutReceptor' => $this->dtes[0]->getReceptor(),
'FchResol' => '',
'NroResol' => '',
'TmstFirmaEnv' => date('Y-m-d\TH:i:s'),
'SubTotDTE' => $SubTotDTE,
], $caratula);
return true;
} | php | public function setCaratula(array $caratula)
{
// si no hay DTEs para generar entregar falso
if (!isset($this->dtes[0])) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::ENVIODTE_FALTA_DTE,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::ENVIODTE_FALTA_DTE)
);
return false;
}
// si se agregaron demasiados DTE error
$SubTotDTE = $this->getSubTotDTE();
if (isset($SubTotDTE[$this->config['SubTotDTE_max'][$this->tipo]])) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::ENVIODTE_TIPO_DTE_MAX,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::ENVIODTE_TIPO_DTE_MAX, $this->config['SubTotDTE_max'][$this->tipo])
);
return false;
}
// generar caratula
$this->caratula = array_merge([
'@attributes' => [
'version' => '1.0'
],
'RutEmisor' => $this->dtes[0]->getEmisor(),
'RutEnvia' => isset($this->Firma) ? $this->Firma->getID() : false,
'RutReceptor' => $this->dtes[0]->getReceptor(),
'FchResol' => '',
'NroResol' => '',
'TmstFirmaEnv' => date('Y-m-d\TH:i:s'),
'SubTotDTE' => $SubTotDTE,
], $caratula);
return true;
} | [
"public",
"function",
"setCaratula",
"(",
"array",
"$",
"caratula",
")",
"{",
"// si no hay DTEs para generar entregar falso",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"dtes",
"[",
"0",
"]",
")",
")",
"{",
"\\",
"sasco",
"\\",
"LibreDTE",
"\\",
"Lo... | Método para asignar la caratula
@param caratula Arreglo con datos del envío: RutEnvia, FchResol y NroResol
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-12-11 | [
"Método",
"para",
"asignar",
"la",
"caratula"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/EnvioDte.php#L78-L111 |
LibreDTE/libredte-lib | lib/Sii/EnvioDte.php | EnvioDte.generar | public function generar()
{
// si ya se había generado se entrega directamente
if ($this->xml_data)
return $this->xml_data;
// si no hay DTEs para generar entregar falso
if (!isset($this->dtes[0])) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::ENVIODTE_FALTA_DTE,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::ENVIODTE_FALTA_DTE)
);
return false;
}
// genear XML del envío
$xmlEnvio = (new \sasco\LibreDTE\XML())->generate([
$this->config['tipos'][$this->tipo] => [
'@attributes' => [
'xmlns' => 'http://www.sii.cl/SiiDte',
'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
'xsi:schemaLocation' => 'http://www.sii.cl/SiiDte '.$this->config['schemas'][$this->tipo].'.xsd',
'version' => '1.0'
],
'SetDTE' => [
'@attributes' => [
'ID' => 'LibreDTE_SetDoc'
],
'Caratula' => $this->caratula,
'DTE' => null,
]
]
])->saveXML();
// generar XML de los DTE que se deberán incorporar
$DTEs = [];
foreach ($this->dtes as &$DTE) {
$DTEs[] = trim(str_replace(['<?xml version="1.0" encoding="ISO-8859-1"?>', '<?xml version="1.0"?>'], '', $DTE->saveXML()));
}
// firmar XML del envío y entregar
$xml = str_replace('<DTE/>', implode("\n", $DTEs), $xmlEnvio);
$this->xml_data = $this->Firma ? $this->Firma->signXML($xml, '#LibreDTE_SetDoc', 'SetDTE', true) : $xml;
return $this->xml_data;
} | php | public function generar()
{
// si ya se había generado se entrega directamente
if ($this->xml_data)
return $this->xml_data;
// si no hay DTEs para generar entregar falso
if (!isset($this->dtes[0])) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::ENVIODTE_FALTA_DTE,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::ENVIODTE_FALTA_DTE)
);
return false;
}
// genear XML del envío
$xmlEnvio = (new \sasco\LibreDTE\XML())->generate([
$this->config['tipos'][$this->tipo] => [
'@attributes' => [
'xmlns' => 'http://www.sii.cl/SiiDte',
'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
'xsi:schemaLocation' => 'http://www.sii.cl/SiiDte '.$this->config['schemas'][$this->tipo].'.xsd',
'version' => '1.0'
],
'SetDTE' => [
'@attributes' => [
'ID' => 'LibreDTE_SetDoc'
],
'Caratula' => $this->caratula,
'DTE' => null,
]
]
])->saveXML();
// generar XML de los DTE que se deberán incorporar
$DTEs = [];
foreach ($this->dtes as &$DTE) {
$DTEs[] = trim(str_replace(['<?xml version="1.0" encoding="ISO-8859-1"?>', '<?xml version="1.0"?>'], '', $DTE->saveXML()));
}
// firmar XML del envío y entregar
$xml = str_replace('<DTE/>', implode("\n", $DTEs), $xmlEnvio);
$this->xml_data = $this->Firma ? $this->Firma->signXML($xml, '#LibreDTE_SetDoc', 'SetDTE', true) : $xml;
return $this->xml_data;
} | [
"public",
"function",
"generar",
"(",
")",
"{",
"// si ya se había generado se entrega directamente",
"if",
"(",
"$",
"this",
"->",
"xml_data",
")",
"return",
"$",
"this",
"->",
"xml_data",
";",
"// si no hay DTEs para generar entregar falso",
"if",
"(",
"!",
"isset",... | Método que genera el XML para el envío del DTE al SII
@return XML con el envio del DTE firmado o =false si no se pudo generar o firmar el envío
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-08-06 | [
"Método",
"que",
"genera",
"el",
"XML",
"para",
"el",
"envío",
"del",
"DTE",
"al",
"SII"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/EnvioDte.php#L135-L175 |
LibreDTE/libredte-lib | lib/Sii/EnvioDte.php | EnvioDte.getSubTotDTE | private function getSubTotDTE()
{
$SubTotDTE = [];
$subtotales = [];
foreach ($this->dtes as &$DTE) {
if (!isset($subtotales[$DTE->getTipo()]))
$subtotales[$DTE->getTipo()] = 0;
$subtotales[$DTE->getTipo()]++;
}
foreach ($subtotales as $tipo => $subtotal) {
$SubTotDTE[] = [
'TpoDTE' => $tipo,
'NroDTE' => $subtotal,
];
}
return $SubTotDTE;
} | php | private function getSubTotDTE()
{
$SubTotDTE = [];
$subtotales = [];
foreach ($this->dtes as &$DTE) {
if (!isset($subtotales[$DTE->getTipo()]))
$subtotales[$DTE->getTipo()] = 0;
$subtotales[$DTE->getTipo()]++;
}
foreach ($subtotales as $tipo => $subtotal) {
$SubTotDTE[] = [
'TpoDTE' => $tipo,
'NroDTE' => $subtotal,
];
}
return $SubTotDTE;
} | [
"private",
"function",
"getSubTotDTE",
"(",
")",
"{",
"$",
"SubTotDTE",
"=",
"[",
"]",
";",
"$",
"subtotales",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"dtes",
"as",
"&",
"$",
"DTE",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"s... | Método que obtiene los datos para generar los tags SubTotDTE
@return Arreglo con los datos para generar los tags SubTotDTE
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-09-02 | [
"Método",
"que",
"obtiene",
"los",
"datos",
"para",
"generar",
"los",
"tags",
"SubTotDTE"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/EnvioDte.php#L183-L199 |
LibreDTE/libredte-lib | lib/Sii/EnvioDte.php | EnvioDte.loadXML | public function loadXML($xml_data)
{
if (!parent::loadXML($xml_data)) {
return false;
}
$tagName = $this->xml->documentElement->tagName;
if ($tagName=='DTE') {
$this->xml = null;
$this->xml_data = null;
$this->arreglo = null;
$Dte = new Dte($xml_data, false);
$this->agregar($Dte);
$this->setCaratula([
'RutEnvia' => $Dte->getEmisor(),
'RutReceptor' => $Dte->getReceptor(),
'FchResol' => date('Y-m-d'),
'NroResol' => ($Dte->getCertificacion()?'0':'').'9999',
]);
if (!parent::loadXML($this->generar())) {
return false;
}
$tagName = $this->xml->documentElement->tagName;
}
if ($tagName=='EnvioDTE') {
$this->tipo = 0;
return $this->xml;
}
if ($tagName=='EnvioBOLETA') {
$this->tipo = 1;
return $this->xml;
}
return false;
} | php | public function loadXML($xml_data)
{
if (!parent::loadXML($xml_data)) {
return false;
}
$tagName = $this->xml->documentElement->tagName;
if ($tagName=='DTE') {
$this->xml = null;
$this->xml_data = null;
$this->arreglo = null;
$Dte = new Dte($xml_data, false);
$this->agregar($Dte);
$this->setCaratula([
'RutEnvia' => $Dte->getEmisor(),
'RutReceptor' => $Dte->getReceptor(),
'FchResol' => date('Y-m-d'),
'NroResol' => ($Dte->getCertificacion()?'0':'').'9999',
]);
if (!parent::loadXML($this->generar())) {
return false;
}
$tagName = $this->xml->documentElement->tagName;
}
if ($tagName=='EnvioDTE') {
$this->tipo = 0;
return $this->xml;
}
if ($tagName=='EnvioBOLETA') {
$this->tipo = 1;
return $this->xml;
}
return false;
} | [
"public",
"function",
"loadXML",
"(",
"$",
"xml_data",
")",
"{",
"if",
"(",
"!",
"parent",
"::",
"loadXML",
"(",
"$",
"xml_data",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"tagName",
"=",
"$",
"this",
"->",
"xml",
"->",
"documentElement",
"->"... | Método que carga un XML de EnvioDte y asigna el objeto XML correspondiente
para poder obtener los datos del envío
@return Objeto XML
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-11-21 | [
"Método",
"que",
"carga",
"un",
"XML",
"de",
"EnvioDte",
"y",
"asigna",
"el",
"objeto",
"XML",
"correspondiente",
"para",
"poder",
"obtener",
"los",
"datos",
"del",
"envío"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/EnvioDte.php#L208-L240 |
LibreDTE/libredte-lib | lib/Sii/EnvioDte.php | EnvioDte.getCaratula | public function getCaratula()
{
return isset($this->arreglo[$this->config['tipos'][$this->tipo]]['SetDTE']['Caratula']) ? $this->arreglo[$this->config['tipos'][$this->tipo]]['SetDTE']['Caratula'] : false;
} | php | public function getCaratula()
{
return isset($this->arreglo[$this->config['tipos'][$this->tipo]]['SetDTE']['Caratula']) ? $this->arreglo[$this->config['tipos'][$this->tipo]]['SetDTE']['Caratula'] : false;
} | [
"public",
"function",
"getCaratula",
"(",
")",
"{",
"return",
"isset",
"(",
"$",
"this",
"->",
"arreglo",
"[",
"$",
"this",
"->",
"config",
"[",
"'tipos'",
"]",
"[",
"$",
"this",
"->",
"tipo",
"]",
"]",
"[",
"'SetDTE'",
"]",
"[",
"'Caratula'",
"]",
... | Método que entrega un arreglo con los datos de la carátula del envío
@return Arreglo con datos de carátula
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-12-11 | [
"Método",
"que",
"entrega",
"un",
"arreglo",
"con",
"los",
"datos",
"de",
"la",
"carátula",
"del",
"envío"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/EnvioDte.php#L248-L251 |
LibreDTE/libredte-lib | lib/Sii/EnvioDte.php | EnvioDte.getID | public function getID()
{
return isset($this->arreglo[$this->config['tipos'][$this->tipo]]['SetDTE']['@attributes']['ID']) ? $this->arreglo[$this->config['tipos'][$this->tipo]]['SetDTE']['@attributes']['ID'] : false;
} | php | public function getID()
{
return isset($this->arreglo[$this->config['tipos'][$this->tipo]]['SetDTE']['@attributes']['ID']) ? $this->arreglo[$this->config['tipos'][$this->tipo]]['SetDTE']['@attributes']['ID'] : false;
} | [
"public",
"function",
"getID",
"(",
")",
"{",
"return",
"isset",
"(",
"$",
"this",
"->",
"arreglo",
"[",
"$",
"this",
"->",
"config",
"[",
"'tipos'",
"]",
"[",
"$",
"this",
"->",
"tipo",
"]",
"]",
"[",
"'SetDTE'",
"]",
"[",
"'@attributes'",
"]",
"[... | Método que entrega el ID de SetDTE
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-12-11 | [
"Método",
"que",
"entrega",
"el",
"ID",
"de",
"SetDTE"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/EnvioDte.php#L258-L261 |
LibreDTE/libredte-lib | lib/Sii/EnvioDte.php | EnvioDte.getDigest | public function getDigest()
{
return isset($this->arreglo[$this->config['tipos'][$this->tipo]]['Signature']['SignedInfo']['Reference']['DigestValue']) ? $this->arreglo[$this->config['tipos'][$this->tipo]]['Signature']['SignedInfo']['Reference']['DigestValue'] : false;
} | php | public function getDigest()
{
return isset($this->arreglo[$this->config['tipos'][$this->tipo]]['Signature']['SignedInfo']['Reference']['DigestValue']) ? $this->arreglo[$this->config['tipos'][$this->tipo]]['Signature']['SignedInfo']['Reference']['DigestValue'] : false;
} | [
"public",
"function",
"getDigest",
"(",
")",
"{",
"return",
"isset",
"(",
"$",
"this",
"->",
"arreglo",
"[",
"$",
"this",
"->",
"config",
"[",
"'tipos'",
"]",
"[",
"$",
"this",
"->",
"tipo",
"]",
"]",
"[",
"'Signature'",
"]",
"[",
"'SignedInfo'",
"]"... | Método que entrega el DigestValue de la firma del envío
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-12-11 | [
"Método",
"que",
"entrega",
"el",
"DigestValue",
"de",
"la",
"firma",
"del",
"envío"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/EnvioDte.php#L268-L271 |
LibreDTE/libredte-lib | lib/Sii/EnvioDte.php | EnvioDte.getFechaEmisionInicial | public function getFechaEmisionInicial()
{
$fecha = '9999-12-31';
foreach ($this->getDocumentos() as $Dte) {
if ($Dte->getFechaEmision() < $fecha)
$fecha = $Dte->getFechaEmision();
}
return $fecha;
} | php | public function getFechaEmisionInicial()
{
$fecha = '9999-12-31';
foreach ($this->getDocumentos() as $Dte) {
if ($Dte->getFechaEmision() < $fecha)
$fecha = $Dte->getFechaEmision();
}
return $fecha;
} | [
"public",
"function",
"getFechaEmisionInicial",
"(",
")",
"{",
"$",
"fecha",
"=",
"'9999-12-31'",
";",
"foreach",
"(",
"$",
"this",
"->",
"getDocumentos",
"(",
")",
"as",
"$",
"Dte",
")",
"{",
"if",
"(",
"$",
"Dte",
"->",
"getFechaEmision",
"(",
")",
"... | Método que entrega la fecha del DTE más antiguo del envio
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-12-12 | [
"Método",
"que",
"entrega",
"la",
"fecha",
"del",
"DTE",
"más",
"antiguo",
"del",
"envio"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/EnvioDte.php#L300-L308 |
LibreDTE/libredte-lib | lib/Sii/EnvioDte.php | EnvioDte.getFechaEmisionFinal | public function getFechaEmisionFinal()
{
$fecha = '0000-01-01';
foreach ($this->getDocumentos() as $Dte) {
if ($Dte->getFechaEmision() > $fecha)
$fecha = $Dte->getFechaEmision();
}
return $fecha;
} | php | public function getFechaEmisionFinal()
{
$fecha = '0000-01-01';
foreach ($this->getDocumentos() as $Dte) {
if ($Dte->getFechaEmision() > $fecha)
$fecha = $Dte->getFechaEmision();
}
return $fecha;
} | [
"public",
"function",
"getFechaEmisionFinal",
"(",
")",
"{",
"$",
"fecha",
"=",
"'0000-01-01'",
";",
"foreach",
"(",
"$",
"this",
"->",
"getDocumentos",
"(",
")",
"as",
"$",
"Dte",
")",
"{",
"if",
"(",
"$",
"Dte",
"->",
"getFechaEmision",
"(",
")",
">"... | Método que entrega la fecha del DTE más nuevo del envio
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-12-12 | [
"Método",
"que",
"entrega",
"la",
"fecha",
"del",
"DTE",
"más",
"nuevo",
"del",
"envio"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/EnvioDte.php#L315-L323 |
LibreDTE/libredte-lib | lib/Sii/EnvioDte.php | EnvioDte.getDocumentos | public function getDocumentos($c14n = true)
{
// si no hay documentos se deben crear
if (!$this->dtes) {
// si no hay XML no se pueden crear los documentos
if (!$this->xml) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::ENVIODTE_GETDOCUMENTOS_FALTA_XML,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::ENVIODTE_GETDOCUMENTOS_FALTA_XML)
);
return false;
}
// crear documentos a partir del XML
$DTEs = $this->xml->getElementsByTagName('DTE');
foreach ($DTEs as $nodo_dte) {
$xml = $c14n ? $nodo_dte->C14N() : $this->xml->saveXML($nodo_dte);
$this->dtes[] = new Dte($xml, false); // cargar DTE sin normalizar
}
}
return $this->dtes;
} | php | public function getDocumentos($c14n = true)
{
// si no hay documentos se deben crear
if (!$this->dtes) {
// si no hay XML no se pueden crear los documentos
if (!$this->xml) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::ENVIODTE_GETDOCUMENTOS_FALTA_XML,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::ENVIODTE_GETDOCUMENTOS_FALTA_XML)
);
return false;
}
// crear documentos a partir del XML
$DTEs = $this->xml->getElementsByTagName('DTE');
foreach ($DTEs as $nodo_dte) {
$xml = $c14n ? $nodo_dte->C14N() : $this->xml->saveXML($nodo_dte);
$this->dtes[] = new Dte($xml, false); // cargar DTE sin normalizar
}
}
return $this->dtes;
} | [
"public",
"function",
"getDocumentos",
"(",
"$",
"c14n",
"=",
"true",
")",
"{",
"// si no hay documentos se deben crear",
"if",
"(",
"!",
"$",
"this",
"->",
"dtes",
")",
"{",
"// si no hay XML no se pueden crear los documentos",
"if",
"(",
"!",
"$",
"this",
"->",
... | Método que entrega el arreglo con los objetos DTE del envío
@return Arreglo de objetos DTE
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-11-21 | [
"Método",
"que",
"entrega",
"el",
"arreglo",
"con",
"los",
"objetos",
"DTE",
"del",
"envío"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/EnvioDte.php#L331-L351 |
LibreDTE/libredte-lib | lib/Sii/EnvioDte.php | EnvioDte.getDocumento | public function getDocumento($emisor, $dte, $folio)
{
$emisor = str_replace('.', '', $emisor);
// si no hay XML no se pueden crear los documentos
if (!$this->xml) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::ENVIODTE_GETDOCUMENTOS_FALTA_XML,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::ENVIODTE_GETDOCUMENTOS_FALTA_XML)
);
return false;
}
// buscar documento
$DTEs = $this->xml->getElementsByTagName('DTE');
foreach ($DTEs as $nodo_dte) {
$e = $nodo_dte->getElementsByTagName('RUTEmisor')->item(0)->nodeValue;
if (is_numeric($emisor))
$e = substr($e, 0, -2);
$d = (int)$nodo_dte->getElementsByTagName('TipoDTE')->item(0)->nodeValue;
$f = (int)$nodo_dte->getElementsByTagName('Folio')->item(0)->nodeValue;
if ($folio == $f and $dte == $d and $emisor == $e) {
return new Dte($nodo_dte->C14N(), false); // cargar DTE sin normalizar
}
}
return false;
} | php | public function getDocumento($emisor, $dte, $folio)
{
$emisor = str_replace('.', '', $emisor);
// si no hay XML no se pueden crear los documentos
if (!$this->xml) {
\sasco\LibreDTE\Log::write(
\sasco\LibreDTE\Estado::ENVIODTE_GETDOCUMENTOS_FALTA_XML,
\sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::ENVIODTE_GETDOCUMENTOS_FALTA_XML)
);
return false;
}
// buscar documento
$DTEs = $this->xml->getElementsByTagName('DTE');
foreach ($DTEs as $nodo_dte) {
$e = $nodo_dte->getElementsByTagName('RUTEmisor')->item(0)->nodeValue;
if (is_numeric($emisor))
$e = substr($e, 0, -2);
$d = (int)$nodo_dte->getElementsByTagName('TipoDTE')->item(0)->nodeValue;
$f = (int)$nodo_dte->getElementsByTagName('Folio')->item(0)->nodeValue;
if ($folio == $f and $dte == $d and $emisor == $e) {
return new Dte($nodo_dte->C14N(), false); // cargar DTE sin normalizar
}
}
return false;
} | [
"public",
"function",
"getDocumento",
"(",
"$",
"emisor",
",",
"$",
"dte",
",",
"$",
"folio",
")",
"{",
"$",
"emisor",
"=",
"str_replace",
"(",
"'.'",
",",
"''",
",",
"$",
"emisor",
")",
";",
"// si no hay XML no se pueden crear los documentos",
"if",
"(",
... | Método que entrega el objeto DTE solicitado del envío
@return Objeto DTE
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-11-21 | [
"Método",
"que",
"entrega",
"el",
"objeto",
"DTE",
"solicitado",
"del",
"envío"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/EnvioDte.php#L359-L383 |
LibreDTE/libredte-lib | lib/Sii/EnvioDte.php | EnvioDte.checkFirma | public function checkFirma()
{
if (!$this->xml)
return null;
// listado de firmas del XML
$Signatures = $this->xml->documentElement->getElementsByTagName('Signature');
// verificar firma de SetDTE
$SetDTE = $this->xml->documentElement->getElementsByTagName('SetDTE')->item(0)->C14N();
$SignedInfo = $Signatures->item($Signatures->length-1)->getElementsByTagName('SignedInfo')->item(0);
$DigestValue = $Signatures->item($Signatures->length-1)->getElementsByTagName('DigestValue')->item(0)->nodeValue;
$SignatureValue = $Signatures->item($Signatures->length-1)->getElementsByTagName('SignatureValue')->item(0)->nodeValue;
$X509Certificate = $Signatures->item($Signatures->length-1)->getElementsByTagName('X509Certificate')->item(0)->nodeValue;
if ($X509Certificate[1]==' ' or $X509Certificate[1]=="\t") {
$lineas = explode("\n", $X509Certificate);
$X509Certificate = '';
foreach($lineas as $l) {
$X509Certificate .= trim($l);
}
}
$X509Certificate = '-----BEGIN CERTIFICATE-----'."\n".wordwrap(trim($X509Certificate), 64, "\n", true)."\n".'-----END CERTIFICATE-----';
$valid = openssl_verify($SignedInfo->C14N(), base64_decode($SignatureValue), $X509Certificate) === 1 ? true : false;
return $valid and $DigestValue===base64_encode(sha1($SetDTE, true));
} | php | public function checkFirma()
{
if (!$this->xml)
return null;
// listado de firmas del XML
$Signatures = $this->xml->documentElement->getElementsByTagName('Signature');
// verificar firma de SetDTE
$SetDTE = $this->xml->documentElement->getElementsByTagName('SetDTE')->item(0)->C14N();
$SignedInfo = $Signatures->item($Signatures->length-1)->getElementsByTagName('SignedInfo')->item(0);
$DigestValue = $Signatures->item($Signatures->length-1)->getElementsByTagName('DigestValue')->item(0)->nodeValue;
$SignatureValue = $Signatures->item($Signatures->length-1)->getElementsByTagName('SignatureValue')->item(0)->nodeValue;
$X509Certificate = $Signatures->item($Signatures->length-1)->getElementsByTagName('X509Certificate')->item(0)->nodeValue;
if ($X509Certificate[1]==' ' or $X509Certificate[1]=="\t") {
$lineas = explode("\n", $X509Certificate);
$X509Certificate = '';
foreach($lineas as $l) {
$X509Certificate .= trim($l);
}
}
$X509Certificate = '-----BEGIN CERTIFICATE-----'."\n".wordwrap(trim($X509Certificate), 64, "\n", true)."\n".'-----END CERTIFICATE-----';
$valid = openssl_verify($SignedInfo->C14N(), base64_decode($SignatureValue), $X509Certificate) === 1 ? true : false;
return $valid and $DigestValue===base64_encode(sha1($SetDTE, true));
} | [
"public",
"function",
"checkFirma",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"xml",
")",
"return",
"null",
";",
"// listado de firmas del XML",
"$",
"Signatures",
"=",
"$",
"this",
"->",
"xml",
"->",
"documentElement",
"->",
"getElementsByTagName",
... | Método que indica si la firma del documento es o no válida
@return =true si la firma del documento del envío es válida, =null si no se pudo determinar
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-04-07 | [
"Método",
"que",
"indica",
"si",
"la",
"firma",
"del",
"documento",
"es",
"o",
"no",
"válida"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/Sii/EnvioDte.php#L420-L442 |
LibreDTE/libredte-lib | lib/PDF.php | PDF.Footer | public function Footer()
{
if (is_array($this->footer) and (!empty($this->footer['left']) or !empty($this->footer['right']))) {
$style = ['width' => 0.5, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => [50, 50, 50]];
$this->Line(0, $this->getY()-1, 290, $this->getY()-2, $style);
$this->SetFont('', 'B', 6);
if (empty($this->papelContinuo)) {
if (!empty($this->footer['left']))
$this->Texto($this->footer['left']);
if (!empty($this->footer['right']))
$this->Texto($this->footer['right'], null, null, 'R');
} else {
if (!empty($this->footer['left']))
$this->Texto($this->footer['left'], null, null, 'C');
if (!empty($this->footer['right'])) {
$this->Ln();
$this->Texto($this->footer['right'], null, null, 'C');
}
}
}
} | php | public function Footer()
{
if (is_array($this->footer) and (!empty($this->footer['left']) or !empty($this->footer['right']))) {
$style = ['width' => 0.5, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => [50, 50, 50]];
$this->Line(0, $this->getY()-1, 290, $this->getY()-2, $style);
$this->SetFont('', 'B', 6);
if (empty($this->papelContinuo)) {
if (!empty($this->footer['left']))
$this->Texto($this->footer['left']);
if (!empty($this->footer['right']))
$this->Texto($this->footer['right'], null, null, 'R');
} else {
if (!empty($this->footer['left']))
$this->Texto($this->footer['left'], null, null, 'C');
if (!empty($this->footer['right'])) {
$this->Ln();
$this->Texto($this->footer['right'], null, null, 'C');
}
}
}
} | [
"public",
"function",
"Footer",
"(",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"this",
"->",
"footer",
")",
"and",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"footer",
"[",
"'left'",
"]",
")",
"or",
"!",
"empty",
"(",
"$",
"this",
"->",
"footer"... | Método que genera el footer del PDF
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]delaf.cl)
@version 2015-03-20 | [
"Método",
"que",
"genera",
"el",
"footer",
"del",
"PDF"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/PDF.php#L98-L118 |
LibreDTE/libredte-lib | lib/PDF.php | PDF.setFooterText | public function setFooterText($footer = true)
{
if ($footer) {
// asignar valor por defecto
if ($footer===true) {
$footer = [
'left' => 'LibreDTE ¡facturación electrónica libre para Chile!',
'right' => 'https://libredte.cl',
];
}
// si no es arreglo se convierte en uno
if (!is_array($footer))
$footer = ['left'=>$footer];
// asignar footer
$this->footer = array_merge(['left'=>'', 'right'=>''], $footer);
} else {
$this->footer = null;
}
} | php | public function setFooterText($footer = true)
{
if ($footer) {
// asignar valor por defecto
if ($footer===true) {
$footer = [
'left' => 'LibreDTE ¡facturación electrónica libre para Chile!',
'right' => 'https://libredte.cl',
];
}
// si no es arreglo se convierte en uno
if (!is_array($footer))
$footer = ['left'=>$footer];
// asignar footer
$this->footer = array_merge(['left'=>'', 'right'=>''], $footer);
} else {
$this->footer = null;
}
} | [
"public",
"function",
"setFooterText",
"(",
"$",
"footer",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"footer",
")",
"{",
"// asignar valor por defecto",
"if",
"(",
"$",
"footer",
"===",
"true",
")",
"{",
"$",
"footer",
"=",
"[",
"'left'",
"=>",
"'LibreDTE ¡... | Método que asigna el texto que se deberá usar en el footer
@param footer =true se asignará texto por defecto. String al lado izquiero o bien arreglo con índices left y right con sus textos
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]delaf.cl)
@version 2016-03-20 | [
"Método",
"que",
"asigna",
"el",
"texto",
"que",
"se",
"deberá",
"usar",
"en",
"el",
"footer"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/PDF.php#L126-L144 |
LibreDTE/libredte-lib | lib/PDF.php | PDF.getTableCellWidth | private function getTableCellWidth($total, $cells)
{
$widths = [];
if (is_int($cells)) {
$width = floor($total/$cells);
for ($i=0; $i<$cells; ++$i) {
$widths[] = $width;
}
}
else if (is_array($cells)){
$width = floor($total/count($cells));
foreach ($cells as $i) {
$widths[$i] = $width;
}
}
return $widths;
} | php | private function getTableCellWidth($total, $cells)
{
$widths = [];
if (is_int($cells)) {
$width = floor($total/$cells);
for ($i=0; $i<$cells; ++$i) {
$widths[] = $width;
}
}
else if (is_array($cells)){
$width = floor($total/count($cells));
foreach ($cells as $i) {
$widths[$i] = $width;
}
}
return $widths;
} | [
"private",
"function",
"getTableCellWidth",
"(",
"$",
"total",
",",
"$",
"cells",
")",
"{",
"$",
"widths",
"=",
"[",
"]",
";",
"if",
"(",
"is_int",
"(",
"$",
"cells",
")",
")",
"{",
"$",
"width",
"=",
"floor",
"(",
"$",
"total",
"/",
"$",
"cells"... | Obtener el ancho de las columnas de una tabla
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]delaf.cl)
@version 2016-01-22 | [
"Obtener",
"el",
"ancho",
"de",
"las",
"columnas",
"de",
"una",
"tabla"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/PDF.php#L151-L167 |
LibreDTE/libredte-lib | lib/PDF.php | PDF.addTableWithoutEmptyCols | public function addTableWithoutEmptyCols($titles, $data, $options = [], $html = true)
{
$cols_empty = [];
foreach ($data as $row) {
foreach ($row as $col => $value) {
if (empty($value)) {
if (!array_key_exists($col, $cols_empty))
$cols_empty[$col] = 0;
$cols_empty[$col]++;
}
}
}
$n_rows = count($data);
$titles_keys = array_flip(array_keys($titles));
foreach ($cols_empty as $col => $rows) {
if ($rows==$n_rows) {
unset($titles[$col]);
foreach ($data as &$row) {
unset($row[$col]);
}
if (isset($options['width']))
unset($options['width'][$titles_keys[$col]]);
if (isset($options['align']))
unset($options['align'][$titles_keys[$col]]);
}
}
if (isset($options['width'])) {
$options['width'] = array_slice($options['width'], 0);
$key_0 = null;
$suma = 0;
foreach ($options['width'] as $key => $val) {
if ($val===0)
$key_0 = $key;
$suma += $val;
}
if ($key_0!==null) {
$options['width'][$key_0] = 190 - $suma;
}
}
if (isset($options['align']))
$options['align'] = array_slice($options['align'], 0);
$this->addTable($titles, $data, $options, $html);
} | php | public function addTableWithoutEmptyCols($titles, $data, $options = [], $html = true)
{
$cols_empty = [];
foreach ($data as $row) {
foreach ($row as $col => $value) {
if (empty($value)) {
if (!array_key_exists($col, $cols_empty))
$cols_empty[$col] = 0;
$cols_empty[$col]++;
}
}
}
$n_rows = count($data);
$titles_keys = array_flip(array_keys($titles));
foreach ($cols_empty as $col => $rows) {
if ($rows==$n_rows) {
unset($titles[$col]);
foreach ($data as &$row) {
unset($row[$col]);
}
if (isset($options['width']))
unset($options['width'][$titles_keys[$col]]);
if (isset($options['align']))
unset($options['align'][$titles_keys[$col]]);
}
}
if (isset($options['width'])) {
$options['width'] = array_slice($options['width'], 0);
$key_0 = null;
$suma = 0;
foreach ($options['width'] as $key => $val) {
if ($val===0)
$key_0 = $key;
$suma += $val;
}
if ($key_0!==null) {
$options['width'][$key_0] = 190 - $suma;
}
}
if (isset($options['align']))
$options['align'] = array_slice($options['align'], 0);
$this->addTable($titles, $data, $options, $html);
} | [
"public",
"function",
"addTableWithoutEmptyCols",
"(",
"$",
"titles",
",",
"$",
"data",
",",
"$",
"options",
"=",
"[",
"]",
",",
"$",
"html",
"=",
"true",
")",
"{",
"$",
"cols_empty",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"data",
"as",
"$",
"row... | Agregar una tabla al PDF removiendo aquellas columnas donde no existen
datos en la columna para todas las filas
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]delaf.cl)
@version 2016-10-06 | [
"Agregar",
"una",
"tabla",
"al",
"PDF",
"removiendo",
"aquellas",
"columnas",
"donde",
"no",
"existen",
"datos",
"en",
"la",
"columna",
"para",
"todas",
"las",
"filas"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/PDF.php#L175-L217 |
LibreDTE/libredte-lib | lib/PDF.php | PDF.addTable | public function addTable($headers, $data, $options = [], $html = true)
{
$options = array_merge($this->defaultOptions['table'], $options);
if ($html) {
$this->addHTMLTable($headers, $data, $options);
} else {
$this->addNormalTable($headers, $data, $options);
}
} | php | public function addTable($headers, $data, $options = [], $html = true)
{
$options = array_merge($this->defaultOptions['table'], $options);
if ($html) {
$this->addHTMLTable($headers, $data, $options);
} else {
$this->addNormalTable($headers, $data, $options);
}
} | [
"public",
"function",
"addTable",
"(",
"$",
"headers",
",",
"$",
"data",
",",
"$",
"options",
"=",
"[",
"]",
",",
"$",
"html",
"=",
"true",
")",
"{",
"$",
"options",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"defaultOptions",
"[",
"'table'",
"]",
... | Agregar una tabla generada al PDF (puede ser en HTML o normal)
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]delaf.cl)
@version 2016-10-06 | [
"Agregar",
"una",
"tabla",
"generada",
"al",
"PDF",
"(",
"puede",
"ser",
"en",
"HTML",
"o",
"normal",
")"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/PDF.php#L224-L232 |
LibreDTE/libredte-lib | lib/PDF.php | PDF.addHTMLTable | private function addHTMLTable($headers, $data, $options = [])
{
$w = (isset($options['width']) and is_array($options['width'])) ? $options['width'] : null;
$a = (isset($options['align']) and is_array($options['align'])) ? $options['align'] : [];
$buffer = '<table style="border:1px solid #333">';
// Definir títulos de columnas
$thead = isset($options['width']) and is_array($options['width']) and count($options['width']) == count($headers);
if ($thead)
$buffer .= '<thead>';
$buffer .= '<tr>';
$i = 0;
foreach ($headers as &$col) {
$width = ($w and isset($w[$i])) ? (';width:'.$w[$i].'mm') : '';
$align = isset($a[$i]) ? $a[$i] : 'center';
$buffer .= '<th style="border-right:1px solid #333;border-bottom:1px solid #333;text-align:'.$align.$width.'"><strong>'.strip_tags($col).'</strong></th>';
$i++;
}
$buffer .= '</tr>';
if ($thead)
$buffer .= '</thead>';
// Definir datos de la tabla
if ($thead)
$buffer .= '<tbody>';
foreach ($data as &$row) {
$buffer .= '<tr>';
$i = 0;
foreach ($row as &$col) {
$width = ($w and isset($w[$i])) ? (';width:'.$w[$i].'mm') : '';
$align = isset($a[$i]) ? $a[$i] : 'center';
$buffer .= '<td style="border-right:1px solid #333;text-align:'.$align.$width.'">'.$col.'</td>';
$i++;
}
$buffer .= '</tr>';
}
if ($thead)
$buffer .= '</tbody>';
// Finalizar tabla
$buffer .= '</table>';
// generar tabla en HTML
$this->writeHTML($buffer, true, false, false, false, '');
} | php | private function addHTMLTable($headers, $data, $options = [])
{
$w = (isset($options['width']) and is_array($options['width'])) ? $options['width'] : null;
$a = (isset($options['align']) and is_array($options['align'])) ? $options['align'] : [];
$buffer = '<table style="border:1px solid #333">';
// Definir títulos de columnas
$thead = isset($options['width']) and is_array($options['width']) and count($options['width']) == count($headers);
if ($thead)
$buffer .= '<thead>';
$buffer .= '<tr>';
$i = 0;
foreach ($headers as &$col) {
$width = ($w and isset($w[$i])) ? (';width:'.$w[$i].'mm') : '';
$align = isset($a[$i]) ? $a[$i] : 'center';
$buffer .= '<th style="border-right:1px solid #333;border-bottom:1px solid #333;text-align:'.$align.$width.'"><strong>'.strip_tags($col).'</strong></th>';
$i++;
}
$buffer .= '</tr>';
if ($thead)
$buffer .= '</thead>';
// Definir datos de la tabla
if ($thead)
$buffer .= '<tbody>';
foreach ($data as &$row) {
$buffer .= '<tr>';
$i = 0;
foreach ($row as &$col) {
$width = ($w and isset($w[$i])) ? (';width:'.$w[$i].'mm') : '';
$align = isset($a[$i]) ? $a[$i] : 'center';
$buffer .= '<td style="border-right:1px solid #333;text-align:'.$align.$width.'">'.$col.'</td>';
$i++;
}
$buffer .= '</tr>';
}
if ($thead)
$buffer .= '</tbody>';
// Finalizar tabla
$buffer .= '</table>';
// generar tabla en HTML
$this->writeHTML($buffer, true, false, false, false, '');
} | [
"private",
"function",
"addHTMLTable",
"(",
"$",
"headers",
",",
"$",
"data",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"w",
"=",
"(",
"isset",
"(",
"$",
"options",
"[",
"'width'",
"]",
")",
"and",
"is_array",
"(",
"$",
"options",
"[",
"... | Agregar una tabla generada a través de código HTML al PDF
@todo Utilizar las opciones para definir estilo de la tabla HTML
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]delaf.cl)
@version 2016-10-06 | [
"Agregar",
"una",
"tabla",
"generada",
"a",
"través",
"de",
"código",
"HTML",
"al",
"PDF"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/PDF.php#L240-L280 |
LibreDTE/libredte-lib | lib/PDF.php | PDF.addNormalTable | private function addNormalTable(array $headers, array $data, array $options = [])
{
// Colors, line width and bold font
$this->SetFillColor(
$options['headerbackground'][0],
$options['headerbackground'][1],
$options['headerbackground'][2]
);
$this->SetTextColor(
$options['headercolor'][0],
$options['headercolor'][1],
$options['headercolor'][2]
);
$this->SetDrawColor(
$options['bordercolor'][0],
$options['bordercolor'][1],
$options['bordercolor'][2]
);
$this->SetLineWidth($options['borderwidth']);
$this->SetFont($this->defaultOptions['font']['family'], 'B', $options['fontsize']);
// corregir indices
$headers_keys = array_keys($headers);
if (is_array($options['width'])) {
$options['width'] = array_combine($headers_keys, $options['width']);
} else {
$options['width'] = $this->getTableCellWidth($options['width'], $headers_keys);
}
if (is_array($options['align'])) {
$options['align'] = array_combine($headers_keys, $options['align']);
foreach ($options['align'] as &$a) {
$a = strtoupper($a[0]);
}
} else if (is_string($options['align'])) {
$align = $options['align'];
$options['align'] = [];
foreach ($headers_keys as $key) {
$options['align'][$key] = $align;
}
}
// Header
$x = $this->GetX();
foreach($headers as $i => $header) {
$this->Cell($options['width'][$i], $options['height'], $headers[$i], 1, 0, $options['align'][$i], 1);
}
$this->Ln();
$y = $this->GetY();
// Color and font restoration
$this->SetFillColor (
$options['bodybackground'][0],
$options['bodybackground'][1],
$options['bodybackground'][2]
);
$this->SetTextColor(
$options['bodycolor'][0],
$options['bodycolor'][1],
$options['bodycolor'][2]
);
$this->SetDrawColor(
$options['bordercolor'][0],
$options['bordercolor'][1],
$options['bordercolor'][2]
);
$this->SetLineWidth($options['borderwidth']);
$this->SetFont($this->defaultOptions['font']['family']);
// Data
foreach ($data as &$row) {
$num_pages = $this->getNumPages();
$this->startTransaction();
// agregar datos de la fila
$this->SetX($x);
$y_0 = $this->GetY();
$y_s = [];
foreach($headers as $i => $header) {
$x_0 = $this->GetX();
$this->SetXY($x_0, $y_0);
$aux = explode("\n", $row[$i]);
$value1 = $aux[0];
$value2 = isset($aux[1]) ? $aux[1] : null;
$y_1 = $this->MultiCell($options['width'][$i], $options['height'], $value1, $options['tdborder'], $options['align'][$i], false, 0);
if ($value2) {
$this->Ln();
$this->SetX($x_0);
$this->SetFont($this->defaultOptions['font']['family'], '', $options['fontsize']-2);
$y_2 = $this->MultiCell($options['width'][$i], $options['height'], $value2, $options['tdborder'], $options['align'][$i], false, 0);
$this->SetFont($this->defaultOptions['font']['family'], '', $options['fontsize']);
$y_s[] = $y_1 + $y_2*0.9;
} else {
$y_s[] = $y_1;
}
}
$this->Ln(max($y_s)*5);
// si se pasó a página siguiente se hace rollback y se crea nueva página con cabecera nuevamente en la tabla
if($num_pages < $this->getNumPages()) {
$this->rollbackTransaction(true);
$this->AddPage();
$this->SetX($x);
foreach($headers as $i => $header) {
$this->Cell($options['width'][$i], $options['height'], $headers[$i], 1, 0, $options['align'][$i], 1);
}
$this->Ln();
$this->SetX($x);
$y_0 = $this->GetY();
$y_s = [];
foreach($headers as $i => $header) {
$x_0 = $this->GetX();
$this->SetXY($x_0, $y_0);
$aux = explode("\n", $row[$i]);
$value1 = $aux[0];
$value2 = isset($aux[1]) ? $aux[1] : null;
$y_1 = $this->MultiCell($options['width'][$i], $options['height'], $value1, $options['tdborder'], $options['align'][$i], false, 0);
if ($value2) {
$this->Ln();
$this->SetX($x_0);
$this->SetFont($this->defaultOptions['font']['family'], '', $options['fontsize']-2);
$y_2 = $this->MultiCell($options['width'][$i], $options['height'], $value2, $options['tdborder'], $options['align'][$i], false, 0);
$this->SetFont($this->defaultOptions['font']['family'], '', $options['fontsize']);
$y_s[] = $y_1 + $y_2*0.9;
} else {
$y_s[] = $y_1;
}
}
$this->Ln(max($y_s)*5);
} else {
$this->commitTransaction();
}
}
// si la tabla tiene indicado un punto específico en Y donde terminar se usa ese punto
if ($options['end']) {
$lx = $x;
$this->Line($lx, $y, $lx, $options['end']);
foreach ($options['width'] as $ancho) {
$lx += $ancho;
$this->Line($lx, $y, $lx, $options['end']);
}
$this->SetXY($x, $options['end']);
} else {
$this->SetX($x);
}
// asignar línea final
$this->Cell(array_sum($options['width']), 0, '', 'T');
$this->Ln();
} | php | private function addNormalTable(array $headers, array $data, array $options = [])
{
// Colors, line width and bold font
$this->SetFillColor(
$options['headerbackground'][0],
$options['headerbackground'][1],
$options['headerbackground'][2]
);
$this->SetTextColor(
$options['headercolor'][0],
$options['headercolor'][1],
$options['headercolor'][2]
);
$this->SetDrawColor(
$options['bordercolor'][0],
$options['bordercolor'][1],
$options['bordercolor'][2]
);
$this->SetLineWidth($options['borderwidth']);
$this->SetFont($this->defaultOptions['font']['family'], 'B', $options['fontsize']);
// corregir indices
$headers_keys = array_keys($headers);
if (is_array($options['width'])) {
$options['width'] = array_combine($headers_keys, $options['width']);
} else {
$options['width'] = $this->getTableCellWidth($options['width'], $headers_keys);
}
if (is_array($options['align'])) {
$options['align'] = array_combine($headers_keys, $options['align']);
foreach ($options['align'] as &$a) {
$a = strtoupper($a[0]);
}
} else if (is_string($options['align'])) {
$align = $options['align'];
$options['align'] = [];
foreach ($headers_keys as $key) {
$options['align'][$key] = $align;
}
}
// Header
$x = $this->GetX();
foreach($headers as $i => $header) {
$this->Cell($options['width'][$i], $options['height'], $headers[$i], 1, 0, $options['align'][$i], 1);
}
$this->Ln();
$y = $this->GetY();
// Color and font restoration
$this->SetFillColor (
$options['bodybackground'][0],
$options['bodybackground'][1],
$options['bodybackground'][2]
);
$this->SetTextColor(
$options['bodycolor'][0],
$options['bodycolor'][1],
$options['bodycolor'][2]
);
$this->SetDrawColor(
$options['bordercolor'][0],
$options['bordercolor'][1],
$options['bordercolor'][2]
);
$this->SetLineWidth($options['borderwidth']);
$this->SetFont($this->defaultOptions['font']['family']);
// Data
foreach ($data as &$row) {
$num_pages = $this->getNumPages();
$this->startTransaction();
// agregar datos de la fila
$this->SetX($x);
$y_0 = $this->GetY();
$y_s = [];
foreach($headers as $i => $header) {
$x_0 = $this->GetX();
$this->SetXY($x_0, $y_0);
$aux = explode("\n", $row[$i]);
$value1 = $aux[0];
$value2 = isset($aux[1]) ? $aux[1] : null;
$y_1 = $this->MultiCell($options['width'][$i], $options['height'], $value1, $options['tdborder'], $options['align'][$i], false, 0);
if ($value2) {
$this->Ln();
$this->SetX($x_0);
$this->SetFont($this->defaultOptions['font']['family'], '', $options['fontsize']-2);
$y_2 = $this->MultiCell($options['width'][$i], $options['height'], $value2, $options['tdborder'], $options['align'][$i], false, 0);
$this->SetFont($this->defaultOptions['font']['family'], '', $options['fontsize']);
$y_s[] = $y_1 + $y_2*0.9;
} else {
$y_s[] = $y_1;
}
}
$this->Ln(max($y_s)*5);
// si se pasó a página siguiente se hace rollback y se crea nueva página con cabecera nuevamente en la tabla
if($num_pages < $this->getNumPages()) {
$this->rollbackTransaction(true);
$this->AddPage();
$this->SetX($x);
foreach($headers as $i => $header) {
$this->Cell($options['width'][$i], $options['height'], $headers[$i], 1, 0, $options['align'][$i], 1);
}
$this->Ln();
$this->SetX($x);
$y_0 = $this->GetY();
$y_s = [];
foreach($headers as $i => $header) {
$x_0 = $this->GetX();
$this->SetXY($x_0, $y_0);
$aux = explode("\n", $row[$i]);
$value1 = $aux[0];
$value2 = isset($aux[1]) ? $aux[1] : null;
$y_1 = $this->MultiCell($options['width'][$i], $options['height'], $value1, $options['tdborder'], $options['align'][$i], false, 0);
if ($value2) {
$this->Ln();
$this->SetX($x_0);
$this->SetFont($this->defaultOptions['font']['family'], '', $options['fontsize']-2);
$y_2 = $this->MultiCell($options['width'][$i], $options['height'], $value2, $options['tdborder'], $options['align'][$i], false, 0);
$this->SetFont($this->defaultOptions['font']['family'], '', $options['fontsize']);
$y_s[] = $y_1 + $y_2*0.9;
} else {
$y_s[] = $y_1;
}
}
$this->Ln(max($y_s)*5);
} else {
$this->commitTransaction();
}
}
// si la tabla tiene indicado un punto específico en Y donde terminar se usa ese punto
if ($options['end']) {
$lx = $x;
$this->Line($lx, $y, $lx, $options['end']);
foreach ($options['width'] as $ancho) {
$lx += $ancho;
$this->Line($lx, $y, $lx, $options['end']);
}
$this->SetXY($x, $options['end']);
} else {
$this->SetX($x);
}
// asignar línea final
$this->Cell(array_sum($options['width']), 0, '', 'T');
$this->Ln();
} | [
"private",
"function",
"addNormalTable",
"(",
"array",
"$",
"headers",
",",
"array",
"$",
"data",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"// Colors, line width and bold font",
"$",
"this",
"->",
"SetFillColor",
"(",
"$",
"options",
"[",
"'hea... | Agregar una tabla generada mediante el método Cell
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]delaf.cl)
@version 2018-04-15 | [
"Agregar",
"una",
"tabla",
"generada",
"mediante",
"el",
"método",
"Cell"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/PDF.php#L287-L428 |
LibreDTE/libredte-lib | lib/PDF.php | PDF.Texto | public function Texto($txt, $x=null, $y=null, $align='', $w=0, $link='', $border=0, $fill=false)
{
if ($x==null) $x = $this->GetX();
if ($y==null) $y = $this->GetY();
$textrendermode = $this->textrendermode;
$textstrokewidth = $this->textstrokewidth;
$this->setTextRenderingMode(0, true, false);
$this->SetXY($x, $y);
$this->Cell($w, 0, $txt, $border, 0, $align, $fill, $link);
// restore previous rendering mode
$this->textrendermode = $textrendermode;
$this->textstrokewidth = $textstrokewidth;
} | php | public function Texto($txt, $x=null, $y=null, $align='', $w=0, $link='', $border=0, $fill=false)
{
if ($x==null) $x = $this->GetX();
if ($y==null) $y = $this->GetY();
$textrendermode = $this->textrendermode;
$textstrokewidth = $this->textstrokewidth;
$this->setTextRenderingMode(0, true, false);
$this->SetXY($x, $y);
$this->Cell($w, 0, $txt, $border, 0, $align, $fill, $link);
// restore previous rendering mode
$this->textrendermode = $textrendermode;
$this->textstrokewidth = $textstrokewidth;
} | [
"public",
"function",
"Texto",
"(",
"$",
"txt",
",",
"$",
"x",
"=",
"null",
",",
"$",
"y",
"=",
"null",
",",
"$",
"align",
"=",
"''",
",",
"$",
"w",
"=",
"0",
",",
"$",
"link",
"=",
"''",
",",
"$",
"border",
"=",
"0",
",",
"$",
"fill",
"=... | Agregar texto al PDF, es una variación del método Text que permite
definir un ancho al texto. Además recibe menos parámetros para ser
más simple (parámetros comunes solamente).
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]delaf.cl)
@version 2014-09-20 | [
"Agregar",
"texto",
"al",
"PDF",
"es",
"una",
"variación",
"del",
"método",
"Text",
"que",
"permite",
"definir",
"un",
"ancho",
"al",
"texto",
".",
"Además",
"recibe",
"menos",
"parámetros",
"para",
"ser",
"más",
"simple",
"(",
"parámetros",
"comunes",
"sola... | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/PDF.php#L437-L449 |
LibreDTE/libredte-lib | lib/PDF.php | PDF.MultiTexto | public function MultiTexto($txt, $x=null, $y=null, $align='', $w=0, $border=0, $fill=false)
{
if ($x==null) $x = $this->GetX();
if ($y==null) $y = $this->GetY();
$textrendermode = $this->textrendermode;
$textstrokewidth = $this->textstrokewidth;
$this->setTextRenderingMode(0, true, false);
$this->SetXY($x, $y);
$this->MultiCell($w, 0, $txt, $border, $align, $fill);
// restore previous rendering mode
$this->textrendermode = $textrendermode;
$this->textstrokewidth = $textstrokewidth;
} | php | public function MultiTexto($txt, $x=null, $y=null, $align='', $w=0, $border=0, $fill=false)
{
if ($x==null) $x = $this->GetX();
if ($y==null) $y = $this->GetY();
$textrendermode = $this->textrendermode;
$textstrokewidth = $this->textstrokewidth;
$this->setTextRenderingMode(0, true, false);
$this->SetXY($x, $y);
$this->MultiCell($w, 0, $txt, $border, $align, $fill);
// restore previous rendering mode
$this->textrendermode = $textrendermode;
$this->textstrokewidth = $textstrokewidth;
} | [
"public",
"function",
"MultiTexto",
"(",
"$",
"txt",
",",
"$",
"x",
"=",
"null",
",",
"$",
"y",
"=",
"null",
",",
"$",
"align",
"=",
"''",
",",
"$",
"w",
"=",
"0",
",",
"$",
"border",
"=",
"0",
",",
"$",
"fill",
"=",
"false",
")",
"{",
"if"... | Método idéntico a Texto, pero en vez de utilizar Cell utiliza
MultiCell. La principal diferencia es que este método no permite
agregar un enlace y Texto si.
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]delaf.cl)
@version 2014-09-20 | [
"Método",
"idéntico",
"a",
"Texto",
"pero",
"en",
"vez",
"de",
"utilizar",
"Cell",
"utiliza",
"MultiCell",
".",
"La",
"principal",
"diferencia",
"es",
"que",
"este",
"método",
"no",
"permite",
"agregar",
"un",
"enlace",
"y",
"Texto",
"si",
"."
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/PDF.php#L458-L470 |
LibreDTE/libredte-lib | lib/File.php | File.rmdir | public static function rmdir($dir)
{
// List the contents of the directory table
$dir_content = scandir ($dir);
// Is it a directory?
if ($dir_content!==false) {
// For each directory entry
foreach ($dir_content as &$entry) {
// Unix symbolic shortcuts, we go
if (!in_array ($entry, array ('.','..'))) {
// We find the path from the beginning
$entry = $dir.DIRECTORY_SEPARATOR. $entry;
// This entry is not an issue: it clears
if (!is_dir($entry)) {
unlink ($entry);
} else { // This entry is a folder, it again on this issue
self::rmdir($entry);
}
}
}
}
// It has erased all entries in the folder, we can now erase
rmdir ($dir);
} | php | public static function rmdir($dir)
{
// List the contents of the directory table
$dir_content = scandir ($dir);
// Is it a directory?
if ($dir_content!==false) {
// For each directory entry
foreach ($dir_content as &$entry) {
// Unix symbolic shortcuts, we go
if (!in_array ($entry, array ('.','..'))) {
// We find the path from the beginning
$entry = $dir.DIRECTORY_SEPARATOR. $entry;
// This entry is not an issue: it clears
if (!is_dir($entry)) {
unlink ($entry);
} else { // This entry is a folder, it again on this issue
self::rmdir($entry);
}
}
}
}
// It has erased all entries in the folder, we can now erase
rmdir ($dir);
} | [
"public",
"static",
"function",
"rmdir",
"(",
"$",
"dir",
")",
"{",
"// List the contents of the directory table",
"$",
"dir_content",
"=",
"scandir",
"(",
"$",
"dir",
")",
";",
"// Is it a directory?",
"if",
"(",
"$",
"dir_content",
"!==",
"false",
")",
"{",
... | Borra recursivamente un directorio
@param dir Directorio a borrar
@author http://en.kioskea.net/faq/793-warning-rmdir-directory-not-empty
@version 2015-04-21 | [
"Borra",
"recursivamente",
"un",
"directorio"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/File.php#L49-L72 |
LibreDTE/libredte-lib | lib/File.php | File.mimetype | public static function mimetype($file)
{
if (!function_exists('finfo_open'))
return false;
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimetype = finfo_file($finfo, $file);
finfo_close($finfo);
return $mimetype;
} | php | public static function mimetype($file)
{
if (!function_exists('finfo_open'))
return false;
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimetype = finfo_file($finfo, $file);
finfo_close($finfo);
return $mimetype;
} | [
"public",
"static",
"function",
"mimetype",
"(",
"$",
"file",
")",
"{",
"if",
"(",
"!",
"function_exists",
"(",
"'finfo_open'",
")",
")",
"return",
"false",
";",
"$",
"finfo",
"=",
"finfo_open",
"(",
"FILEINFO_MIME_TYPE",
")",
";",
"$",
"mimetype",
"=",
... | Método que entrega el mimetype de un archivo
@param file Ruta hacia el fichero
@return Mimetype del fichero o =false si no se pudo determinar
@author http://stackoverflow.com/a/23287361
@version 2015-11-03 | [
"Método",
"que",
"entrega",
"el",
"mimetype",
"de",
"un",
"archivo"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/File.php#L81-L89 |
LibreDTE/libredte-lib | lib/File.php | File.compress | public static function compress($file, $options = [])
{
// definir opciones por defecto
$options = array_merge([
'format' => 'gz',
'delete' => false,
'download' => true,
'commands' => [
'gz' => 'gzip --keep :in',
'tar.gz' => 'tar czf :in.tar.gz :in',
'tar' => 'tar cf :in.tar :in',
'bz2' => 'bzip2 --keep :in',
'tar.bz2' => 'tar cjf :in.tar.bz2 :in',
'zip' => 'zip -r :in.zip :in',
],
], $options);
// si el archivo no se puede leer se entrega =false
if (!is_readable($file)) {
\sasco\LibreDTE\Log::write(Estado::COMPRESS_ERROR_READ, Estado::get(Estado::COMPRESS_ERROR_READ));
return false;
}
// si es formato gz y es directorio se cambia a tgz
if (is_dir($file)) {
if ($options['format']=='gz') $options['format'] = 'tar.gz';
else if ($options['format']=='bz2') $options['format'] = 'tar.bz2';
}
// obtener directorio que contiene al archivo/directorio y el nombre de este
$filepath = $file;
$dir = dirname($file);
$file = basename($file);
$file_compressed = $file.'.'.$options['format'];
// empaquetar/comprimir directorio/archivo
if ($options['format']=='zip') {
// crear archivo zip
$zip = new \ZipArchive();
if ($zip->open($dir.DIRECTORY_SEPARATOR.$file.'.zip', \ZipArchive::CREATE)!==true) {
\sasco\LibreDTE\Log::write(Estado::COMPRESS_ERROR_ZIP, Estado::get(Estado::COMPRESS_ERROR_ZIP));
return false;
}
// agregar un único archivo al zip
if (!is_dir($filepath)) {
$zip->addFile($filepath, $file);
}
// agregar directorio al zip
else if (is_dir($filepath)) {
$Iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($filepath));
foreach ($Iterator as $f) {
if (!$f->isDir()) {
$path = $f->getPath().DIRECTORY_SEPARATOR.$f->getFilename();
$zip->addFile($path, str_replace($filepath, '', $file.DIRECTORY_SEPARATOR.$path));
}
}
}
// escribir en el sistema de archivos y cerrar archivo
file_put_contents($dir.DIRECTORY_SEPARATOR.$file_compressed, $zip->getStream(md5($filepath)));
$zip->close();
} else {
exec('cd '.$dir.' && '.str_replace(':in', $file, $options['commands'][$options['format']]));
}
// enviar archivo
if ($options['download']) {
ob_clean();
header ('Content-Disposition: attachment; filename='.$file_compressed);
$mimetype = self::mimetype($dir.DIRECTORY_SEPARATOR.$file_compressed);
if ($mimetype)
header ('Content-Type: '.$mimetype);
header ('Content-Length: '.filesize($dir.DIRECTORY_SEPARATOR.$file_compressed));
readfile($dir.DIRECTORY_SEPARATOR.$file_compressed);
unlink($dir.DIRECTORY_SEPARATOR.$file_compressed);
}
// borrar directorio o archivo que se está comprimiendo si así se ha
// solicitado
if ($options['delete']) {
if (is_dir($filepath)) self::rmdir($filepath);
else unlink($filepath);
}
} | php | public static function compress($file, $options = [])
{
// definir opciones por defecto
$options = array_merge([
'format' => 'gz',
'delete' => false,
'download' => true,
'commands' => [
'gz' => 'gzip --keep :in',
'tar.gz' => 'tar czf :in.tar.gz :in',
'tar' => 'tar cf :in.tar :in',
'bz2' => 'bzip2 --keep :in',
'tar.bz2' => 'tar cjf :in.tar.bz2 :in',
'zip' => 'zip -r :in.zip :in',
],
], $options);
// si el archivo no se puede leer se entrega =false
if (!is_readable($file)) {
\sasco\LibreDTE\Log::write(Estado::COMPRESS_ERROR_READ, Estado::get(Estado::COMPRESS_ERROR_READ));
return false;
}
// si es formato gz y es directorio se cambia a tgz
if (is_dir($file)) {
if ($options['format']=='gz') $options['format'] = 'tar.gz';
else if ($options['format']=='bz2') $options['format'] = 'tar.bz2';
}
// obtener directorio que contiene al archivo/directorio y el nombre de este
$filepath = $file;
$dir = dirname($file);
$file = basename($file);
$file_compressed = $file.'.'.$options['format'];
// empaquetar/comprimir directorio/archivo
if ($options['format']=='zip') {
// crear archivo zip
$zip = new \ZipArchive();
if ($zip->open($dir.DIRECTORY_SEPARATOR.$file.'.zip', \ZipArchive::CREATE)!==true) {
\sasco\LibreDTE\Log::write(Estado::COMPRESS_ERROR_ZIP, Estado::get(Estado::COMPRESS_ERROR_ZIP));
return false;
}
// agregar un único archivo al zip
if (!is_dir($filepath)) {
$zip->addFile($filepath, $file);
}
// agregar directorio al zip
else if (is_dir($filepath)) {
$Iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($filepath));
foreach ($Iterator as $f) {
if (!$f->isDir()) {
$path = $f->getPath().DIRECTORY_SEPARATOR.$f->getFilename();
$zip->addFile($path, str_replace($filepath, '', $file.DIRECTORY_SEPARATOR.$path));
}
}
}
// escribir en el sistema de archivos y cerrar archivo
file_put_contents($dir.DIRECTORY_SEPARATOR.$file_compressed, $zip->getStream(md5($filepath)));
$zip->close();
} else {
exec('cd '.$dir.' && '.str_replace(':in', $file, $options['commands'][$options['format']]));
}
// enviar archivo
if ($options['download']) {
ob_clean();
header ('Content-Disposition: attachment; filename='.$file_compressed);
$mimetype = self::mimetype($dir.DIRECTORY_SEPARATOR.$file_compressed);
if ($mimetype)
header ('Content-Type: '.$mimetype);
header ('Content-Length: '.filesize($dir.DIRECTORY_SEPARATOR.$file_compressed));
readfile($dir.DIRECTORY_SEPARATOR.$file_compressed);
unlink($dir.DIRECTORY_SEPARATOR.$file_compressed);
}
// borrar directorio o archivo que se está comprimiendo si así se ha
// solicitado
if ($options['delete']) {
if (is_dir($filepath)) self::rmdir($filepath);
else unlink($filepath);
}
} | [
"public",
"static",
"function",
"compress",
"(",
"$",
"file",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"// definir opciones por defecto",
"$",
"options",
"=",
"array_merge",
"(",
"[",
"'format'",
"=>",
"'gz'",
",",
"'delete'",
"=>",
"false",
",",
"'do... | Método que empaqueta y comprime archivos (uno o varios, o directorios).
Si se pide usar formato zip entonces se usará ZipArchive de PHP para
comprimir
@param filepath Directorio (o archivo) que se desea comprimir
@param options Arreglo con opciones para comprmir (format, download, delete)
@todo Preparar datos si se pasa un arreglo
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]delaf.cl)
@version 2015-11-03 | [
"Método",
"que",
"empaqueta",
"y",
"comprime",
"archivos",
"(",
"uno",
"o",
"varios",
"o",
"directorios",
")",
".",
"Si",
"se",
"pide",
"usar",
"formato",
"zip",
"entonces",
"se",
"usará",
"ZipArchive",
"de",
"PHP",
"para",
"comprimir"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/File.php#L101-L177 |
LibreDTE/libredte-lib | lib/FirmaElectronica.php | FirmaElectronica.error | private function error($msg)
{
if (class_exists('\sasco\LibreDTE\Estado') and class_exists('\sasco\LibreDTE\Log')) {
$msg = \sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::FIRMA_ERROR, $msg);
\sasco\LibreDTE\Log::write(\sasco\LibreDTE\Estado::FIRMA_ERROR, $msg);
return false;
} else {
throw new \Exception($msg);
}
} | php | private function error($msg)
{
if (class_exists('\sasco\LibreDTE\Estado') and class_exists('\sasco\LibreDTE\Log')) {
$msg = \sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::FIRMA_ERROR, $msg);
\sasco\LibreDTE\Log::write(\sasco\LibreDTE\Estado::FIRMA_ERROR, $msg);
return false;
} else {
throw new \Exception($msg);
}
} | [
"private",
"function",
"error",
"(",
"$",
"msg",
")",
"{",
"if",
"(",
"class_exists",
"(",
"'\\sasco\\LibreDTE\\Estado'",
")",
"and",
"class_exists",
"(",
"'\\sasco\\LibreDTE\\Log'",
")",
")",
"{",
"$",
"msg",
"=",
"\\",
"sasco",
"\\",
"LibreDTE",
"\\",
"Est... | Método para generar un error usando una excepción de SowerPHP o terminar
el script si no se está usando el framework
@param msg Mensaje del error
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-08-04 | [
"Método",
"para",
"generar",
"un",
"error",
"usando",
"una",
"excepción",
"de",
"SowerPHP",
"o",
"terminar",
"el",
"script",
"si",
"no",
"se",
"está",
"usando",
"el",
"framework"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/FirmaElectronica.php#L107-L116 |
LibreDTE/libredte-lib | lib/FirmaElectronica.php | FirmaElectronica.normalizeCert | private function normalizeCert($cert)
{
if (strpos($cert, '-----BEGIN CERTIFICATE-----')===false) {
$body = trim($cert);
$cert = '-----BEGIN CERTIFICATE-----'."\n";
$cert .= wordwrap($body, $this->config['wordwrap'], "\n", true)."\n";
$cert .= '-----END CERTIFICATE-----'."\n";
}
return $cert;
} | php | private function normalizeCert($cert)
{
if (strpos($cert, '-----BEGIN CERTIFICATE-----')===false) {
$body = trim($cert);
$cert = '-----BEGIN CERTIFICATE-----'."\n";
$cert .= wordwrap($body, $this->config['wordwrap'], "\n", true)."\n";
$cert .= '-----END CERTIFICATE-----'."\n";
}
return $cert;
} | [
"private",
"function",
"normalizeCert",
"(",
"$",
"cert",
")",
"{",
"if",
"(",
"strpos",
"(",
"$",
"cert",
",",
"'-----BEGIN CERTIFICATE-----'",
")",
"===",
"false",
")",
"{",
"$",
"body",
"=",
"trim",
"(",
"$",
"cert",
")",
";",
"$",
"cert",
"=",
"'... | Método que agrega el inicio y fin de un certificado (clave pública)
@param cert Certificado que se desea normalizar
@return Certificado con el inicio y fin correspondiente
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-08-20 | [
"Método",
"que",
"agrega",
"el",
"inicio",
"y",
"fin",
"de",
"un",
"certificado",
"(",
"clave",
"pública",
")"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/FirmaElectronica.php#L125-L134 |
LibreDTE/libredte-lib | lib/FirmaElectronica.php | FirmaElectronica.getID | public function getID()
{
// RUN/RUT se encuentra en la extensión del certificado, esto de acuerdo
// a Ley 19.799 sobre documentos electrónicos y firma electrónica
$x509 = new \phpseclib\File\X509();
$cert = $x509->loadX509($this->certs['cert']);
if (isset($cert['tbsCertificate']['extensions'])) {
foreach ($cert['tbsCertificate']['extensions'] as $e) {
if ($e['extnId']=='id-ce-subjectAltName') {
return ltrim($e['extnValue'][0]['otherName']['value']['ia5String'], '0');
}
}
}
// se obtiene desde serialNumber (esto es sólo para que funcione la firma para tests)
if (isset($this->data['subject']['serialNumber'])) {
return ltrim($this->data['subject']['serialNumber'], '0');
}
// no se encontró el RUN
return $this->error('No fue posible obtener el ID de la firma');
} | php | public function getID()
{
// RUN/RUT se encuentra en la extensión del certificado, esto de acuerdo
// a Ley 19.799 sobre documentos electrónicos y firma electrónica
$x509 = new \phpseclib\File\X509();
$cert = $x509->loadX509($this->certs['cert']);
if (isset($cert['tbsCertificate']['extensions'])) {
foreach ($cert['tbsCertificate']['extensions'] as $e) {
if ($e['extnId']=='id-ce-subjectAltName') {
return ltrim($e['extnValue'][0]['otherName']['value']['ia5String'], '0');
}
}
}
// se obtiene desde serialNumber (esto es sólo para que funcione la firma para tests)
if (isset($this->data['subject']['serialNumber'])) {
return ltrim($this->data['subject']['serialNumber'], '0');
}
// no se encontró el RUN
return $this->error('No fue posible obtener el ID de la firma');
} | [
"public",
"function",
"getID",
"(",
")",
"{",
"// RUN/RUT se encuentra en la extensión del certificado, esto de acuerdo",
"// a Ley 19.799 sobre documentos electrónicos y firma electrónica",
"$",
"x509",
"=",
"new",
"\\",
"phpseclib",
"\\",
"File",
"\\",
"X509",
"(",
")",
";"... | Método que entrega el RUN/RUT asociado al certificado
@return RUN/RUT asociado al certificado en formato: 11222333-4
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2016-02-12 | [
"Método",
"que",
"entrega",
"el",
"RUN",
"/",
"RUT",
"asociado",
"al",
"certificado"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/FirmaElectronica.php#L142-L161 |
LibreDTE/libredte-lib | lib/FirmaElectronica.php | FirmaElectronica.getTotalDays | public function getTotalDays()
{
$start = new \DateTime($this->getFrom());
$end = new \DateTime($this->getTo());
$diff = $start->diff($end);
return $diff->format('%a');
} | php | public function getTotalDays()
{
$start = new \DateTime($this->getFrom());
$end = new \DateTime($this->getTo());
$diff = $start->diff($end);
return $diff->format('%a');
} | [
"public",
"function",
"getTotalDays",
"(",
")",
"{",
"$",
"start",
"=",
"new",
"\\",
"DateTime",
"(",
"$",
"this",
"->",
"getFrom",
"(",
")",
")",
";",
"$",
"end",
"=",
"new",
"\\",
"DateTime",
"(",
"$",
"this",
"->",
"getTo",
"(",
")",
")",
";",... | Método que entrega los días totales que la firma es válida
@return int Días totales en que la firma es válida
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2019-02-12 | [
"Método",
"que",
"entrega",
"los",
"días",
"totales",
"que",
"la",
"firma",
"es",
"válida"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/FirmaElectronica.php#L218-L224 |
LibreDTE/libredte-lib | lib/FirmaElectronica.php | FirmaElectronica.getExpirationDays | public function getExpirationDays($desde = null)
{
if (!$desde) {
$desde = date('Y-m-d H:i:s');
}
$start = new \DateTime($desde);
$end = new \DateTime($this->getTo());
$diff = $start->diff($end);
return $diff->format('%a');
} | php | public function getExpirationDays($desde = null)
{
if (!$desde) {
$desde = date('Y-m-d H:i:s');
}
$start = new \DateTime($desde);
$end = new \DateTime($this->getTo());
$diff = $start->diff($end);
return $diff->format('%a');
} | [
"public",
"function",
"getExpirationDays",
"(",
"$",
"desde",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"desde",
")",
"{",
"$",
"desde",
"=",
"date",
"(",
"'Y-m-d H:i:s'",
")",
";",
"}",
"$",
"start",
"=",
"new",
"\\",
"DateTime",
"(",
"$",
"desd... | Método que entrega los días que faltan para que la firma expire
@return int Días que faltan para que la firma expire
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2019-02-12 | [
"Método",
"que",
"entrega",
"los",
"días",
"que",
"faltan",
"para",
"que",
"la",
"firma",
"expire"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/FirmaElectronica.php#L232-L241 |
LibreDTE/libredte-lib | lib/FirmaElectronica.php | FirmaElectronica.getModulus | public function getModulus()
{
$details = openssl_pkey_get_details(openssl_pkey_get_private($this->certs['pkey']));
return wordwrap(base64_encode($details['rsa']['n']), $this->config['wordwrap'], "\n", true);
} | php | public function getModulus()
{
$details = openssl_pkey_get_details(openssl_pkey_get_private($this->certs['pkey']));
return wordwrap(base64_encode($details['rsa']['n']), $this->config['wordwrap'], "\n", true);
} | [
"public",
"function",
"getModulus",
"(",
")",
"{",
"$",
"details",
"=",
"openssl_pkey_get_details",
"(",
"openssl_pkey_get_private",
"(",
"$",
"this",
"->",
"certs",
"[",
"'pkey'",
"]",
")",
")",
";",
"return",
"wordwrap",
"(",
"base64_encode",
"(",
"$",
"de... | Método que obtiene el módulo de la clave privada
@return Módulo en base64
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2014-12-07 | [
"Método",
"que",
"obtiene",
"el",
"módulo",
"de",
"la",
"clave",
"privada"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/FirmaElectronica.php#L271-L275 |
LibreDTE/libredte-lib | lib/FirmaElectronica.php | FirmaElectronica.getCertificate | public function getCertificate($clean = false)
{
if ($clean) {
return trim(str_replace(
['-----BEGIN CERTIFICATE-----', '-----END CERTIFICATE-----'],
'',
$this->certs['cert']
));
} else {
return $this->certs['cert'];
}
} | php | public function getCertificate($clean = false)
{
if ($clean) {
return trim(str_replace(
['-----BEGIN CERTIFICATE-----', '-----END CERTIFICATE-----'],
'',
$this->certs['cert']
));
} else {
return $this->certs['cert'];
}
} | [
"public",
"function",
"getCertificate",
"(",
"$",
"clean",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"clean",
")",
"{",
"return",
"trim",
"(",
"str_replace",
"(",
"[",
"'-----BEGIN CERTIFICATE-----'",
",",
"'-----END CERTIFICATE-----'",
"]",
",",
"''",
",",
"$... | Método que entrega el certificado de la firma
@return Contenido del certificado, clave pública del certificado digital, en base64
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-08-24 | [
"Método",
"que",
"entrega",
"el",
"certificado",
"de",
"la",
"firma"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/FirmaElectronica.php#L295-L306 |
LibreDTE/libredte-lib | lib/FirmaElectronica.php | FirmaElectronica.getPrivateKey | public function getPrivateKey($clean = false)
{
if ($clean) {
return trim(str_replace(
['-----BEGIN PRIVATE KEY-----', '-----END PRIVATE KEY-----'],
'',
$this->certs['pkey']
));
} else {
return $this->certs['pkey'];
}
} | php | public function getPrivateKey($clean = false)
{
if ($clean) {
return trim(str_replace(
['-----BEGIN PRIVATE KEY-----', '-----END PRIVATE KEY-----'],
'',
$this->certs['pkey']
));
} else {
return $this->certs['pkey'];
}
} | [
"public",
"function",
"getPrivateKey",
"(",
"$",
"clean",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"clean",
")",
"{",
"return",
"trim",
"(",
"str_replace",
"(",
"[",
"'-----BEGIN PRIVATE KEY-----'",
",",
"'-----END PRIVATE KEY-----'",
"]",
",",
"''",
",",
"$"... | Método que entrega la clave privada de la firma
@return Contenido de la clave privada del certificado digital en base64
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2015-08-24 | [
"Método",
"que",
"entrega",
"la",
"clave",
"privada",
"de",
"la",
"firma"
] | train | https://github.com/LibreDTE/libredte-lib/blob/39156263b625216c62f1ef1e93b5bfd3307327d9/lib/FirmaElectronica.php#L314-L325 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.