text:
<?php

namespace JHWEB\GestionDocumentalBundle\Controller;

use JHWEB\GestionDocumentalBundle\Entity\GdDocumento;
use JHWEB\GestionDocumentalBundle\Entity\GdTrazabilidad;
use JHWEB\GestionDocumentalBundle\Entity\GdRemitente;
use JHWEB\GestionDocumentalBundle\Entity\GdMedidaCautelar;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;

/**
 * Gddocumento controller.
 *
 * @Route("gddocumento")
 */
class GdDocumentoController extends Controller
{
    /**
     * Lists all gdDocumento entities.
     *
     * @Route("/", name="gddocumento_index")
     * @Method("GET")
     */
    public function indexAction()
    {
        $helpers = $this->get("app.helpers");

        $em = $this->getDoctrine()->getManager();

        $documentos = $em->getRepository('JHWEBGestionDocumentalBundle:GdDocumento')->findBy(
            array(
                'estado' => array('PENDIENTE','RECHAZADO','RESPUESTA REALIZADA'),
                'activo'=>true
            )
        );

        $response['data'] = array();

        if ($documentos) {
            $response = array(
                'status' => 'success',
                'code' => 200,
                'message' => count($documentos)." Registros encontrados",
                'data'=> $documentos,
            );
        }

        return $helpers->json($response);
    }

