PageRenderTime 58ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/includes/db.php

http://buscocarro.googlecode.com/
PHP | 739 lines | 522 code | 60 blank | 157 comment | 144 complexity | b07757a7b29543a8d2abe83aafb2a2ff MD5 | raw file
Possible License(s): BSD-3-Clause, BSD-2-Clause, LGPL-2.1
  1. <?php
  2. include_once 'constants.php';
  3. /**
  4. * Clase para el manejo de la Base de Datos
  5. * @author Anyul Rivas
  6. * @version 3.2
  7. */
  8. Class db {
  9. /**
  10. * host
  11. * @var string Host
  12. */
  13. private $host = HOST;
  14. /**
  15. * nombre de usuario
  16. * @var string usuario
  17. */
  18. private $user = USER;
  19. /**
  20. * contraseńa de acceso
  21. * @var string contraseńa
  22. */
  23. private $password = PASSWORD; //"CEP7F5n8YF";
  24. /**
  25. * Tabla
  26. * @var string tabla
  27. */
  28. private $db = DB;
  29. /**
  30. * mysqli instance
  31. * @var msqli sql
  32. */
  33. private $mysqli = null;
  34. /**
  35. * Debug indica si está en modo debug y muestra en un campo las consultas realizadas;
  36. */
  37. private $debug = true;
  38. public function __construct() {
  39. try {
  40. set_error_handler('Misc::error_handler');
  41. $this->mysqli = new mysqli($this->host, $this->user, $this->password, $this->db);
  42. $this->mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 10);
  43. $this->mysqli->query("SET NAMES 'utf8'");
  44. } catch (Exception $exc) {
  45. echo $this->mysqli->connect_errno . " " . $this->mysqli->connect - error;
  46. echo $exc->getTraceAsString();
  47. exit("No se pudo conectar con la Base de Datos. Consulte al administrador del sistema.");
  48. }
  49. }
  50. public function __destruct() {
  51. //if(is_object($this->msqli)
  52. $this->mysqli->close();
  53. restore_error_handler();
  54. }
  55. /**
  56. * Realiza una consulta y devuelve un array con los resultados
  57. * @param string $query Consulta
  58. * @return array El array de los resultados
  59. */
  60. public function dame_query($query) {
  61. try {
  62. $resultado = $this->mysqli->query($query);
  63. $result = array();
  64. $r['suceed'] = true;
  65. if ($this->debug) {
  66. $r['query'] = $query;
  67. }
  68. if ($this->mysqli->errno == 0) {
  69. while ($fila = $resultado->fetch_array(MYSQLI_ASSOC)) {
  70. $result[] = $fila;
  71. }
  72. $r['data'] = $result;
  73. $r['stats']['affected_rows'] = $this->mysqli->affected_rows;
  74. } else {
  75. throw new Exception;
  76. }
  77. } catch (Exception $exc) {
  78. $r['suceed'] = false;
  79. if ($this->debug) {
  80. $r['query'] = $query;
  81. }
  82. $r['stats']['errno'] = $this->mysqli->errno;
  83. $r['stats']['error'] = $this->mysqli->error;
  84. $r['data'] = $exc->getTraceAsString();
  85. }
  86. return $r;
  87. }
  88. /**
  89. * ejecuta una sentencia SQL y devuelve el resultado
  90. * @param string $query instrucción SQL
  91. * @return mysqli query
  92. */
  93. public function exec_query($query) {
  94. try {
  95. $r = array();
  96. $r['suceed'] = true;
  97. $r['data'] = $this->mysqli->query($query);
  98. $r['stats']['affected_rows'] = $this->mysqli->affected_rows;
  99. } catch (Exception $exc) {
  100. $r['suceed'] = false;
  101. $r['stats']['errno'] = $this->mysqli->errno;
  102. $r['stats']['error'] = $this->mysqli->error;
  103. $r['data'] = $exc->getTraceAsString();
  104. }
  105. return $r;
  106. }
  107. /**
  108. * Realiza una consulta y devuelve los resultados en una matriz asociativa
  109. * @param array $columnas un arreglo de las columnas a seleccionar ['col1','col2','col3'] o un solo campo
  110. * @param array $tablas un arreglo de las tablas a seleccionar ['tabla1','tabla2','tabla3'] o una sola tabla
  111. * @param array $condicion una cadena o un arreglo con las condiciones de la busqueda
  112. * @param array $join una cadena o un arreglo con los join {por desarrollar}
  113. * @param array $order una cadena o un arreglo con el orden del select
  114. * @param array $groupby una cadena o un arreglo con los campos a agrupar
  115. * @return array el arreglo asociativo con los resultados de la consulta
  116. */
  117. public function select($columnas = null, $tablas = null, $condicion = null, $join = null, $order = null, $groupby = null) {
  118. try {
  119. $r = array();
  120. if ($columnas != null && $tablas != null) {
  121. $query = "select ";
  122. if (is_array($columnas)) {
  123. for ($i = 0; $i < count($columnas); $i++) {
  124. $query.= $columnas[$i] . (($i < (count($columnas) - 1)) ? ", " : " ");
  125. }
  126. } else {
  127. $query.= $columnas;
  128. }
  129. $query.= " from ";
  130. if (is_array($tablas)) {
  131. } else {
  132. $query.= $this->db . "." . $tablas;
  133. }
  134. if ($condicion != null) {
  135. if (count(array_keys($condicion)) == 1) {
  136. $query.= " where " . key($condicion) . " = " . $condicion[key($condicion)];
  137. } else {
  138. $columnasCondicion = array_keys($condicion);
  139. $valoresCondicion = array_values($condicion);
  140. for ($q = 0; $q < count($condicion); $q++) {
  141. if ($q == 0) {
  142. $query.=' where ';
  143. } else {
  144. $query.= ' and ';
  145. }
  146. $query.= $columnasCondicion[$q] . " = '" . $valoresCondicion[$q] . "'";
  147. }
  148. }
  149. }
  150. if ($join != null) {
  151. //to do
  152. }
  153. if ($order != null) {
  154. $query.= " order by ";
  155. if (is_array($order)) {
  156. foreach ($order as $key => $val) {
  157. $query.= $key . " " . $val;
  158. }
  159. }
  160. }
  161. if ($groupby != null) {
  162. //to do
  163. }
  164. $resultado = $this->mysqli->query($query);
  165. $a = array();
  166. if ($this->mysqli->errno == 0) {
  167. while ($fila = $resultado->fetch_array(MYSQLI_ASSOC)) {
  168. $a[] = $fila;
  169. }
  170. if ($this->debug) {
  171. $r['query'] = $query;
  172. }
  173. $r['suceed'] = true;
  174. $r['data'] = $a;
  175. $r['stats']['affected_rows'] = $this->mysqli->affected_rows;
  176. } else {
  177. throw new Exception;
  178. }
  179. }
  180. } catch (Exception $exc) {
  181. if ($this->debug) {
  182. $r['query'] = $query;
  183. }
  184. $r['suceed'] = false;
  185. $r['stats']['errno'] = $this->mysqli->errno;
  186. $r['stats']['error'] = $this->mysqli->error;
  187. $r['data'] = $exc->getTraceAsString();
  188. }
  189. return $r;
  190. }
  191. /**
  192. * Inserta Valores en una tabla del sistema (utiliza mysqli)
  193. * @param string $tabla la tabla en la que se insertarán los autos
  194. * @param array $datos los datos en una matriz asociativa con las columnas y valores
  195. * @return bool true si la operación fue efectiva, false si hubo algún fallo.
  196. */
  197. public function insert($tabla = null, $datos = null) {
  198. try {
  199. if ($tabla != null && $datos != null) {
  200. $columnas = array_keys($datos);
  201. $valores = array_values($datos);
  202. $query = "insert into ";
  203. $query.= $tabla;
  204. $query.= "(";
  205. for ($i = 0; $i < count($columnas); $i++) {
  206. $query.= ' ' . (isset($columnas[$i]) ? $columnas[$i] : '');
  207. if ($i < (count($columnas) - 1)) {
  208. $query.=",";
  209. }
  210. }
  211. $query.= ") values(";
  212. for ($z = 0; $z < count($valores); $z++) {
  213. $query.= " '" . (isset($valores[$z]) ? $this->mysqli->real_escape_string($valores[$z]) . "'" : '');
  214. if ($z < (count($valores) - 1)) {
  215. $query.=",";
  216. }
  217. }
  218. $query.= ")";
  219. }
  220. $r = array();
  221. $resultado = $this->mysqli->query($query);
  222. if ($this->mysqli->errno == 0) {
  223. $r['suceed'] = $resultado;
  224. $r['insert_id'] = $this->mysqli->insert_id;
  225. if ($this->debug) {
  226. $r['query'] = $query;
  227. }
  228. $r['stats']['affected_rows'] = $this->mysqli->affected_rows;
  229. } else {
  230. throw new Exception;
  231. }
  232. } catch (Exception $exc) {
  233. if ($this->debug) {
  234. $r['query'] = $query;
  235. }
  236. $r['suceed'] = false;
  237. $r['stats']['errno'] = $this->mysqli->errno;
  238. $r['stats']['error'] = $this->mysqli->error;
  239. $r['data'] = $exc->getTraceAsString();
  240. }
  241. return $r;
  242. }
  243. /**
  244. * Actualiza los datos de una tabla
  245. * @param string $tabla la tabla objetivo
  246. * @param array $datos matriz asociativa con las columnas y valores
  247. * @param array $condicion matriz asociativa con las condiciones y valores
  248. * @return bool true si es exitoso, false en caso de error
  249. */
  250. public function update($tabla = null, $datos = null, $condicion = null) {
  251. try {
  252. if ($tabla != null && $datos != null) {
  253. $columnas = array_keys($datos);
  254. $valores = array_values($datos);
  255. $query = "update ";
  256. $query.= $this->db . "." . $tabla;
  257. $query.= " SET ";
  258. for ($i = 0; $i < count($datos); $i++) {
  259. $query.= $columnas[$i] . " = '" . $valores[$i] . "'";
  260. if ($i < (count($datos) - 1)) {
  261. $query.= ", ";
  262. }
  263. }
  264. if ($condicion != null) {
  265. if (count(array_keys($condicion)) == 1) {
  266. $query.= " where " . key($condicion) . " = " . $condicion[key($condicion)];
  267. } else {
  268. $columnasCondicion = array_keys($condicion);
  269. $valoresCondicion = array_values($condicion);
  270. for ($q = 0; $q < count($condicion); $q++) {
  271. if ($q == 0) {
  272. $query.=' where ';
  273. } else {
  274. $query.= ' and ';
  275. }
  276. $query.= $columnasCondicion[$q] . " = '" . $valoresCondicion[$q] . "'";
  277. }
  278. }
  279. }
  280. }
  281. $r = array();
  282. if ($this->debug) {
  283. $r['query'] = $query;
  284. }
  285. $r['suceed'] = $this->mysqli->query($query);
  286. $r['stats']['affected_rows'] = $this->mysqli->affected_rows;
  287. if ($r['suceed'] != TRUE) {
  288. $r['stats']['errno'] = $this->mysqli->errno;
  289. $r['stats']['error'] = $this->mysqli->error;
  290. }
  291. } catch (Exception $exc) {
  292. $r['stats']['errno'] = $this->mysqli->errno;
  293. $r['stats']['error'] = $this->mysqli->error;
  294. $r['suceed'] = false;
  295. $r['data'] = $exc->getTraceAsString();
  296. }
  297. return $r;
  298. }
  299. /**
  300. * Elimina datos de una tabla
  301. * @param string tabla la tabla objetivo
  302. * @param array matriz asociativa con las codiciones y valores
  303. * @return bool true si la operación fue exitosa, false en caso contrario
  304. */
  305. public function delete($tabla = null, $condicion = null) {
  306. try {
  307. if ($tabla != null && $condicion != null) {
  308. $query = 'delete from ';
  309. $query.= $this->db . "." . $tabla;
  310. if ($condicion != null) {
  311. if (count(array_keys($condicion)) == 1) {
  312. $query.= " where " . key($condicion) . " = " . $condicion[key($condicion)];
  313. } else {
  314. $columnasCondicion = array_keys($condicion);
  315. $valoresCondicion = array_values($condicion);
  316. for ($q = 0; $q < count($condicion); $q++) {
  317. if ($q == 0) {
  318. $query.=' where ';
  319. } else {
  320. $query.= ' and ';
  321. }
  322. $query.= $columnasCondicion[$q] . " = '" . $valoresCondicion[$q] . "'";
  323. }
  324. }
  325. }
  326. }
  327. $r = array();
  328. if ($this->debug) {
  329. $r['query'] = $query;
  330. }
  331. $r['suceed'] = $this->mysqli->query($query);
  332. if ($this->mysqli->errno == 0) {
  333. $r['stats']['affected_rows'] = $this->mysqli->affected_rows;
  334. } else {
  335. throw new Exception;
  336. }
  337. } catch (Exception $exc) {
  338. if ($this->debug) {
  339. $r['query'] = $query;
  340. }
  341. $r['suceed'] = false;
  342. $r['stats']['errno'] = $this->mysqli->errno;
  343. $r['stats']['error'] = $this->mysqli->error;
  344. $r['data'] = $exc->getTraceAsString();
  345. }
  346. return $r;
  347. }
  348. /*
  349. * Creando las funciones estáticas
  350. */
  351. /**
  352. * Función estática para relizar consultas
  353. * @param string $query consulta sql
  354. */
  355. public static function query($consulta) {
  356. $a = new db();
  357. return $a->dame_query($consulta);
  358. }
  359. }
  360. /**
  361. * Clases miscelaneas
  362. * @author Anyul Rivas
  363. */
  364. Class Misc {
  365. /**
  366. * Determina el país de visita de una ip
  367. * @param string $ipAddr la dirección ip. ($_SERVER['REMOTE_ADDR'])
  368. * @return matriz asociativa con el país y código.
  369. */
  370. public static function countryCityFromIP($ipAddr) {
  371. if (ip2long($ipAddr) == -1 || ip2long($ipAddr) === false) {
  372. trigger_error("invalid class", E_USER_ERROR);
  373. }
  374. $ipDetail = array();
  375. $xml = file_get_contents("http://api.hostip.info/?ip=" . $ipAddr);
  376. preg_match("@<Hostip>(\s)*<gml:name>(.*?)</gml:name>@si", $xml, $match);
  377. $ipDetail['city'] = $match[2];
  378. preg_match("@<countryName>(.*?)</countryName>@si", $xml, $matches);
  379. $ipDetail['<strong class="highlight">country</strong>'] = $matches[1];
  380. preg_match("@<countryAbbrev>(.*?)</countryAbbrev>@si", $xml, $cc_match);
  381. $ipDetail['country_code'] = $cc_match[1]; //assing the <strong class="highlight">country</strong> code to array
  382. return $ipDetail;
  383. }
  384. /**
  385. * Manejador de errores en el sistema. Envía un correo detallando lo sucedido y las peticiones hechas.
  386. * @param Integer $num El tipo de Error
  387. * @param String $err el mensaje de error
  388. * @param String $file el archivo asociado
  389. * @param Integer $line la línea del error
  390. */
  391. public static function error_handler($num, $err, $file, $line) {
  392. $headers = 'MIME-Version: 1.0' . "\r\n";
  393. $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
  394. $headers .= 'From: BuscoCarro Daemon <info@buscocarro.com.ve>' . "\r\n";
  395. $html = "";
  396. // <editor-fold defaultstate="collapsed" desc="tipos de errores">
  397. $errortype = array(
  398. 1 => "Error",
  399. 2 => "Advertencia",
  400. 4 => "Error de interpretación",
  401. 8 => "Noticia",
  402. 16 => "Error en el núcleo",
  403. 32 => "Advertencia en el núcleo",
  404. 64 => "Error de compilación",
  405. 128 => "Advertencia de compilación",
  406. 256 => "Error de Usuario",
  407. 512 => "Advertencia de Usuario",
  408. 1024 => "Noticia de Usuario",
  409. 2048 => "E_ALL",
  410. 2049 => "PHP5 E_STRICT");
  411. // </editor-fold>
  412. // <editor-fold defaultstate="collapsed" desc="Armando mensaje">
  413. $html.="<style>
  414. pre{
  415. max-width: 100%;
  416. word-break: break-all;
  417. white-space: pre-line;
  418. word-wrap: break-word;
  419. }</style>";
  420. $html.="<fieldset>";
  421. $html.= "<legend>" . (isset($errortype[@$num]) ? $errortype[@$num] : ('Error Desconocido ' . $num)) . '</legend>';
  422. $html.="<p><b> Error: </b>" . $err . '</p>';
  423. $html.= "<p><b> Archivo: </b>" . $file . '</p>';
  424. $html.= "<p><b> Línea: </b>" . $line . '</p>';
  425. $entorno = array();
  426. $entorno['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
  427. $entorno['direccion_ip'] = $_SERVER['REMOTE_ADDR'];
  428. $entorno['archivo'] = $_SERVER['SCRIPT_FILENAME'];
  429. $entorno['script_name'] = $_SERVER['SCRIPT_NAME'];
  430. $entorno['query_string'] = $_SERVER['QUERY_STRING'];
  431. $entorno['request_uri'] = $_SERVER['REQUEST_URI'];
  432. $entorno['php_self'] = $_SERVER['PHP_SELF'];
  433. $entorno['url_completa'] = "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
  434. $html.="<hr/>";
  435. $html.="<pre><h4>Entorno</h4><code>" . Misc::dump($entorno) . "</code></pre>";
  436. if (isset($_GET) && sizeof($_GET) > 0) {
  437. $html.="<hr/>";
  438. $html.= "<pre><h4>GET</h4><code>" . misc::dump($_GET) . "</code></pre>";
  439. }
  440. if (isset($_POST) && sizeof($_POST) > 0) {
  441. $html.="<hr/>";
  442. $html.= "<pre><h4>POST</h4><code>" . misc::dump($_POST, 1) . "</code></pre>";
  443. }
  444. if (isset($_FILES) && sizeof($_FILES) > 0) {
  445. $html.="<hr/>";
  446. $html.= "<pre><h4>Archivos cargados</h4><code>" . misc::dump($_FILES, 1) . "</code></pre>";
  447. }
  448. if (isset($_SESSION) && sizeof($_SESSION) > 0) {
  449. $html.="<hr/>";
  450. $html.= "<pre><h4>Sesion</h4><code>" . misc::dump($_SESSION, 1) . "</code></pre>";
  451. }
  452. $html.="<hr/>";
  453. $html.="<h1>Error.$err</h1>";
  454. // $html.= "<pre><b>Server:</b></pre><code>" . misc::dump($_SERVER) . "</code>";
  455. $html.="</fieldset>";
  456. // </editor-fold>
  457. // <editor-fold defaultstate="collapsed" desc="comprobacion de errores">
  458. if ((!stristr($file, "simplepie.inc") && !stristr($file, "krumo") && !stristr($err, "mysqli")) && ($num == 1 || $num == 2 || $num == 4 || $num == 8 || $num == 16 || $num == 256 || $num == 2048 || $num == 2049)) {
  459. // echo "<code style='border:1px solid black; background-color:white!important; border-radius:5px;'>" . $html . "</code>";
  460. if (EMAIL_ERROR)
  461. mail(EMAIL_CONTACTO, EMAIL_TITULO, $html, $headers);
  462. if (MOSTRAR_ERROR)
  463. echo $html;
  464. } elseif (!stristr($file, "simplepie.inc") && !stristr($file, "krumo.php") && !stristr($err, "mysqli")) {
  465. // echo "<code style='border:1px solid black; background-color:white!important; border-radius:5px;'>" . $html . "</code>";
  466. if (EMAIL_ERROR)
  467. mail(EMAIL_CONTACTO, EMAIL_TITULO, $html, $headers);
  468. if (MOSTRAR_ERROR)
  469. echo $html;
  470. exit("<h2>Ocurrió algo inesperado. Contacte con el Administrador del Sistema.</h2>");
  471. } else {
  472. //mail("anyulled@gmail.com", "BuscoCarro.com.ve: Error", $html, $headers);
  473. }
  474. // </editor-fold>
  475. }
  476. /**
  477. * Recorta un texto en la longitud especificada sin cortar las palabras
  478. * @param String $input Texto a recortar
  479. * @param Integer $length Longitud a recortar
  480. * @param Boolean $ellipses indica si agrega puntos suspensivos al final del texto
  481. * @param Boolean $strip_html inidica si remueve las etiquetas html
  482. * @param Boolean $output_entities indica si reemplaza los caracteres especiales por entidades html
  483. * @return <type>
  484. */
  485. public static function trim_text($input, $length, $ellipses = true, $strip_html = true, $output_entities = false) {
  486. // Strip tags, if desired
  487. if ($strip_html) {
  488. $input = strip_tags($input);
  489. }
  490. // No need to trim, already shorter than trim length
  491. if (strlen($input) <= $length) {
  492. return $input;
  493. }
  494. // Find last space within length
  495. $last_space = strrpos(substr($input, 0, $length), ' ');
  496. $trimmed_text = substr($input, 0, $last_space);
  497. // Add ellipses (...)
  498. if ($ellipses) {
  499. $trimmed_text .= '...';
  500. }
  501. if ($output_entities) {
  502. $trimmed_text = htmlentities($trimmed_text);
  503. }
  504. return $trimmed_text;
  505. }
  506. /**
  507. * Comprueba si una variable es de tipo entero
  508. * @param String $variable la variable de ingreso
  509. * @return Boolean
  510. */
  511. public static function comprobar_tipo($variable) {
  512. settype($variable, "integer");
  513. return $variable;
  514. }
  515. /**
  516. * Especifica el tipo de error ocurrido en la carga de imagen
  517. * @param mixed $error el arreglo con los datos de la imagen cargada
  518. * @return string el mensaje de error
  519. */
  520. public static function error_carga_imagen($error) {
  521. switch ($error) {
  522. case UPLOAD_ERR_INI_SIZE:
  523. case UPLOAD_ERR_FORM_SIZE:
  524. $mensaje_error = ' El tamańo del archivo es demasiado grande. ';
  525. case UPLOAD_ERR_PARTIAL:
  526. $mensaje_error = ' El archivo fue subido parcialmente ';
  527. case UPLOAD_ERR_NO_FILE:
  528. $mensaje_error = ' No se cargó el archivo ';
  529. case UPLOAD_ERR_NO_TMP_DIR:
  530. $mensaje_error = ' No se pudo encontrar la carpeta temporal ';
  531. case UPLOAD_ERR_CANT_WRITE:
  532. $mensaje_error = ' Error al guardar el archivo en disco ';
  533. case UPLOAD_ERR_EXTENSION:
  534. $mensaje_error = ' Extensión incorrecta ';
  535. default:
  536. $mensaje_error = ' Error desconocido ';
  537. }
  538. return $mensaje_error;
  539. }
  540. public static function comprobar_query($query) {
  541. $blacklist = array('union', 'unhex', 'hex', 'char', 'UNION', 'UNHEX', 'HEX', 'CHAR', 'INFORMATION_SCHEMA');
  542. $query = str_replace(array('(', ')', ','), ' ', $query);
  543. $words = explode(" ", $query);
  544. $result = array_intersect($blacklist, $words);
  545. if (count($result) > 0) {
  546. $db = new db();
  547. $db->insert("log", array(
  548. "ip" => $_SERVER['REMOTE_ADDR'],
  549. "querystring" => $_SERVER['QUERY_STRING'],
  550. "php_server" => var_export($_SERVER, 1)
  551. ));
  552. trigger_error("Consulta no permitida.<br/>" . var_export($_SERVER, 1), E_USER_NOTICE);
  553. die("Consulta no permitida");
  554. } else {
  555. return true;
  556. }
  557. }
  558. public static function dump($args) {
  559. return nl2br(str_replace(
  560. array(' ', ';', '[', ']'), array(' ', '; ', '<b>', '</b>'), print_r($args, true)));
  561. }
  562. /**
  563. * genera una cadena formateada para insertar en url de previsualizacion de carros
  564. * @param type $marca La marca
  565. * @param type $modelo El modelo
  566. * @param type $anio el ańo
  567. * @return string la cadena formateada
  568. */
  569. public static function url_carro($marca, $modelo, $anio) {
  570. $result = strtolower(str_replace(" ", "-", $marca));
  571. $result .= "-" . strtolower(str_replace(" ", "-", $modelo));
  572. $result .= "-" . $anio;
  573. return $result;
  574. }
  575. public static function noticias_rss($item_limit = 4) {
  576. include_once SERVER_ROOT . 'includes/simplepie.inc';
  577. include_once SERVER_ROOT . 'includes/idn/idna_convert.class.php';
  578. $feed = new SimplePie();
  579. $feed->set_feed_url(array(
  580. "http://www.autonews.com.ve/feed",
  581. "http://www.delvolante.com/feed/",
  582. "http://www.f1latam.com/rss/rss.php",
  583. "http://feeds.feedburner.com/BlogCochescom",
  584. "http://feeds.feedburner.com/diariomotor"));
  585. $feed->item_limit = $item_limit;
  586. $feed->enable_order_by_date();
  587. $feed_success = $feed->init();
  588. $feed->handle_content_type();
  589. $noticias = array();
  590. if ($feed_success) {
  591. foreach ($feed->get_items() as $item) {
  592. array_push($noticias, array(
  593. "fuente" => $item->get_feed()->get_title(),
  594. "titulo" => $item->get_title(),
  595. "contenido" => $item->get_content(),
  596. "fecha" => $item->get_date(),
  597. "link" => $item->get_permalink()));
  598. }
  599. }
  600. return $noticias;
  601. }
  602. public static function url_sortable($campo = "id", $direccion = "") {
  603. $params = explode("&", $_SERVER['QUERY_STRING']);
  604. $newParams = array();
  605. if (count($params) > 0) {
  606. foreach ($params as $param) {
  607. /* si no encuentro el campo ni la direccion en la url */
  608. if (stristr($param, $campo) === false && stristr($param, $direccion) === false) {
  609. array_push($newParams, $param);
  610. } else {
  611. $direccion = ($direccion == "") ? "desc" : $direccion;
  612. }
  613. }
  614. $pagina = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  615. if (count($newParams) != 0) {
  616. $pagina .= "?" . htmlentities(implode("&", $newParams));
  617. $pagina .= "&order=$campo&dir=$direccion";
  618. } else {
  619. $pagina.= "?order=$campo&dir=$direccion";
  620. }
  621. }
  622. return $pagina;
  623. }
  624. }
  625. /**
  626. * Acortador de URl de Google
  627. * @author David Walsh
  628. * @author Anyul Rivas
  629. * @version 1.1
  630. */
  631. class GoogleUrlApi {
  632. var $key = 'AIzaSyDNK-CJQBBisWGj7huMvQSjjmWT8RJkLiA';
  633. // Constructor
  634. public function GoogleURLAPI($key = '', $apiURL = 'https://www.googleapis.com/urlshortener/v1/url') {
  635. if ($key == '')
  636. $key == $this->key;
  637. $this->apiURL = $apiURL . '?key=' . $key;
  638. }
  639. /**
  640. * Acorta una url
  641. * @param String $url
  642. * @return Boolean
  643. */
  644. public function shorten($url) {
  645. $response = $this->send($url);
  646. return isset($response['id']) ? $response['id'] : false;
  647. }
  648. /**
  649. * Expande una url acortada
  650. * @param String $url
  651. * @return Boolean
  652. */
  653. public function expand($url) {
  654. $response = $this->send($url, false);
  655. return isset($response['longUrl']) ? $response['longUrl'] : false;
  656. }
  657. /**
  658. * Envía la información a los servidores de Google
  659. * @param String $url
  660. * @param Boolean $shorten
  661. * @return Json
  662. */
  663. private function send($url, $shorten = true) {
  664. $ch = curl_init();
  665. if ($shorten) {
  666. curl_setopt($ch, CURLOPT_URL, $this->apiURL);
  667. curl_setopt($ch, CURLOPT_POST, 1);
  668. curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array("longUrl" => $url)));
  669. curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
  670. } else {
  671. curl_setopt($ch, CURLOPT_URL, $this->apiURL . '&shortUrl=' . $url);
  672. }
  673. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  674. $result = curl_exec($ch);
  675. curl_close($ch);
  676. return json_decode($result, true);
  677. }
  678. }
  679. ?>