PageRenderTime 25ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/util.php

https://github.com/migmartri/feeder
PHP | 213 lines | 119 code | 22 blank | 72 comment | 32 complexity | d48b44ae898c8392b5da4d6cf6a51a60 MD5 | raw file
  1. <?php
  2. /*
  3. * Clase Utilities
  4. * Implementación de las utilidades básicas y repetitivas
  5. * de la aplicación.
  6. *
  7. */
  8. class Utilities {
  9. /* Devolverá la contraseña codificada
  10. * @pass Contraseña
  11. */
  12. function codificaPasswd($pass) {
  13. return sha1($pass);
  14. }
  15. /* Verificar si un campo es vacio
  16. * @field Campo a verificar
  17. * deprecated?
  18. */
  19. function isEmpty($field) {
  20. return count($field);
  21. }
  22. /* Validaciones */
  23. /* Campo obligatorio
  24. * @field Campo a verificar que tiene contenido
  25. * @msg Mensaje de error a devolver
  26. */
  27. function validatesPresenceOf($field, $msg){
  28. if(!isset($msg)){$msg = "No se puede dejar vacío";}
  29. if(strlen($field) == 0){
  30. array_push($GLOBALS["errors"], $msg);
  31. }
  32. }
  33. /* Unica existencia
  34. * No puede dejamos introducir valores repetidos en tablas como "users"
  35. * @table Tabla de la BD a verificar que no existe
  36. * @conditions Condiciones de consulta sql
  37. * @msg mensaje de error
  38. */
  39. function validatesUniquenessOf($table, $conditions, $msg){
  40. if(!isset($msg)){$msg = "ya existe, elije otro";}
  41. $exist = $GLOBALS["conn"]->selectFromDB("first", $table, array("*"), $conditions);
  42. if($exist != false) {
  43. array_push($GLOBALS["errors"], $msg);
  44. }
  45. }
  46. /* Confirmación
  47. * Verificar contraseñas iguales en login
  48. * @field1 Contraseña 1
  49. * @field2 Contraseña 2
  50. * @msg Mensaje de error
  51. */
  52. function validatesConfirmationOf($field1, $field2, $msg){
  53. if(!isset($msg)){$msg = "$field1 no coincide con $field2";}
  54. if($field1 != $field2) {
  55. array_push($GLOBALS["errors"], $msg);
  56. }
  57. }
  58. /* Formato de email
  59. * Verificamos mediante expresión regular que el email introducido
  60. * tiene un formato correcto.
  61. * @email Cadena de email
  62. * @msg Mensaje de error
  63. */
  64. function validatesEmailFormatOf($email, $msg){
  65. if(!isset($msg)){$msg = "Formato de email incorrecto";}
  66. if(!self::is_valid_email_address($email)) {
  67. array_push($GLOBALS["errors"], $msg);
  68. }
  69. }
  70. /*Formato de url
  71. * Verificamos mediante expresión regular que la url introducida
  72. * tiene un formato correcto.
  73. * @url Cadena de url
  74. * @msg Mensaje de error
  75. */
  76. function validatesUrlFormatOf($url, $msg) {
  77. if(!isset($msg)){$msg = "La url no tiene un formato correcto";}
  78. if((!preg_match('/^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/' ,$url)) && (strlen($url) > 0)) {
  79. array_push($GLOBALS["errors"], $msg);
  80. }
  81. }
  82. /* Validamos si el feed es válido, válido para nuestra librería.
  83. * @feed_url Dirección del xml.
  84. * @msg Mensaje de error.
  85. */
  86. function validatesFeed($feed_url, $msg){
  87. if(!isset($msg)){$msg = "Feed no válido";}
  88. try{
  89. $fp = @fopen($feed_url, "r");
  90. if(!$fp)
  91. throw new Exception('Error en la lectura del XML',1001);
  92. $rawFeed = file_get_contents($feed_url);
  93. $xml = @simplexml_load_string($rawFeed);
  94. if (!is_object($xml))
  95. throw new Exception('Error en la lectura del XML',1001);
  96. //Devolvemos el título
  97. return $xml->channel->title;
  98. }catch(Exception $e){
  99. array_push($GLOBALS["errors"], $msg);
  100. }
  101. }
  102. /* Expresión regular para verificar el email
  103. * Función de apoyo.
  104. * @email Cadena que contiene el email.
  105. */
  106. function is_valid_email_address($email){
  107. $qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
  108. $dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
  109. $atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c'.
  110. '\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
  111. $quoted_pair = '\\x5c[\\x00-\\x7f]';
  112. $domain_literal = "\\x5b($dtext|$quoted_pair)*\\x5d";
  113. $quoted_string = "\\x22($qtext|$quoted_pair)*\\x22";
  114. $domain_ref = $atom;
  115. $sub_domain = "($domain_ref|$domain_literal)";
  116. $word = "($atom|$quoted_string)";
  117. $domain = "$sub_domain(\\x2e$sub_domain)*";
  118. $local_part = "$word(\\x2e$word)*";
  119. $addr_spec = "$local_part\\x40$domain";
  120. return preg_match("!^$addr_spec$!", $email) ? 1 : 0;
  121. }
  122. /* Filtro de acceso, requiere que el usuario esté logueado.
  123. */
  124. function loginRequired(){
  125. if(!isset($_SESSION['user'])) {
  126. $_SESSION['flash_error'] = "Acceso denegado";
  127. header("Location: ../index.php");
  128. }
  129. }
  130. /* Devuelve el usuario actual.
  131. */
  132. function currentUser(){
  133. $conn = new Sgbd();
  134. if(isset($_SESSION['user']) && !isset($_SESSION['current_user'])) {
  135. $user = $conn->selectFromDB("first", "users", array("*"), array("id" => $_SESSION['user']));
  136. $_SESSION['current_user'] = $user;
  137. }
  138. return $_SESSION['current_user'];
  139. }
  140. //Devuelve si está logueada o no
  141. function loggedIn(){
  142. return isset($_SESSION['user']);
  143. }
  144. /* Valor devuelto de los formularios.
  145. * En caso de error se vuelve a completar los formularios.
  146. */
  147. function formValue($field){
  148. $values = $_SESSION['form_values'];
  149. if($values != '') {
  150. $res = $values[$field];
  151. if(isset($res)){
  152. return $res;
  153. }
  154. }
  155. return '';
  156. }
  157. /* Comprobamos que es un número de teléfono.
  158. * Comprobamos que es numérico y mayor que cero.
  159. * @field campo a comprobar.
  160. */
  161. function validatesNumericalityOf($field, $msg) {
  162. if(!isset($msg)){$msg = "El teléfono no es válido";}
  163. if (!(is_numeric($field)) && (strlen($field) > 0))
  164. array_push($GLOBALS["errors"], $msg);
  165. }
  166. /* Comprobamos la longitud
  167. * @field Campo a medir.
  168. * @length Tamaño requerido.
  169. * @msg Mensaje de error.
  170. */
  171. function validatesLengthOf($field, $length, $msg) {
  172. if(!isset($msg)){$msg = "Debe ser de longitud $length";}
  173. if(strlen($field) != $length && strlen($field) > 0){
  174. array_push($GLOBALS["errors"], $msg);
  175. }
  176. }
  177. /* Original PHP code by Chirp Internet: www.chirp.com.au
  178. * Please acknowledge use of this code by including this header.
  179. */
  180. function truncate($string, $limit, $break=" ", $pad="...")
  181. {
  182. // return with no change if string is shorter than $limit
  183. if(strlen($string) <= $limit) return $string;
  184. $string = substr($string, 0, $limit);
  185. if(false !== ($breakpoint = strrpos($string, $break))) {
  186. $string = substr($string, 0, $breakpoint);
  187. }
  188. return $string . $pad;
  189. }
  190. }
  191. ?>