Uname: Linux info 3.0 #1337 SMP Tue Jan 01 00:00:00 CEST 2000 all GNU/Linux
Software: Apache
PHP version: 5.6.40 [ PHP INFO ] PHP os: Linux
Server Ip: 217.160.0.194
Your Ip: 216.73.217.62
User: u72294154 (9179942) | Group: ftpusers (600)
Safe Mode: OFF
Disable Function:
NONE

name : utils.php
<?
/**
 * 
 ************************************************************************************** 
 * 14/04/2010
 * ARCHIVO PARA FORMATEO CIFRAS (ES/EN) 
 * Formato de la cifra XXXX.xx (ej: 9999.22)
 * Nota: -estudiar posibilidad de ampliar para formatos de otros países 
 ************************************************************************************** 
 * 
 */
function format_number($number,$idioma='ES',$n_decimales=null){ 
	
	//Comprobamos que la cifra proporciona sea numerica
	if(!is_numeric($number)){
		return "La cifra no es numerica";
	}
	else{
		//Valores por defecto para ES
		$miles = "."; 
		$decimal = ",";

		if($idioma == 'EN'){
			$miles = ",";
			$decimal = ".";
		}
		//Comprobamos si hemos pasado numero de decimales (y es entero)
		if($n_decimales == null || !is_int($n_decimales)){
			//Si no han pasado numero de decimales obtenemos el número que tiene la cifra
			$esdecimal = strpos("$number",'.');
			if($esdecimal){
				$n_decimales = strlen("$number")-$esdecimal-1;
					//echo substr($number,$esdecimal,$n_decimales);
				if(substr($number,$esdecimal+1,$n_decimales) == 0){
					$n_decimales = 0;
				}
			}
			else{
				$n_decimales = 0;
			}
		}
		
		//Devolvemos la cifra formateada con los decimales y en el formato de idioma pedido
		return number_format($number,$n_decimales,$decimal,$miles);
	}
}

/**
 * 
 ************************************************************************************** 
 * 15/04/2010
 * ARCHIVO PARA FORMATEO TEXTO EN FORMA URL
 * (Ej: "Los molinos más famosos de España" >> los-molinos-mas-famosos-de-espana ) 
 ************************************************************************************** 
 * 
 */
function format_url($texto){ 
	
	$spacer = "-";
	$url = trim($texto);
    $url = str_replace(array("á","à","ä","Á","À","Ä","ª"),"a",$url);
    $url = str_replace(array("é","è","ë","É","È","Ë"),"e",$url);
    $url = str_replace(array("í","ì","ï","Í","Ì","Ï"),"i",$url);
    $url = str_replace(array("ó","ò","ö","Ó","Ò","Ö","º"),"o",$url);
    $url = str_replace(array("ú","ù","ü","Ú","Ù","Ü"),"u",$url);
    $url = str_replace(array("ñ","Ñ"),"n",$url);
    $url = str_replace(array('"',"'","´","`",",",".",";"),$spacer,$url);
    $url = str_replace(array("ç","Ç"),"c",$url);
    $url = str_replace(array("¡","!","¿","?","(",")",".","/","\\"),$spacer,$url);
	$url = preg_replace("/[ \t\n\r]+/", $spacer, $url);
	$url = preg_replace("/^[¡¿-]+/", "", $url);
	$url = preg_replace("/[?!-]+$/", "", $url);
	$url = str_replace(" ", $spacer, $url);
	$url = str_replace(array("[","]"), "", $url);
	$url = preg_replace("/[ -]+/", $spacer, $url);
	$url = strtolower($url);
 
   
	return $url; 
	
}

/**
 * 
 ************************************************************************************** 
 * 14/04/2010
 * ARCHIVO PARA LIMITAR TEXTO A N_CARACTERES
 ************************************************************************************** 
 * 
 */