    /**
     * Creates a new gdDocumento entity.
     *
     * @Route("/new", name="gddocumento_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request)
    {
        $helpers = $this->get("app.helpers");
        $hash = $request->get("authorization",null);
        $authCheck = $helpers->authCheck($hash);

        if($authCheck == true){
            $json = $request->get("data",null);
            $params = json_decode($json);

            $em = $this->getDoctrine()->getManager();

            $documento = new GdDocumento();

            $fechaRegistro = new \Datetime(date('Y-m-d h:i:s'));

            $consecutivo = $em->getRepository('JHWEBGestionDocumentalBundle:GdDocumento')->getMaximo(
                $fechaRegistro->format('Y')
            );
            $consecutivo = (empty($consecutivo['maximo']) ? 1 : $consecutivo['maximo']+=1);
            $documento->setConsecutivo($consecutivo);

            $documento->setNumeroRadicado(str_pad($consecutivo, 3, '0', STR_PAD_LEFT).'-'.$fechaRegistro->format('Y')
            );

            $documento->setFolios($params->folios);
            $documento->setFechaRegistro($fechaRegistro);

            if ($params->peticionarioNombres) {
                $documento->setPeticionarioNombres(
                    strtoupper($params->peticionarioNombres)
                );
            }

            if ($params->peticionarioApellidos) {
                $documento->setPeticionarioApellidos(
                    strtoupper($params->peticionarioApellidos)
                );
            }

            if ($params->identificacion) {
                $documento->setIdentificacion($params->identificacion);
            }

            if ($params->entidadCargo) {
                $documento->setEntidadCargo(strtoupper($params->entidadCargo));
            }

            if ($params->entidadNombre) {
                $documento->setEntidadNombre(strtoupper($params->entidadNombre));
            }

            if (isset($params->idTipoIdentificacion)) {
                $tipoIdentificacion = $em->getRepository('JHWEBUsuarioBundle:UserCfgTipoIdentificacion')->find(
                    $params->idTipoIdentificacion
                );
                $documento->setTipoIdentificacion($tipoIdentificacion);
            }

            $documento->setEstado('PENDIENTE');

            $em->persist($documento);
            $em->flush();

            $response = array(
                'status' => 'success',
                'code' => 200,
                'message' => "Registro creado con éxito, su número de radicado es: ".$documento->getNumeroRadicado(),
                'data' => $documento
            );
        }else{
            $response = array(
                'status' => 'error',
                'code' => 400,
                'message' => "Autorización no valida",
            );
        }

        return $helpers->json($response);
    }

    /**
     * Finds and displays a gdDocumento entity.
     *
     * @Route("/show", name="gddocumento_show")
     * @Method({"GET", "POST"})
     */
    public function showAction(Request $request)
    {
        $helpers = $this->get("app.helpers");
        $hash = $request->get("authorization", null);
        $authCheck = $helpers->authCheck($hash);

        if ($authCheck == true) {
            $json = $request->get("data",null);
            $params = json_decode($json);

            $em = $this->getDoctrine()->getManager();

            $documento = $em->getRepository('JHWEBGestionDocumentalBundle:GdDocumento')->find($params->id);

            if ($documento) {
                $response = array(
                    'status' => 'success',
                    'code' => 200,
                    'message' => "Registro encontrado",
                    'data'=> $documento,
                );
            }else{
                $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'message' => "El registro no se encuentra en la base de datos",
                );
            }
        }else{
            $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'message' => "Autorizacion no valida",
                );
        }

        return $helpers->json($response);

    }

    /**
     * Displays a form to edit an existing gdDocumento entity.
     *
     * @Route("/{id}/edit", name="gddocumento_edit")
     * @Method({"GET", "POST"})
     */
    public function editAction(Request $request, GdDocumento $gdDocumento)
    {
        $deleteForm = $this->createDeleteForm($gdDocumento);
        $editForm = $this->createForm('JHWEB\GestionDocumentalBundle\Form\GdDocumentoType', $gdDocumento);
        $editForm->handleRequest($request);

        if ($editForm->isSubmitted() && $editForm->isValid()) {
            $this->getDoctrine()->getManager()->flush();

            return $this->redirectToRoute('gddocumento_edit', array('id' => $gdDocumento->getId()));
        }

        return $this->render('gddocumento/edit.html.twig', array(
            'gdDocumento' => $gdDocumento,
            'edit_form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Deletes a gdDocumento entity.
     *
     * @Route("/{id}/delete", name="gddocumento_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, GdDocumento $gdDocumento)
    {
        $form = $this->createDeleteForm($gdDocumento);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->remove($gdDocumento);
            $em->flush();
        }

        return $this->redirectToRoute('gddocumento_index');
    }

    /**
     * Creates a form to delete a gdDocumento entity.
     *
     * @param GdDocumento $gdDocumento The gdDocumento entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm(GdDocumento $gdDocumento)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('gddocumento_delete', array('id' => $gdDocumento->getId())))
            ->setMethod('DELETE')
            ->getForm()
        ;
    }

    /* ========================================================= */

    /**
     * Busca si existen documentos radicado por identificaccion de peticionario, nombre de la entidad o numero de oficio.
     *
     * @Route("/search", name="gddocumento_search")
     * @Method({"GET", "POST"})
     */
    public function searchAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $helpers = $this->get("app.helpers");
        $hash = $request->get("authorization", null);
        $authCheck = $helpers->authCheck($hash);
        $documentos = null;

        if ($authCheck == true) {
            $json = $request->get("data",null);
            $params = json_decode($json);

            $documentos = $em->getRepository('JHWEBGestionDocumentalBundle:GdDocumento')->getByFilter(
                $params
            );

            if ($documentos) {
                $response = array(
                    'status' => 'success',
                    'code' => 200,
                    'message' => count($documentos)." Documentos registrados.",
                    'data'=> $documentos,
                );
            }else{
                $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'message' => "Ningún resultado encontrado.",
                );
            }
        }else{
            $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'message' => "Autorizacion no valida",
                );
        }

        return $helpers->json($response);
    }

    /**
     * Busca si existen documentos radicado por el estado.
     *
     * @Route("/search/state", name="gddocumento_search_state")
     * @Method({"GET", "POST"})
     */
    public function searchByStateAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $helpers = $this->get("app.helpers");
        $hash = $request->get("authorization", null);
        $authCheck = $helpers->authCheck($hash);
        $documentos = null;

        if ($authCheck == true) {
            $json = $request->get("data",null);
            $params = json_decode($json);

            $documentos = $em->getRepository('JHWEBGestionDocumentalBundle:GdDocumento')->findByEstado(
                $params->state
            );

            if ($documentos) {
                $response = array(
                    'status' => 'success',
                    'code' => 200,
                    'message' => count($documentos)." Documentos registrados.",
                    'data'=> $documentos,
                );
            }else{
                $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'message' => "Ningún resultado encontrado.",
                );
            }
        }else{
            $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'message' => "Autorizacion no valida",
                );
        }

        return $helpers->json($response);
    }

    /**
     * Asigna el documento a un funcionario para que genere un respuesta.
     *
     * @Route("/update", name="gddocumento_update")
     * @Method({"GET", "POST"})
     */
    public function updateAction(Request $request)
    {
        $helpers = $this->get("app.helpers");
        $hash = $request->get("authorization", null);
        $authCheck = $helpers->authCheck($hash);
        $documentos = null;

        if ($authCheck == true) {
            $json = $request->get("data",null);
            $params = json_decode($json);

            $em = $this->getDoctrine()->getManager();

            $documento = $em->getRepository('JHWEBGestionDocumentalBundle:GdDocumento')->find(
                $params->documento->id
            );

            if ($documento) {
                if ($params->documento->direccion) {
                    $documento->setDireccion(
                        $params->documento->direccion
                    );
                }

                if ($params->documento->telefono) {
                    $documento->setTelefono(
                        $params->documento->telefono
                    );
                }

                if ($params->documento->correo) {
                    $documento->setCorreo(
                        $params->documento->correo
                    );
                }

                if ($params->documento->municipio) {
                    $medioCorrespondenciaLlegada = $em->getRepository('JHWEBGestionDocumentalBundle:GdCfgMedioCorrespondencia')->find(
                        $params->documento->municipio
                    );
                    $documento->setMedioCorrespondenciaLlegada($medioCorrespondenciaLlegada);
                }

                $fechaActual = new \Datetime(date('Y-m-d'));

                if ($params->documento->numeroOficio) {
                    $documento->setNumeroOficio(
                        $params->documento->numeroOficio
                    );
                }else{
                    $documento->setNumeroOficio('No registra');
                }

                $documento->setDescripcion($params->documento->descripcion);

                if ($params->documento->detalleLlegada) {
                    $documento->setDetalleLlegada(
                        $params->documento->detalleLlegada
                    );
                }

                if ($params->documento->fechaLlegada) {
                    $documento->setFechaLlegada(
                        new \Datetime($params->documento->fechaLlegada)
                    );
                }

                if ($params->documento->municipio) {
                    $municipio = $em->getRepository('JHWEBConfigBundle:CfgMunicipio')->find(
                        $params->documento->municipio
                    );
                    $documento->setMunicipio($municipio);
                }

                if ($params->documento->idMedioCorrespondenciaLlegada) {
                    $medioCorrespondenciaLlegada = $em->getRepository('JHWEBGestionDocumentalBundle:GdCfgMedioCorrespondencia')->find(
                        $params->documento->idMedioCorrespondenciaLlegada
                    );
                    $documento->setMedioCorrespondenciaLlegada($medioCorrespondenciaLlegada);
                }

                if ($params->documento->idTipoCorrespondencia) {
                    $tipoCorrespondencia = $em->getRepository('JHWEBGestionDocumentalBundle:GdCfgTipoCorrespondencia')->find(
                        $params->documento->idTipoCorrespondencia
                    );
                    $documento->setTipoCorrespondencia($tipoCorrespondencia);
                }

                if ($params->documento->vigencia) {
                    $vigencia = $params->documento->vigencia;
                }else{
                    $vigencia = $tipoCorrespondencia->getDiasVigencia();
                }

                $fechaVencimiento = $this->get('app.gestion.documental')->getFechaVencimiento(
                    new \Datetime($params->documento->fechaLlegada),
                    $vigencia + 1
                );
                $documento->setFechaVencimiento($fechaVencimiento);
                $documento->setDiasVigencia($vigencia);
                $documento->setNumeroCarpeta($params->documento->numeroCarpeta);

                $file = $request->files->get('file');

                if ($file) {
                    $extension = $file->guessExtension();
                    //$filename = md5(rand().time()).".".$extension;
                    $filename = 'radicado_'.$documento->getNumeroRadicado().".".$extension;
                    $dir=__DIR__.'/../../../../web/docs';

                    $file->move($dir,$filename);
                    $documento->setUrl($filename);
                }

                if ($params->idComparendo) {
                    $comparendo = $em->getRepository('JHWEBContravencionalBundle:CvCdoComparendo')->find(
                        $params->idComparendo
                    );
                    $documento->setComparendo($comparendo);
                }

                $em->flush();

                $response = array(
                    'status' => 'success',
                    'code' => 200,
                    'message' => "Radicado No. ".$documento->getNumeroRadicado()." ha registrado la información complementaria",
                    'data' => $documento
                );
            }else{
                $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'message' => "Registro no encontrado"
                );
            }
        }else{
            $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'message' => "Autorizacion no valida",
                );
        }
        return $helpers->json($response);
    }

    /**
     * Asigna el documento a un funcionario para que genere un respuesta.
     *
     * @Route("/finish", name="gddocumento_finish")
     * @Method({"GET", "POST"})
     */
    public function finishAction(Request $request)
    {
        $helpers = $this->get("app.helpers");
        $hash = $request->get("authorization", null);
        $authCheck = $helpers->authCheck($hash);
        $documentos = null;

        if ($authCheck == true) {
            $json = $request->get("data",null);
            $params = json_decode($json);

            $em = $this->getDoctrine()->getManager();

            $documento = $em->getRepository('JHWEBGestionDocumentalBundle:GdDocumento')->find(
                $params->idDocumento
            );

            if ($documento) {
                $file = $request->files->get('file');

                if ($file) {
                    $extension = $file->guessExtension();
                    //$filename = md5(rand().time()).".".$extension;
                    $filename = 'radicado_'.$documento->getNumeroRadicado().".".$extension;
                    $dir=__DIR__.'/../../../../web/docs';

                    $file->move($dir,$filename);
                    $documento->setUrlFinalizado($filename);
                    $documento->setEstado('FINALIZADO');
                }

                $em->flush();

                $response = array(
                    'status' => 'success',
                    'code' => 200,
                    'message' => "Radicado No. ".$documento->getNumeroRadicado()." ha Sido finalizado",
                    'data' => $documento
                );
            }else{
                $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'message' => "Registro no encontrado"
                );
            }
        }else{
            $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'message' => "Autorizacion no valida",
                );
        }
        return $helpers->json($response);
    }

    /**
     * Asigna el documento a un fiuncionario para que genere un respuesta.
     *
     * @Route("/assign", name="gddocumento_assign")
     * @Method({"GET", "POST"})
     */
    public function assignAction(Request $request)
    {
        $helpers = $this->get("app.helpers");
        $hash = $request->get("authorization", null);
        $authCheck = $helpers->authCheck($hash);
        $documentos = null;

        if ($authCheck == true) {
            $json = $request->get("data",null);
            $params = json_decode($json);

            $em = $this->getDoctrine()->getManager();

            $documento = $em->getRepository('JHWEBGestionDocumentalBundle:GdDocumento')->find(
                $params->idDocumento
            );

            if ($documento) {
                $documento->setEstado('ASIGNADO');

                $trazabilidad = new GdTrazabilidad();

                if (isset($params->observaciones)) {
                    $trazabilidad->setObservaciones($params->observaciones);
                }

                $trazabilidad->setEstado('PENDIENTE');
                $trazabilidad->setFechaAsignacion(
                    new \Datetime(date('Y-m-d h:i:s'))
                );
                $trazabilidad->setAceptada(false);
                $trazabilidad->setActivo(true);

                $trazabilidad->setDocumento($documento);

                $funcionario = $em->getRepository('JHWEBPersonalBundle:PnalFuncionario')->find(
                    $params->idFuncionario
                );
                $trazabilidad->setResponsable($funcionario);

                $em->persist($trazabilidad);
                $em->flush();

                if ($documento->getComparendo()) {
                    $estado = $em->getRepository('JHWEBContravencionalBundle:CvCdoCfgEstado')->find(27);
                    $comparendo = $documento->getComparendo();

                    $trazabilidadComparendo = $helpers->generateTrazabilidad($comparendo, $estado);
                    $trazabilidadComparendo->setFuncionario($funcionario);
                    $em->flush();
                }

                $response = array(
                    'status' => 'success',
                    'code' => 200,
                    'message' => "Radicado No. ".$trazabilidad->getDocumento()->getNumeroRadicado()." se encuentra ".$trazabilidad->getDocumento()->getEstado(),
                    'data' => $trazabilidad
                );
            }else{
                $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'message' => "Registro no encontrado"
                );
            }
        }else{
            $response = array(
                'status' => 'error',
                'code' => 400,
                'message' => "Autorizacion no valida",
            );
        }
        return $helpers->json($response);
    }

    /**
     * Busca peticionario por cedula o por nombre entidad y numero de oficio.
     *
     * @Route("/print", name="gddocumento_print")
     * @Method({"GET", "POST"})
     */
    public function printAction(Request $request)
    {
        $helpers = $this->get("app.helpers");
        $hash = $request->get("authorization", null);
        $authCheck = $helpers->authCheck($hash);
        $documentos = null;

        if ($authCheck == true) {
            $json = $request->get("data",null);
            $params = json_decode($json);

            $em = $this->getDoctrine()->getManager();

            $documento = $em->getRepository('JHWEBGestionDocumentalBundle:GdDocumento')->find(
                $params->idDocumento
            );

            if ($documento) {
                $organismoTransito = $em->getRepository('JHWEBConfigBundle:CfgOrganismoTransito')->find(
                    $params->idOrganismoTransito
                );
                $documento->setOrganismoTransito($organismoTransito);

                $medioCorrespondenciaEnvio = $em->getRepository('JHWEBGestionDocumentalBundle:GdCfgMedioCorrespondencia')->find(
                    $params->idMedioCorrespondenciaEnvio
                );
                $documento->setMedioCorrespondenciaEnvio($medioCorrespondenciaEnvio);
                $documento->setFechaEnvio(new \Datetime(date('Y-m-d h:i:s')));
                $documento->setDetalleEnvio($params->detalleEnvio);
                $documento->setObservaciones($params->observaciones);
                $documento->setEstado('ENVIADA');

                $em->flush();

                $response = array(
                    'status' => 'success',
                    'code' => 200,
                    'message' => "Radicado No. ".$documento->getNumeroRadicado()." ".$documento->getEstado(),
                    'data' => $documento
                );
            }else{
                $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'message' => "Registro no encontrado"
                );
            }
        }else{
            $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'message' => "Autorizacion no valida",
                );
        }
        return $helpers->json($response);
    }

    /**
     * Asigna el documento a un fiuncionario para que genere un respuesta.
     *
     * @Route("/template", name="gddocumento_template")
     * @Method({"GET", "POST"})
     */
    public function templateAction(Request $request)
    {
        $helpers = $this->get("app.helpers");
        $hash = $request->get("authorization", null);
        $authCheck = $helpers->authCheck($hash);
        $documentos = null;

        if ($authCheck == true) {
            $file = $request->files->get('file');

            if ($file) {
                $extension = $file->guessExtension();
                if ($extension == 'docx') {
                    $filename = "template.".$extension;
                    $dir=__DIR__.'/../../../../web/uploads';

                    $file->move($dir,$filename);

                    $response = array(
                        'status' => 'success',
                        'code' => 200,
                        'message' => 'Plantilla cargada con exito.'
                    );
                }else{
                    $response = array(
                        'status' => 'error',
                        'code' => 400,
                        'message' => "Solo se admite formato .docx"
                    );
                }
            }else{
                $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'message' => "Ningún archivo seleccionado"
                );
            }
        }else{
            $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'message' => "Autorizacion no valida",
                );
        }
        return $helpers->json($response);
    }

    /**
     * Busca peticionario por cedula o por nombre entidad y numero de oficio.
     *
     * @Route("/{id}/pdf", name="gddocumento_pdf")
     * @Method({"GET", "POST"})
     */
    public function pdfAction(Request $request, GdDocumento $gdDocumento)
    {
        $html = $this->renderView('@JHWEBGestionDocumental/gddocumento/pdf.template.html.twig', array(
            'gdDocumento'=>$gdDocumento,
        ));

        $pdf = $this->container->get("white_october.tcpdf")->create(
            'PORTRAIT',
            PDF_UNIT,
            PDF_PAGE_FORMAT,
            true,
            'UTF-8',
            false
        );
        $pdf->SetAuthor('qweqwe');
        $pdf->SetTitle('Prueba TCPDF');
        $pdf->SetSubject('Your client');
        $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
        $pdf->setFontSubsetting(true);

        $pdf->SetFont('helvetica', '', 11, '', true);
        $pdf->SetMargins('25', '25', '25');
        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

        $pdf->SetFont('helvetica', '', 11, '', true);
        $pdf->AddPage();

        $pdf->writeHTMLCell(
            $w = 0,
            $h = 0,
            $x = '',
            $y = '',
            $html,
            $border = 0,
            $ln = 1,
            $fill = 0,
            $reseth = true,
            $align = '',
            $autopadding = true
        );

        $pdf->Output("example.pdf", 'I');
        die();
    }

    /**
     * Busca si existen documentos entre fechas.
     *
     * @Route("/report", name="gddocumento_report")
     * @Method({"GET", "POST"})
     */
    public function reportAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $helpers = $this->get("app.helpers");
        $hash = $request->get("authorization", null);
        $authCheck = $helpers->authCheck($hash);
        $documentos = null;

        if ($authCheck == true) {
            $json = $request->get("data",null);
            $params = json_decode($json);

            $fechaInicial = new \Datetime($params->fechaInicial);
            $fechaFinal = new \Datetime($params->fechaFinal);

            if ($fechaInicial < $fechaFinal) {
                $documentos = $em->getRepository('JHWEBGestionDocumentalBundle:GdDocumento')->getByDates(
                    $fechaInicial, $fechaFinal
                );

                if ($documentos) {
                    $response = array(
                        'title' => 'Perfecto!',
                        'status' => 'success',
                        'code' => 200,
                        'message' => count($documentos)." Documentos registrados.",
                        'data'=> $documentos,
                    );
                }else{
                    $response = array(
                        'title' => 'Atención!',
                        'status' => 'warning',
                        'code' => 400,
                        'message' => "Ningún resultado encontrado.",
                    );
                }
            }else{
                $response = array(
                    'title' => 'Atención!',
                    'status' => 'warning',
                    'code' => 400,
                    'message' => "La fecha inicial debe ser menor a la fecha final.",
                );
            }
        }else{
            $response = array(
                'title' => 'Error!',
                'status' => 'error',
                'code' => 400,
                'message' => "Autorizacion no valida",
            );
        }

        return $helpers->json($response);
    }

    /**
     * Creates a new gdDocumento entity.
     *
     * @Route("/exit", name="gddocumento_exit")
     * @Method({"GET", "POST"})
     */
    public function exitAction(Request $request)
    {
        $helpers = $this->get("app.helpers");
        $hash = $request->get("authorization",null);
        $authCheck = $helpers->authCheck($hash);

        if($authCheck == true){
            $json = $request->get("data",null);
            $params = json_decode($json);
            $em = $this->getDoctrine()->getManager();

            $documento = new GdDocumento();

            $fechaRegistro = new \Datetime(date('Y-m-d h:i:s'));

            $consecutivoSalida = $em->getRepository('JHWEBGestionDocumentalBundle:GdDocumento')->getMaximoSalida(
                $fechaRegistro->format('Y')
            );
            $consecutivoSalida = (empty($consecutivoSalida['maximo']) ? 1 : $consecutivoSalida['maximo']+=1);
            $documento->setConsecutivo($consecutivoSalida);

            $documento->setNumeroSalida('SH-STTOTTEDN-'.str_pad($consecutivoSalida, 3, '0', STR_PAD_LEFT).'-'.$fechaRegistro->format('Y'));

            $documento->setFechaRegistro($fechaRegistro);
            $documento->setFolios($params->documento->folios);

            if ($params->documento->peticionarioNombres) {
                $documento->setPeticionarioNombres(
                    strtoupper($params->documento->peticionarioNombres)
                );
            }

            if ($params->documento->peticionarioApellidos) {
                $documento->setPeticionarioApellidos(
                    strtoupper($params->documento->peticionarioApellidos)
                );
            }

            if ($params->documento->identificacion) {
                $documento->setIdentificacion($params->documento->identificacion);
            }

            if ($params->documento->entidadCargo) {
                $documento->setEntidadCargo(strtoupper($params->documento->entidadCargo));
            }

            if ($params->documento->entidadNombre) {
                $documento->setEntidadNombre(strtoupper($params->documento->entidadNombre));
            }

            if (isset($params->documento->idTipoIdentificacion)) {
                $tipoIdentificacion = $em->getRepository('JHWEBUsuarioBundle:UserCfgTipoIdentificacion')->find(
                    $params->documento->idTipoIdentificacion
                );
                $documento->setTipoIdentificacion($tipoIdentificacion);
            }

            $persona = $em->getRepository('JHWEBPersonalBundle:PnalFuncionario')->find($params->idFuncionario);

            $documento->setOrganismoTransito($persona->getOrganismoTransito());

            $medioCorrespondenciaEnvio = $em->getRepository('JHWEBGestionDocumentalBundle:GdCfgMedioCorrespondencia')->find(
                $params->idMedioCorrespondenciaEnvio
            );
            $documento->setMedioCorrespondenciaEnvio($medioCorrespondenciaEnvio);
            $documento->setFechaEnvio(new \Datetime(date('Y-m-d h:i:s')));
            $documento->setDetalleEnvio($params->detalleEnvio);
            $documento->setObservaciones($params->observaciones);
            $documento->setEstado('ENVIADA');

            if ($params->documento->idTipoCorrespondencia) {
                $tipoCorrespondencia = $em->getRepository('JHWEBGestionDocumentalBundle:GdCfgTipoCorrespondencia')->find(
                    $params->documento->idTipoCorrespondencia
                );
                $documento->setTipoCorrespondencia($tipoCorrespondencia);
            }

            if ($params->documento->vigencia) {
                $vigencia = $params->documento->vigencia;
            }else{
                $vigencia = $tipoCorrespondencia->getDiasVigencia();
            }

            $fechaVencimiento = $this->get('app.gestion.documental')->getFechaVencimiento(
                new \Datetime($params->documento->fechaLlegada),
                $vigencia + 1
            );
            $documento->setFechaVencimiento($fechaVencimiento);
            $documento->setDiasVigencia($vigencia);
            $documento->setNumeroCarpeta($params->documento->numeroCarpeta);

            $file = $request->files->get('file');

            if ($file) {
                $extension = $file->guessExtension();
                //$filename = md5(rand().time()).".".$extension;
                $filename = 'radicado_'.$documento->getNumeroSalida().".".$extension;
                $dir=__DIR__.'/../../../../web/docs';

                $file->move($dir,$filename);
                $documento->setUrlFinalizado($filename);
                $documento->setEstado('FINALIZADO');
            }
            if ($params->idComparendo) {
                $comparendo = $em->getRepository('JHWEBContravencionalBundle:CvCdoComparendo')->find(
                    $params->idComparendo
                );
                $documento->setComparendo($comparendo);
            }

            $em->persist($documento);
            $em->flush();

            $response = array(
                'status' => 'success',
                'code' => 200,
                'message' => "Registro creado con éxito, su número de radicado es: ".$documento->getNumeroRadicado(),
                'data' => $documento
            );
        }else{
            $response = array(
                'status' => 'error',
                'code' => 400,
                'message' => "Autorización no valida",
            );
        }

        return $helpers->json($response);
    }
}


