<?php
	function repeatstr($char,$long) {
		if (isset($long)) {
			for($i=0;$i<$long;$i++)
				$str.=$char;
		}
		return $str;
	}
	
	function makeattr($attr,$val) {
		if(!$val=="")
			return ' '.$attr.'="'.$val.'"';
		else
			return '';
	}
	
	function maketag($tagname, $id, $class, $emptytag = false, $extratag='') {
		$str='<'.$tagname.makeattr('id',$id).makeattr('class',$class);
		$str.= $extratag ? $extratag : '';
		$str.= $emptytag ? ' />' : '>';
		return $str;
	}
	
	function endtag($tagname) {
		return "</".$tagname.">";
	}
	
	function rsstag($tagname, $txt) {
		return  $txt ? '<'.$tagname.'>'.$txt.'</'.$tagname.'>' : '';	
	}
	
	function maketagext($tagname, $arrlist, $emptytag = false, $extratag=''){
		$str='<'.$tagname;
		foreach($arrlist as $attr=>$val)
				$str.=makeattr($attr,$val);
		$str.= $extratag ? ' '.$extratag : '';
		$str.= $emptytag ? ' />' : '>';
		return $str;
	}
	
	function parsetag($tagname, $id, $class, $data='', $extratag='') {
		$str=maketag($tagname,$id,$class,false,$extratag);
		$str.=$data;
		$str.=endtag($tagname);
		return $str;
	}
	
	function parsepages ($quants,$pag,$n,$extra='') {
		$str='';
		$tot = $quants-$quants%10; #($quants%$pag==0) ? intval($quants/$pag) : intval($quants/$pag)+1;
		$s = 10*$pag;
		$i = $n-$s;
		$j = ($tot-$n-$i<0) ? true : false; #¿Quedan más de 10 pag's?
		if ($j) $i -= (9*$pag-($tot-$n));
		
		while ($a<20 && $i<$quants) {
			if ($i<0) {
				$i=$i+$pag;
			} else {
				$act = (intval($i/$pag)+1);
				if ($n==$i) {
					$str.="&nbsp;$act&nbsp;";
				} else {
					if ($extra<>'') {
						$str.="&nbsp;<a href='?$extra&amp;num=$i'>$act</a>$br&nbsp;";
					} else {
						$str.="&nbsp;<a href='?num=$i'>$act</a>&nbsp;";
					}
				}
				$i=$i+$pag;
				$a++;
			}
		}
		return $str;
	}
	
	function texttohtml($string) {
		$str=$string;
		$find = array('&',        'á',        'é',        "í",         "ó",         "ú",        "ñ",        "",       "º",        "<br>",    "\n");
		$repl = array('&amp;',    '&aacute;', '&eacute;', '&iacute;',  '&oacute;',  '&uacute;', "&ntilde;", "&#8230;", "&ordm;",   '<br />',  '<br />');
		$str = str_replace($find, $repl, $str);
		return $str;
	}
	
	function textfilter($string) {
		$str=$string;
		static $find = array('^', '(', ')', '<', '>', '`', '\'', '"', '+', '[', ']', '{', '}', '\\', '=', '#', '\'', ';', '!', '*');
		static $repl = array('', '', '', '', '', '', '',  '',  '', '', '',  '', '', '', '', '' , '', '', '', '');
		$str = str_replace($find, $repl, $str);
		$str = preg_replace('/[\n\r]/is', ' ', $str);
		$str = preg_replace('/\b&[a-zA-Z]+;\b/', ' ', $str);
		$str = trim($str);	
		$str = stripslashes($str);
		return $str;
	}
	
	function str_nl2br($text) {
		$text = str_replace(array("\n", "\r"), array('<br />', "\n"), $text);
		return $text;
	}
	
	function get_date($ConHora) {
		$mes = Date(m); $dia = Date(d); $hora = Date(H); $min = Date(i); $year = Date(Y);
		if ($ConHora) {return($dia."/".$mes."/".$year." ".$hora.":".$min);} else {return($dia."/".$mes."/".$year);}
	}
	
	function dateformat($date) {
		$chr = (strstr($date, '-')) ? '-' : '/';
		
		if (strpos($date, $chr)) {
			$formate=explode($chr, $date);
			$date=$formate[0]."-".$formate[1]."-".$formate[2];
		}
		
		if (strpos(substr($date,0,4), $chr)) {
			$formate=explode("-",$date);
			return($formate[2]."-".$formate[1]."-".$formate[0]);
		} else
			return($date);
	}
	
	function dateunformat($date) {
		$date = (string)$date;
		$formate=explode("-",$date);
		return($formate[2]."-".$formate[1]."-".$formate[0]);
	}
	
	function hourformat($hour) {
		$hour = (string)$hour;
		$formate=explode(":", $hour);
		return($formate[0].":".$formate[1]);
	}

/**
 * @brief Return the html generated by the objects. ( calls to $obj->render() )
 * @param &$obj array reference of objects to render
 * @return HTML code generated
*/
	function renders(&$obj) {
		foreach ($obj as $o)
			$str.=$o->render();
		return $str;
	}
	