function limit_text($texto,$n_caracteres){ 
	//Eliminamos tags html en caso de que los haya menos los saltos de linea.
	$texto = strip_tags($texto,'<br>');
	//No pasamos un numero entero de caracteres
	if(!is_int($n_caracteres)){
		return "El número de caracteres no es un entero";
	}
	//Pasamos un texto vacio
	if(strlen($texto)<= 0){
		return "El texto está vacío";
	}
	//Si la longitud del texto es menor al limite no tocamos nada
	if(strlen($texto) < $n_caracteres){
		return $texto;
	}
	
	$texto_troceado = explode(" ",trim($texto));
	$texto_mod = '';
	// Vamos concatenando trozos del texto original sin sobrepasar el limite
	// y añadimos "..." al final
	foreach($texto_troceado as $trozo){
		if(strlen("$texto_mod $trozo") > $n_caracteres-3)
			break;
		else
			$texto_mod .= " $trozo";
	}
	
	return "$texto_mod...";
	
}

/************************************************************************************** 
 * 24/08/2011
 * ARCHIVO PARA CORTAR TEXTO A N_CARACTERES
 ************************************************************************************** 
 * 
 */
function cut_text($texto,$n_caracteres){ 
	//Eliminamos tags html en caso de que los haya menos los saltos de linea.
	$texto = strip_tags($texto,'<br>');
	//No pasamos un numero entero de caracteres
	if(!is_int($n_caracteres)){
		return "El número de caracteres no es un entero";
	}
	//Pasamos un texto vacio
	if(strlen($texto)<= 0){
		return "El texto está vacío";
	}
	//Si la longitud del texto es menor al limite no tocamos nada
	if(strlen($texto) < $n_caracteres){
		return $texto;
	}
	
	return substr($texto,0,$n_caracteres);
	
}

/**
 * 
 ************************************************************************************** 
 * 15/04/2010
 * ARCHIVO PARA FORMATEO TEXTO A ASCII 
 * (Ej: pruebaprueba.com >>  
 ************************************************************************************** 
 * 
 */
function int_to_ascii($int){ 

	$ascii = '';
	 foreach (str_split($int) as $obj) 
    { 
        $ascii .= '&#' . ord($obj) . ';'; 
    }
	echo $ascii;
	return($ascii);

}

/**
 * 
 ************************************************************************************** 
 * 28/04/2010
 * INCRUSTA REPRODUCTOR YOUTUBE  con las dimensiones y el video que se indica
 * Ej: http://www.youtube.com/watch?v=zVt9kQWNp3I&feature=player_embedded 
 * youtube('zVt9kQWNp3I',800,600)
 * donde ancho = 800px
 *       alto = 600px
 *       codigo del video en youtube = zVt9kQWNp3I 
 ************************************************************************************** 
 * 
 */
function youtube($codigo=null,$ancho=480,$alto=385){ 

	return '<object width="'.$ancho.'" height="'.$alto.'">
				<param name="movie" value="http://www.youtube.com/v/'.$codigo.'"></param>
				<param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param>
				<embed src="http://www.youtube.com/v/'.$codigo.'" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="'.$ancho.'" height="'.$alto.'"></embed>
			</object>';

}