text:
require 'test_helper'
require 'generators/guts/tinymce/tinymce_generator'

module Guts
  class TinymceGeneratorTest < Rails::Generators::TestCase
    tests Guts::TinymceGenerator
    destination Rails.root.join('tmp', 'generators', 'tinymce')
    setup :prepare_destination

    test 'generator copies tinymce file' do
      config_dir = "#{destination_root}/config"
      FileUtils.mkdir_p(config_dir)

      run_generator

      assert File.exist? "#{config_dir}/tinymce.yml"
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
Meteor.methods({
    /**
     * @param {String}  id The Mongo id of the to be altered post
     * @param {Boolean} publish Publish the post yes/no
     */
    publishPost: function (id, publish) {
        PostsCollection.update({
            _id: id
        }, {
            $set: {
                published: publish
            }
        });
    }
});


text:
'use strict';

var icsGroups = require('./icsGroups');
var WBEvent = require('./WBEvent');
var ical = require('ical');
var getUrl = require('get-urls');
var utils = require('./utils');
var Promise = require('promise');
var moment = require('moment-timezone');
var clc = require('cli-color');
var config = require('../config');

function trimAfterAt(uid) {
  var trimAfterAtRegex = /(\w*)@.*/;
  return uid.match(trimAfterAtRegex)[ 1 ];
}

