Função que gera um print dos metadados
176356
public function getPrintMetadata() {
        $metadata = new Metadata($this->getDbAdapter());

        foreach ($metadata->getSchemas() as $valueSchema) {

            echo 'In Schema ' . $valueSchema . PHP_EOL;

            // get the table names
            $tableNames = $metadata->getTableNames($valueSchema);

            foreach ($tableNames as $tableName) {
                echo 'In Table ' . $tableName . PHP_EOL;

                $table = $metadata->getTable($tableName, $valueSchema);


                echo '    With columns: ' . PHP_EOL;
                foreach ($table->getColumns() as $column) {
                    echo '        ' . $column->getName()
                    . ' -> ' . $column->getDataType()
                    . PHP_EOL;
                }

                echo PHP_EOL;
                echo '    With constraints: ' . PHP_EOL;

                foreach ($metadata->getConstraints($tableName, $valueSchema) as $constraint) {
                    /** @var $constraint Zend\Db\Metadata\Object\ConstraintObject */
                    echo '        ' . $constraint->getName()
                    . ' -> ' . $constraint->getType()
                    . PHP_EOL;
                    if (!$constraint->hasColumns()) {
                        continue;
                    }
                    echo '            column: ' . implode(', ', $constraint->getColumns());
                    if ($constraint->isForeignKey()) {
                        $fkCols = array();
                        foreach ($constraint->getReferencedColumns() as $refColumn) {
                            $fkCols[] = $constraint->getReferencedTableName() . '.' . $refColumn;
                        }
                        echo ' => ' . implode(', ', $fkCols);
                    }
                    echo PHP_EOL;
                }

                echo '----' . PHP_EOL;
            }
            echo '-------------------------------------------' . PHP_EOL;
        }
    }
350041
private function ___attForeign($value, $meta)
    {

        if (!$value) {
            return false;
        }

        $value = count(
            array_filter(
                array_keys($value),
                'is_string'
            )
        ) > 0 ? [$value] : $value;

        $aInstance = [];
        foreach ($value as $item) {

            $class = $meta->getComposition()->getClass();

            if (!$item || !is_array($item)) {
                $msg = "Tentativa de atribuição de dependência [ {$meta->getAlias()} ] com valor não array.";

                throw new Exception($msg, 400);
            }

            $instance = call_user_func_array([$class, 'make'], [$item]);

            if ($meta->getType() === 'json') {
                $instance->withNotNull();

                $instance = $instance->toArray(true);
            }

            $aInstance[] = $instance;
        }

        $aInstance = count($aInstance) === 1 ? $aInstance[0] : $aInstance;

        if ($meta->getType() === 'json') {
            $aInstance = json_encode($aInstance);
        }

        return $aInstance;
    }