/**
 * 
 ************************************************************************************** 
 * 21/05/2010
 * Devuelve el primer párrafo de un texto html. Si no tiene etiquetas <p></p> 
 * devuelve el texto completo con etiquetas <p></p>
 ************************************************************************************** 
 * 
 */
 
 function first_paragraph($html){
	
	$inicio = strpos($html,'<p>');
	$fin = strpos($html,'</p>');
	
	if($inicio !==  false && $fin !== false)
		return substr($html,$inicio,$fin + strlen('</p>'));
	else
		return "<p>$html</p>";
		
 }
 
 
 /**
 * 
 ************************************************************************************** 
 * 24/05/2010
 * Formatea una fecha procedente de bbdd en formato español y anglosajón
 * y con el separador personalizado
 ************************************************************************************** 
 * 
 */
 
 function format_date($fecha,$separador='-',$formato='ES'){
	
	if(!preg_match("/^([0-9]{4,4})-([0-9]{2,2})-([0-9]{2,2})$/",$fecha))
		return "Compruebe el formato de la fecha: $fecha";
	
	$temp = explode("-",$fecha);
	
	if($formato == 'ES')
		return "{$temp[2]}$separador{$temp[1]}$separador{$temp[0]}";
	else
		return "{$temp[1]}$separador{$temp[2]}$separador{$temp[0]}";
	
 }
 
 
 /**
 * 
 ************************************************************************************** 
 * 03/06/2010
 * Echo recursivo de una variable para visualizarla en el navegador
 ************************************************************************************** 
 * 
 */
 
 function volcar_variable($variable){
	
	echo "<pre>";
	var_dump($variable);
	echo "<pre>";
 
 }

 /**
 * 
 ************************************************************************************** 
 * 04/06/2010
 * Formatea un telefono en grupos de dos o tres cifras
 ************************************************************************************** 
 * 
 */
 
 function format_phone($telefono,$dos_format=false){
	
	$temp = str_replace(array(" ","-"),"",$telefono);

	if(!preg_match('/([0-9]+){9,}/',$temp))
		return "El formato de telefono no es correcto: $telefono";
	else{
	
			$numero = substr($telefono,-6);
			$prefijo = substr($telefono,0,(strlen($telefono)-1)-6);
			
			if($dos_format)
				return  "$prefijo ".implode(" ",str_split($numero,2));
			else
				return  "$prefijo ".implode(" ",str_split($numero,3));
	}
 
 }
 
 
 /**
 * 
 ************************************************************************************** 
 * 20/07/2010
 * Obteniene contenido DOM respuesta a una peticion de una página de un servidor
 * cuando no es posible el uso por temas de seguridad con file_get_contents o file
 *  Uso:
 *       $xml = loadXML2("127.0.0.1", "/path/to/xml/server.php?code=do_something");
 *       if($xml) {
 *          // xml doc cargado
 *       } else {
 *         // fllo. mostramos mensaje de error.
 *       }
 ************************************************************************************** 
 * 
 */
 function loadXML2($domain, $path, $timeout = 30) {

    $fp = fsockopen($domain, 80, $errno, $errstr, $timeout);
    if($fp) {
        // make request
        $out = "GET $path HTTP/1.1\r\n";
        $out .= "Host: $domain\r\n";
        $out .= "Connection: Close\r\n\r\n";
        fwrite($fp, $out);
       
        // get response
        $resp = "";
        while (!feof($fp)) {
            $resp .= fgets($fp, 128);
        }
        fclose($fp);
        // check status is 200
        $status_regex = "/HTTP\/1\.\d\s(\d+)/";
	
        if(preg_match($status_regex, $resp, $matches) && $matches[1] == 200) {   
            // load xml as object
            $parts = explode("\r\n\r\n", $resp);  
            return simplexml_load_int($parts[1]);               
        }
    }
    return false;
   
	} 
	
/**
 * 
 ************************************************************************************** 
 * 05/08/2011
 * Escapa los caracteres especiales de una cadena para su uso con consultas a bbdd.
 * Tiene en cuenta la versión de php instalada en el servidor
 *
 ************************************************************************************** 
 * 
 */
	function my_real_escape_int($int=false){
		
		if(function_exists('mysql_real_escape_int')){
			return mysql_real_escape_int($int);
		}
		else{
			return addslashes($int);
		}
		
	}
	
	
/**
 * 
 ************************************************************************************** 
 * 23/08/2011
 * Crea SELECT o añade OPTIONs a un SELECT
 * 
 *
 ************************************************************************************** 
 * 
 */
	function my_select($options=array(),$name=false,$selected=false,$label=false,$value=false,$extra_option=false,$select=true,$extra=false){
		
		if($select){
			echo '<select';
		
			if($name)
				echo " name=\"$name\" ";
				
			if($extra)
				echo " $extra ";
			
			echo '>';
		}
		
		if(is_array($options)){
			
			if(is_array($extra_option)){
				$options = array_merge(array($extra_option),$options);
				// $options[] = $extra_option;
			}
			
			if(!empty($options)){
				
				foreach($options as $option){
					if(is_array($option)){
						$elegido = '';
						$valor = $option[1];
						$etiqueta = $option[0];
						
						if($label && $value){
							$valor = $option[$value];
							$etiqueta = $option[$label];
						}	
						
						if((string)$valor == (string)$selected)
							$elegido = ' selected="selected"';	
							
						echo "<option value=\"$valor\"$elegido>$etiqueta</option>";
					}
					else{
						if((string)$option == (string)$selected)
							$elegido = ' selected="selected"';	
							
						echo "<option value=\"$option\"$elegido>$option</option>";
					}
						
				} //End foreach
				
			}
			
		}
		
		if($select)
			echo '</select>';
	}
	
