<?
////////////////////////////////////////////////////
// Conciliación: gestión de conciliación de activos
// Version: 1.0
//
// Copyright (C) 2014  Eustotem Multimedia, S.L.
//
// License: MIT, see LICENSE
////////////////////////////////////////////////////



function __autoload($classname){
	$file = '../phplib/'.$classname.'.class.php';
	if (file_exists($file)){
		require_once $file;
	}else{
	}
}

function debug($param,$die=false){
	echo "<pre>";
	echo "---------------------------------------------------------------<br />";
	var_dump($param);
	echo "---------------------------------------------------------------";
	echo "</pre>";
	if($die==true) die();
}


function validationMessage($param){
	$n=chr(13);
	$t=chr(9);
	$cadena='';
	$cadena.='<strong>' . LOGIN_ERRORS_INTRO . '</strong><br /><br />';
	foreach($param as $key=>$value){
		$cadena.=$t.$t.'- ' . $value . '<br />'.$n;
	}
	return $cadena;
}


function changeUrlParam($clave,$valor){
	$a=$_GET;
	$a[$clave]=$valor;
	return http_build_query($a,'','&amp;');
}
function changeUrlParams($arr,$arr2){
	$cadena="";
	foreach($arr2 as $key=>$value){
		$arr[$key]=$value;
	}
	foreach($arr as $key=>$value){
		$cadena.=$key . "=" . $value . "&";
	}
	$cadena=rtrim($cadena,"&");
	return $cadena;
}

function deleteUrlParam($clave){
	$arr=array_splice($_GET,0);
	$cadena="";
	foreach($arr as $key=>$value){
		if($key==$clave){
			unset($arr[$key]);
		}else{
			$cadena.=$key . "=" . $value . "&";
		}
	}
	$cadena=rtrim($cadena,"&");
	return $cadena;
}
function changeUrlParamExt($url,$clave,$valor){
	$temp=explode("?",$url);
	$params=explode("&",$temp[1]);
	$cadena="";
	$found=false;
	foreach($params as $item){
		$kk=explode("=",$item);
		if($kk[0]==$clave){
			$cadena.=$kk[0] . "=" . $valor . "&";
			$found=true;
		}else{
			$cadena.=$kk[0] . "=" . $kk[1] . "&";
		}
	}
	if($found==false) $cadena.=$clave . "=" . $valor . "&";
	return $temp[0] . "?" . $cadena;
}


function sluggify($str, $replace=array(), $delimiter='-') {
	$old_locale = setlocale(LC_ALL, NULL);										
	setlocale(LC_ALL, 'en_US.UTF8');											
	
	if( !empty($replace) ) $str = str_replace((array)$replace, ' ', $str);
	$clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
	$clean = preg_replace("/[^\.a-zA-Z0-9\/_|+ -]/", '', $clean);
	$clean = strtolower(trim($clean, '-'));
	$clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);
	
	setlocale(LC_ALL, $old_locale);												
	return $clean;
}


function formatbytes($file, $type){
	switch($type){
		case "KB":
			$filesize = filesize($file) * .0009765625; 
			break;
		case "MB":
			$filesize = (filesize($file) * .0009765625) * .0009765625; 
			break;
		case "GB":
			$filesize = ((filesize($file) * .0009765625) * .0009765625) * .0009765625; 
			break;
	}
	if($filesize <= 0){
		return $filesize = 'unknown file size';
	}else{
		return round($filesize, 1).' '.$type;
	}
} 


function extractLang($texto, $idioma){
	$pattern="@\<!-- lang:$idioma --\>(.*)\<!-- \/lang:$idioma --\>@";
	preg_match($pattern, $texto, $matches, PREG_OFFSET_CAPTURE);
	return ($matches[1][0]);
}


function anti_sql_inject($value){
	if (get_magic_quotes_gpc()) {
		$value = stripslashes($value);
	}
	$value = mysql_real_escape_string($value);
	return $value;
}