381587
public function index() {
        $this->layout = 'Stats.default';
        $this->elementMenu = 'Stats.menu';
        
        // por default ordenar por sumatoria de dinero vendido
        $conditions['order'] = array('ventas DESC',"cant DESC");
        if ( !empty( $this->request->query ) && $this->request->query['cant_o_tot'] == 1 ) {
            // ordenado por cantidad de unidades vendidas            
            $conditions['order'] = array("cant DESC", 'ventas DESC');
        }

        

        $this->Prg->commonProcess();
        $conds = $this->DetalleComanda->parseCriteria( $this->Prg->parsedParams() );
        $conditions['conditions'] = $conds;
        $conditions['conditions']['Mesa.deleted'] = 0;


		$this->DetalleComanda->Producto->recursive = -1;        
        $conditions['group'] = array('Producto.id', 'Producto.name');        
        $conditions['joins'] = array(
            array(
                'table' => 'detalle_comandas',
                'alias' => 'DetalleComanda',
                'type' => 'left',
                'conditions' => 'Producto.id = DetalleComanda.producto_id',
            ),
            array(
                'table' => 'comandas',
                'alias' => 'Comanda',
                'type' => 'left',
                'conditions' => 'Comanda.id = DetalleComanda.comanda_id',
            ),
            array(
                'table' => 'mesas',
                'alias' => 'Mesa',
                'type' => 'left',
                'conditions' => 'Mesa.id = Comanda.mesa_id',
            ), 
        );
        $conditions['fields'] = array(
            'Producto.name', 
            'sum(DetalleComanda.cant-DetalleComanda.cant_eliminada)*Producto.precio as "ventas"',
            'Producto.precio', 
            'sum(DetalleComanda.cant-DetalleComanda.cant_eliminada) as "cant"',
            );


        if ( empty($this->request->query['desde']) ) {
            $desde = $this->DetalleComanda->find('first', array(
                'order' => array('DetalleComanda.created' => 'ASC')
                ));
            $desde = $desde['DetalleComanda']['created'];
        } else {
            $desde = $this->request->query['desde'];
        }

        if ( empty($this->request->query['hasta']) ) {
            $hasta = $this->DetalleComanda->find('first', array(
                'order' => array('DetalleComanda.created' => 'DESC')
                ));
            $hasta = $hasta['DetalleComanda']['created'];
        } else {
            $hasta = $this->request->query['hasta'];
        }
                                

        $comandas  = $this->DetalleComanda->Producto->find('all', $conditions);
        $cantTotal = 0;
        $ventasTotal = 0;
        foreach ($comandas as $c) {
            $cantTotal += $c[0]['cant'];
            $ventasTotal += $c[0]['ventas'];
        }

        if ( !empty( $this->request->query ) && $this->request->query['cant_o_tot'] == 1 ) {
            $this->request->data['DetalleComanda']['cant_o_tot']  = 1;
        }

        $this->set('categorias', $this->DetalleComanda->Producto->Categoria->generateTreeList());
        $this->set('productos', $this->DetalleComanda->Producto->find('list', array('order' => 'name')));
        $this->set('tags', $this->DetalleComanda->Producto->Tag->find('list', array('order' => 'name')));
		$this->set(compact('comandas', 'cantTotal', 'ventasTotal','tags', 'desde', 'hasta'));
	}
108659
public function start_el( &$output, $item, $depth = 0, $args = array(), $current_object_id = 0 )
	{
		global $wp_query, $wpdb;
		$indent = ( $depth > 0 ? str_repeat( "\t", $depth ) : '' ); // code indent


		// só faz pesquisa pelos filhos no primeiro nível
		$has_children = 0;
		if($depth == 0){
			$has_children = $wpdb -> get_var( "SELECT COUNT(meta_id) FROM {$wpdb->prefix}postmeta WHERE meta_key='_menu_item_menu_item_parent' AND meta_value='" . $item->ID . "'" );

		}

		// depth dependent classes
		$depth_classes = array(
			( $depth == 0 ? 'dropdown' : 'sub-menu-item' ),
			$item->current ? 'active' : '',

		);
		$depth_class_names = esc_attr( implode( ' ', $depth_classes ) );

		// passed classes
		$classes = empty( $item->classes ) ? array() : (array) $item->classes;
		$class_names = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ) );

		// build html
		$output .= $indent . '<li id="nav-menu-item-'. $item->ID . '" class="' . $depth_class_names . ' ' . $class_names . '">';

		// link attributes
		// <a href="#" class="dropdown-toggle" data-toggle="dropdown">biblioteca <b class="caret"></b></a>
		$attributes  = ! empty( $item->attr_title ) ? ' title="'  . esc_attr( $item->attr_title ) .'"' : '';
		$attributes .= ! empty( $item->target )     ? ' target="' . esc_attr( $item->target     ) .'"' : '';
		$attributes .= ! empty( $item->xfn )        ? ' rel="'    . esc_attr( $item->xfn        ) .'"' : '';
		$attributes .= ! empty( $item->url )        ? ' href="'   . esc_attr( $item->url        ) .'"' : '';
		$attributes .= ' class="menu-link menu-depth-'.$depth . ( $depth > 0 ? '' : ' dropdown-toggle' ) . '"';
		$attributes .= $has_children > 0 ? ' data-toggle="dropdown"' : '';

		$caret = $has_children > 0 ? ' <b class="caret"></b>' : '';

		$item_output = sprintf( '%1$s<a%2$s>%3$s%4$s%5$s</a>%6$s',
			$args->before,
			$attributes,
			$args->link_before,
			apply_filters( 'the_title', $item->title, $item->ID ),
			$args->link_after . $caret,
			$args->after
		);

		// build html
		$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
	}