/**
 * 
 ************************************************************************************** 
 * 25/08/2011
 * Te devuelve url a un archivo de icono en funcion de la extensión del archivo que
 * se le da
 *
 ************************************************************************************** 
 * 
 */
	function mime_type($archivo=null,$carpeta='/imagenes/comunes/iconos/'){ 
		
		if($archivo != null)
		{	
			
			if(strrpos($archivo,'.') !== FALSE)
			{
				$extension = substr($archivo,strrpos($archivo,'.')+1,strlen($archivo)-strrpos($archivo,'.')+1);
				
				if(file_exists($_SERVER['DOCUMENT_ROOT'].$carpeta.$extension.'.png')){
					return $carpeta.$extension.'.png';
				}
				else
				{	
				
					$tipos = array(
									'xls'=>array('xls','xlsx','xlsm','xlsb','xltx','xltm','csv'),
									'ppt'=>array('ppt','pptx','pptm','potx','pot','potm','ppsx','ppsm','pps'),
									'doc'=>array('doc','docx','docm','dotx','dot','dotm','rtf','txt'),
									'image'=>array('jpeg','jpg','gif','tiff','raw','bmp')
								);
								
					foreach($tipos as $icon=>$tipo){
					
						if(in_array($extension,$tipo)){
							return $carpeta.$icon.'.png';
							exit;
						}
					}
					
					return $carpeta.'file.png';
					
				}
				
			}
			
		}
		
		else
		{
			return FALSE;
		}

	}
	
	
/**
 * 
 ************************************************************************************** 
 * 27/08/2011
 * Te devuelve últimos n tweets de un timeline formateado
 * 
 *
 ************************************************************************************** 
 * 
 */
	function twitter_feed($n_tweets=4,$user=false){ 
		
		
		require_once $_SERVER['DOCUMENT_ROOT']."/requires/sources/lib/twitteroauth/tmhOAuth.php";
		$tmhOAuth = new tmhOAuth(array(
			'consumer_key' => 'IggNYICO489Ls2h053Dw',
		 	'consumer_secret' => 'IZZIhXxOmNB0EXtVReuz3TUMc3nv3mzcn0v8Ow9f0c',
			'user_token' => '1630879166-e5MXhdSBjKoNK8bichI1ta5wRC3TsTPykr2Z2Xl',
			'user_secret' => 'ss9GBgE9eKDAXapr5Wpmk2NoNu8Cn6OXVdjoVMScOo',
			'curl_ssl_verifypeer' => false
		));
		
		// Comprobamos que existe un archivo local con el feed (para no pasarnos con las peticiones al API //
		if(@is_file($_SERVER['DOCUMENT_ROOT']."/feeds/@$user.json")){ 
			$lastmod = filemtime($_SERVER['DOCUMENT_ROOT']."/feeds/@$user.json");
			if(time() > ($lastmod + (15*60))){ // Si el fichero lleva sin actualizarse más de 15 minutos, actualizamos
			
				/* Modificacion por cambio API Twitter */
				 
				$code = $tmhOAuth->request('GET',
											$tmhOAuth->url('1.1/statuses/user_timeline'),
											array('screen_name'=>$user, 'exclude_replies' => true));
				 
				$response = $tmhOAuth->response['response'];
				
				if(!preg_match('/errors/',$response)){ // Detectamos si hay error en la respuesta
					$feedFile = fopen($_SERVER['DOCUMENT_ROOT']."/feeds/@$user.json",'w');
					fwrite($feedFile,$response);
					fclose($feedFile);
				}
				
			}
		
		}
		// Si no hay fichero local lo creamos desde la url remota
		else{
	
			/* Modificacion por cambio API Twitter */
			 
			$code = $tmhOAuth->request('GET',
										$tmhOAuth->url('1.1/statuses/user_timeline'),
										array('screen_name'=>$user, 'exclude_replies' => true));
			 
			$response = $tmhOAuth->response['response'];
			
			
			if(!preg_match('/errors/',$response)){ // Detectamos si hay error en la respuesta
				$feedFile = fopen($_SERVER['DOCUMENT_ROOT']."/feeds/@$user.json",'w');
				fwrite($feedFile,$response);
				fclose($feedFile);
			}
			else{
				return FALSE;
			}
		}
		
		// echo $code;
		// volcar_variable($response);
		// die;
		
		if($user){
		
			// Leemos el feed de manera local
			$timeline = file_get_contents($_SERVER['DOCUMENT_ROOT']."/feeds/@$user.json");
				
			
			if($timeline){
				
				$widget = '';
				$entidades = array();
				$tweets = array();
				$indice = 0;
				$tw = json_decode($timeline,TRUE);
				
				/* PROCESAMOS CADA TWEET y SUS ENTIDADES links, mentions, hashtags PARA DARLES ESTILOS POR CSS*/
				foreach($tw as $key=>$status){
					
					if($indice == $n_tweets) // Salimos si no llegamos al limite
						break;
							
					$fecha = $status["created_at"];
					$texto = htmlspecialchars_decode($status["text"],ENT_NOQUOTES);
							
					$patrones = array('/(^|\s)@(\w+)/','/(^|\s)#(\S+)/',"/(^|\s)http:\/\/([^\s]+)(\s|$)/");
					$sustituciones = array('\1<span class="entity mention">@\2</span>','\1<span class="entity hashtag">#\2</span>','\1<a href="http://\2" rel="no-follow" class="entity blank">http://\2</a>\3');
							
					$texto = preg_replace($patrones, $sustituciones, $texto);
							
					// $hace = date('d/m/Y H:i:s',strtotime($fecha));
					$hace = time()-strtotime($fecha);
							
					if($hace < 60){
						 $hace = 'hace menos de 1 minuto';
					}
					elseif($hace >= 60 && $hace < 5*60){
							$hace = 'hace menos de 5 minutos';
						}elseif($hace >= 5*60 && $hace < 10*60){
							$hace = 'hace menos de 10 minutos';
							}elseif($hace >= 10*60 && $hace < 15*60){
								$hace = 'hace menos de 15 minutos';
								}elseif($hace >= 15*60 && $hace < 20*60){
									$hace = 'hace menos de 20 minutos';
									}elseif($hace >= 20*60 && $hace < 25*60){
										$hace = 'hace menos de 25 minutos';
									}elseif($hace >= 25*60 && $hace < 30*60){
											$hace = 'hace menos de 30 minutos';
											}elseif($hace >= 30*60 && $hace < 60*60){
												$hace = 'hace menos de 1 hora';
												}elseif($hace >= 60*60 && $hace < 60*60*2){
													$hace = 'hace menos de 2 horas';
													}elseif(date('d/m/Y',strtotime($fecha)) == date('d/m/Y',time()) ){
														$hace = 'hoy a las '.date('H\hi',strtotime($fecha));
														}elseif(mktime(0,0,0) - strtotime($fecha) < 24*60*60){
															$hace = 'ayer a las '.date('H\hi',strtotime($fecha));
															}else{
																$hace = date('\e\l d/m/Y \a \l\a\s H:i',strtotime($fecha));
																}
							
							
							
						$tweets[] = array('fecha'=>$hace,'tweet'=>$texto);
						$indice++;
					}
						
					
					return $tweets;
				
			}
			else{
				return FALSE;
			}
		}
		else{
			return FALSE;
		}
	}
	