function getUrlfromDescriptionOrGroupUrl(eventToCheck) {
  if (eventToCheck.url && eventToCheck.url.length > 1) {
    return eventToCheck.url;
  } else if (!eventToCheck.description || eventToCheck.description.length < 1) {
    return eventToCheck.group_url;
  } else if (getUrl(eventToCheck.description)[ 0 ]) {
    return getUrl(eventToCheck.description)[ 0 ];
  } else {
    return eventToCheck.group_url;
  }
}

function hasLocation(eventToCheck) {
  if (eventToCheck.location.indexOf(config.city) >= 0) {
    return true;
  } else if (eventToCheck.location.indexOf(config.city.toLowerCase()) >= 0) {
    return true;
  } else if (eventToCheck.group_name === 'SG Hack & Tell') {
    return eventToCheck.location += ', ' + config.city;
  } else {
    return false;
  }
}

function isInFuture(eventToCheck) {
  return moment(eventToCheck.start_time).isAfter(moment());
}

function getAllIcsGroups(callback) {
  var events = [];
  var countReplies = 0;

  icsGroups.forEach(function(group) {
    ical.fromURL(group.ics_url, {}, function(err, data) {
      if (err) {
        console.log(clc.yellow('Warn: Cannot read ICS Group ' + group.group_name + ': ' + err));
      } else {
        var thisEvent = {};

        for (var key in data) {
          if (data.hasOwnProperty(key)) {
            if (data[ key ].start && data[ key ].end) {
              thisEvent = {};
              thisEvent.group_name = group.group_name;
              thisEvent.group_url = group.group_url;
              thisEvent.start_time = data[ key ].start;
              thisEvent.end_time = data[ key ].end;
              thisEvent.uid = data[ key ].uid;
              thisEvent.name = data[ key ].summary;
              thisEvent.description = data[ key ].description;
              thisEvent.location = data[ key ].location;
              events.push(thisEvent);
            }
          }
        }
      }

      countReplies++;

      if (countReplies >= icsGroups.length) {
        callback(events);
      }
    });
  })
}