function replaceSpecialParams($param,$f=NULL){
	global $resId;
	if(substr($param,0,3)=='{@_'){
		$temp=str_replace('{@_','',$param);
		$temp=str_replace('}','',$temp);
		$param=$_SESSION[(string)$temp];
	}
	if(substr($param,0,7)=='{@POST_'){
		$pattern = '/{@POST_(.*?)}/';
		preg_match_all($pattern, $param, $matches);
		for($i=0;$i<count($matches[0]);$i++){
			$param=str_replace($matches[0][$i],$_POST[$matches[1][$i]],$param);
		}
	}
	if(strpos($param,"{@")!==false){
		$param=str_replace('{@parentId}',$_REQUEST['parentId'],$param);		
		$param=str_replace('{@resId}',$resId,$param);						
		$param=str_replace('{@uId}',$_SESSION[session_id()]['id'],$param);	
		$param=str_replace('{@GET}',$_SERVER['QUERY_STRING'],$param);		
		$param=str_replace('{@today}',date("Y-m-d"),$param);				
		$param=str_replace('{@now}',date("Y-m-d H:i:s"),$param);			
	}
	if(strpos($param, "{%%" ) !== false){
		$pattern = '/{%%(.*?)}/';
		preg_match_all($pattern, $param, $matches);
		for($i=0;$i<count($matches[0]);$i++){
			$param=str_replace($matches[0][$i],$f[$matches[1][$i]],$param);
		}
	}else if(strpos($param,"{%")!==false){
		$pattern = '/{%(.*?)}/';
		preg_match_all($pattern, $param, $matches);
		for($i=0;$i<count($matches[0]);$i++){
			$param=str_replace($matches[0][$i],$f[$matches[1][$i]],$param);
		}
	}
	return $param;
}

function exclContent($param){
	global $conf;
	if(isset($conf->data->field_author)){
		if($_SESSION[session_id()]['exclAccess']=="1" && $_SESSION[session_id()]['level']>2){
			return str_replace('{@authid}'," AND " . $conf->data->field_author . "=" . $_SESSION[session_id()]['id'],$param);
		}
	}
	return str_replace('{@authid}','',$param);
}

function cutf($param){
	return iconv("iso-8859-1","utf-8",$param);
}


function disguise_curl($url){
	$curl = curl_init();
	$header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
	$header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
	$header[] = "Cache-Control: max-age=0";
	$header[] = "Connection: keep-alive";
	$header[] = "Keep-Alive: 300";
	$header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
	$header[] = "Accept-Language: en-us,en;q=0.5";
	$header[] = "Pragma: ";
	
	
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	$html = curl_exec($curl);
	curl_close($curl);
	return $html;
}
function http_get($domain,$url){
   $fp = fsockopen($domain, 80);
   $query  = 'GET ' . $url . " HTTP/1.1\r\n";
   $query .= 'Host: ' . "www.amurriotrueke.org";
   $query .= "\r\n\r\n";
   fwrite($fp, $query);
   while ($tmp = fread($fp, 1024))
   {
       $buffer .= $tmp;
   }
   fclose($fp);
   preg_match('/Content-Length: ([0-9]+)/', $buffer, $parts);
   return substr($buffer, - $parts[1]);
}
function estaArchivoIncluido($param){
	$archivos=get_included_files();
	foreach($archivos as $file){
		if(strpos($file,$param)!==false) return true;
	}
	return false;
}




function registerLog($resource,$operation, $id="",$cadenaenlace=""){
	$cadenarecurso=registerLogAux($resource);		
	$sql="INSERT INTO " . SYS_LOG_TABLE . "(fecha,idUser,idResource,strResource,operation,link,idRecord) VALUES (NOW()," . $_SESSION[session_id()]['id'] . ",'$resource','$cadenarecurso',$operation,'$cadenaenlace','$id')";
	mysql_query($sql);
}
function registerLogAux($resource){
	$retorno='';
	$f=mysql_fetch_assoc(mysql_query("SELECT label,parent FROM ".SYS_RESOURCES_TABLE." WHERE idResource='$resource'"));
	if($f['parent']!='0'){
		$retorno=registerLogAux($f['parent']) . " >> " . $f['label'];
	}else{
		$retorno=$f['label'];
	}
	return $retorno;
}