/**
 * 	
 ************************************************************************************** 
 * 05/08/2011
 * Escapa los caracteres especiales de una cadena para su uso con consultas a bbdd.
 * Tiene en cuenta la versión de php instalada en el servidor
 *
 ************************************************************************************** 
 * 
 */
	function my_real_escape_string($string=false){
		
		if(function_exists('mysql_real_escape_string')){
			return mysql_real_escape_string($string);
		}
		else{
			return addslashes($string);
		}
		
	}
	
	
/**
 * 
 ************************************************************************************** 
 * 23/11/2011
 * Te devuelve últimos n post de un wordpress
 * 
 *
 ************************************************************************************** 
 * 
 */
	function wordpress_feed($feed,$n_posts=3,$extra){ 
		
		
		// Comprobamos que existe un archivo local con el feed  //
		if(@is_file($_SERVER['DOCUMENT_ROOT']."/feeds/wp.xml")){ 
			$lastmod = filemtime($_SERVER['DOCUMENT_ROOT']."/feeds/wp.xml");
			if(time() > ($lastmod + (2*60*60))){ // Si el fichero lleva sin actualizarse más de 2 horas, actualizamos
				$ch = curl_init($feed);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Sacamos la salidad directamente como string
				curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // Seguimos la petición por si hay algún redireccionamiento
				curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15); // Tiempo máximo espera
				$xml = curl_exec($ch);
				$xml = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $xml); //Moficamos los nodos con ":" para que se carguen correctamente con simplexml_load_file
				curl_close($ch);
				
				$feedFile = fopen($_SERVER['DOCUMENT_ROOT']."/feeds/wp.xml",'w');
				fwrite($feedFile,$xml);
				fclose($feedFile);
			}
					
		}
		// Si no hay fichero local lo creamos desde la url remota
		else{
			$ch = curl_init($feed);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Sacamos la salidad directamente como string
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // Seguimos la petición por si hay algún redireccionamiento
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15); // Tiempo máximo espera
			$xml = curl_exec($ch);
			$xml = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $xml); //Moficamos los nodos con ":" para que se carguen correctamente con simplexml_load_file
			curl_close($ch);
			
			$feedFile = fopen($_SERVER['DOCUMENT_ROOT']."/feeds/wp.xml",'w');
			fwrite($feedFile,$xml);
			fclose($feedFile);
		}
		
		
		
		if($feed){
			
			$rss = @simplexml_load_file($_SERVER['DOCUMENT_ROOT']."/feeds/wp.xml");
		
			if($rss){
				
				// $widget = '<ol>';
				$posts = array();
				$entidades = array();
				
				$limit = 3;
				if($n_posts && is_numeric($n_posts))
					$limit = $n_posts;
				
				// volcar_variable($rss);
				// die;
				$index = 0;
				/* PROCESAMOS CADA POST PARA DARLES ESTILOS POR CSS*/
				foreach($rss->channel->item as $post){
				
					
					$categorias = array();
					if($index == $limit)
						break;
					
					$texto = htmlspecialchars_decode($post->description,ENT_NOQUOTES);
					
					$patrones = array('/(^|\s)@(\w+)/','/(^|\s)#(\S+)/',"/(^|\s)http:\/\/([^\s]+)(\s|$)/");
					$sustituciones = array('\1<span class="entity mention">@\2</span>','\1<span class="entity hashtag">#\2</span>','\1<a href="http://\2" rel="no-follow" class="entity blank">http://\2</a>\3');
					
					$texto = preg_replace($patrones, $sustituciones, $texto);
					
					
					$widget.=  "<li><a href=\"".$post->link."\" class=\"blank\"><h4>".$post->title."</h4><p>".limit_text($texto,60)." $extra</p></a></li>";
					
					foreach($post->category as $categoria){
						$categorias[] = (string)$categoria;
					}
					
					$posts[] = array('titulo'=>$post->title,'contenido'=>$texto,'link'=>$post->link,'fecha'=>$post->pubDate,'categorias'=>$categorias,'autor'=>$post->dccreator);
					$index ++;
				}
				
				$widget .= "</ol>";
				
				// return $widget;
				return $posts;
				
			}
			else{
				return FALSE;
			}
		}
		else{
			return FALSE;
		}
	}
	