function getIcsEvents() {
  var normEvents;

  return new Promise(function(resolve) {
    getAllIcsGroups(function(events) {
      normEvents = events.map(function(ev) {
        var wbEvent = new WBEvent();

        wbEvent.id = trimAfterAt(ev.uid);
        wbEvent.name = ev.name || '';
        wbEvent.description = ev.description || '';
        wbEvent.location = ev.location || '';
        wbEvent.url = getUrlfromDescriptionOrGroupUrl(ev);
        wbEvent.group_name = ev.group_name;
        wbEvent.group_url = ev.group_url;
        wbEvent.formatted_time = utils.formatLocalTime(ev.start_time);
        wbEvent.start_time = utils.localTime(ev.start_time).toISOString();
        wbEvent.end_time = utils.localTime(ev.end_time).toISOString();

        return wbEvent;
      })

      normEvents = normEvents.filter(hasLocation);
      console.log(clc.blue('Info: Found ' + normEvents.length + ' ics events in total'));
      normEvents = normEvents.filter(isInFuture);
      console.log(clc.blue('Info: Found ' + normEvents.length + ' ics future events in SG with location'));

      resolve(normEvents);
    })
  })

}

exports.getAllIcsGroups = getAllIcsGroups;
exports.get = getIcsEvents;

exports.trimAfterAt = trimAfterAt;
exports.getUrlfromDescriptionOrGroupUrl = getUrlfromDescriptionOrGroupUrl;
exports.hasLocation = hasLocation;
exports.isInFuture = isInFuture;