956201
public static function atualizarLinhaDigitavel($linha, Carbon $vencto, $valor)
    {
        $inicio = substr($linha, 0, 32);

        $vencto = str_pad(self::fatorVencimento($vencto), 4, '0', STR_PAD_LEFT); // Novo fator de vencimento
        $valor = str_pad(self::fatorValor($valor), 10, '0', STR_PAD_LEFT); // Valor atualizado

        // Montar nova barra para calcular o novo dígito
        $barra = substr($linha, 0, 4)
            //. substr($linha, 32,  1)
            . $vencto . $valor
            . substr($linha, 4, 5)
            . substr($linha, 10, 10)
            . substr($linha, 21, 10);

        $digito = self::modulo11($barra);

        return sprintf('%s%s%s%s', $inicio, $digito, $vencto, $valor);
    }
1072426
public  function send( $printaitorViewObj ) {
            $texto = $printaitorViewObj->viewTextRender;
            $idFiscalPrinter = $printaitorViewObj->printerId;
            $hostname = $printaitorViewObj->hostName;
            
            if ( empty($hostname) ) {
                $hostname = Configure::read('Printers.server');
            }            
            
            if ( !$hostname  || $hostname == 'auto' ) {
                $hostname = getenv('HTTP_X_FORWARDED_FOR');
                if ( empty($hostname) ){
                    $hostname = $_SERVER['REMOTE_ADDR'];
                }
            }


            $Printer = ClassRegistry::init('Printers.Printer');
            $printer = $Printer->read(null, $idFiscalPrinter);            
            // cambiar el encoding del texto si esta configurado
            $encoding = Configure::read('Printers.encoding');
            CakeLog::write('debug', "Encoding actual es ::: " . mb_detect_encoding($texto));

            if (!empty( $encoding )) {

                CakeLog::write('debug', "Cambiando encoding x ::: $encoding ");

                $texto = mb_convert_encoding($texto, $encoding, mb_detect_encoding($texto));
            }
                  
            // preparar argumentos del proc_open
            $descriptorspec = array(
               0 => array("pipe", "r"), //esto lo uso para mandarle comandos
               1 => array("pipe", "w"),  // el stdout a un archivo tmp
               2 => array("file", "/tmp/lprerrout.txt", "a") // el stderr a un archivo tmp
            );
            $comando = 'lp -h '.$hostname.' -d '.$printer['Printer']['alias'];

            CakeLog::write('debug', "Se envió a imprimir por CUPS ::: $comando");

            CakeLog::write('debug', "TEXT ::: $texto ");
            
            $process = proc_open($comando, $descriptorspec, $pipes, '/tmp');

            // escribir en el pipe de escritura
            if (is_resource($process)) 
            {
                    fwrite($pipes[0],$texto);
                    fclose($pipes[0]);
                    fclose($pipes[1]);
                    $ret =  proc_close($process);
                    return true;
            }


            return false;
        }
295980
private static function checkType(Meta $m)
    {
        if (in_array($m->getType(), ["tinyint", "smallint", "mediumint", "int", "bigint"])) {
            if (!is_numeric($m->getValue()))
                $m->setError("número inválido");

        } elseif ($m->getType() === "decimal") {

        } elseif (in_array($m->getType(), array("double", "real", "float"))) {
            if (!is_numeric($m->getValue()))
                $m->setError("valor não é um número");

        } elseif (in_array($m->getType(), array("bit", "boolean", "serial"))) {
            if (!is_bool($m->getValue()))
                $m->setError("valor boleano inválido. (true ou false)");

        } elseif (in_array($m->getType(), array("datetime", "timestamp"))) {
            if (!preg_match('/\d{4}-\d{2}-\d{2}[T\s]+\d{2}:\d{2}/i', $m->getValue()))
                $m->setError("formato de data inválido ex válido:(2017-08-23 21:58:00)");

        } elseif ($m->getType() === "date") {
            if (!preg_match('/\d{4}-\d{2}-\d{2}/i', $m->getValue()))
                $m->setError("formato de data inválido ex válido:(2017-08-23)");

        } elseif ($m->getType() === "time") {
            if (!preg_match('/\d{2}:\d{2}/i', $m->getValue()))
                $m->setError("formato de tempo inválido ex válido:(21:58)");

        } elseif ($m->getType() === "json" && !Check::isJson($m->getValue())) {
            $m->setError("formato json inválido");
        }
    }