/**
 * @brief Create an object with the name of the parameter.
 * @param string $objstr
 * @return New Object
 * @tutorial cclass("H3('Mi Texto')")
 */
	function cclass($objstr) {
		eval('$obj = new '.$objstr.";");
		return $obj;
	}
	
	function obj_render(&$obj) {
		return $obj->render();
	}
	
	function secure_mail($mail) {
		if (strstr($mail,'@')) {
			$em = explode('@', $mail);
			return $em[0].' (-@-) '.$em[1];
		} else
			return $mail;
	}
	
	function get_size($path) {
		$bytes = array('B','KB','MB','GB','TB');
		
		if (file_exists($path))
			$size = filesize($path);
		else
			return '';	
		
		foreach($bytes as $val) {
			if($size > 1024){
				$size = $size / 1024;
			} else break;
		}
		return round($size, 2)." ".$val;
	}
	
	function get_ext($file) {
		$arr = explode('.', $file);
		return strtolower($arr[count($arr)-1]);
	}
	
	function get_icon($file) {
		$arr = explode('.', $file);
		$ext = strtolower($arr[count($arr)-1]);
		$pdf = 'pdf';
		$txt = array('doc', 'txt', 'odt', 'html', 'htm', 'chm');
		$com = array('rar', 'zip', 'ace'. 'bz', 'tar', 'bz2', '7z', 'gz');
		$str.= ($ext==$pdf) ? 'pdf.png' : '';
		$str.= arr_search($ext, $txt) ? 'text.png' : '';
		$str.= arr_search($ext, $com) ? 'compressed.png' : '';
		$str.= ($str!='') ? '' : 'unknown.png';
		return IMG.$str;
	}
	
	function arr_search($search, $arr) {
		if (is_array($arr)) {
			foreach($arr as $a) {
				if ($search==$a)
					return true;
			}
		}
		return false;
	}
	
	function make_insert($table, $arr, $arr_ignore='', $field_prefix='') {
		$k=array_keys($arr);
		$v=array_values($arr);
		$q=count($k);
		
		for($i=0; $i<$q; $i++) {
			$ignore = false;
			if (is_array($arr_ignore)) {
				foreach($arr_ignore as $ki) {
					if ($ki==$k[$i])
						$ignore=true;
				}
			}
			
			if (!$ignore && $k[$i]!='enviar' && $k[$i]!='send' ) {
				$keys.= $field_prefix.$k[$i].", ";
				$v[$i] = addslashes($v[$i]);
				$values.= "'".$v[$i]."', ";
			}
		}
		$keys = substr($keys,0,strlen($keys)-2);
		$values = substr($values,0,strlen($values)-2);
		
		return "INSERT INTO ".$table." (".$keys.") VALUES (".$values.")";
	}
	
	function make_update($table, $arr, $field_id_name, $arr_ignore='', $field_prefix='') {
		$k=array_keys($arr);
		$v=array_values($arr);
		
		for($i=0;$i<count($k);$i++) {
			$ignore = false;
			if (is_array($arr_ignore)) {
				foreach($arr_ignore as $ki) {
					if ($ki==$k[$i])
						$ignore=true;
				}
			}
			
			if (!$ignore)
				if ($field_id_name==$field_prefix.$k[$i])
					$field_id_value = $v[$i];
				elseif ($k[$i]!='enviar' && $k[$i]!='send') {
					$v[$i] = addslashes($v[$i]);
					$fields.=$field_prefix.$k[$i]."='".$v[$i]."', ";
				}
		}
		$fields = substr($fields,0,strlen($fields)-2);
		
		if (isset($field_id_value))
			return "UPDATE ".$table." SET ".$fields." WHERE ".$field_id_name."=".$field_id_value;
		else
			return false;
	}
	
	function make_delete($table, $field_id_name, $field_id_value) {
		return "DELETE FROM ".$table." WHERE ".$field_id_name."=".$field_id_value;
	}
	
	function slash_arr(&$arr) {
		if (is_array($arr)) {
			foreach($arr as $n=>$v)
				$arr[$n] = addslashes($v);
			return $arr;
		} else
			return $arr = addslashes($arr);
	}
	
	function secure ($seccion) {
		if ($seccion) {
			session_start();
			if ( !isset( $_SESSION['session_name'] ) || !isset( $_SESSION['session_pass'] ) ) {
				cPage::adddata("Debes comenzar una session.");
				return false;
			} else {
				if (USER_NAME != $_SESSION['session_name'] || USER_PASS != $_SESSION['session_pass'] || USER_CODE != $_SESSION['session_code']) {
					if( isset($_SERVER['HTTP_X_FORWARDED_FOR']) ) {
						$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
					} elseif ( isset($_SERVER['HTTP_VIA']) ) {
						$ip = $_SERVER['HTTP_VIA'];
					} elseif ( isset($_SERVER['REMOTE_ADDR']) ) {
						$ip = $_SERVER['REMOTE_ADDR'];
					} else { 
						$ip = "Desconocida";
					}
					
				/*	$fecha = date ("d/m/Y H:i");
					$guardar= "$ip - $fecha<br />";
					$archivo = fopen ("ips.htm", "a");
					fputs ($archivo,$guardar);
					fclose ($archivo); */
					
					cPage::adddata("Tu ip acaba de ser guardada por sospecha de intento de hackeo. Tu ip es: $ip");
					return false;
				}
			 }
		}
		
		return true;
	}
	
	function trace( $err ) {
		if ( DEBUG == true ) {
			$file = fopen ( "./traced_errors", "a" );
			fputs ( $file, $err."\n" );
			fclose ($file);
		}
	}
	
	function print_vars($obj) {
		$data = '';
		$arr = get_object_vars($obj);
		
		while ( list($prop, $val) = each($arr) )
			$data += "$prop\t$val\n";
			
		return $data;
	}
?>