text:
.class Lcom/android/server/policy/ImmersiveModeConfirmation$ClingWindowView$6$1;
.super Ljava/lang/Object;
.source "ImmersiveModeConfirmation.java"

# interfaces
.implements Landroid/animation/ValueAnimator$AnimatorUpdateListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/android/server/policy/ImmersiveModeConfirmation$ClingWindowView$6;->run()V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$2:Lcom/android/server/policy/ImmersiveModeConfirmation$ClingWindowView$6;

# direct methods
.method constructor <init>(Lcom/android/server/policy/ImmersiveModeConfirmation$ClingWindowView$6;)V
    .locals 0

    iput-object p1, p0, Lcom/android/server/policy/ImmersiveModeConfirmation$ClingWindowView$6$1;->this$2:Lcom/android/server/policy/ImmersiveModeConfirmation$ClingWindowView$6;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onAnimationUpdate(Landroid/animation/ValueAnimator;)V
    .locals 2

    invoke-virtual {p1}, Landroid/animation/ValueAnimator;->getAnimatedValue()Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Ljava/lang/Integer;

    invoke-virtual {v1}, Ljava/lang/Integer;->intValue()I

    move-result v0

    iget-object v1, p0, Lcom/android/server/policy/ImmersiveModeConfirmation$ClingWindowView$6$1;->this$2:Lcom/android/server/policy/ImmersiveModeConfirmation$ClingWindowView$6;

    iget-object v1, v1, Lcom/android/server/policy/ImmersiveModeConfirmation$ClingWindowView$6;->this$1:Lcom/android/server/policy/ImmersiveModeConfirmation$ClingWindowView;

    invoke-static {v1}, Lcom/android/server/policy/ImmersiveModeConfirmation$ClingWindowView;->-get2(Lcom/android/server/policy/ImmersiveModeConfirmation$ClingWindowView;)Landroid/graphics/drawable/ColorDrawable;

    move-result-object v1

    invoke-virtual {v1, v0}, Landroid/graphics/drawable/ColorDrawable;->setColor(I)V

    return-void
