PageRenderTime 62ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/funciones.php

https://github.com/phyluis/librerias-php
PHP | 1237 lines | 724 code | 220 blank | 293 comment | 98 complexity | e27b52a2074c197a734409ef7c9e0d98 MD5 | raw file
  1. <?php
  2. /**
  3. *
  4. * Librería general de funciones.
  5. * @author Roger
  6. * @version 2010-05-21
  7. * @licence GPL
  8. * 2010/06/20 + js_confirm
  9. * 2010/06/29 + mensajeHTML
  10. * 2010/06/28 corregido mimplode
  11. * 2010/05/21 correciones en mysql_template : /uims
  12. * 2010/05/19 ereg sustituido por preg_match
  13. * 2010/05/11 mprint tiene un 3º parametros opcional HTML=true
  14. * 2010/05/11 por_defecto ahora devuelve el ultimo argumento
  15. * 2010/05/04 recuperar funciones de fechas.
  16. * 2010/04/30 Correciones repetidas
  17. * 2010-03-22 + por_defecto
  18. * 2010-03-03 + filesize2bytes
  19. * 2010-03-03 + bytes2filesize
  20. * 2010-02-25 + add_querystring_var
  21. * 2010-02-25 + remove_querystring_var
  22. * 2010-02-03 c mysql_template.
  23. * 2010-01-30 + fecha_formato
  24. * 2010-01-30 - fecha_php_mysql, fecha_mysql_php
  25. * 2009-11-24 + mQueryStringDel()
  26. * 2009-11-24 + mQueryStringAdd()
  27. * 2009-11-24 + urlAddHttp ..por nomenclatura
  28. * 2009-07-19 c msyql_template..ahora es incompatible con anterior.
  29. * 2009-06-25 + mimplode
  30. * 2009-06-14 m mysql_plantilla..ahora con %[campo]
  31. * 2009-06-14 + mysql_template
  32. * 2009-05-08 c mysql_plantilla
  33. * 2009-06-14 + mysql_template
  34. * 2009-05-08 c mysql_plantilla
  35. * 2009-04-14 + url_add_http
  36. * 2009-01-00 + mdate_diff( $f, $desde, $hasta )1
  37. * 2008-11-17 + MesEof, MesBof.
  38. * 2008-10-20 + mDate
  39. * c fecha_php_mysql. detecta formato: MM/DD/AAAA y lo pasa a AAAA/MM/DD
  40. * 2008-03-13 + limpiaRequest
  41. * 2008-03-13 r listaSQL a mysql_mlistaSQL
  42. * 2008-03-13 r listaClavesSQL a mysql_mlistaClavesSQL
  43. * 2008-03-12 + mTabla
  44. * 2008-02-26 c mesDe, diaDe
  45. * + mControl
  46. * 2008-02-20 + lista_archivos
  47. * 2008-01-28 + cerrar_etiquetas.
  48. * 2007-09-27 + mysql_plantilla
  49. * 2007-04-27 + in_lista
  50. * 2007-04-17 + mysql_query_lista añadido parámetro hash.
  51. * 2007-01-12 + m_split ( cadena, longitudlinea, cSaltoDeLinea, cPrefijo )
  52. * 2006-09-12 + ampliado extrae_ExtensionNombre() a path.
  53. * 2006-06-30 + mysql_CampoClave ()
  54. * + extrae_ExtensionNombre()
  55. * 2006-06-23 c limpiaSQLinjectionTexto.
  56. * 2006-06-21 - booleantoSiNoConClase
  57. * + añadido mysql_query_registro
  58. * 2006-06-15 + mysql_query_lista
  59. * + limpiaSQLinjectionTexto,Numero,Busca,ID
  60. * 2006-02-16 + fecha_mysql_php
  61. * + fecha_php_mysql
  62. */
  63. function js_confirm ($texto) {
  64. return " onclick=\"return confirm('$texto');\" ";
  65. }
  66. /*
  67. * miscelania
  68. */
  69. function mPrint($que,$level=1, $html=true){
  70. if (is_array($que)) {
  71. $level++;
  72. foreach( $que as $i=>$valor){
  73. echo ( $html ? "<br>": "\n" ), str_repeat( ($html?"&nbsp;": " "),$level*3) ,"$i = ";
  74. mPrint($valor,$level,$html);
  75. }
  76. } else {
  77. echo $que;
  78. }
  79. }
  80. function por_defecto(){
  81. foreach ( func_get_args() as $arg ){
  82. if ($arg) {
  83. return $arg;
  84. }
  85. }
  86. return $arg;
  87. }
  88. /**
  89. * como date pero tiene en cuenta el idioma.
  90. *
  91. * Las fechas tambien se pueden hacer con:
  92. * setlocale (LC_TIME, "sp");
  93. * strftime("%A, %d de %B."), Lunes, 5 de Septiembre
  94. * pero requiere tener instalado el idioma seleccionado en el servidor.
  95. *
  96. */
  97. function fecha_formato ( $fecha, $idioma="es", $formato=""){
  98. switch ($idioma){
  99. case "es":
  100. preg_match( '#([0-9]{1,2})[-/]([0-9]{1,2})[-/]([0-9]{1,4})#ui', $fecha, $temp);
  101. $dia = $temp[1];
  102. $mes = $temp[2];
  103. $anno = $temp[3];
  104. if ( !$formato ) {
  105. $formato="d/m/Y"; // DD-MM-AAAA
  106. }
  107. break;
  108. case "eu":
  109. preg_match( '#([0-9]{2,4})[-/]([0-9]{1,2})[-/]([0-9]{1,2})#ui', $fecha, $temp);
  110. $dia = $temp[3];
  111. $mes = $temp[2];
  112. $anno = $temp[1];
  113. if ( !$formato ) {
  114. $formato="Y/m/d"; // AAAA-MM-DD
  115. }
  116. break;
  117. default :
  118. preg_match( '#([0-9]{1,2})[-/]([0-9]{1,2})[-/]([0-9]{1,4})#ui', $fecha, $temp);
  119. $dia = $temp[2];
  120. $mes = $temp[1];
  121. $anno = $temp[3];
  122. if ( !$formato ) {
  123. $formato="m/d/Y"; // MM/DD/AAAA
  124. }
  125. }
  126. return date($formato, mktime( 0,0,0, $dia, $mes, $anno));
  127. }
  128. /**
  129. * Convierte fecha de mysql a normal
  130. *
  131. * Las fechas tambien se pueden hacer con:
  132. * setlocale (LC_TIME, "sp");
  133. * strftime("%A, %d de %B."), Lunes, 5 de Septiembre
  134. * pero requiere tener instalado el modulol idionma seleccionado en el servidor.
  135. *
  136. */
  137. function fecha_mysql_php($fecha, $formato='Y/m/j'){
  138. $tempFecha = str_replace ( '/', '-', $fecha);
  139. preg_match( '#([0-9]{2,4})-([0-9]{1,2})-([0-9]{1,2})#ui', $tempFecha, $mifecha);
  140. /* TODO añadir mas marcadores */
  141. return strtr ( $formato,
  142. array (
  143. 'Y' => $mifecha[1],
  144. 'y' => substr($mifecha[1],2,2),
  145. 'j' => ltrim($mifecha[3],'0') ,
  146. 'd' => $mifecha[3],
  147. 'n' => ltrim($mifecha[2],'0'),
  148. 'm' => $mifecha[2] ));
  149. }
  150. /**
  151. * Convierte fecha de normal a mysql.
  152. */
  153. function fecha_php_mysql($fecha, $formato='y/m/d'){
  154. $fecha = str_replace ( '-', '/', $fecha);
  155. // intentamos una conversión simple entre MM/DD/AAAA a AAAA/MM/DD
  156. if ( preg_match( "#([0-9]{1,2})/([0-9]{1,2})/([0-9]{4})#ui", $fecha, $regs ) ) {
  157. if ( $regs[2] > 12 ) {
  158. $temp = $regs[2];
  159. $regs[2] = $regs[1];
  160. $regs[1] = $temp;
  161. }
  162. $fecha = "$regs[3]/$regs[2]/$regs[1]";
  163. }
  164. preg_match( '#([0-9]{1,4})/([0-9]{1,2})/([0-9]{1,2})#ui', $fecha, $mifecha);
  165. $cRet = strtr( $formato, array (
  166. '-' => '/',
  167. 'd' =>$mifecha[3],
  168. 'j' =>$mifecha[3],
  169. 'm' =>$mifecha[2],
  170. 'n' =>$mifecha[2],
  171. 'Y' =>$mifecha[1],
  172. 'y' =>$mifecha[1] ));
  173. return $cRet;
  174. }
  175. /**
  176. * Convierte fecha de normal a mysql.
  177. */
  178. // Pasa del formato DD/MM/AAAA al formato AAAA-MM-DD 00:00:0
  179. function mmktime($fecha){
  180. if ( preg_match( '#([0-9]{1,4})[/-]([0-9]{1,4})[/-]([0-9]{1,4})#ui', $fecha, $afecha) ){
  181. return mktime (0,0,0,$afecha[2],$afecha[3],$afecha[1] );
  182. }
  183. return '';
  184. }
  185. function formatoFechaToDateTimeMySql($fecha){
  186. if ( preg_match( '#([0-9]{1,4})/([0-9]{1,4})/([0-9]{1,4})#ui', $fecha, $afecha) ){
  187. return ( $afecha[3] . '-' . $afecha[2] . '-' . $afecha[1] . ' 00:00:00' );
  188. }
  189. return '';
  190. }
  191. // Pasa del formato DD/MM/AA o DD/MM/AAAA al formato AAAA-MM-DD
  192. function formatoFechaToDateMySql($fecha){
  193. if ( preg_match( '#([0-9]{1,2})/([0-9]{1,2})/([0-9]{1,4})#ui', $fecha, $afecha) ){
  194. return (strlen($afecha[3])<3?'20':"") . $afecha[3] . '-' . $afecha[2] . '-' . $afecha[1] ;
  195. }
  196. return '';
  197. }
  198. // Pasa del formato AAAA-MM-DD a DD/MM/AA
  199. function formatoMySqlToFecha($fecha){
  200. if ( preg_match( '#([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2})#ui', $fecha, $afecha) ){
  201. return $afecha[3] . '-' . $afecha[2] . '-' . substr($afecha[1] ,2,2);
  202. }
  203. return '';
  204. }
  205. /**
  206. * Devuelve el mes de castellano o euskera.
  207. * Util, si no funcionan las locale.
  208. */
  209. function mesDe( $fecha ='', $idioma='es' ){
  210. if ( is_numeric($fecha)) {
  211. $mes= $fecha;
  212. } elseif ( $fecha=='') {
  213. $mes = date('n');
  214. } else {
  215. $mes = date('n', $fecha );
  216. };
  217. $aMeses= array (
  218. 'es' => array (
  219. 'Enero', 'Febrero', 'Marzo',
  220. 'Abril', 'Mayo', 'Junio',
  221. 'Julio', 'Agosto', 'Septiembre',
  222. 'Octubre', 'Noviembre', 'Diciembre' ),
  223. 'eu' => array (
  224. 'Urtarila', 'Otsaila', 'Martxoa',
  225. 'Aprila', 'Maiatza', 'Ekaina',
  226. 'Uztaila', 'Abuztua', 'Iraila',
  227. 'Urria', 'Azaroa', 'Abendua' ) );
  228. return $aMeses[$idioma][($mes-1)];
  229. }
  230. /**
  231. * Devuelve el literal dia de una fecha (de hoy si se omite)
  232. */
  233. function diaDe( $fecha = '', $idioma='es'){
  234. if ( is_numeric ($fecha) ){
  235. $dia = $fecha ;
  236. } elseif ( $fecha =='' ) {
  237. $dia = date('w');
  238. } else {
  239. $dia = date('w', $fecha );
  240. }
  241. $aDias= array (
  242. 'es' => array ('Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sabado'),
  243. 'eu' => array ('Igandea', 'Astelehena', 'Asteartea', 'Asteazkena', 'Osteguna', 'Ostirala', 'Larunbata' ) );
  244. return $aDias[$dia];
  245. }
  246. function MesEof($fecha,$mes="") {
  247. if ( $mes=="" ){
  248. $anno= date("Y",$fecha);
  249. $mes = date("n",$fecha);
  250. } else {
  251. $anno= $fecha;
  252. $fecha= mktime(0,0,0,$mes,1,$anno);
  253. }
  254. return mktime(0,0,0,$mes, date("t",$fecha), $anno );
  255. }
  256. function MesBof($fecha,$mes="") {
  257. if ( $mes=="" ){
  258. $anno= date("Y",$fecha);
  259. $mes = date("n",$fecha);
  260. } else {
  261. $anno= $fecha;
  262. }
  263. return mktime(0,0,0,$mes, 1, $anno );
  264. }
  265. function mdate_diff( $f, $desde, $hasta ){
  266. if ( $desde > $hasta ) {
  267. $temp = $desde;
  268. $desde = $hasta;
  269. $hasta = $temp;
  270. }
  271. $dif = $hasta - $desde;
  272. switch ($f) {
  273. case "d": return floor($dif/3600*24); // dias
  274. case "h": return floor($dif/3600); // horas
  275. case "i": return floor($dif/60); // segundos
  276. case "s": return $dif;
  277. case "i:s" : return floor($dif/60). ":" . $dif%60; // minutos:segundos
  278. case "h:i:s": return floor($dif/3600) . ":" . floor(($dif%3600)/60). ":" . $dif%60; // horas:minutos:segundo
  279. }
  280. return 0;
  281. }
  282. /**
  283. * Pasa un valor 0/1 a No Si (0 es NO, y otro valor SI)
  284. * @return Si | No
  285. */
  286. function booleanToSiNo( $Valor, $ClaseSI='', $ClaseNO=''){
  287. if ($Valor==1) {
  288. return ( $ClaseSI =='' ? 'Si' : "<span class='$ClaseSI'>Si</span>" );
  289. } else {
  290. return ( $ClaseNO =='' ? 'No' : "<span class='$ClaseNO'>No</span>" );
  291. }
  292. }
  293. /**
  294. * Devuelve la fecha dada o hoy en formato aaaa/mm/dd.
  295. */
  296. function mDate ($cCual='', $idioma='es'){
  297. switch ($idioma){
  298. case "es": $formato = "d/m/Y"; break;
  299. case "eu": $formato = "Y/m/d"; break;
  300. default : $formato = "d/m/Y"; break;
  301. }
  302. return ($cCual==''? date($formato) : date($formato, strtotime($cCual)));
  303. }
  304. /**
  305. * Devuelve la fecha dada o vacio en formato aaaa/mm/dd.
  306. */
  307. function mFecha ($cCual){
  308. return ($cCual==0? '&nbsp;': date('Y/m/d', strtotime($cCual)));
  309. }
  310. /***/
  311. function url_add_http($url){
  312. return ( preg_match ("|^(https?://)|", $url ) ? $url : "http://$url" );
  313. }
  314. function urlAddHttp($url){
  315. return ( preg_match ("|^(https?://)|", $url ) ? $url : "http://$url" );
  316. }
  317. /**
  318. * manejo variables de sessión y request.
  319. */
  320. function mRequest($cCual){
  321. $cTemp='';
  322. if (isset( $_REQUEST[$cCual])) {
  323. $cTemp= $_REQUEST[$cCual];
  324. $_SESSION[$cCual]= $cTemp;
  325. } elseif (isset( $_SESSION[$cCual])){
  326. $cTemp= $_SESSION[$cCual];
  327. }
  328. return $cTemp;
  329. }
  330. function mQueryStringAdd ($nuevas=false, $urlEncoded=true){
  331. // convertir en array
  332. $resul = array();
  333. if ( $q = $_SERVER["QUERY_STRING"]){
  334. $pares= explode("&",$q);
  335. foreach ($pares as $par ){
  336. list($variable,$valor)=explode("=",$par);
  337. $resul[$variable] = ($urlEncoded ? $valor : urldecode($valor) );
  338. }
  339. }
  340. // ahora añadir los nuevos
  341. if ( $nuevas ){
  342. foreach ( $nuevas as $variable => $valor){
  343. $resul[$variable] = ($urlEncoded ? urlencode($valor) : $valor );
  344. }
  345. }
  346. return $resul;
  347. }
  348. function mQueryStringDel ($borrar, $urlEncoded=true){
  349. // convertir en array
  350. $resul = array();
  351. if ( $q = $_SERVER["QUERY_STRING"]){
  352. $pares= explode("&",$q);
  353. foreach ($pares as $par ){
  354. list($variable,$valor)=explode("=",$par);
  355. if ( !in_array ($variable, $borrar) ){
  356. $resul[$variable] = ($urlEncoded ? $valor : urldecode($valor) );
  357. }
  358. }
  359. }
  360. return $resul;
  361. }
  362. function add_querystring_var($url, $key, $value) {
  363. // FUENTE: http://snipplr.com/view/8323/add-and-remove-querystring-variables/
  364. $url = preg_replace('/(.*)(\?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
  365. $url = substr($url, 0, -1);
  366. if (strpos($url, '?') === false) {
  367. return ($url . '?' . $key . '=' . $value);
  368. } else {
  369. return ($url . '&' . $key . '=' . $value);
  370. }
  371. }
  372. function remove_querystring_var($url, $key) {
  373. // FUENTE: http://snipplr.com/view/8323/add-and-remove-querystring-variables/
  374. $url = preg_replace('/(.*)(\?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
  375. $url = substr($url, 0, -1);
  376. return ($url);
  377. }
  378. function mRequest_id($cCual='ID'){
  379. if (isset($_REQUEST[$cCual])) {
  380. return limpiaSQLinjectionID($_REQUEST[$cCual]);
  381. }
  382. return false;
  383. }
  384. /**
  385. *
  386. * F U N C I O N E S DE A V I S O
  387. *
  388. */
  389. function paginaHTML($cMensaje, $title='ERROR', $css=''){
  390. return "<html><head><title>$title</title>" .
  391. ($css ? "<link rel='stylesheet' href='$css'>" : "" ) ."</head>".
  392. "<body>$cMensaje</body></html>";
  393. }
  394. function mensajeHTML ( $texto, $tipo="OK" ) {
  395. return "\n<div class='mensaje-{$tipo}'>$texto</div>\n";
  396. }
  397. /**
  398. *
  399. * F U N C I O N E S DE C A D E N A
  400. *
  401. */
  402. function m_split ( $s , $nMax, $br = "\n", $pre="&lt; " ) {
  403. $a= explode( " ", $s);
  404. $ret = $pre;
  405. $actual = 0;
  406. foreach ( $a as $c) {
  407. if (strlen($c)+$actual > $nMax ) {
  408. $actual = 0 ;
  409. $ret .= "$br$pre$c";
  410. } else {
  411. $ret .= ( $actual==0 ? "" : " ") . $c;
  412. }
  413. $actual += strlen($c);
  414. }
  415. return $ret;
  416. }
  417. function corta ( $cadena, $longitud=80., $annadir =".."){
  418. return substr( strip_tags("".$cadena.""),0,$longitud). (strlen($cadena)>$longitud? $annadir :"" );
  419. }
  420. function completaUrl ( $cURL ) {
  421. if ( substr($cURL,0,7)=='http://' or substr($cURL,0,8)=='https://' ) {
  422. return $cURL ;
  423. } else {
  424. return 'http://'. $cURL;
  425. }
  426. }
  427. function plantilla_opcion ( $valor, $plantilla0, $plantilla1="", $plantilla2="") {
  428. $plantilla2= por_defecto ( $plantilla2, $plantilla1, $plantilla0);
  429. $plantilla1= por_defecto ( $plantilla1, $plantilla0);
  430. switch ( $valor ) {
  431. case 0 : return strtr( $plantilla0, array ("%0"=>$valor ) );
  432. case 1 : return strtr( $plantilla1, array ("%0"=>$valor ) );
  433. default: return strtr( $plantilla2, array ("%0"=>$valor ) );
  434. }
  435. }
  436. function lista(){
  437. foreach ( func_get_args() as $i=>$valor ) {
  438. if ($i==0) {
  439. $separador=$valor;
  440. } else {
  441. $resultado.= ( $i==1 ? "" : $separador ) . $valor;
  442. }
  443. }
  444. return $resultado;
  445. }
  446. function mimplode ($patron, $array, $separador = "") {
  447. foreach ($array as $k=>$valor) {
  448. $cRet .= $sep . sprintf($patron, $k, $valor);
  449. $sep = $separador;
  450. }
  451. return $cRet;
  452. }
  453. /**
  454. *
  455. * F U N C I O N E S DE FICHEROS
  456. *
  457. */
  458. /*
  459. * Ejemplos de resultados.
  460. * foo => ext="",nombre="foo", tiene=false
  461. * foo. => ext="",nombre="foo", tiene=true
  462. * foo.bar => ext="bar",nombre="foo", tiene=true
  463. * foo.bar.ex => ext="ex",nombre="foo.bar", tiene=true
  464. */
  465. function extrae_ExtensionNombre ( $cFileCompleto ){
  466. $lEsPathRelativo = true;
  467. $nAt = strrpos ( $cFileCompleto, "/");
  468. if ( $nAt === false ) {
  469. $cNombreFichero = $cFileCompleto;
  470. $cPath = "" ;
  471. $lHayPath = false;
  472. } else {
  473. $cPath = substr($cFileCompleto,0,$nAt+1);
  474. $cNombreFichero = substr($cFileCompleto,$nAt+1);
  475. $lHayPath = true;
  476. $lEsPathRelativo = ($nAt>0);
  477. }
  478. $nAt = strrpos ( $cNombreFichero, ".");
  479. if ( $nAt === false ) {
  480. $cNombre = $cNombreFichero;
  481. $lHayExtension = false;
  482. $cExt = "";
  483. } else {
  484. $lHayExtension = true;
  485. $cNombre = substr($cNombreFichero,0,$nAt);
  486. $cExt = substr($cNombreFichero,$nAt+1);
  487. }
  488. return array ( "path" => $cPath, "nombre" =>$cNombre , "ext" =>$cExt,
  489. "hayPath"=>$lHayPath, "hayExt"=>$lHayExtension, "esPathRelativo"=>$lEsPathRelativo );
  490. }
  491. /*
  492. * devuelve un array con todos los ficheros de una determinada extensión
  493. * de un directorio. Acepta una extensión o varias: "jpg", "jpeg|jpg".
  494. * Con PHP 4 se puede utilizar glob.
  495. */
  496. function lista_archivos ( $path, $extension ){
  497. $aRet = array();
  498. if ( is_dir ($path) ) {
  499. $rsDir = opendir ($path);
  500. while (($archivo = readdir($rsDir)) !== false) {
  501. if ( preg_match ( "/\.$extension\$/i", $archivo ) ) {
  502. $aRet[]= $archivo;
  503. }
  504. }
  505. closedir($rsDir);
  506. }
  507. return $aRet;
  508. }
  509. /*
  510. * @author Svetoslav Marinov (con modificaciones )
  511. */
  512. function filesize2bytes($str) {
  513. $bytes = 0;
  514. $bytes_array = array("B"=>0,"K"=>1,"M"=>2,"G"=>3, "T"=>4, "P"=>5 );
  515. $bytes = floatval($str);
  516. $str = str_ireplace ( "bytes","B", $str);
  517. $str = str_ireplace ( "byte","B", $str);
  518. if (preg_match('#([BKMGTP])B?$#si', $str, $matches) && !empty($bytes_array[$matches[1]])) {
  519. $bytes *= pow(1024,$bytes_array[$matches[1]]);
  520. }
  521. $bytes = intval(round($bytes, 2));
  522. return $bytes;
  523. }
  524. /*
  525. * @author: nak5ive@gmail.com
  526. */
  527. function bytes2filesize($bytes, $precision = 2) {
  528. //
  529. $units = array('B', 'KB', 'MB', 'GB', 'TB');
  530. $bytes = max($bytes, 0);
  531. $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
  532. $pow = min($pow, count($units) - 1);
  533. $bytes /= pow(1024, $pow);
  534. return round($bytes, $precision) . ' ' . $units[$pow];
  535. }
  536. /**
  537. *
  538. * F U N C I O N E S DE L I S T A Y SQL
  539. *
  540. */
  541. /**
  542. * formatear errores de Mysql
  543. */
  544. function mysql_merror(){
  545. return "<div style='align:left'><B>ERROR MYSQL</B><BR>C&oacute;digo: ". mysql_errno(). "<br>Descripci&oacute;n: " . mysql_error() . "</div>";
  546. }
  547. /**
  548. * función para generar una plantilla combinada con una consulta SQL. La consulta
  549. * debe devolver entre 1 y 10 valores.
  550. * @deprecated usar mysql_template
  551. * @return plantilla generada
  552. */
  553. function mysql_plantilla( $cSQL , $cPlantilla, $cInicio="", $cNoHay="" ){
  554. if ( $cInicio ) {
  555. $cTemplate = cerrar_etiquetas ( $cInicio,"{%REPEAT" . $cPlantilla. "REPEAT-END%}" );
  556. } else {
  557. $cTemplate = $cPlantilla;
  558. }
  559. $cTemplate = preg_replace ( "/%([0-9])/Uis", '%[$1]',$cTemplate );
  560. return mysql_template ( $cSQL, $cTemplate, $cNoHay);
  561. }
  562. function mysql_template( $cSQL , $cTemplate, $cNoHay="" ){
  563. $cRet = "" ;
  564. $cTemp = "" ;
  565. $rsEmaitza = mysql_query ( $cSQL );
  566. // examinamos la template para extrar la plantilla repetitiva
  567. if ( $hayTemplate= preg_match ( "/{%REPEAT(.*)REPEAT-END%}/Uis", $cTemplate, $aResul) ){
  568. $cPlantilla = $aResul[1];
  569. } else {
  570. $cPlantilla= $cTemplate;
  571. }
  572. if ( $hayWhen = stripos ( $cPlantilla, "{%WHEN" )!== false ){
  573. $cPlantilla = preg_replace ("/{%WHEN ([^:]*):(.*)WHEN-END%}/Uim", '{%WHEN $1%:%$2WHEN-END%}', $cPlantilla );
  574. }
  575. // examinamos las sumas
  576. if ( preg_match_all ( "/%suma([0-9])/",$cTemplate, $temp) ){
  577. foreach ( $temp[1] as $valor) {
  578. $sumas[$valor]=0;
  579. }
  580. } else {
  581. $sumas = false;
  582. }
  583. // calculos la plantilla repetitiva
  584. $contador = 0;
  585. $par = true;
  586. while ( $lerroa = mysql_fetch_array ( $rsEmaitza, MYSQL_BOTH ) ) {
  587. $contador++;
  588. $par = !$par;
  589. //sumas
  590. if ( $sumas ) {
  591. foreach ($sumas as $key => $value ) {
  592. $sumas[$key] += $lerroa[$key] ;
  593. }
  594. }
  595. $lerroa [ "contador"] = $contador ;
  596. $lerroa [ "par"] = ( $par ? "even" : "odd" ) ;
  597. foreach ( $lerroa as $k=>$valor ){
  598. $sustituciones [ "%[$k]" ] = $valor ;
  599. }
  600. $cRet .= strtr ( $cPlantilla, $sustituciones );
  601. }
  602. mysql_free_result ($rsEmaitza);
  603. if ( !$contador and $cNoHay ){
  604. return $cNoHay;
  605. }
  606. // insertar resultado repetitivo en template.
  607. if ( $hayTemplate ){
  608. $cRet = str_replace ( $aResul[0], $cRet, $cTemplate );
  609. }
  610. $cRet = strtr ($cRet, array ("%total"=>$contador ) );
  611. // sumas
  612. if ( $sumas ) {
  613. foreach ($sumas as $key => $value ) {
  614. $rSumas["%suma$key"] = $value ;
  615. }
  616. $cRet = strtr( $cRet, $rSumas );
  617. }
  618. // quitamos las condicionales (When)
  619. if ( $hayWhen ) {
  620. //quitar las condicionales vacias.
  621. //$cRet = preg_replace ("/{%WHEN[ ]*%:%.*WHEN-END%}/Uims", "", $cRet );
  622. $cRet = preg_replace ("#{%WHEN [-\ 0]*%:%.*WHEN-END%}#Uims", "", $cRet );
  623. //quitar los WHEN...
  624. // este filtro no funciona si no se han eliminado todas las condificones vaciones.
  625. $cRet = preg_replace ("/{%WHEN (.)+%:%(.*)WHEN-END%}/Uims", '$2', $cRet );
  626. }
  627. // ahora solo quedan las traducciones
  628. if ( preg_match_all ( "/%t\[([^\]]*)\]/", $cRet, $ts )){
  629. foreach ( $ts[1] as $t ){
  630. $tsus["%t[$t]"]= t($t);
  631. }
  632. $cRet = strtr ( $cRet, $tsus );
  633. }
  634. /* Correcciones finales */
  635. $cRet = str_replace ("%%" , "%", $cRet );
  636. return $cRet;
  637. }
  638. /**
  639. * función para devuelve el nombre del campo clave primaria de una tabla
  640. * @return nombre campo clave
  641. */
  642. function mysql_campoClave ( $tabla ) {
  643. $rsEmaitza = mysql_query("SHOW COLUMNS FROM $tabla");
  644. $aurkitu = "";
  645. while ( $lerroa = mysql_fetch_array ( $rsEmaitza) ){
  646. if ( $lerroa["Key"] =="PRI" ) {
  647. $aurkitu = $lerroa[0];
  648. break;
  649. }
  650. }
  651. mysql_free_result ( $rsEmaitza );
  652. return $aurkitu;
  653. }
  654. /**
  655. * funcion para localizar rapidamente un dato mediante SQL.
  656. * @param Sentencia SQL-SELECT
  657. * @return El primer campo select, o NULL si no devuelve registros.
  658. */
  659. function mysql_mlookup( $cSql){
  660. $ret = NULL;
  661. $rsEmaitza = mysql_query($cSql);
  662. if ( $rsEmaitza ) {
  663. if ( $temp= mysql_fetch_array($rsEmaitza) ) {
  664. $ret = $temp[0];
  665. }
  666. mysql_free_result($rsEmaitza);
  667. }
  668. return $ret;
  669. }
  670. /**
  671. * funcion para localizar rapidamente un dato mediante SQL.
  672. * @param Sentencia SQL-SELECT
  673. * @return El primer campo select, o NULL si no devuelve registros.
  674. */
  675. function mysql_mexiste( $cSql){
  676. $ret = false;
  677. $rsEmaitza = mysql_query( $cSql);
  678. if ($rsEmaitza and mysql_fetch_array($rsEmaitza)){
  679. $ret= true;
  680. }
  681. mysql_free_result ( $rsEmaitza);
  682. return $ret;
  683. }
  684. /**
  685. * función para obtener una lista a partir de una sentencia SQL.
  686. * @param Sentencia SQL-SELECT
  687. * @return array con lista.
  688. */
  689. function mysql_query_lista($cSql, $hash = false){
  690. $aTemp = false;
  691. $rsEmaitza = mysql_query( $cSql);
  692. while ( $lerroa = mysql_fetch_array($rsEmaitza)){
  693. if ( $hash )
  694. $aTemp[$lerroa[0]]= $lerroa[1];
  695. else
  696. $aTemp[]= $lerroa[0];
  697. }
  698. mysql_free_result ( $rsEmaitza);
  699. return $aTemp;
  700. }
  701. /**
  702. * función para obtener el primer registro de un sentencia SQL.
  703. * @param Sentencia SQL-SELECT
  704. * @return El primer registro o FALSE
  705. */
  706. function mysql_query_registro($cSql){
  707. $rsEmaitza = mysql_query($cSql);
  708. $lerroa = mysql_fetch_array($rsEmaitza);
  709. mysql_free_result ( $rsEmaitza);
  710. return $lerroa;
  711. }
  712. /**
  713. * función para obtener todos los registros de un sentencia SQL.
  714. * @param Sentencia SQL-SELECT
  715. * @return Todos los registros o FALSE
  716. */
  717. function mysql_query_registros($cSql){
  718. $rsEmaitza = mysql_query($cSql);
  719. $temp = false;
  720. while ( $temp[]= mysql_fetch_array($rsEmaitza) ){
  721. }
  722. mysql_free_result ( $rsEmaitza);
  723. return $temp;
  724. }
  725. /*
  726. * Construye un array a partir de una sentencia SQL
  727. */
  728. function mysql_mlistaSQL ( $cSQL, $aValores= array() ){
  729. $resultado= mysql_query($cSQL);
  730. while ( $fila = mysql_fetch_array($resultado)){
  731. $aValores[]= $fila[0];
  732. }
  733. mysql_free_result ( $resultado );
  734. return $aValores;
  735. }
  736. /**
  737. * construye un array hash a partir de una sentencia SQL, que devuelve primero la clave
  738. * y luego el valor.
  739. */
  740. function mysql_mlistaClavesSQL ( $cSQL, $aValores= array() ){
  741. $resultado= mysql_query( $cSQL);
  742. while ( $fila = mysql_fetch_array($resultado)){
  743. $aValores[ $fila[0] ] = $fila[1];
  744. }
  745. mysql_free_result ( $resultado );
  746. return $aValores;
  747. }
  748. /**
  749. * algunas funciones para hacer limpieza .
  750. */
  751. function limpiaRequest($cCual){
  752. return ( isset($_REQUEST[$cCual]) ? limpiaSQLinjectionTexto($_REQUEST[$cCual]) : "" );
  753. }
  754. function limpiaSQLinjectionTexto ( $cTexto ){
  755. return strtr($cTexto, array("'"=>"\"", "$" =>""));
  756. }
  757. function limpiaSQLinjectionBuscar ( $cTexto ){
  758. return strtr($cTexto, array("'"=>"\"", "\"" =>"", "$" =>"" , "*" =>""));
  759. }
  760. function limpiaSQLinjectionID ( $cTexto ){
  761. return ( (int) $cTexto );
  762. }
  763. function limpiaSQLinjectionNumero ( $cTexto ){
  764. return ( is_numeric($cTexto) ? $cTexto : -1 );
  765. }
  766. /**
  767. * funcion para devolver el literal de la lista
  768. * @param aLista, aValor
  769. * @return el literal de la lista o aValor si no se encuentra.
  770. * @deprecated by in_array (php 4)
  771. */
  772. function in_lista ( $aguja ){
  773. $aDatos = func_get_args();
  774. foreach($aDatos as $i=>$valor ){
  775. if ( $i > 0 and $aguja==$valor ){
  776. return true;
  777. }
  778. }
  779. return false;
  780. }
  781. /**
  782. * Examina si clave esta en lista. Esta pued
  783. * ser un array o una cadena separada por "|"
  784. */
  785. function mLista( $aLista, $clave){
  786. if ( is_array ( $aLista) ) {
  787. $cTemp = $aLista[$clave];
  788. } else {
  789. $aOtro = explode("|", $aLista);
  790. $cTemp = $aOtro[$clave];
  791. }
  792. return ( $cTemp ? $cTemp : $clave );
  793. }
  794. /**
  795. *
  796. * F U N C I O N E S DE I N P U T S
  797. *
  798. */
  799. /**
  800. * devuelve un cadena HTML para un Select de una lista de valores
  801. */
  802. function mInputLista( $aValores, $cName, $cDefecto="", $cEstilo="" ){
  803. $cRet="<select name='$cName' class='$cEstilo'>\n";
  804. foreach( $aValores as $unValor ){
  805. $cRet.= "<option value='". $unValor . "' ". ($cDefecto==$unValor?"selected": "") .">$unValor</option>\n";
  806. }
  807. $cTemp.="</select>\n" ;
  808. return $cRet;
  809. }
  810. function mInputSiNo01 ( $cName , $cInicial, $cClass=""){
  811. $cRet ="<select name='$cName'";
  812. if ( $cClass!="") {
  813. if ( is_array($cClass) ){
  814. foreach ( $cClass as $atributo => $valor ) {
  815. $cRet .= " $atributo='$valor'";
  816. }
  817. } else {
  818. $cRet .= " class='$cClass' ";
  819. }
  820. }
  821. $cRet .= ">" ;
  822. $cRet .= "<option value='0' ". ($cInicial==0?" SELECTED ": "") .">No</option>\n" ;
  823. $cRet .= "<option value='1' ". ($cInicial==1?" SELECTED ": "") ." >Si</option>\n" ;
  824. $cRet .= "</select>";
  825. return $cRet;
  826. }
  827. /**
  828. * devuelve un cadena HTML para un Select de una lista hash (clave, valor).
  829. */
  830. function mInputListaClaves( $aValores, $cName, $valorInicial, $atributos=""){
  831. $cTemp ="\n<select name='$cName' ". ( $cEstilo!="" ? "class='$cEstilo' " : "" ) . ">\n";
  832. foreach( $aValores as $clave => $valor ){
  833. $cTemp.= sprintf( "<option value='$clave'%s>$valor</option>\n",
  834. ($clave==$valorInicial?" selected='selected'": "" ));
  835. }
  836. $cTemp.="</select>\n" ;
  837. return $cTemp;
  838. }
  839. /**
  840. * Construye un input a partir de una sentecni Select SQL que devuelve clave, valor.
  841. */
  842. function mInputSQL ( $cSQL, $cName, $cValorInicial, $cEstilo="", $opcionInicial=""){
  843. if ( $opcionInicial) {
  844. if ( is_array ( $opcionInicial ) ) {
  845. $TempList = $opcionInicial;
  846. } else {
  847. $TempList = array ( $opcionInicial );
  848. }
  849. $TempList = mysql_mlistaClavesSQL($cSQL, $TempList);
  850. } else {
  851. $TempList = mysql_mlistaClavesSQL($cSQL);
  852. }
  853. $cEstilo = ( $cEstilo ? " class='$cEstilo'" :"" );//@TODO revisar
  854. return mInputListaClaves ( $TempList, $cName, $cValorInicial, $cEstilo );
  855. }
  856. /**
  857. * Select de un entero booleano (0/1 pasa a NO/SI)
  858. */
  859. function mInputCheckbox( $cName, $cInicial, $cValue=1){
  860. return "<input type='checkbox' name='$cName' value='$cValue'" . ($cInicial==$cValue ? " checked='checked' ": "" ) . ">";
  861. }
  862. /**
  863. * Devuelve un control según el tipo especificado)
  864. */
  865. function mControl ( $cTipo, $cEtiqueta, $cName, $cValor="", $cEstilo="dl", $aOpciones="" ){
  866. $cId = ( isset($aOpciones['id']) ? $aOpciones['id'] : $cName );
  867. $cAdicional = "id='$cId'" ;
  868. if ( isset($aOpciones['class'])){
  869. $cAdicional .= " class='{ " . $aOpciones["class"] . "}'" ;
  870. }
  871. // construir el input
  872. $cLabel = "<label for='$cId'>$cEtiqueta</label>";
  873. switch ( $cTipo ){
  874. case "cadena":
  875. $campo = "<input type='text' name='$cName' value='$cValor' $cAdicional >";
  876. break;
  877. case "texto" :
  878. $campo = "<textarea name='$cName' $cAdicional>$cValor</textarea>";
  879. break;
  880. case "boolean":
  881. case "booleano":
  882. $cValue = ( isset($aOpciones['value']) ? $aOpciones['value'] : 1 );
  883. $cCampo = "<input type='radio' name='$cName' $cAdicional value='$value'" . ($cValor? " selected ": "" ) . ">";
  884. break;
  885. }
  886. if ( isset($aOpciones["adicional"] )) {
  887. $Campo .= ' ' . $aOpciones["adicional"];
  888. }
  889. // construir la label
  890. if ( isset($aOpciones["obligatorio"] )) {
  891. $cLabel = "<label for='$cId' class='obligatorio'>$cEtiqueta <span class='obligatorio'>(*)</span></label>";
  892. } else {
  893. $cLabel = "<label for='$cId'>$cEtiqueta</label>";
  894. }
  895. // maquetar label y control según estilo
  896. $aEstilo = array (
  897. "dl" => '<dd>%s</dd><dt>%s</dt>',
  898. "p" => '<p>%s %s</p>',
  899. "p-br" => '<p>%s <br> %s</p>',
  900. "table" => '<tr><th>%s</th><td>%s</td></tr>');
  901. return sprintf( $aEstilo[$cEstilo], $cLabel,$cCampo ) . "\n";
  902. }
  903. /*
  904. * funciones para el manejo de etiquetas
  905. */
  906. /**
  907. * cierra las etiquetas dadas.
  908. */
  909. function cerrar_etiquetas( $etiquetas, $texto="" ){
  910. $cRet = '';
  911. if (preg_match_all ("/(?:<(.*)>)/Ui" , $etiquetas,$aTemp)){
  912. $aTemp = array_reverse( $aTemp[1] );
  913. foreach ( $aTemp as $i=>$v ){
  914. preg_match ("/([^ ]*)/i" , $v,$aWord);
  915. $cRet .= "</{$aWord[1]}>";
  916. }
  917. }
  918. return $etiquetas.$texto.$cRet;
  919. }
  920. /**
  921. * para manejar XHTML hay tres funciones
  922. * xhtml_set, xhtml_get y xhtml_atributo, implementadas a través de
  923. * _mxhtml,
  924. */
  925. function _mxhtml( $accion, $atributo='' ){
  926. static $xhtml = true;
  927. switch ( $accion ) {
  928. case 'set':
  929. $xhtml = $atributo;
  930. case 'get':
  931. return $xhtml;
  932. case 'atributo':
  933. return ( $xhtml ? " $atributo='$atributo' " : " $atributo " );
  934. }
  935. }
  936. function xhtml_set ($valor = true){
  937. return _mxhtml ( 'set', $valor);
  938. }
  939. function xhtml_get (){
  940. return _mxhtml ( 'get');
  941. }
  942. function xhtml_atributo ( $atributo, $valor=''){
  943. if ( $valor !== '') {
  944. _mxhtml ( 'set', $valor);
  945. }
  946. return _mxhtml ( 'atributo', $atributo);
  947. }
  948. function mTabla ( $cabeceras, $datos, $adicionales="" ){
  949. $output = sprintf ( "<table %s %s>\n<thead><tr>",
  950. ( isset($adicionales["id"]) ? " id='{$adicionales[id]}'" : "" ),
  951. ( isset($adicionales["class"]) ? " class='{" . $adicionales['class'] . "'" : "" ) );
  952. // dibujar cabeceras
  953. foreach ( $cabeceras as $i=>$th ){
  954. if ( is_array ($th) ){
  955. $temp = "";
  956. foreach ( $th as $i => $v ) {
  957. if ( $i != "th" ){
  958. $temp .= " $i=\"$v\"";
  959. }
  960. }
  961. $output .= "<th$temp >{$th[th]}</th>";
  962. $claseTD[] = ( $th["class"] ? " class='". $th["class"]. "'" : "");
  963. } else {
  964. $output .= "<th>$th</th>";
  965. $claseTD[] = "";
  966. }
  967. }
  968. $output .= "</tr></thead>\n<tbody>\n";
  969. // dibujar los datos
  970. $par = true;
  971. foreach ($datos as $i=>$fila ){
  972. $output .= sprintf ( "<tr %s>", ( $par ? " class='par' " : "" ) ) ;
  973. foreach ($fila as $j=>$columna ){
  974. $output .= "<td{$claseTD[j]}>$columna</td>";
  975. }
  976. $output .= "</tr>\n";
  977. $par = !$par;function por_defecto(){
  978. foreach ( func_get_args() as $arg ){
  979. if ($arg) {
  980. return $arg;
  981. }
  982. }
  983. return false;
  984. }
  985. }
  986. $output .= "</tbody></table>\n";
  987. return $output;
  988. }
  989. /*
  990. * test de unidad
  991. */
  992. /*
  993. $fecha= "10/12-5";
  994. echo fecha_formato( $fecha, "es"),"<br>";
  995. echo fecha_formato( $fecha, "eu"),"<br>";
  996. echo fecha_formato( $fecha, "eu","c"),"<br>";
  997. echo mTabla ( array("Nombre","Apellidos", array ( "th"=>"fecha", "class"=>"flecha") ),
  998. array (
  999. array ("roger", "Martin", "15-68"),
  1000. array ("fermin", "Lopez", "68")),
  1001. array ( "id"=>"Personal"));
  1002. */
  1003. /* cerrar_etiquetas
  1004. echo cerrar_etiquetas ( '<li class=\'algo\'><a>','');
  1005. echo '\n';
  1006. echo cerrar_etiquetas ( '<li class=\'algo\'><a>','texto'); */
  1007. /*
  1008. echo mControl ("texto","Nombre","nombre","nada","dl");
  1009. echo mControl ("cadena","Nombre","nombre","nada","dl");
  1010. mprint (mQueryStringAdd ());
  1011. mprint (mQueryStringAdd (array("hola"=>"1&1")));
  1012. mprint (mQueryStringDel (array("hola"),false)); */