conecta($params['host'],$params['user'],$params['pass'],$params['db']); } else { global $db_vars; global $host_vars; global $user_vars; global $pass_vars; $this->conecta($host_vars,$user_vars,$pass_vars,$db_vars); } } function conecta($host,$user,$pass,$db) { $this->id = @mysql_connect($host,$user,$pass) ; if($this->id) { $this->bd = mysql_select_db($db,$this->id); } } function desconecta() { mysql_close($this->id); } } class query { var $conexion; var $resultado; var $row; var $numrows; var $data; var $eof = false; var $elquery; function query($con) { $this->conexion = $con; } function exec($sql="") { if($sql == "") { $this->resultado = 0; $this->numrows = 0; $this->row = -1; } // echo $sql; $this->resultado = mysql_query($sql,$this->conexion->id); if($this->resultado == false){ echo ''; } $strSQL = strtolower(substr($sql,0,3)); if($strSQL == "sel" or $strSQL == "des") { $this->numrows = mysql_num_rows($this->resultado); $this->row = 0; if($this->numrows>0) { $this->go(); } } else { $this->numrows = mysql_affected_rows($this->conexion->id); } $this->elquery = $sql; } function inic() { $this->row = 0; $this->go(); } function nxt() { $this->row = ($this->row < ($this->numrows -1)) ? ++$this->row : ($this->numrows -1); $this->go(); } function prv() { $this->row = ($this->row > 0) ? --$this->row : 0; $this->go(); } function lst() { $this->row = $this->numrows -1; $this->go(); } function go_to($lin) { if($lin >= 0 AND $lin < $this->numrows) { $this->row = $lin; $this->go(); } } function go() { mysql_data_seek($this->resultado,$this->row); $this->data = mysql_fetch_array($this->resultado,MYSQL_ASSOC); if($this->row == $this->numrows -1) $this->eof = true; else $this->eof = false; } function free() { mysql_free_result($this->resultado); } } class insert { var $con; var $tabla; var $col; var $_col; function insert($tabla,$con){ $this->con = $con; $this->tabla = $tabla; $q = new query($this->con); $q->exec("show columns from " . $this->tabla); $q->inic(); for($i=0;$i<$q->numrows;$i++) { $row = $q->data; $this->_col[$row['Field']] = $row['Field']; $q->nxt(); } $q->free(); } function update(){ $inscols = "insert into `" . $this->tabla . "` ("; $insstr = ""; foreach($this->col as $c => $cc){ if (!isset($this->_col[$c])){ //echo('No existe el campo \'' . $c . '\''); } else{ $inscols .= "`" . $c . "`,"; if($cc == 'NOW()'){ $insstr .= $cc.","; }else{ $insstr .= "'" .$cc. "',"; } } } $inscols = substr($inscols,0,strlen($inscols)-1) . ")"; $insstr = " values (" . substr($insstr,0,strlen($insstr)-1) . ")"; $q = new query($this->con); $q->exec($inscols . $insstr); //echo $inscols . $insstr . "\n"; /* unset($this->col); unset($this->_col);*/ } } class doupdate { var $con; var $tabla; var $col; var $_col; var $campo; var $var; function doupdate($tabla,$con,$campo,$vars){ $this->con = $con; $this->tabla = $tabla; $this->vars = $vars; $this->campo = $campo; $q = new query($this->con); $q->exec("show columns from " . $this->tabla); $q->inic(); for($i=0;$i<$q->numrows;$i++) { $row = $q->data; $this->_col[$row['Field']] = $row['Field']; $q->nxt(); } $q->free(); } function update(){ $inscols = "UPDATE `" . $this->tabla . "` SET "; $insstr = ""; foreach($this->col as $c => $cc){ if (!isset($this->_col[$c])){ //die('No existe el campo \'' . $c . '\''); } else { $inscols .= "`" . $c . "` = "."'".$cc."'".","; } } $inscols = substr($inscols,0,strlen($inscols)-1); $q = new query($this->con); $q->exec($inscols." WHERE ".$this->campo." = ".$this->vars); //echo $inscols . $insstr." WHERE ".$this->campo." = ".$this->vars.'
'; } } ?> 0) { if (headers_sent()) { echo "\n"; }else { header("Location: " . $pURL); } exit(); } } //redimencionar imagen function redimensionar($ruta,$file_name,$file_temp,$id,$tamanhos){ $filename = stripslashes($file_name); $extension = getExtension($filename); $extension = strtolower($extension); if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { $errors=1; }else{ $size=filesize($file_temp); list($width, $heigth) = getimagesize($file_temp); $size = $width*$heigth*3; echo var_dump($size); $mem = ini_get('memory_limit'); ini_set('memory_limit', '75M'); //Aumento temporal de la memoria para tratar imagenes comprimidas de ~5MB $other_images = pow(600+123+110,2)*3; // Calculo aproximadamente cuanto pesan en memoria el resto de imagenes //echo var_dump($other_images ); if ($size > 75*1024*1024 - $other_images){ $change='
You have exceeded uncompressed file size limit (>75MB)!. Choose a picture with less resolution
'; $errors=1; echo $change; }else{ $uploadedfile = $file_temp; if($extension=="jpg" || $extension=="jpeg" ){ $src = imagecreatefromjpeg($uploadedfile); }else if($extension=="png"){ $src = imagecreatefrompng($uploadedfile); }else{ $src = imagecreatefromgif($uploadedfile); } echo $scr; list($width,$height)=getimagesize($uploadedfile); foreach($tamanhos as $tam){ $newwidth = $tam['ancho']; $newheight=($height/$width)*$newwidth; //echo var_dump($newheight); //echo var_dump($tam['alto']); if($newheight > $tam['alto']){ $newheight = $tam['alto']; $newwidth=($width/$height)*$newheight; if($newwidth > $tam['ancho']){ $height = $newheight; $width = $newwidth; $newheight=($height/$width)*$newwidth; } } $tmp=imagecreatetruecolor($newwidth,$newheight); imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height); $filename = $ruta.'img_'.$id.'_'.$tam['nombre'].'.'.$extension; imagejpeg($tmp,$filename,100); imagedestroy($tmp); } imagedestroy($src); } ini_set('memory_limit', $mem); // devolucion del limite de memoria a su nivel. } } //funcion para obtener la extencion function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } //Funcion para borrar imagenes function eliminar_archivos($carpeta,$id) { $dir = '../file_sitio/'.$carpeta.'/'.$id.'/'; if(is_dir($dir)){ $directorio=opendir($dir); while ($archivo = readdir($directorio)) { if($archivo != '.' and $archivo != '..') { @unlink($dir.$archivo); } } closedir($directorio); @rmdir($dir); } } //funcion para generar las direcciones dinamicas de las publicaciones. function obtener_seo_url($titulo,$id,$tabla){ $seo_url = generar_url($titulo); $url = $seo_url; //verifico a que tabla corresponde el id $idn = ($tabla == 'noticias')?$id:0; $idp = ($tabla == 'productos')?$id:0; //tengo que verificar que la url en cuestion no este en uso por alguna de las publicaciones viejas. while(existe_seo_url('noticias','id_noticia', $url,$idn) == true AND existe_seo_url('productos','id_producto', $url,$idp) == true){ $cola = substr(md5(date('H:i:s d/m/Y')),0,5); //genero una cola para la url basada en el md5 de la fecha completa actual y de esta saco los primeros 5 caracteres. $url = $seo_url.'-'.$cola; } return $url; } //funcion para saber si una url existe function existe_seo_url($tabla,$nombre_id ,$url, $id_omitido){ $con = new Conn(); $cons = new query($con); $sql = 'SELECT url_dinamica FROM '.$tabla.' WHERE url_dinamica = "'.$url.'" AND '.$nombre_id.' != '.$id_omitido; $cons->exec($sql); if($cons->numrows > 0){ return true; } return false; } //funcion para generar las seo url function generar_url($titulo){ // generar URL dinamica $data = strtolower($titulo); $data = str_replace(array('/',' ','á','é','í','ó','ú','ñ' ,'ç','ã','â','ê','õ','ô','ü','"'), array('-','-','a','e','i','o','u','n' ,'c','a','a','e','o','o','u',''),$data); $data = ereg_replace('[^a-z0-9.-]','',$data); $data = preg_replace('#-{2,}#','-',$data); $data = trim($data,'-'); return $data; } //funcion para cortar un texto pero no las palabras. function cortar_palabras($texto, $limite, $break='.', $pad='...'){ if(strlen($texto) <= $limite) return $texto; $quiebre = strpos($texto, $break, $limite); if( $quiebre != false){ if($quiebre < (strlen($texto) - 1)){ $texto = substr($texto, 0, $quiebre).$pad; } } return $texto; } //Funcion para cortar textos. Se corta en cuanto se detecte un
function cortar($string, $maximo = 80) { $cantidad = strlen($string); $len_br = strtok($string, "
"); //echo $len_br; //$cantidad = min($cantidad, $len_br); if($cantidad > $maximo) { $maximo = $maximo - 3; $a = cut_html(substr($string, 0, $maximo)); $a .= "..."; return $a; } else { return $string; } } function cortar2($string, $maximo = 80) { $string = str_replace("
", "", $string); $cantidad = strlen($string); if($cantidad > $maximo) { $maximo = $maximo - 3; $a = cut_html(substr($string, 0, $maximo)); $a .= "..."; return $a; } else { return $string; } } //Funcion para evitar que se cortan caracteres html function cut_html($string) { $a=$string; while ($a = strstr($a, '&')) { $b=strstr($a, ';'); if (!$b) { $nb=strlen($a); return substr($string, 0, strlen($string)-$nb); } $a=substr($a,1,strlen($a)-1); } return $string; } //FUNCION PARA OBTENER EL VALOR DE UN CAMPO function obtener_campo($tabla,$campo,$where = 1){ $con = new Conn(); $q = new query($con); $sql = 'SELECT '.$campo.' FROM '.$tabla.' WHERE '.$where; $q->exec($sql); //echo var_dump($sql); return $q->data[$campo]; } function obtener_campo_order($tabla,$campo,$where = 1, $order){ $con = new Conn(); $q = new query($con); $sql = 'SELECT '.$campo.' FROM '.$tabla.' WHERE '.$where.'ORDER BY '.$order; $q->exec($sql); //echo var_dump($sql); return $q->data[$campo]; } function obtener_campo_adv($tabla,$campo,$join, $where, $order){ $con = new Conn(); $q = new query($con); $sql = 'SELECT '.$campo.' FROM '.$tabla.' WHERE '.$where; $q->exec($sql); echo var_dump($sql); return $q->data[$campo]; } //function para generar select multiples function generar_multiple($tabla,$id,$nombre,$default = array()){ $con = new Conn(); $q = new query($con); $consulta = 'SELECT * FROM '.$tabla.' ORDER BY '.$nombre.' ASC '; $q->exec($consulta); for($i=0; $i < $q->numrows; $i++, $q->nxt()){ $option .=''; } for($i=0; $i < count($default); $i++){ $option = str_replace('value="'.$default[$i]['id_tipo_producto'].'"','value="'.$default[$i]['id_tipo_producto'].'" selected', $option); } return ''; } /* Funcion para generar los option de los tag select $tabla -> el nombre de la tabla de donde sacar los datos $id -> el nombre de la columna con los id de los datos $nombre -> lista de campos separados por coma y en orden con el contenido a mostrar en el select $default -> el valor que debe estar seleccionado por defecto */ function generar_option($tabla,$id,$nombre,$texto,$default = 0,$where){ $con = new Conn(); $q = new query($con); $consulta = 'SELECT * FROM '.$tabla; if(isset($where)){ $consulta .= ' WHERE '.$where; } $consulta .= ' ORDER BY '.$nombre.' ASC'; $q->exec($consulta); $nombre = explode(',',$nombre); if($texto != ''){ $option =''; }else{ $option = ''; } for($i=0; $i < $q->numrows; $i++, $q->nxt()){ for($j=1; $j < count($nombre); $j++){ $q->data[$nombre[0]] = $q->data[$nombre[0]].','.$q->data[$nombre[$j]]; } $option .=''; } $option = str_replace('value="'.$default.'"','value="'.$default.'" selected', $option); return $option; } function obtener_archivos($ruta){ $file[0] = 'none'; if(is_dir($ruta)){ $directorio=opendir($ruta); $i = 0; while ($archivo = readdir($directorio) ){ if( $archivo != '.' and $archivo != '..'){ $file[$i] = $ruta.$archivo; $i++; } } closedir($directorio); } return $file; } function obtener_archivo($ruta){ $file = 'none'; if(is_dir($ruta)){ $directorio=opendir($ruta); while ($archivo = readdir($directorio) ){ if( $archivo != '.' and $archivo != '..'){ $file = $ruta.$archivo; } } closedir($directorio); } return $file; } function get_pais(){ //como en la base de datos los idiomas los manejo como numeros genero un vector para la conversion $idiomas = array('sp'=>'1','en'=>'2','fr'=>'3','de'=>'4','br'=>'5','it'=>'6'); $con = new Conn(); $q = new query($con); $sql = 'SELECT country_code2,country_name, idioma FROM ipdatabase WHERE IP_FROM<=inet_aton("'.$_SERVER['REMOTE_ADDR'].'") AND IP_TO>=inet_aton("'.$_SERVER['REMOTE_ADDR'].'") '; $q->exec($sql); // echo $sql; $_SESSION['idioma'] = $idiomas[$q->data['idioma']]; } //genero la lista de las marcas de paises para el buscador function buscador_marcas($def){ $con = new Conn(); $oGen = new Generica($con,'impresora_marca','id_marca'); $param['sql_select'] = ' DISTINCT impresora_marca.nombre,impresora_marca.id_marca '; $param['sql_more_table'] = ' productos_imp_marca '; $param['sql_where'] = ' productos_imp_marca.id_imp_marca = impresora_marca.id_marca '; $param['sql_order'] = ' impresora_marca.nombre ASC '; $data = $oGen->listar($param); $option = ' '; foreach($data as $dato){ $option .= ''; } return str_replace('value="'.$def.'"','value="'.$def.'" selected = "selected" ',$option); } //funcion para rellenar numeros function rellenar_izq($long_total,$valor='',$relleno=' '){ $cadena =''; $long_actual = strlen($valor); $long_resto = $long_total - $long_actual; for( $i = 0 ;$i < $long_resto; $i++) { $cadena.=$relleno; } $cadena.= $valor; return $cadena; } function generar_excel($id){ include_once("excelwriter.inc.php"); $con = new Conn(); $oPedidos = new Pedidos($con); $params['id_pedido'] = $id; $lista = $oPedidos->obtener_pedidos($id); //genero el nombre del archivo $vect = explode(' ',$lista['fecha_creacion']); $fecha = str_replace('-','.',$vect[0]); $hora = str_replace(':','.',$vect[1]); $tipo = ($lista['tipo'] == 'compra')?'PED':'OFE'; //el nombre del archivo tiene el sigueinte formato YYYY.MM.DD.HH.II.CODCLIENTE.PED.CODPEDIDO.xls $archivo = $fecha.'.'.$hora.'.'.rellenar_izq(7,$lista['codigo_cliente'],'0').'.'.$tipo.'.'.rellenar_izq(5,$lista['id_pedido'],'0').'.xls'; $excel = new ExcelWriter('ftp/Downloads/'.$archivo); //genero el contenido del archivo $prod_ext = $oPedidos->productos_externos_xls($params); $assoc = array( "Codigo Madre","Codigo Hijo","Codigo Cliente","Cantidad","Descripcion","Observaciones"); $excel->writeLine($assoc); foreach($prod_ext as $key =>$value){ $assoc = array( $value['cod_madre'], $value['cod_hijo'], $lista['codigo_cliente'], $value['cantidad'], strip_tags($value['descripcion']), $value['observaciones']); $excel->writeLine($assoc); } $excel->close(); } function cant_imagenes($carpeta,$id){ $ruta = '../file_sitio/'.$carpeta.'/'.$id.'/'; $i = 0; if(is_dir($ruta)){ $dh = opendir($ruta); while (($file = readdir($dh)) !== false){ if ($file!="." && $file!=".."){ if(stristr($file,'mini') !== false) $i++; } } } return $i; } function cant_archivos($carpeta,$id){ $ruta = '../file_sitio/'.$carpeta.'/'.$id.'/'; $i = 0; if(is_dir($ruta)){ $dh = opendir($ruta); while (($file = readdir($dh)) !== false){ if ($file!="." && $file!=".."){ $i++; } } } return $i; } //obtener datos de la relacion entre dos tablas function obtener_datos($tabla,$campo,$where){ $con = new Conn(); $oGen = new Generica($con,$tabla,'id_rel'); $param_def['sql_select'] = $campo; $param_def['sql_where'] = $where; $data = $oGen->listar($param_def); if($oGen->total_resultados != 0){ foreach($data as $dato){ $resultado .= $dato[$campo].','; } $resultado = substr($resultado,0,-1); }else{ $resultado = 0; } return $resultado; } function obtener_datos_adv($tabla,$campo,$join, $where, $order){ $con = new Conn(); $oGen = new Generica($con,$tabla,'id_rel'); $param_def['sql_select'] = $campo; $param_def['sql_where'] = $where; $param_def['sql_left_join'] = $join; $param_def['sql_order'] = $order; $data = $oGen->listar($param_def); if($oGen->total_resultados != 0){ foreach($data as $dato){ $resultado .= $dato[$campo].','; } $resultado = substr($resultado,0,-1); }else{ $resultado = 0; } return $resultado; } //obtener datos de la relacion entre dos tablas function obtener_lista_system($dato,$system,$tamanho){ $con = new Conn(); $oGen = new Generica($con,$dato,'id_'.$dato); $param_def['sql_select'] = $dato.'.id_'.$dato.' as id, name '; $param_def['sql_left_table'] = ' LEFT JOIN rel_system_'.$dato.' ON(rel_system_'.$dato.'.id_'.$dato.'='.$dato.'.id_'.$dato.') '; $param_def['sql_where'] = ' rel_system_'.$dato.'.id_system = '.$system; $data = $oGen->listar($param_def); if($oGen->total_resultados != 0){ $resultado = ''; foreach($data as $datos){ $resultado .= 'javascript:getInfo(\''.$dato.'\','.$datos['id'].')'; if($dato == 'tracker'){ $system = $datos['id']; } } //$resultado .= ''; }else{ $resultado = 'Data not available'; } return $resultado; } //obtener datos de la relacion entre dos tablas function obtener_lista_motor($id_tracker){ $con = new Conn(); $oGen = new Generica($con,'motordescription','id_motordescription'); $param_def['sql_select'] = 'motordescription.id_motordescription as id, name '; $param_def['sql_left_table'] = ' LEFT JOIN rel_tracker_motordescription ON(rel_tracker_motordescription.id_motordescription = motordescription.id_motordescription) '; $param_def['sql_where'] = ' rel_tracker_motordescription.id_tracker = '.$id_tracker; $data = $oGen->listar($param_def); //echo var_dump($data); if($oGen->total_resultados != 0){ //$resultado = ''; }else{ $resultado = ''; } return $resultado; } //calcular dias entre fechas function calcular_dias($open_date, $date = ''){ // calculo los días - mktime(hora,minuto,segundo,mes,dia,año) if($date == '' || $date == '0000-00-00') $date = date('Y-m-d'); $fecha = explode('-',$open_date); $fecha_open = mktime(0,0,0,$fecha[1],$fecha[2],$fecha[0]); $fecha = explode('-',$date); $fecha_actual = mktime(0,0,0,$fecha[1],$fecha[2],$fecha[0]); $dias = $fecha_actual - $fecha_open; $dias = $dias/60/60/24; return ($dias+1); //Añado un dia para incluir el dia de cierre } // funcion para calcular la cantidad de dias de un mes function UltimoDia($anho,$mes){ if (((fmod($anho,4)==0) and (fmod($anho,100)!=0)) or (fmod($anho,400)==0)) { $dias_febrero = 29; } else { $dias_febrero = 28; } switch($mes) { case 1: case 01: return 31; break; case 2: case 02: return $dias_febrero; break; case 3: case 03: return 31; break; case 4: case 04: return 30; break; case 5: case 05: return 31; break; case 6: case 06: return 30; break; case 7: case 07: return 31; break; case 8: case 08: return 31; break; case 9: case 09: return 30; break; case 10: return 31; break; case 11: return 30; break; case 12: return 31; break; } } //funcion para sumar dias function dateadd($givendate,$day=0,$mth=0,$yr=0) { $cd = explode('-',$givendate); if($cd[2]==NULL) //Para sumar meses en los que no se indica el dia. { $cd[2]=1; $newdate = date('Y-m', mktime(0,0, 0, $cd[1]+$mth,$cd[2]+$day, $cd[0]+$yr)); } else{ $newdate = date('Y-m-d', mktime(0,0, 0, $cd[1]+$mth,$cd[2]+$day, $cd[0]+$yr)); } return $newdate; } function timeadd($giventime, $hour, $min, $sec) { $giventime+=$hour*3600+$min*60+$sec; return $giventime; } // funcion para rellenar con ceros a la izquierda los numeros menores a 10 function cero_izq($num){ if($num < 10){ $num='0'.$num; } return $num; } //Funcion para hacer una lista de fechas (con dias) entre dos fechas function list_days($dateStart, $dateEnd) { $list = Array(); $day = $dateStart; $nDays = calcular_dias($dateStart, $dateEnd)-1; if($nDays<0) return; for($i=0;$i<=$nDays;$i++) { $list[$i] = $day; $day = dateadd($day,1,0,0); } return($list); } //Funcion para hacer una lista de fechas (solo meses) entre dos fechas function list_months($dateStart, $dateEnd) { $list = Array(); $date= $dateStart; $start = explode('-',$dateStart); $end = explode('-',$dateEnd); $nMon = ($end[0]*12+$end[1]) - ($start[0]*12+$start[1]) ; if($nMon <0) return; for($i=0;$i<=$nMon ;$i++) { $list[$i] = $date; $date= dateadd($date.'-01',0,1,0); $date=substr($date, 0, strlen($date)-3); //Para elimnar el dia de la fecha } return($list); } //Funcion para cerear un vector de horas de un dia con saltos indicados en hours, min o sec. function list_time($hour, $min, $sec) { $list = Array(); $time = mktime(0,0,0); // hora de inicio $end = mktime(23,59,59); //Hora Fin $i=0; while($time<$end && $i<1440) { $list[$i] = date('H:i:s', $time); $time = timeadd($time,$hour, $min, $sec); $i++; } return $list; } function ShowFileName($filepath) { preg_match('/[^?]*/', $filepath, $matches); $string = $matches[0]; #split the string by the literal dot in the filename $pattern = preg_split('/\./', $string, -1, PREG_SPLIT_OFFSET_CAPTURE); #get the last dot position $lastdot = $pattern[count($pattern)-1][1]; #now extract the filename using the basename function $filename = basename(substr($string, 0, $lastdot-1)); #return the filename part return $filename; } //obtengo las coordenadas function fraction_to_min_sec($coord) { $pos = $coord>=0; $coord = abs($coord); $deg = floor($coord); $coord = ($coord-$deg)*60; $min = floor($coord); $sec = round(($coord-$min)*60,4); $signo = '+'; if(!$pos) $signo = '-'; return $signo.$deg.'° '.$min.'\' '.$sec.'"'; } function dateSp($fecha){ $fechas = explode(' ',$fecha); $f = explode('-',$fechas[0]); return $f[2].'-'.$f[1].'-'.$f[0]; } function datetimeSp($fecha){ $fechas = explode(' ',$fecha); $f = explode('-',$fechas[0]); return $f[2].'-'.$f[1].'-'.$f[0].' '.$fechas[1]; } function dateEn($fecha){ $f = explode('-',$fecha); return $f[2].'-'.$f[1].'-'.$f[0]; } function download($fileName, $baseFile) { header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment;filename="'.$baseFile.'"'); $fp=fopen($fileName,'r'); fpassthru($fp); fclose($fp); } function getRealIP() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) return $_SERVER['HTTP_CLIENT_IP']; if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) return $_SERVER['HTTP_X_FORWARDED_FOR']; return $_SERVER['REMOTE_ADDR']; } function getUsersOnline() { $count = array(); $handle = opendir("../TMP/" ); if ($handle == false) return -1; while (($file = readdir($handle)) != false) { //echo fileatime("../TMP/".$file)."\n"; if (!(!strcmp(".", $file) || !strcmp("..", $file) ) ) { $date = fileatime("../TMP/".$file); if(time()- $date < 900) { // 15 minutes session $count[]=$file; } } } closedir($handle); return $count; } ?> Link "MalParido" de la url arreglado > & to & para que valide el HTML * *Parcheada 22/08/08 (Aeryus) > Si la pagina es uno, no pone el get p=1 ya que eso haria doble duplucado de la pagina, Google Friendly (Discover By The Power of Ator) * *Implementacion 02/07/08 (Aeryus) > Se puede poner el formato del ultimo numero del paginador * *Parcheada 19/03/07 (Aeryus) > Arreglado el bug "- RompeTodo" cuando devuelve el limit * > Optimizado el constructor de la clase y la forma de uso * > Arreglado la variable $url que permitia ataques xss * *Parcheada 12/03/07 (Aeryus) > El get['p'] "sospechoso" de hacer sql injection * *Parcheada 06/02/07 (Aeryus) > Arreglado el bug "Numeral Maligno" */ class Paginator { var $pie; //Templates var $final; var $siguiente; var $anterior; var $inicio; var $numeros; var $numeros_s; //Configs var $limitar_paginas; var $offset; var $limit; var $numPages; var $pagina; function __construct($resultados, $limit , $limitar_paginas = 5,$formatos = '') { if(isset($_GET['p']) || empty($_GET['p'])) $pagina=$_GET['p']; else $pagina=1; if(!is_numeric($_GET['p']) && isset($_GET['p'])) { die(); } $resultados = (int) $resultados; $limit = max((int) $limit, 1); $pagina = (int) $pagina; $numPages = ceil($resultados / $limit); $pagina = max($pagina, 1); $pagina = min($pagina, $numPages); $this->offset = ($pagina - 1) * $limit; $this->limit = $limit; $this->numPages = $numPages; $this->pagina = $pagina; $this->limitar_paginas = $limitar_paginas; if(!empty($formatos)) { $this->setFormatos($formatos); } $this->armarpie(); } function getOffset() { return $this->offset ; } function getLimit() { return $this->limit ; } function getAmountPages() { return $this->numPages ; } function getCurrentPage() { return $this->pagina ; } #Nuevas Funciones function getConsulta($cons) { if($this->getOffset() >= 0) { return $cons . ' LIMIT '.$this->getOffset().",".$this->getLimit(); } else { return $cons; } } function setFormatos($formatos) { if(is_array($formatos)) { $this->inicio = $formatos['inicio']; $this->anterior = $formatos['anterior']; $this->siguiente = $formatos['siguiente']; $this->final = $formatos['final']; $this->numeros = $formatos['pagina']; $this->numeros_s = $formatos['pagina_s']; $this->numeros_last = $formatos['numeros_last']; $this->numeros_last_s = $formatos['numeros_last_s']; } else { return false; } } #Fin nuevas funciones function armarpie() { $url = str_replace('?'.$_SERVER['QUERY_STRING'],'',$_SERVER['REQUEST_URI']); foreach ($_GET as $key => $value) { if($key != 'p') { $vars .= '&'.$key.'=' . $value; } } $vars_len = strlen($vars); $limitar_paginas = $this->limitar_paginas; if($this->getCurrentPage() > 1) { if($this->inicio != '') { $this->pie .= str_replace('"#"','"'.($url.($vars_len > 0 ? '?'.substr($vars,5,$vars_len) : '' )).'"',$this->inicio); } if($this->anterior != '') { if($this->getCurrentPage()-1 == 1) { $this->pie .= str_replace('"#"','"'.$url.($vars_len > 0 ? '?'.substr($vars,5,$vars_len) : '' ).'"',$this->anterior); } else { $this->pie .= str_replace('"#"','"'.$url.'?p='.($this->getCurrentPage()-1).$vars.'"',$this->anterior); } } } if($limitar_paginas) { if($this->getAmountPages() >= $limitar_paginas) { $cant = $this->getLimit(); $paginas = ceil($this->getAmountPages()); $actual = ceil(($this->getCurrentPage() + 1)); $mitad_sum = ceil(($limitar_paginas/2)+1); $mitad_desc = floor(($limitar_paginas/2)); if($actual<=$mitad_sum) { $ini=1; $limite=$limitar_paginas; } else if($actual>$paginas-$mitad_desc) { $ini=$paginas-($limitar_paginas-1); $limite=$paginas ; } else { $ini=$actual-$mitad_desc; $limite=$actual+$mitad_sum-2; } } else { $ini = 1; $limite = $this->getAmountPages() ; } } else { $ini = 1; $limite = $this->getAmountPages() ; } if($this->getAmountPages() != 1) { for($i=$ini;$i<= $limite ;$i++) { if($i == 0) { continue; } //Generamos el link para paginar if($i == 1) { /* Para no hacer doble contenido en la pagina numero 1, Google friendly */ if($vars_len > 0) { $link_paginar = $url.'?'.substr($vars,5,$vars_len); } else { $link_paginar = $url; } } else { $link_paginar = $url."?p=".($i).$vars; } //Si es la ultima Pagina if($i >= $this->getAmountPages() && $this->numeros_last != '') { if(($i) == $this->getCurrentPage()) { $this->pie .= str_replace('"#"','"'.$link_paginar.'"',str_replace("{P}" , $i , $this->numeros_last_s)); } else { $this->pie .= str_replace('"#"','"'.$link_paginar.'"',str_replace("{P}" , $i , $this->numeros_last)); } } else { if($this->getAmountPages() >= $limitar_paginas) { if(($i) == $this->getCurrentPage()) { $this->pie .= str_replace('"#"','"'.$link_paginar.'"',str_replace("{P}" , $i , $this->numeros_s)); } else { $this->pie .= str_replace('"#"','"'.$link_paginar.'"',str_replace("{P}" , $i , $this->numeros)); } } else { if($i == $this->getCurrentPage()) { $this->pie .= str_replace('"#"','"'.$link_paginar.'"',str_replace("{P}" , $i , $this->numeros_s)); } else { $this->pie .= str_replace('"#"','"'.$link_paginar.'"',str_replace("{P}" , $i , $this->numeros)); } } } } } if($this->getCurrentPage() < $this->getAmountPages()) { if($this->siguiente != '') { $this->pie .= str_replace('"#"','"'.$url.'?p='.($this->getCurrentPage()+1).$vars.'"',$this->siguiente); } if($this->final != '') { $this->pie .= str_replace('"#"','"'.$url.'?p='.($this->getAmountPages()).$vars.'"',$this->final); } } return $this->pie; } } /* USO: //Un array con los formatos (podria ir en el header , genvars, etc) - El {P} se va a reemplazar por el numero de la pagina $formatos['inicio'] = '<< '; $formatos['anterior'] = '< '; $formatos['siguiente'] = '> '; $formatos['final'] = '>> '; $formatos['pagina'] = '{P} '; $formatos['pagina_s'] = '{P} '; $formatos['numeros_last'] = '{P}  '; $formatos['numeros_last_s'] = '{P}  '; $cons ='SELECT * FROM productos'; $q->exec($cons); //5 es la cantidad de resultados a mostrar //3 es la cantidad de numeritos a mostrar siempre (EJ(3): < 3 4 5 > , EJ(5): < 3 4 5 6 7 >) //$formatos es el array con los formatos $pg = new Paginator($q->numrows,5,3,$formatos); $q->exec($pg->getConsulta($cons)); //Se imprime el paginador echo $pg->pie; // OPCIONES EXTRAS echo $pg->getAmountPages(); //Devuelve el total de las paginas echo $pg->getCurrentPage(); //Devuelve la pagina actual que es lo mismo que echo $_GET['p'] */ ?>con = $con; $this->table = 'news'; $this->table_id = 'id_news'; parent::__construct($con,$this->table,$this->table_id ); } public function borrar($id_del){ if(is_array($id_del)) foreach($id_del as $id) parent::eliminar($id); else parent::eliminar($id_del); } public function guardar($data = array()) { //$data['date']="01/01/2000"; $data['article_title'] = addslashes($data['article_title']); $data['news_text'] = addslashes($data['news_text']); return parent::guardar($data); } public function describir_tabla(){ return parent::describir_table(); } public function subir_imagen($id, $files = array()){ $ruta = '../file_sitio/news/'.$id.'/'; @mkdir($ruta); $cont = cant_imagenes('news',$id); if($cont < 10){ $tamanhos = array( '0' => array('alto' => '123', 'ancho' => '167', 'nombre' =>'lista'), '1' => array('alto' => '248', 'ancho' => '330', 'nombre' =>'ficha'), '2' => array('alto' => '119', 'ancho' => '159', 'nombre' =>'thumb'), '3' => array('alto' => '600', 'ancho' => '800', 'nombre' =>'grande'), '4' => array('alto' => '123', 'ancho' => '167', 'nombre' =>'mini'),); redimensionar($ruta,$files['name'], $files['tmp_name'],$cont,$tamanhos); } } public function borrar_foto($foto, $id_prod){ $ruta = '../file_sitio/news/'.$id_prod.'/'; //obtengo el id de la foto $data = explode('_',$foto); $id_foto = $data[1]; //obtengo la extención $data2 = explode('.',$data[2]); $ext = $data2[1]; //borro las 4 fotos @unlink($ruta.'img_'.$id_foto.'_lista.'.$ext); @unlink($ruta.'img_'.$id_foto.'_ficha.'.$ext); @unlink($ruta.'img_'.$id_foto.'_thumb.'.$ext); @unlink($ruta.'img_'.$id_foto.'_mini.'.$ext); @unlink($ruta.'img_'.$id_foto.'_grande.'.$ext); //obtengo la cantidad de imagenes $cant = cant_imagenes('news',$id_prod); for($i=0;$i<$cant;$i++){ if($i == $id_foto){ @rename($ruta.'img_'.($id_foto+1).'_lista.jpg',$ruta.'img_'.$id_foto.'_lista.'.$ext); @rename($ruta.'img_'.($id_foto+1).'_ficha.jpg',$ruta.'img_'.$id_foto.'_ficha.'.$ext); @rename($ruta.'img_'.($id_foto+1).'_mini.jpg',$ruta.'img_'.$id_foto.'_mini.'.$ext); @rename($ruta.'img_'.($id_foto+1).'_grande.jpg',$ruta.'img_'.$id_foto.'_grande.'.$ext); @rename($ruta.'img_'.($id_foto+1).'_thumb.jpg',$ruta.'img_'.$id_foto.'_thumb.'.$ext); $id_foto ++; } } } public function obtener_datos_tabla($params = array()){ $params['sql_select'] = ' id_news, date, article_title '; $data = parent::listar($params); return $data; } public function listar_front($params = array()){ if(isset($params['destacada'])){ $params['sql_where'] = ' highlight = "y" '; } $params['sql_order'] = ' date DESC'; $data = parent:: listar($params); return $data; } } ?>