.end method


text:
package de.matthiasmann.twlthemeeditor.fontgen;

import java.util.HashMap;

/**
 *
 * @author Matthias Mann
 */
public class FontInfo {

    public final int maxGlyphHeight;
    public final int maxGlyphDecent;
    public final int maxGlyphAscent;
    public final HashMap<Object, Object> effectData;

    public FontInfo(int maxGlyphHeight, int maxGlyphDecent, int maxGlyphAscent) {
        this.maxGlyphHeight = maxGlyphHeight;
        this.maxGlyphDecent = maxGlyphDecent;
        this.maxGlyphAscent = maxGlyphAscent;
        this.effectData = new HashMap<Object, Object>();
    }

}


text:
/*!
    \file  usbh_hcs.c
    \brief this file implements functions for opening and closing host channels
*/

/*
    Copyright (C) 2017 GigaDevice

    2017-02-10, V1.0.0, firmware for GD32F30x
*/

#include "usbh_hcs.h"

static uint16_t usbh_freechannel_get (usb_core_handle_struct *pudev);

/*!
    \brief      open a channel
    \param[in]  pudev: pointer to usb device
    \param[in]  channel_num: host channel number which is in (0..7)
    \param[in]  dev_addr: USB device address allocated to attached device
    \param[in]  dev_speed: USB device speed (Full speed/Low speed)
    \param[in]  ep_type: endpoint type (bulk/int/ctl)
    \param[in]  ep_mps: max packet size
    \param[out] none
    \retval     operation status
*/
uint8_t usbh_channel_open (usb_core_handle_struct *pudev,
                           uint8_t  channel_num,
                           uint8_t  dev_addr,
                           uint8_t  dev_speed,
                           uint8_t  ep_type,
                           uint16_t ep_mps)
{
    usb_hostchannel_struct *puhc = &pudev->host.host_channel[channel_num];
    uint16_t channel_info = puhc->info;

    puhc->endp_id   = (uint8_t)channel_info & 0x7FU;
    puhc->endp_in   = (uint8_t)(channel_info & 0x80U) >> 7;
    puhc->endp_type = ep_type;
    puhc->endp_mps  = ep_mps;
    puhc->dev_addr  = dev_addr;
    puhc->dev_speed = dev_speed;

    puhc->data_tg_in  = 0U;
    puhc->data_tg_out = 0U;

    usb_hostchannel_init(pudev, channel_num);

    return (uint8_t)HC_OK;
}