/**
 * 
 ************************************************************************************** 
 * 24/11/2011
 * Enmascarar email
 * 
 *
 ************************************************************************************** 
 * 
 */
 
	function maskEmail($email) {
	  $maskedEmail = '';
	  $longitud = strlen($email);
	  
	  for ($j = 0; $j < $longitud ; $j++) {
		//Enamascaramiento adicional con tags ocultos
		if(substr($email, $j, 1) == '@'){
			$maskedEmail .= '<span style="display:none;">'.substr(md5(uniqid(rand(), true)), 0, 5).'</span>';
		}
		
		$maskedEmail .= '&#' . ord(substr($email, $j, 1)) . ';' ;
		
		if(substr($email, $j, 1) == '@'){
			$maskedEmail .= '<span style="display:none;">'.substr(md5(uniqid(rand(), true)), 0, 5).'</span>';
		}
	  }
		
	  
		$maskedEmail = '<span style="display:none;">'.substr(md5(uniqid(rand(), true)), 0, 5).'</span>'.$maskedEmail;
		$maskedEmail .= '<span style="display:none;">'.substr(md5(uniqid(rand(), true)), 0, 5).'</span>';
	  
	  return $maskedEmail;
	}
	
/**
 * 
 ************************************************************************************** 
 * 27/08/2011
 * Te devuelve el feed de una cuenta en flickr 
 * 
 *
 ************************************************************************************** 
 * 
 */
	function flickr_feed($n_fotos=4,$userID=false){ 
		
		
		
		// Comprobamos que existe un archivo local con el feed (para no pasarnos con las peticiones al API //
		if(@is_file($_SERVER['DOCUMENT_ROOT']."/feeds/$userID.xml")){ 
			$lastmod = filemtime($_SERVER['DOCUMENT_ROOT']."/feeds/$userID.xml");
			if(time() > ($lastmod + (15*60))){ // Si el fichero lleva sin actualizarse más de 15 minutos, actualizamos
			}
			else{
				
			}			
		}
		// Si no hay fichero local lo creamos desde la url remota
		else{
			$restAPIurl = "http://api.flickr.com/services/feeds/photos_public.gne?id=$userID&lang=en-us&format=rss_200";
			$ch = curl_init($restAPIurl);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Sacamos la salidad directamente como string
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15); // Tiempo máximo espera
			$xml = curl_exec($ch);
			curl_close($ch);
			$xml = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $xml);
			
			$feedFile = fopen($_SERVER['DOCUMENT_ROOT']."/feeds/$userID.xml",'w');
			fwrite($feedFile,$xml);
			fclose($feedFile);
		}
		
		
		if($userID){
			
			$feed = simplexml_load_file($_SERVER['DOCUMENT_ROOT']."/feeds/$userID.xml");
			// volcar_variable($feed);
			if($feed){
				
				$widget = '';
				$fotos = array();
				$entidades = array();
				$indice = 1;
				/* PROCESAMOS CADA ENTRADA y SUS ENTIDADES links, mentions, hashtags PARA DARLES ESTILOS POR CSS*/
				foreach($feed->channel->item as $image){
					// volcar_variable($image);
					// die;
					// $widget .= " <a href=\"{$image->link}\" target=\"_blank\"><img src=\"{$image->mediathumbnail->attributes()->url}\" alt=\"{$image->title}\" /></a>";
					$fotos[] = array('link'=>$image->link,'thumbnail'=>$image->mediathumbnail->attributes()->url,'titulo'=>$image->title);
					$indice++;
					
					if($indice > $n_fotos)
						break;	
				}
				
				// return $widget;
				return $fotos;
				
			}
			else{
				return FALSE;
			}
		}
		else{
			return FALSE;
		}
	}
	
	/**
 * 
 ************************************************************************************** 
 * 27/08/2011
 * Te devuelve el feed (búsqueda) de un usuario en youtube 
 * 
 *
 ************************************************************************************** 
 * 
 */
	function youtube_widget($n_videos=1,$user=false){ 
		
		$restAPIurl = "http://gdata.youtube.com/feeds/api/videos?author=$user&max-results=$n_videos&orderby=published";
		
		if($user){
			// $file = file_get_contents($restAPIurl);
			
			$ch = curl_init($restAPIurl);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Sacamos la salidad directamente como string
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15); // Tiempo máximo espera
			$file = curl_exec($ch);
			curl_close($ch);
			
			$file = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $file);
			$feed = simplexml_load_string($file);
			// volcar_variable($feed);
			if($feed){
				
				$widget = '';
				$entidades = array();
				$indice = 1;
				// echo '<pre style="display:none;">';
				// volcar_variable($feed);
				// echo '</pre>';
				// die;
				/* PROCESAMOS CADA ENTRADA VIDEO */
				foreach($feed->entry as $video){
					// volcar_variable($image);
					// die;
					preg_match('/[^\/]+$/',$video->id,$id);
					$widget .= youtube($id[0],220,179);
					
					$indice++;
					
					if($indice > $n_videos)
						break;	
				}
				
				return $widget;
				
			}
			else{
				return FALSE;
			}
		}
		else{
			return FALSE;
		}
	}
	
	
	/**
 * 
 ************************************************************************************** 
 * 25/09/2012
 * Obtiene el html para insertar el logo de interactivaclic
 * 
 *
 ************************************************************************************** 
 * 
 */
	function interactivaclic($mode='black'){ 
		
		
		$url = "http://www.interactivaclic.com/logo/?mode=$mode";
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Sacamos la salidad directamente como string
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15); // Tiempo máximo espera
		echo $xml = curl_exec($ch);
		curl_close($ch);
	
			
		
	}
?>
© 2026 GrazzMean