function raiseAppEvent($tipo,$param=NULL){
	if(is_null($tipo) or !is_numeric($tipo)) return false;
	$sql="SELECT * FROM ".SYS_ACTIONS_TABLE." WHERE estado=2 AND tipo=$tipo ORDER BY id DESC LIMIT 0,1";
	$q=mysql_query($sql);
	if(mysql_num_rows($q)==0) return false;
	$f=mysql_fetch_assoc($q);
	
	$e=array();
	$e['type']=$f['tipo'];
	$e['user']=$_SESSION[session_id()];
	$e['date']=date("Y-m-d H:i:s");
	$e['name']=$f['nombre'];
	$e['description']=$f['descripcion'];
	
	include($f['actions_file']);
	$nombreclase=(string)$f['actions_class'];
	$metodo=(string)$f['actions_method'];
	$objeto=new $nombreclase();
	
	switch($f['tipo']){
		case 9:
			$ahora=date("Y-m-d H:i:s");
			if(is_null($f['tstamp']) || $f['tstamp']=='0000-00-00 00:00:00' || $f['tstamp']==''){
			}
			break;
		case 1:							
			$e['post']=$_POST;
			break;
		case 2:							
			$e['post']=$_POST;
			break;
		case 3:							
		case 4:							
		case 5:							
		case 6:							
		case 7:							
		case 8:							
		case 10:						
			break;
		default:						
	}
	
	$objeto->$metodo($e,$param);
}

@include_once("../phplib/phpmailer/class.phpmailer.php");
@include_once("../phplib/envio_boletines.php");
$mail=NULL;		
$ymail=NULL;
if(class_exists("phpmailer")){
	$mail = new PHPMailer();
	$mail->SetLanguage("es","../phplib/phpmailer/language/");
	$mail->PluginDir="../phplib/phpmailer/";
	$mail->IsHTML(true);
	$mail->CharSet="utf8";
	$mail->Mailer=		"smtp";	
	$mail->SMTPAuth=	true; 
	$mail->Host=		SYS_MAILER_SMTPSERVER;
	$mail->Username=	SYS_MAILER_USER;
	$mail->Password=	SYS_MAILER_PASSWORD;
	$mail->From=		SYS_MAILER_FROM;
	$mail->FromName=	SYS_MAILER_FROMNAME;
	$mail->SMTPAuth=true;
	$ymail=$mail;
}else{
}
function cronMail(){
	if(!class_exists("phpmailer")) return false;
	global $ymail; global $lngs;
	$massiveSender=new envio_boletines();
	$massiveSender->mail=$ymail;
	$sql="SELECT * FROM ". SYS_PREFS_TABLE ." WHERE nombre='sys_last_mailing'";
	$qsend=mysql_query($sql) or die($sql);
	if(mysql_num_rows($qsend)>0){
		$fsend=mysql_fetch_assoc($qsend);
		if($fsend['valor']!='' && $fsend['valor']!=NULL){
			$antes=strtotime($fsend['valor']);
			$ahora=strtotime("now");
			$diferencia=$ahora-$antes;		
			if($diferencia>=SYS_BULKMAIL_TIMER){
				$sql="SELECT * FROM cra_news_envios WHERE estado=1 ORDER BY id_newsletter LIMIT 0," . SYS_BULKMAIL_LIMIT;
				$qdest=mysql_query($sql);
				if(mysql_num_rows($qdest)>0){
					$massiveSender->envia();
				}
			}
		}
	}else{
		$qq=mysql_query("INSERT INTO ".SYS_PREFS_TABLE."(nombre, valor) VALUES('sys_last_mailing','".date("Y-m-d H:i:s")."')");
	}

}
function uuid($prefix = ''){
	$chars = md5(uniqid(mt_rand(), true));
	$uuid  = substr($chars,0,8) . '-';
	$uuid .= substr($chars,8,4) . '-';
	$uuid .= substr($chars,12,4) . '-';
	$uuid .= substr($chars,16,4) . '-';
	$uuid .= substr($chars,20,12);
	return $prefix . $uuid;
}