960618
function preview(print)
	{
		var autoOrigin = onePageCheckBox.checked || pageCountCheckBox.checked;
		var printScale = parseInt(pageScaleInput.value) / 100;
		
		if (isNaN(printScale))
		{
			printScale = 1;
			pageScaleInput.value = '100%';
		}
		
		// Workaround to match available paper size in actual print output
		printScale *= 0.75;

		var pf = graph.pageFormat || mxConstants.PAGE_FORMAT_A4_PORTRAIT;
		var scale = 1 / graph.pageScale;
		
		if (autoOrigin)
		{
    		var pageCount = (onePageCheckBox.checked) ? 1 : parseInt(pageCountInput.value);
			
			if (!isNaN(pageCount))
			{
				scale = mxUtils.getScaleForPageCount(pageCount, graph, pf);
			}
		}

		// Negative coordinates are cropped or shifted if page visible
		var gb = graph.getGraphBounds();
		var border = 0;
		var x0 = 0;
		var y0 = 0;

		// Applies print scale
		pf = mxRectangle.fromRectangle(pf);
		pf.width = Math.ceil(pf.width * printScale);
		pf.height = Math.ceil(pf.height * printScale);
		scale *= printScale;
		
		// Starts at first visible page
		if (!autoOrigin && graph.pageVisible)
		{
			var layout = graph.getPageLayout();
			x0 -= layout.x * pf.width;
			y0 -= layout.y * pf.height;
		}
		else
		{
			autoOrigin = true;
		}
		
		var preview = PrintDialog.createPrintPreview(graph, scale, pf, border, x0, y0, autoOrigin);
		preview.open();
	
		if (print)
		{
			PrintDialog.printPreview(preview);
		}
	}
554906
public function renderPDF($print = false, $instrucoes = true)
    {
        $pdf = new Pdf();
        $pdf->addBoleto($this);
        !$print || $pdf->showPrint();
        $instrucoes || $pdf->hideInstrucoes();

        return $pdf->gerarBoleto('S', null);
    }
522754
private static function checkSize(Meta $m)
    {
        if ($m->getSize()) {
            $length = strlen($m->getValue());
            if ($m->getType() === "varchar" && $length > $m->getSize())
                $m->setError("tamanho máximo de caracteres excedido. Max {$m->getSize()}");

            elseif ($m->getType() === "char" && $length > 1)
                $m->setError("tamanho máximo de caracteres excedido. Max {$m->getSize()}");

            elseif ($m->getType() === "tinytext" && ($length > 255 || $length > $m->getSize()))
                $m->setError("tamanho máximo de caracteres excedido. Max {$m->getSize()}");

            elseif ($m->getType() === "text" && ($length > 65535 || $length > $m->getSize()))
                $m->setError("tamanho máximo de caracteres excedido. Max {$m->getSize()}");

            elseif ($m->getType() === "mediumtext" && ($length > 16777215 || $length > $m->getSize()))
                $m->setError("tamanho máximo de caracteres excedido. Max {$m->getSize()}");

            elseif ($m->getType() === "longtext" && ($length > 4294967295 || $length > $m->getSize()))
                $m->setError("tamanho máximo de caracteres excedido. Max {$m->getSize()}");

            elseif ($m->getType() === "tinyint" && ($m->getValue() > self::intLength($m->getSize()) || $m->getValue() > self::intLength(8)))
                $m->setError("numero excedeu seu limite. Max " . self::intLength($m->getSize()));

            elseif ($m->getType() === "smallint" && ($m->getValue() > self::intLength($m->getSize()) || $m->getValue() > self::intLength(16)))
                $m->setError("numero excedeu seu limite. Max " . self::intLength($m->getSize()));

            elseif ($m->getType() === "mediumint" && ($m->getValue() > self::intLength($m->getSize()) || $m->getValue() > self::intLength(24)))
                $m->setError("numero excedeu seu limite. Max " . self::intLength($m->getSize()));

            elseif ($m->getType() === "int" && !in_array($m->getKey(), ["extend", "extend_add", "list", "list_mult", "selecao", "selecao_mult", "checkbox_rel", "extend_mult", "checkbox_mult"]) && ($m->getValue() > self::intLength($m->getSize()) || $m->getValue() > self::intLength(32)))
                $m->setError("numero excedeu seu limite. Max " . self::intLength($m->getSize()));

            elseif ($m->getType() === "bigint" && ($m->getValue() > self::intLength($m->getSize()) || $m->getValue() > self::intLength(64)))
                $m->setError("numero excedeu seu limite. Max " . self::intLength($m->getSize()));
        }
    }
