3v4l.org

run code in 300+ PHP versions simultaneously
<?php /** * DIRECCION EJECUTIVA DE INGRESOS * GENERADOR DE URL CORTA, DEI-MOVIL * 2014 */ class Api{ // Variable MySQL para manipular BD con la clase DataBase. private $mysql = NULL; // Variable para manipular Response en JSON. private $json_responses = NULL; // Variable para utilizar otras funciones de la clase utilidades. private $utils = NULL; // Variable para manipular clase para enviar el correo. private $emailServer = NULL; // Variable para validar RTN (class). private $RTN = NULL; // Variables para inicializar BD. private $dbuser; private $dbpassword; private $dbhost; private $dbname; // Data form private $post_data; // Final response public $api_response = ""; // Variable para verificar validez de parámetros. private $response_validate = ""; // Variable Link servicio URL private $url_host; // Variable Tamaño token de URL Corto private $tam_token; // Variable Link Formularios PreImpresos DEI private $url_formularios; // Variable cantidad dias, validez URL private $validez_url; // Variable controlar el numero de peticiones en un link private $num_peticiones; // Variable que contiene los formularios estaticos. private $formularios_estaticos; // Variable que contiene valor TOKEN generado para el link. private $token; // Variable para almacenar la respuesta final (JSON). private $response = ""; // Variable para almacenar el LINK o QUERY STRING del formulario generado. private $http_query = ""; // Initialize api public function __construct($datosDB, $request, $post_data_object, $formularios_estaticos = "", $url_host = "", $tam_token = "", $url_formularios = "", $validez_url = "", $num_peticiones = ""){ $this->dbhost = $datosDB["host"]; $this->dbname = $datosDB["db"]; $this->dbpassword = $datosDB["pass"]; $this->dbuser = $datosDB["user"]; $this->url_host = $url_host; $this->tam_token = $tam_token; $this->url_formularios = $url_formularios; $this->validez_url = $validez_url; $this->num_peticiones = $num_peticiones; $this->formularios_estaticos = $formularios_estaticos; $this->post_data = $post_data_object; // Inicializamos JSON response $this->json_response_init(); // Inicializamos conexión MySQL $this->mysql_init(); // Inicializamos las utilidades $this->utils_init(); // Inicializamos el servidor SMTP $this->smtp_init(); // Iniciamos el validar de RTN $this->RTN_init(); if(in_array($request, array("generar", "url"))){ $this->api_response = $this->{"request_".$request}(); }else{ if($request == NULL || $request == ""){ $this->json_responses->makeError("ApiRequestException", "Se requiere un metodo para consumir el web service."); }else{ $this->json_responses->makeError("ApiRequestException", $request . " no existe en el web service."); } $this->api_response = $this->json_responses->getStringResponseOut(); } } private function mysql_init(){ $this->mysql = new Database($this->dbhost, $this->dbuser, $this->dbpassword, $this->dbname); } private function json_response_init(){ $this->json_responses = new JSONResponse(); } private function utils_init(){ $this->utils = new Utilidades(); } private function smtp_init(){ $this->emailServer = new enviarEmail(SMTP_SERVER, SMTP_SERVER_PORT, SMTP_USER, SMTP_PASSWORD, FROM_NAME); } private function RTN_init(){ $this->RTN = new RTN(RTN_SERVIDOR, RTN_METODO_WS, RTN_PARAMETRO); } /** * GENERAR URL */ private function request_generar(){ $this->verificarSiFormularioEstatico($this->post_data->form); // Verificamos que sea un formulario estatico o no-generado en el sistema. if(isset($this->post_data->form)){ if(empty($this->post_data->form)){ $this->json_responses->makeError("FormValidateException", "Se requiere de un codigo de formulario."); } }else{ $this->json_responses->makeError("FormValidateException", "No se recibio el codigo del formulario."); } if(isset($this->post_data->rtn)){ if(empty($this->post_data->rtn)){ $this->json_responses->makeError("FormValidateException", "Se requiere de un numero RTN valido."); }elseif(strlen($this->post_data->rtn) < TAM_RTN){ $this->json_responses->makeError("FormValidateException", "El RTN ingresado no es valido. Debe contener 14 digitos."); }elseif(!$this->RTN->validar($this->post_data->rtn)){ // Validamos RTN en la DEI. $this->json_responses->makeError("RTNValidateException", "El RTN ingresado no EXISTE. Ingrese uno valido o existente."); } }else{ $this->json_responses->makeError("FormValidateException", "No se recibio el numero RTN."); } if(isset($this->post_data->correo)){ if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $this->post_data->correo)){ $this->json_responses->makeError("FormValidateException", "El correo ".$this->post_data->correo." no es valido."); } }else{ $this->json_responses->makeError("FormValidateException", "El correo no fue recibido."); } $this->response_validate = $this->json_responses->getStringResponseOut(); if(!empty($this->response_validate)){ return $this->response_validate; }else{ $this->response_validate = ""; } $this->BuildRequestGenerar(); // Generamos el resultado. return $this->json_responses->getStringResponseOut(); } private function BuildRequestGenerar(){ if($this->json_responses->getStringResponseOut() == "" || $this->json_responses->getStringResponseOut() == NULL){ $this->generarParametros(); $this->BuildRequestGenerarInsertarLink(); $this->BuildRequestGenerarInsertarDatosGenerados(); $this->BuildRequestGenerarResultados(); $this->json_responses->makeResponse($this->response); } } private function BuildRequestGenerarInsertarLink(){ $this->token = substr(md5(time()."apiKeyToken"),0,$this->tam_token); $datos_link = array( "id" => $this->token, "link" => $this->http_query, "session_vida" => time(), "peticiones" => $this->num_peticiones, "correo" => $this->post_data->correo, ); $this->mysql->insert("Links", $datos_link); } private function BuildRequestGenerarInsertarDatosGenerados(){ $datos_generados = array( "tipo_formulario" => $this->post_data->form, "ip" => ip2long($this->utils->obtenerIP()), // ip2long, convertimos a int long unsigned la ip, y la guardamos con entero en la BD. "id_dispositivo" => $this->post_data->dispositivo, "nombre_contribuyente" => $this->post_data->nombre, "nombre_contribuyente_ext" => $this->post_data->nombre2, "rtn" => $this->post_data->rtn, "correo" => $this->post_data->correo ); $this->mysql->insert("Generados", $datos_generados); } private function BuildRequestGenerarResultados(){ $this->response = new StdClass(); $this->response->mensaje = "OK"; $this->response->url = $this->url_host . $this->token; if($this->emailServer->enviarLink($this->post_data->correo, $this->url_host . $this->token)){ $this->response->correo = "Fue enviado."; }else{ $this->response->correo = "No fue enviado."; } } /** * TRAE DATOS DEL LINK */ private function request_url(){ if(isset($this->post_data->id)){ if(empty($this->post_data->id)){ $this->json_responses->makeError("UrlParamException", "Se requiere de un parametro para continuar."); } }else{ $this->json_responses->makeError("UrlParamException", "No se recibio el parametro."); } $this->response_validate = $this->json_responses->getStringResponseOut(); if(!empty( $this->response_validate)){ return $this->response_validate; }else{ $this->response_validate = ""; } if($this->json_responses->getStringResponseOut() == "" || $this->json_responses->getStringResponseOut() == NULL){ $token = $this->mysql->getResults("SELECT link, session_vida, peticiones, correo FROM `Links` WHERE id = '".$this->mysql->_real_escape($this->post_data->id)."'"); if(!is_null($token) && !empty($token[0])){ if((time() - $token[0]->session_vida) <= $this->utils->HoraVencimiento($this->validez_url)){ // Verificamos que el enlace no tenga mas tiempo vivo. if($this->utils->verificarPeticiones($token[0]->peticiones) != "UrlRequestExceeded"){ $response = new StdClass(); $response->mensaje = "OK"; if($this->utils->verificarTipoLinkGenerado($token[0]->link)){ // Aqui verificamos si es QUERY STRING O un LINK EXTERNO O ENTERO CON IGUAL O DIFERENTE DOMINIO DE LA DEI. $response->url = $token[0]->link; }else{ $response->url = $this->url_formularios . $token[0]->link; } $this->modificarPeticionesLink(($token[0]->peticiones-1), $this->post_data->id); $this->json_responses->makeResponse($response); }else{ $this->json_responses->makeError("UrlRequestExceededException", "Ya ha superado el limite de peticiones/descargas a este formulario."); } }else{ $this->json_responses->makeError("UrlTimeException", "El tiempo de vigencia del Formulario ha expirado."); } }else{ $this->json_responses->makeError("UrlRequestException", "La URL no existe o ha expirado."); } } return $this->json_responses->getStringResponseOut(); } /** * OTROS METODOS */ private function generarParametros(){ $datos = array( "nombre" => $this->post_data->nombre, "mxw_nombre_charsleft" => $this->post_data->mxw_nombre_charsleft, "nombre2" => $this->post_data->nombre2, "mxw_nombre2_charsleft" => $this->post_data->mxw_nombre2_charsleft, "rtn" => $this->post_data->rtn, "form" => $this->post_data->form, "ip" => $this->utils->obtenerIP(), "fecha" => date("d/m/Y"), "KT_Custom1" => "Generar+Formulario", "KT_Custom1" => "Generar+Formulario" ); $this->http_query = http_build_query($datos); } private function modificarPeticionesLink($peticion, $id_url){ $datos = array("peticiones" => $peticion); $this->mysql->update('Links', $datos, array("id" => $id_url)); //Para actualizar peticiones al entrar al link. --i; } private function verificarSiFormularioEstatico($formulario){ if(array_key_exists($formulario, $this->formularios_estaticos)){ if(isset($this->post_data->rtn)){ if(empty($this->post_data->rtn)){ $this->json_responses->makeError("FormValidateException", "Se requiere de un numero RTN valido."); }elseif(strlen($this->post_data->rtn) < TAM_RTN){ $this->json_responses->makeError("FormValidateException", "El RTN ingresado no es valido. Debe contener 14 digitos."); }elseif(!$this->RTN->validar($this->post_data->rtn)){ // Validamos RTN en la DEI. $this->json_responses->makeError("RTNValidateException", "El RTN ingresado no EXISTE. Ingrese uno valido o existente."); } }else{ $this->json_responses->makeError("FormValidateException", "No se recibio el numero RTN."); } if(isset($this->post_data->correo)){ if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $this->post_data->correo)){ $this->json_responses->makeError("FormValidateException", "El correo ".$this->post_data->correo." no es valido."); } }else{ $this->json_responses->makeError("FormValidateException", "El correo no fue recibido."); } $this->response_validate = $this->json_responses->getStringResponseOut(); if(!empty($this->response_validate)){ return $this->response_validate; }else{ $this->response_validate = ""; } $this->http_query = $this->formularios_estaticos[$formulario]; $this->BuildRequestGenerarInsertarLink(); $this->BuildRequestGenerarInsertarDatosGenerados(); $this->BuildRequestGenerarResultados(); $this->json_responses->makeResponse($this->response); } } } ?>

preferences:
26.91 ms | 402 KiB | 5 Q