function getSpecialButtons($param){
	$cadena='';
	foreach($param->button as $butt){
		$sp_btn_params=(string)$butt['action'];
		$sp_btn_label=Content::parse((string)$butt['label']);
		$sp_btn_target="";
		$sp_btn_id="";
		$sp_btn_class="";
		$arr_classes=array('grad_red','grad_orange','grad_yellow','grad_green','grad_blue','grad_purple','grad_grey','ui-button-primary','ui-button-success','ui-button-error');
		if(isset($butt['class'])){
			if(in_array((string)$butt['class'],$arr_classes)) $sp_btn_class=(string)$butt['class'];
		}
		if(stripos($sp_btn_params,"url:")===0){
			$sp_btn_params=str_replace("url:","",$sp_btn_params);
			$sp_btn_href=Content::parse($sp_btn_params);
			if(isset($butt['target'])) $sp_btn_target="target='" . (string)$butt['target'] . "'";
		}else if(stripos($sp_btn_params,"javascript:")===0){
			$sp_btn_href=$sp_btn_params;
		}else if(stripos($sp_btn_params,"ajax:")===0){
			$sp_btn_params=Content::parse(str_replace("ajax:","",$sp_btn_params));
			$sp_btn_href="#"; $sp_btn_id="id='{$sp_btn_params}'";
		}else{
			debug("MIERDA!!");
			continue;
		}
		$cadena.="<a href=\"{$sp_btn_href}\" {$sp_btn_target} {$sp_btn_id} class='link_button {$sp_btn_class}'>{$sp_btn_label}</a>";
	}
	return $cadena;
}
function getRecordCount($page,$pagesize,$totalrows,$currows){
	if($totalrows==0) return PAGINATOR_NORECORDS; 
	$cadena=PAGINATOR_TEXT;	
	$cadena=str_replace("{xxx}","<strong>" . (($pagesize*$page)+1) . "</strong>",$cadena);
	$cadena=str_replace("{yyy}","<strong>" . (($pagesize*$page)+$currows) . "</strong>",$cadena);
	$cadena=str_replace("{zzz}","<strong>" . $totalrows . "</strong>",$cadena);
	return $cadena;
}

function getPaginator($page,$pages,$items=7){
	if($pages<2) return;
	$url=basename($_SERVER['SCRIPT_FILENAME']);
	$cadena='<div class="paginator">';
	if($page>0){								
		$cadena.='<a href="'.$url.'?'.changeUrlParam('page',0).'" style="font-style:normal" class="button">'.PAGINATOR_FIRST.'</a>';
		$cadena.='<a href="'.$url.'?'.changeUrlParam('page',$page-1).'" style="font-style:normal" class="button">'.PAGINATOR_PREV.'</a>';
	}else{
		$cadena.='<span class="inactive button-disabled">'.PAGINATOR_FIRST.'</span>';
		$cadena.='<span class="inactive button-disabled">'.PAGINATOR_PREV.'</span>';
	}
	$l1=$page>$items ? $page-$items : 0;		
	$l2=$pages-$page>$items ? $page+$items : $pages;
	for($i=$l1;$i<$l2;$i++){
		if($page==$i){
			$cadena.='<span class="current button grad_orange">' . ($i+1) . '</span>';
		}else{
			$cadena.='<a href="'.$url.'?' . changeUrlParam('page',$i) . '" style="font-style:normal" class="current button">' . ($i+1) . '</a>';
		}
	}		
	if($page<$pages-1){							
		$cadena.='<a href="'.$url.'?' . changeUrlParam('page',$page+1) . '" style="font-style:normal" class="button">'.PAGINATOR_NEXT.'</a>';
		$cadena.='<a href="'.$url.'?' . changeUrlParam('page',$pages-1) . '" style="font-style:normal" class="button">'.PAGINATOR_LAST.'</a>';
	}else{
		$cadena.='<span class="inactive button-disabled">'.PAGINATOR_NEXT.'</span>';
		$cadena.='<span class="inactive button-disabled">'.PAGINATOR_LAST.'</span>';
	}
	$cadena.="</div>";
	return $cadena;
}
?>