888962
public function gerarCampoLivre(ArrayObject $data)
    {
        if ($this->carteira instanceof Carteira09) {
            $this->alterarTamanho('Conta', 7);
            $this->alterarTamanho('Agencia', 4);
            $this->alterarTamanho('Carteira', 2);
            $this->alterarTamanho('FatorVencimento', 4);
            $this->alterarTamanho('NossoNumero', 11);
            $this->alterarTamanho('CodigoCedente', 7);
            $this->alterarTamanho('Valor', 10);

            $this->layout = ':Banco:Moeda:FatorVencimento:Valor:Agencia:Carteira:NossoNumero:Conta0';

            return $data;
        }

        $this->alterarTamanho('Agencia', 4);
        $this->alterarTamanho('Carteira', 2);
        $this->alterarTamanho('NossoNumero', 11);
        $this->alterarTamanho('CodigoCedente', 7);

        $this->layout = ':Banco:Moeda:FatorVencimento:Valor:Agencia:Carteira:NossoNumero:CodigoCedente0';

        return $data;
    }
190596
private function checkSelecaoUnique(Meta $meta): string
    {
        $mult = "";

        $tpl = new \Helpers\Template("form");
        foreach ($meta->getSelect() as $select) {

            if (!empty($select->getValue())) {
                $dr = new Dicionario($select->getRelation());
                $dr->setData($select->getValue());
                $tplData = array_merge($select->getDados(), ["title" => $dr->getRelevant()->getValue(), "id" => $select->getValue()]);
            } else {
                $tplData = array_merge($select->getDados(), ["title" => "", "id" => ""]);
            }

            $tplData['nome'] = preg_match('/s$/i', $select->getNome()) ? substr($select->getNome(), 0, strlen($select->getNome()) - 1) : $select->getNome();
            $tplData['genero'] = preg_match('/a$/i', $select->getNome()) ? "a" : "o";
            $tplData['parentColumn'] = $meta->getColumn();
            $tplData['parentValue'] = $meta->getValue() ? 1 : "";
            $tplData['column'] = $select->getColumn();
            $tplData['ngmodel'] = "dados." . $select->getColumn();
            $tplData['entity'] = $meta->getRelation();

            $mult .= $tpl->getShow("selecaoUnique", $tplData);
        }

        return $mult;
    }
387311
public function main()
    {
        // cargar XML y extraer arreglo con datos de carátula y DTEs
        $EnvioDte = new \sasco\LibreDTE\Sii\EnvioDte();
        $EnvioDte->loadXML(file_get_contents($this->args['xml']));
        $Caratula = $EnvioDte->getCaratula();
        $Documentos = $EnvioDte->getDocumentos();
        // procesar cada DTEs e ir creando los archivos PDF
        foreach ($Documentos as $DTE) {
            if (!$DTE->getDatos())
                $this->error('No se pudieron obtener los datos de uno de los DTE del XML');
            $this->out('Generando PDF para DTE '.$DTE->getID());
            $pdf = new \sasco\LibreDTE\Sii\Dte\PDF\Dte($this->args['papel']);
            $pdf->setFooterText();
            if ($this->args['logo'])
                $pdf->setLogo($this->args['logo']);
            $pdf->setResolucion(['FchResol'=>$Caratula['FchResol'], 'NroResol'=>$Caratula['NroResol']]);
            $pdf->setWebVerificacion($this->args['web']);
            $pdf->agregar($DTE->getDatos(), $DTE->getTED());
            if (isset($this->args['cedible'])) {
                $pdf->setCedible(true);
                $pdf->agregar($DTE->getDatos(), $DTE->getTED());
            }
            $pdf->Output($this->args['dir'].'/dte_'.$Caratula['RutEmisor'].'_'.$DTE->getID().'.pdf', 'F');
        }
        return 0;
    }