/*!
    \brief      modify a channel
    \param[in]  pudev: pointer to usb device
    \param[in]  channel_num: host channel number which is in (0..7)
    \param[in]  dev_addr: USB Device address allocated to attached device
    \param[in]  dev_speed: USB device speed (Full speed/Low speed)
    \param[in]  ep_type: endpoint type (bulk/int/ctl)
    \param[in]  ep_mps: max packet size
    \param[out] none
    \retval     operation status
*/
uint8_t usbh_channel_modify (usb_core_handle_struct *pudev,
                             uint8_t  channel_num,
                             uint8_t  dev_addr,
                             uint8_t  dev_speed,
                             uint8_t  ep_type,
                             uint16_t ep_mps)
{
    usb_hostchannel_struct *puhc = &pudev->host.host_channel[channel_num];

    if (0U != dev_addr) {
        puhc->dev_addr = dev_addr;
    }

    if ((puhc->endp_mps != ep_mps) && (0U != ep_mps)) {
        puhc->endp_mps = ep_mps;
    }

    if ((puhc->dev_speed != dev_speed) && (0U != dev_speed)) {
        puhc->dev_speed = dev_speed;
    }

    usb_hostchannel_init(pudev, channel_num);

    return (uint8_t)HC_OK;
}

/*!
    \brief      allocate a new channel for the pipe
    \param[in]  pudev: pointer to usb device
    \param[in]  ep_addr: endpoint for which the channel to be allocated
    \param[out] none
    \retval     host channel number
*/
uint8_t usbh_channel_alloc (usb_core_handle_struct *pudev, uint8_t ep_addr)
{
    uint16_t hc_num = usbh_freechannel_get(pudev);

    if ((uint16_t)HC_ERROR != hc_num) {
        pudev->host.host_channel[hc_num].info = HC_USED | ep_addr;
    }

    return (uint8_t)hc_num;
}

/*!
    \brief      free the usb host channel
    \param[in]  pudev: pointer to usb device
    \param[in]  index: channel number to be freed  which is in (0..7)
    \param[out] none
    \retval     host operation status
*/
uint8_t usbh_channel_free (usb_core_handle_struct *pudev, uint8_t index)
{
    if (index < HC_MAX) {
        pudev->host.host_channel[index].info &= HC_USED_MASK;
    }

    return USBH_OK;
}

/*!
    \brief      free all usb host channel
    \param[in]  pudev: pointer to usb device
    \param[out] none
    \retval     host operation status
*/
uint8_t usbh_allchannel_dealloc (usb_core_handle_struct *pudev)
{
    uint8_t index;

    for (index = 2U; index < HC_MAX; index ++) {
        pudev->host.host_channel[index].info = 0U;
    }

    return USBH_OK;
}

/*!
    \brief      get a free channel number for allocation to a device endpoint
    \param[in]  pudev: pointer to usb device
    \param[out] none
    \retval     free channel number
*/
static uint16_t usbh_freechannel_get (usb_core_handle_struct *pudev)
{
    uint8_t index = 0U;

    for (index = 0U; index < HC_MAX; index++) {
        if (0U == (pudev->host.host_channel[index].info & HC_USED)) {
            return (uint16_t)index;
        }
    }

    return HC_ERROR;
}


text:
<?php
namespace Anuncio\Model\Table;

use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\TableGateway\Feature;
use Zend\Db\Sql\Sql;

class VeiculoFabricanteTable extends AbstractTableGateway implements ServiceLocatorAwareInterface
{
	protected $serviceLocator;

	public function __construct()
	{
		$this->table = 'veiculoFabricante';
		$this->featureSet = new Feature\FeatureSet();
		$this->featureSet->addFeature(new Feature\GlobalAdapterFeature());
		$this->initialize();
	}

	public function insert($set)
	{
		unset($set['submit']);

		return parent::insert($set);
	}

	public function update($set, $where = null)
	{
		unset($set['submit']);

		return parent::update($set, $where);
	}

	public function getFabricantesByIdTipo($id)
	{
		$sql = new Sql($this->serviceLocator->get('database'));
		$select = $sql->select()
					  ->columns(array('idFabricante', 'nomeFabricante'))
					  ->from(array('a' => $this->table))
					  ->join(array('b' => 'veiculoTipoFabricante'), 'a.idFabricante = b.idFabricante', array())
					  ->where(array('b.idTipo = '. $id));

		$statement = $sql->prepareStatementForSqlObject($select);
		$result = $statement->execute();

		return $result;
	}

	public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
	{
		$this->serviceLocator = $serviceLocator;
	}

	public function getServiceLocator()
	{
		return $serviceLocator;
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  Copyright (c) 2012 Manning
  See the file license.txt for copying permission.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.manning.androidhacks.hack017"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="7" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".CreateAccountActivity"
            android:configChanges="orientation|keyboardHidden"
            android:screenOrientation="portrait"
            android:theme="@style/dialog_login" />
    </application>

</manifest>


text:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title></title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="keywords" content="">
    <meta name="author" content="">

    <!-- Styley Styles -->
    <link href="" rel="stylesheet">

    <!-- Favicon -->
    <!-- <link href="" rel="shortcut icon"> -->
  </head>

  <body>
    <!-- Scripty Scripts -->
    <script src=""></script>
  </body>
</html>