PageRenderTime 55ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/index.php

https://github.com/hablutzel1/MockRequests
PHP | 477 lines | 434 code | 36 blank | 7 comment | 20 complexity | cd6606eaca86d9f07ecadfe1aca43a16 MD5 | raw file
  1. <?php
  2. // LIbraries
  3. function backwardStrpos($haystack, $needle, $offset = 0) {
  4. $length = strlen($haystack);
  5. $offset = ($offset > 0) ? ($length - $offset) : abs($offset);
  6. $pos = strpos(strrev($haystack), strrev($needle), $offset);
  7. return ($pos === false) ? false : ($length - $pos - strlen($needle));
  8. }
  9. function simpleXMLToArray($xml,
  10. $flattenValues = true,
  11. $flattenAttributes = true,
  12. $flattenChildren = true,
  13. $valueKey = '@value',
  14. $attributesKey = '@attributes',
  15. $childrenKey = '@children') {
  16. $return = array();
  17. if (!($xml instanceof SimpleXMLElement)) {
  18. return $return;
  19. }
  20. $name = $xml->getName();
  21. $_value = trim((string) $xml);
  22. if (strlen($_value) == 0) {
  23. $_value = null;
  24. }
  25. ;
  26. if ($_value!==null) {
  27. if (!$flattenValues) {
  28. $return[$valueKey] = $_value;
  29. }
  30. else {
  31. $return = $_value;
  32. }
  33. }
  34. $children = array();
  35. $first = true;
  36. foreach ($xml->children() as $elementName => $child) {
  37. $value = simpleXMLToArray($child, $flattenValues, $flattenAttributes, $flattenChildren, $valueKey, $attributesKey, $childrenKey);
  38. if (isset($children[$elementName])) {
  39. if ($first) {
  40. $temp = $children[$elementName];
  41. unset($children[$elementName]);
  42. $children[$elementName][] = $temp;
  43. $first = false;
  44. }
  45. $children[$elementName][] = $value;
  46. }
  47. else {
  48. $children[$elementName] = $value;
  49. }
  50. }
  51. if (count($children) > 0) {
  52. if (!$flattenChildren) {
  53. $return[$childrenKey] = $children;
  54. }
  55. else {
  56. $return = array_merge($return, $children);
  57. }
  58. }
  59. $attributes = array();
  60. foreach ($xml->attributes() as $name => $value) {
  61. $attributes[$name] = trim($value);
  62. }
  63. if (count($attributes) > 0) {
  64. if (!$flattenAttributes) {
  65. $return[$attributesKey] = $attributes;
  66. }
  67. else {
  68. $return = array_merge($return, $attributes);
  69. }
  70. }
  71. return $return;
  72. }
  73. function obtenerTablaQueRodeaOcurrenciaDeCadena($subject, $string) {
  74. $offset = strpos($subject, $string);
  75. $firsttableOffset = backwardStrpos($subject, "<table", $offset);
  76. $lastTableOffset = strpos($subject, "</table>", $firsttableOffset);
  77. $entireString = substr($subject, $firsttableOffset, ($lastTableOffset - $firsttableOffset + 8));
  78. return $entireString;
  79. }
  80. function simplificarHtml($string) {
  81. // clean all attributes
  82. $patron = '/<([a-z]+) (.*?)>/i';
  83. $sustitucion = '<$1>';
  84. $response = preg_replace($patron, $sustitucion, $string);
  85. // clean img
  86. $patron = '/<img>/i';
  87. $sustitucion = '';
  88. $response = preg_replace($patron, $sustitucion, $response);
  89. // create xml from string
  90. $response = html_entity_decode($response);
  91. $response = utf8_encode($response);
  92. return $response;
  93. }
  94. function xmlStringToArray($string) {
  95. $xmlObj = simplexml_load_string($string);
  96. $xmlArray = simpleXMLToArray($xmlObj);
  97. return $xmlArray;
  98. }
  99. function valueToString($value) {
  100. $result = '';
  101. if (is_array($value)) {
  102. $result = implode(" ", $value);
  103. } else {
  104. $result = $value;
  105. }
  106. return $result;
  107. }
  108. function parseTextAndComposePerson($hc, $nombreCarrion, $curl_exec) {
  109. // identificar y extraer seccion de interes
  110. $entireString = obtenerTablaQueRodeaOcurrenciaDeCadena($curl_exec, "DATOS PERSONALES");
  111. $response = simplificarHtml($entireString);
  112. $xmlArray = xmlStringToArray($response);
  113. $person = array();
  114. $person['hc'] = $hc;
  115. $person['nombre'] = valueToString($xmlArray['tr'][1]['td'][1]['B']);
  116. $person['fecha_nacimiento'] = valueToString($xmlArray['tr'][2]['td'][1]);
  117. $person['dni'] = valueToString($xmlArray['tr'][2]['td'][3]);
  118. $person['tipo_asegurado'] = valueToString($xmlArray['tr'][3]['td'][1]);
  119. $person['codigo_asegurado'] = valueToString($xmlArray['tr'][3]['td'][3]);
  120. $person['tipo_seguro'] = valueToString($xmlArray['tr'][4]['td'][3]);
  121. $person['centro_asistencial'] = valueToString($xmlArray['tr'][6]['td'][1]['b']);
  122. $person['afiliado_desde'] = valueToString($xmlArray['tr'][6]['td'][3]['b']);
  123. $person['direccion'] = valueToString($xmlArray['tr'][7]['td'][1]);
  124. $person['afiliado_hasta'] = valueToString($xmlArray['tr'][7]['td'][3]['b']);
  125. $person['centro_afiliacion'] = valueToString($xmlArray['tr'][8]['td'][1]);
  126. $person['nombre_hc_carrion'] = $nombreCarrion;
  127. return $person;
  128. }
  129. global $cabecera;
  130. $cabecera = 0;
  131. function generarCabecera($person) {
  132. global $cabecera;
  133. // only work if it is touched the first time
  134. $row = '';
  135. if ($cabecera == 0) {
  136. $i = 0;
  137. foreach ($person as $key => $data) {
  138. $i++;
  139. $row .= $key;
  140. if ($i < count($person)) {
  141. $row .= ",";
  142. }
  143. }
  144. $row .= "\n";
  145. $cabecera = 1;
  146. }
  147. return $row;
  148. }
  149. global $resultadosFile;
  150. $resultadosFile = "resultados.csv";
  151. // crear function para persistir una persona en la base de datos
  152. function guardarRegistro($person) {
  153. global $resultadosFile;
  154. $myFile = $resultadosFile;
  155. $fh = fopen($myFile, 'a') or die("can't open file");
  156. $cabecera = generarCabecera($person);
  157. $row = $cabecera;
  158. $i = 0;
  159. foreach ($person as $key => $data) {
  160. $i++;
  161. $row .= "\"";
  162. $row .= str_replace("\"", "'", $data);
  163. $row .= "\"";
  164. if ($i < count($person)) {
  165. $row .= ",";
  166. }
  167. }
  168. $row .= "\n";
  169. fwrite($fh, $row);
  170. fclose($fh);
  171. }
  172. function guardarRegistroNoExistente($hc) {
  173. $myFile = "resultados.csv";
  174. $fh = fopen($myFile, 'a') or die("can't open file");
  175. $row = "\"$hc\"";
  176. $row .= ",";
  177. $row .= "\"no asegurado\"";
  178. $row .= "\n";
  179. fwrite($fh, $row);
  180. fclose($fh);
  181. }
  182. /////////////////
  183. // create mock data
  184. $searchArray = array();
  185. $searchArray[] = array('apellidopat' => '');
  186. $level = array_key_exists('level', $_GET) ? $_GET['level'] : 1;
  187. //if ($level == null) {
  188. // $level = 1;
  189. //}
  190. // retrieve cookie
  191. if ($level == null || $level == '1') {
  192. // make request to a web page with curl
  193. $ch = curl_init('http://ww4.essalud.gob.pe:7777/acredita/index.jsp');
  194. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  195. curl_setopt($ch, CURLOPT_HEADER, 1);
  196. //curl_setopt($ch, CURLOPT_VERBOSE, true); // Display communication with server
  197. // captura cookies
  198. $curl_exec = curl_exec($ch);
  199. // echo $curl_exec;
  200. preg_match('/^Set-Cookie: (.*?);/m', $curl_exec, $m);
  201. // list cookies
  202. $var = $m[1];
  203. $cookie = parse_url($var);
  204. $cookie = $cookie['path'];
  205. // create form with image
  206. ?>
  207. <html>
  208. <head>
  209. </head>
  210. <body>
  211. <form action="index.php?level=3" method="POST">
  212. <img src="index.php?cookie=<?php echo urlencode($cookie); ?>&level=2" alt=""/>
  213. <br/>
  214. <label>captcha:</label> <input type="text" name="captcha_code"/> <br/>
  215. <input type="hidden" name="cookie"
  216. value="<?php echo urlencode($cookie); ?>"/>
  217. <label>tipo busqueda:</label>dni
  218. <input type="radio" name="tipo" value="dni" checked="checked"/> nombre <input
  219. type="radio" name="tipo" value="nombre"/> <br/>
  220. <!--
  221. <label>Nombre 1:</label> <input name="nom1" /> <br />
  222. <label>Nombre 2:</label> <input name="nom2" /> <br />
  223. <label>ap. paterno: </label> <input name="apepat" /> <br />
  224. <label>ap. materno: </label> <input name="apemat" /> <br />
  225. <label>dni:</label> <input type="text" name="document" /> <br />
  226. -->
  227. <!-- --> <!-- $tipo = $_POST['tipo'];--> <!-- $apePaterno = $_POST['apepat'];-->
  228. <!-- $apeMaterno = $_POST['apemat'];--> <!-- $nombre1 = $_POST['nom1'];-->
  229. <!-- $nombre2 = $_POST['nom2'];--> <input type="submit"/></form>
  230. </body>
  231. </html>
  232. <?php
  233. // allow the user to make a request for retrieving data
  234. // create the formof the expected request
  235. } else if ($level == '2') {
  236. // recibir cookie necesaria
  237. $cookie = $_GET['cookie'];
  238. header("Content-type: image/jpeg");
  239. // get captcha image url with cookie
  240. $ch = curl_init('http://ww4.essalud.gob.pe:7777/acredita/captcha.jpg');
  241. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  242. // curl_setopt($ch, CURLOPT_HEADER, 1);
  243. curl_setopt($ch, CURLOPT_COOKIE, urldecode($cookie));
  244. // curl_setopt($ch, CU)
  245. // display it
  246. $curl_exec = curl_exec($ch);
  247. // y mostrar la imagen
  248. curl_close($ch);
  249. echo $curl_exec;
  250. } else if ($level == '3') {
  251. unlink($resultadosFile);
  252. /////////////////
  253. $captcha = $_POST['captcha_code'];
  254. $cookie = $_POST['cookie'];
  255. // $dni = $_POST['document'];
  256. $tipo = $_POST['tipo'];
  257. // $apePaterno = strtoupper($_POST['apepat']);
  258. // $apeMaterno = strtoupper($_POST['apemat']);
  259. // $nombre1 = strtoupper($_POST['nom1']);
  260. // $nombre2 = strtoupper($_POST['nom2']);
  261. // iterar sobre los datos de origen
  262. if (($handle = fopen("fuente_con_dni_muestra.csv", "r")) !== FALSE) {
  263. while (($data = fgetcsv($handle, null, ",")) !== FALSE) {
  264. $hc = $data[0];
  265. $apePaterno = $data[1];
  266. $apeMaterno = $data[2];
  267. $nombre1 = $data[3];
  268. $nombre2 = $data[4];
  269. $nombreHcCarrion = $apePaterno . " " . $apeMaterno . ", " . $nombre1 . " " . $nombre2;
  270. $dni = $data[5];
  271. // create request model
  272. $ch = curl_init("http://ww4.essalud.gob.pe:7777/acredita/servlet/Ctrlwacre");
  273. // set to POST
  274. curl_setopt($ch, CURLOPT_POST, true);
  275. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  276. // set the Referer:
  277. curl_setopt($ch, CURLOPT_REFERER, "http://ww4.essalud.gob.pe:7777/acredita/index.jsp?td=1");
  278. // set the received cookie
  279. curl_setopt($ch, CURLOPT_COOKIE, urldecode($cookie));
  280. $requestContent = '';
  281. if ($tipo == 'dni' || $tipo == null) {
  282. // set the request content
  283. $requestContent = "pg=1&ll=Libreta+Electoral%2FDNI&td=1&nd=" . $dni . "&submit=Consultar&captchafield_doc=" . $captcha;
  284. //pg=1&ll=Libreta+Electoral%2FDNI&td=1&nd=45377113&submit=Consultar&captchafield_doc=64329
  285. } else if ($tipo == 'nombre') {
  286. $requestContent = "pg=1&ap=" . urlencode($apePaterno) . "&am=" . urlencode($apeMaterno) . "&n1=" . urlencode($nombre1) . "&n2=" . urlencode($nombre2) . "&submit=Consultar&captchafield_nom=" . $captcha;
  287. // $requestContent= urlencode($requestContent);
  288. }
  289. curl_setopt($ch, CURLOPT_POSTFIELDS, $requestContent);
  290. // execute request
  291. // display it
  292. $curl_exec = curl_exec($ch);
  293. // y mostrar la imagen
  294. curl_close($ch);
  295. // identificar de que tipo de respuesta se trata: vacio, u otros
  296. $notFound = strpos($curl_exec, "No se encontraron registros para las siguientes condiciones");
  297. if ($notFound != false) {
  298. // asociar los datos de entrada a un registro no existente
  299. // echo "no se encontraron registros";
  300. guardarRegistroNoExistente($hc);
  301. } else {
  302. // echo "multiples registros";
  303. // identificar unico o multiple
  304. $multiple = strpos($curl_exec, "Listado de asegurados");
  305. if ($multiple != false) {
  306. // multiples registros, navegar cada uno y asociar los datos de todos al mismo registro de origen
  307. // search TableListado and get the wrapper table
  308. $entireString = obtenerTablaQueRodeaOcurrenciaDeCadena($curl_exec, "\"TableListado\"");
  309. $entireString = simplificarHtml($entireString);
  310. $xmlArray = xmlStringToArray($entireString);
  311. $persons = array();
  312. for ($i = 1; $i < count($xmlArray['tr']); $i++) {
  313. // create and make request
  314. $ch = curl_init("http://ww4.essalud.gob.pe:7777/acredita/servlet/CtrlwAseg?ori=list");
  315. // set to POST
  316. curl_setopt($ch, CURLOPT_POST, true);
  317. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  318. // set the Referer:
  319. curl_setopt($ch, CURLOPT_REFERER, "Referer: http://ww4.essalud.gob.pe:7777/acredita/servlet/Ctrlwacre");
  320. // set the received cookie
  321. curl_setopt($ch, CURLOPT_COOKIE, urldecode($cookie));
  322. $numeroAsegurado = trim($xmlArray['tr'][$i]['td'][2]['a'], chr(0xC2) . chr(0xA0));
  323. $requestContent = "pg=1&ap=" . urlencode($apePaterno) . "&am=" . urlencode($apeMaterno) . "&n1=" . urlencode($nombre1) . "&n2=" . urlencode($nombre2) . "&td=&nd=&pg=1&opt=1&tdVerAseg=7&ndVerAseg=" . $numeroAsegurado;
  324. curl_setopt($ch, CURLOPT_POSTFIELDS, $requestContent);
  325. // display it
  326. $curl_exec = curl_exec($ch);
  327. // y mostrar la imagen
  328. curl_close($ch);
  329. // get and parse result
  330. $person = parseTextAndComposePerson($hc, $nombreHcCarrion, $curl_exec);
  331. $persons[] = $person;
  332. guardarRegistro($person);
  333. }
  334. } else {
  335. // echo "registro unico";
  336. $person = parseTextAndComposePerson($hc, $nombreHcCarrion, $curl_exec);
  337. guardarRegistro($person);
  338. }
  339. }
  340. }
  341. fclose($handle);
  342. }
  343. ////////////////////////////////////
  344. echo "Completado, revisar resultados.csv";
  345. }
  346. ?>