825609
public function create()
    {
        $fs = new Filesystem();

        if (!$this->sourceDir) {
            throw new \Exception('O diretório de código fonte "singular.directory.src" da aplicação não foi definido!');
        }

        $migrationDir = $this->getMigrationDir();

        if (!$fs->exists($migrationDir)) {
            throw new \Exception(sprintf('O diretório de migration não existe!'));
        }

        $template = file_get_contents(
            __DIR__.DIRECTORY_SEPARATOR."templates".DIRECTORY_SEPARATOR."migration.tpl"
        );

        $dt = new \DateTime('now', new \DateTimeZone('UTC'));
        $date = $dt->format('YmdHis');
        $timestamp = time();

        $components = $this->getComponentsToMigration();

        $template = str_replace('$TIMESTAMP',$timestamp, $template);
        $template = str_replace('$COMPONENTS', $this->arrayToString($components, $timestamp) , $template);

        $this->clearMigrations();

        file_put_contents($migrationDir.DIRECTORY_SEPARATOR.$date.'_insere_registros_componentes_'.$timestamp.'.php', $template);

        return count($components);
    }
372418
public function create()
    {
        $fs = new Filesystem();

        if (!$this->sourceDir) {
            throw new \Exception('O diretório de código fonte "singular.directory.src" da aplicação não foi definido!');
        }

        $migrationDir = $this->getMigrationDir();

        if (!$fs->exists($migrationDir)) {
            throw new \Exception(sprintf('O diretório de migration não existe!'));
        }

        $timestamp = time();

        $aplicacoes = $this->getAplicacoesToMigration();

        if (count($aplicacoes) > 0) {
            $template = file_get_contents(
                __DIR__.DIRECTORY_SEPARATOR."templates".DIRECTORY_SEPARATOR."app_migration.tpl"
            );

            $template = str_replace('$TIMESTAMP',$timestamp, $template);
            $template = str_replace('$APLICACOES', $this->arrayToString($aplicacoes, $timestamp) , $template);

            $dt = new \DateTime('now', new \DateTimeZone('UTC'));
            $date = $dt->format('YmdHis');

            file_put_contents($migrationDir.DIRECTORY_SEPARATOR.$date.'_insere_registros_aplicacoes_'.$timestamp.'.php', $template);
        }

        $modulos = $this->getModulosToMigration();

        if (count($modulos) > 0) {
            $template = file_get_contents(
                __DIR__.DIRECTORY_SEPARATOR."templates".DIRECTORY_SEPARATOR."mod_migration.tpl"
            );

            $template = str_replace('$TIMESTAMP',$timestamp, $template);
            $template = str_replace('$MODULOS', $this->arrayToString($modulos, $timestamp) , $template);

            sleep(1);

            $dt = new \DateTime('now', new \DateTimeZone('UTC'));
            $date = $dt->format('YmdHis');

            file_put_contents($migrationDir.DIRECTORY_SEPARATOR.$date.'_insere_registros_modulos_'.$timestamp.'.php', $template);
        }

        $this->clearMigrations();

        return count($modulos) + count($aplicacoes);
    }
490642
public function escribirCerrar()
    {
        if (!$this->iniciado) {
            throw new \RuntimeException('La sesión no fue iniciada previamente.');
        }

        if (!$this->adaptador->escribir($this->id, $this->datos)) {
            throw new \RuntimeException('Hubo un error escribiendo la sesión.');
        }

        $this->adaptador->cerrar();
        $this->iniciado = false;

        return true;
    }
285599
def CrearPlantillaPDF(self, papel="A4", orientacion="portrait"):
        ""
        
        # genero el renderizador con propiedades del PDF
        t = Template(
                 format=papel, orientation=orientacion,
                 title="F 1116 B/C %s" % (self.NroOrden),
                 author="CUIT %s" % self.Cuit,
                 subject="COE %s" % self.params_out.get('coe'),
                 keywords="AFIP Liquidacion Electronica Primaria de Granos", 
                 creator='wslpg.py %s (http://www.PyAfipWs.com.ar)' % __version__,)
        self.template = t
        return True