<?php
function ainia_update_conceptos_personalizados (){
	$date = date('m/d/Y h:i:s a', time());
	error_log(print_r($date.' ********************* INICIO ACTUALIZACIÓN CONCEPTOS PERSONALIZADOS ****************************
					', TRUE),3,"C:\\log\\cron_log.log");
	$conceptos_personalizados= get_terms( 'concepto_personalizado', array(
								'orderby'    => 'count',
								'hide_empty' => 0
							) );
	
	foreach( $conceptos_personalizados as $concepto ) {
		
		error_log(print_r('--------------------------------------'.$concepto->name.'-
			', TRUE),3,"C:\\log\\cron_log.log");
		ainia_update_conceptos_personalizados_por_post($concepto);
	
	///	ainia_update_conceptos_personalizados_por_categoria ($categoria);
	}
	
	$date2 = date('m/d/Y h:i:s a', time());
	error_log(print_r($date2.'********************* FIN ACTUALIZACIÓN CONCEPTOS PERSONALIZADOS ****************************
					', TRUE),3,"C:\\log\\cron_log.log");
}

/*function ainia_update_conceptos_personalizados_por_categoria ($categoria){
	$conceptos_seguimiento= ainia_get_conceptos_personalizados($categoria->term_id);
	

	foreach( $conceptos_seguimiento as $concepto ) {
		//echo '---categoría---'.$categoria->name;
		error_log("---categoría---".$concepto->name,3,"C:\\log\\cron_log.log");
		ainia_update_conceptos_personalizados_por_post ($concepto,$categoria->term_id);
	
	}

}

function ainia_get_conceptos_personalizados_por_categoria($categoria_ID){
	error_log(print_r('-- Recuperando los conceptos personalizados para la categoria con ID '.$categoria_ID.'--
			', TRUE),3,"C:\\log\\cron_log.log");
	global $wpdb;
	$conceptos=null;
	
	$query_str='select conc_seg.*, ttax_cseg.term_taxonomy_id,op.option_value from wp_term_relationships cat_conc_seg inner join wp_terms conc_seg on cat_conc_seg.object_id= conc_seg.term_id inner join 
  wp_term_taxonomy ttax_cseg on ttax_cseg.term_id=conc_seg.term_id and taxonomy=\'concepto_personalizado\' inner join wp_options op on 
  op.option_name= concat(\'concepto_personalizado_eng_\',conc_seg.term_id) inner join wp_term_taxonomy ttax_prod on ttax_prod.term_taxonomy_id=cat_conc_seg.term_taxonomy_id
where  ttax_prod.term_id=%d';

	error_log(print_r('-------ID CATEGORIA ---'.$categoria_ID.'--------------
	', TRUE),3,"C:\\log\\cron_log.log");

	try {
		//error_log(print_r('-------------TRY------------------<br>', TRUE),3,"C:\\log\\cron_log.log");
		$conceptos = $wpdb->get_results($wpdb->prepare( $query_str,$categoria_ID));
		//error_log(print_r('-------------TRY 22------------------', TRUE),3,"C:\\log\\cron_log.log");
		//error_log(print_r($wpdb->last_query, TRUE),3,"C:\\log\\cron_log.log");
	} catch (Exception $e) {
		error_log(print_r('------------------------------CATCH-------------------------------
				', TRUE),3,"C:\\log\\cron_log.log");
		error_log(print_r($e, TRUE),3,"C:\\log\\cron_log.log");
		error_log(print_r('
			', TRUE),3,"C:\\log\\cron_log.log");
	}
			error_log(print_r('
			', TRUE),3,"C:\\log\\cron_log.log");

	if($wpdb->num_rows>0){
			error_log(print_r(' El producto '.$categoria_ID.' tiene '.sizeof($conceptos).' conceptos de seguimiento 
			', TRUE),3,"C:\\log\\cron_log.log");	
	}else{
				error_log(print_r('
			!!!!!!!!!!!!!!!!!!!!!!!! 00 !!!!!!!!!!!', TRUE),3,"C:\\log\\cron_log.log");
		
	}

	
	return $conceptos;

}*/
	
	/*$query_str='insert into wp_term_relationships (select posts.ID,301,0 from wp_posts posts inner join wp_term_relationships rel_cat on rel_cat.object_id=posts.ID inner join wp_term_taxonomy ttax_cat
			on rel_cat.term_taxonomy_id=ttax_cat.term_taxonomy_id inner join wp_terms term_cat on term_cat.term_id=ttax_cat.term_id
			where posts.post_type=\'post\' and ttax_cat.taxonomy=\'category\' and term_cat.term_id=241 and posts.ID  not in (select object_id from wp_term_relationships where
					term_taxonomy_id=301) and (lower(post_content) like lower('%Acuicultura%') or lower (post_title) like lower('%Acuicultura%') or lower(post_content)
							like lower('%aquaculture%') or lower(post_title) like lower ('%Aquaculture%')) )'*/
function ainia_update_conceptos_personalizados_por_post ($concepto){
	error_log("---CONCEPTO - ainia update ---",3,"C:\\log\\cron_log.log");
	global $wpdb;
	//$conceptos=0;
	
		//error_log("---CONCEPTO - ainia update 2---",3,"C:\\log\\cron_log.log");
		//error_log("---CONCEPTO - ainia update +---".$concepto->name,3,"C:\\log\\cron_log.log");
	$pos=strpos($concepto->name,'+');
	//error_log("---CONCEPTO - ainia update 3---",3,"C:\\log\\cron_log.log");
	
		error_log("---POS - ainia update +---".$pos,3,"C:\\log\\cron_log.log");
	if ($pos===false){
		$query_str='insert into wp_term_relationships (select DISTINCT  posts.ID,'.$concepto->term_taxonomy_id.',1 from wp_posts posts inner join wp_term_relationships rel_cat on rel_cat.object_id=posts.ID inner join wp_term_taxonomy ttax_cat
			on rel_cat.term_taxonomy_id=ttax_cat.term_taxonomy_id inner join wp_terms term_cat on term_cat.term_id=ttax_cat.term_id
			where posts.post_type=\'post\'  and posts.ID  not in (select object_id from wp_term_relationships where
					term_taxonomy_id=%d) and (lower(post_content) like lower(%s) or lower (post_title) like lower(%s) ';
		if (''!=$concepto->option_value)	{	
		$query_str=$query_str.'	or lower(post_content)
								like lower(%s) or lower(post_title) like lower (%s)';
		}						
		$query_str=$query_str.'	) )';									
		/*Acuicultura*/
		if (''!=$concepto->option_value)	{
			$conceptos = $wpdb->query($wpdb->prepare( $query_str,$concepto->term_taxonomy_id,'%'.$concepto->name.'%','%'.$concepto->name.'%','%'.$concepto->option_value.'%','%'.$concepto->option_value.'%'));
		} else{
			$conceptos = $wpdb->query($wpdb->prepare( $query_str,$concepto->term_taxonomy_id,'%'.$concepto->name.'%','%'.$concepto->name.'%'));
		}
	}else{
		$query_str='insert into wp_term_relationships (select DISTINCT  posts.ID,'.$concepto->term_taxonomy_id.',1 from wp_posts posts inner join wp_term_relationships rel_cat on rel_cat.object_id=posts.ID inner join wp_term_taxonomy ttax_cat
			on rel_cat.term_taxonomy_id=ttax_cat.term_taxonomy_id inner join wp_terms term_cat on term_cat.term_id=ttax_cat.term_id
			where posts.post_type=\'post\'  and posts.ID  not in (select object_id from wp_term_relationships where
					term_taxonomy_id=%d) and ';
		
		//error_log("---QUERY +---".$concepto,3,"C:\\log\\cron_log.log");
		
		$palabras= explode('+',$concepto->name);
		$i=0;
		
		$parametros[]=	$concepto->term_taxonomy_id;
		foreach ($palabras as $palabra){
			$palabra_limpia=trim($palabra,' ');		
		
		error_log(print_r('
			---PALABRA LIMPIA +---'.$palabra_limpia.'------------', TRUE),3,"C:\\log\\cron_log.log");
		
			if($i>0){
				$query_str=$query_str.' and ';
			}
			$query_str=$query_str.'(lower(post_content) like lower(%s) or lower (post_title) like lower(%s)) ';
								
				$parametros[]='%'.$palabra_limpia.'%';	
				$parametros[]='%'.$palabra_limpia.'%';
				/* No es un error que haya dos lineas iguales, hay que incluir dos veces cada concepto*/
				$i++;
			
		}
		$query_str=$query_str.'	 )';		
		/*error_log(print_r('
			---QUERY str +---'.$query_str .'------------', TRUE),3,"C:\\log\\cron_log.log");*/
		
		$conceptos = $wpdb->query($wpdb->prepare( $query_str,$parametros));

			error_log(print_r('
			---QUERY +---'.$wpdb->last_query .'------------
			', TRUE),3,"C:\\log\\cron_log.log");
		
	}

	

	error_log(print_r('-$categoria_id-'.$categoria_id.'
			-$concepto->object_id-'.$concepto->object_id.'
			-$concepto->name-'.$concepto->name.'
			-$concepto->option_value-'.$concepto->option_value.'
			', TRUE),3,"C:\\log\\cron_log.log");
	
	error_log(print_r('***************************************************************************
						'. $wpdb->last_query.'
			***************************************************************************
			', TRUE),3,"C:\\log\\cron_log.log");
	
	error_log(print_r('--------------------   POSTS ACTUALIZADOS:'.$conceptos .'------------
			', TRUE),3,"C:\\log\\cron_log.log");

		update_option( 'etiquetado_'.$concepto->term_id, 'Actualizado' );
}

//--------------------------------------- NEWSLETTER ----------------------------------//
function ainia_send_newsletter_conc_personalizados()
{
	$date2 = date('m/d/Y h:i:s a', time());
	error_log(print_r($date2.'--------------------  ainia_send_newsletter------------
			', TRUE),3,"C:\\log\\cron_log.log");
	$cuantos_mails = 0;
	$users = ainia_get_users_with_terms('concepto_personalizado');
	$usuarios_enviados = "";
	foreach($users as $user)
	{		
		error_log(print_r('
		***********************************  user: '.$user->user_email.'*******'.$user->ID.'****************************
			', TRUE),3,"C:\\log\\cron_log.log");
		$cuantos = 0;
		$sent_posts = array();
		$enviar=false;
		
		$period_days = intval(get_the_author_meta( 'newsletter', $user->ID ));
		$last_newsletter_date  = get_last_date_of_user_relation(  $user->ID, 'newsletter' );
				error_log(print_r('---- '.$user->user_email.' ultimo envio del boletin: '.$last_newsletter_date.'------------
			', TRUE),3,"C:\\log\\cron_log.log");
				error_log(print_r('---- '.$user->user_email.' frecuencia de envio: '.$period_days.'------------
			', TRUE),3,"C:\\log\\cron_log.log");
		$date= date('Y-m-d', strtotime('-30 days'));
		if($last_newsletter_date != null){		
					$now = new DateTime("now +1 hours");				
					$objTimeZone = new DateTimeZone("Europe/Madrid");		
					$now->setTimezone($objTimeZone);
					$last = new DateTime($last_newsletter_date);			
					$dif = $last->diff($now);	
					$date=	$last_newsletter_date;				
					$enviar = $dif->days >= $period_days && $period_days > 0 ? true : false;
					if(!$last_newsletter_date && $period_days)$enviar = true;
		}	else if ($period_days > 0){
				error_log(print_r('---- '.$user->user_email.' TIENE CONFIGURADO BOLETIN, PERO ESTE ES EL PRIMER ENVÍO------------
			', TRUE),3,"C:\\log\\cron_log.log");
			$date= date('Y-m-d', strtotime('-'.$period_days.' days'));
			$enviar = true;
		}	else{
			error_log(print_r('---- '.$user->user_email.' NO TIENE CONFIGURADO BOLETIN------------
			', TRUE),3,"C:\\xampp\\htdocs\\iWatch4.0\\iWatch4.0\\iWatch4.0\\log\\php_error.log");
		}				
		error_log(print_r('--------------------  ENVIAR: '.$enviar.'------------
			', TRUE),3,"C:\\log\\cron_log.log");
			error_log(print_r('----##########  $date ########## ----------'.$date.'
			', TRUE),3,"C:\\log\\cron_log.log");
		
		if($enviar)
		{
			//Calcular el mensaje a enviar
			/*$max_days = intval(get_option('ainia_max_days'));
			$max_posts = intval(get_option('ainia_max_posts'));*/
		
			global $wpdb;
			global $post;
error_log(print_r('--------------------  ENVIAR: A------------
			', TRUE),3,"C:\\log\\cron_log.log");
			
			$user_id = $user->ID;
			$user_categories = ainia_get_user_terms($user_id, 'category',array(fields=>'ids'));
	
			//$user_categories = get_user_products($user_id);
			$user_conceptos_seguimiento=get_user_conceptos_personalizado2($user_id);
			error_log(print_r('--------------------  ENVIAR: B------------
			', TRUE),3,"C:\\log\\cron_log.log");
			$str_categorias =implode(",",$user_categories);
			$filtered_post_ids=get_post_by_user_conceptos_personalizado($user_id);
	error_log(print_r('--------------------  ENVIAR: C------------
			', TRUE),3,"C:\\log\\cron_log.log");
			$filtros_adicionales='posts.ID in ('.implode(",",$filtered_post_ids).')';
			$id_ultimo_newsletter=get_last_id_of_user_relation( $user->ID,'newsletter');
	
			if($id_ultimo_newsletter){
				$posts_enviados=get_user_relation_meta($id_ultimo_newsletter,'posts',true);
				error_log(print_r('- Posts enviados previamente: '.$posts_enviados.'------------
				', TRUE),3,"C:\\log\\cron_log.log");
				if($posts_enviados){
					 $filtros_adicionales=$filtros_adicionales.'and posts.ID not in ('.$posts_enviados.')';
				}
			}
				
			//echo implode(",",$filtered_post_ids);
			//$cuerpo_correo = $cuerpo_correo . implode(",",$user_categories);
			/*error_log(print_r('--------- $filtered_post_ids: '.implode(",",$filtered_post_ids).'------------
			', TRUE),3,"C:\\log\\cron_log.log");
				error_log(print_r('--------- $user_categories: '.implode(",",$user_categories).'------------
			', TRUE),3,"C:\\log\\cron_log.log");*/
			$query_str=get_query_noticias_boletin_Ecoembes();
						/*error_log(print_r('--------------------  ENVIAR: D ------------
			', TRUE),3,"C:\\log\\cron_log.log");*/
			$query_str= str_replace  ('#LIMIT# #OFFSET#','',$query_str);
			$query_str= str_replace  ('#categorias_usuario#',$str_categorias,$query_str);
			$query_str= str_replace  ('#condiciones_adicionales#',$filtros_adicionales,$query_str);
				
				
			ob_start();	
			$cuerpo_correo='';
			$cuerpo_correo = $cuerpo_correo . open_header();
			$cuerpo_correo = $cuerpo_correo . get_style();  
			$cuerpo_correo = $cuerpo_correo . close_header();
			$cuerpo_correo = $cuerpo_correo . open_body(); 
			$cuerpo_correo = $cuerpo_correo . get_logo_table();
			$cuerpo_correo = $cuerpo_correo . get_after_logo_table();
			$cuerpo_correo = $cuerpo_correo . get_header_picture_table();
			$cuerpo_correo = $cuerpo_correo . get_after_header_picture_table($user->display_name);
			$cuerpo_correo = $cuerpo_correo . inicio_categorias_suscritas('<u>Conceptos personalizados</u>:');
					foreach($user_conceptos_seguimiento as $conc_seg):
						$texto= $conc_seg->name;
						//.' - '.get_concepto_personalizado_eng($conc_seg->term_id);
						$cuerpo_correo = $cuerpo_correo .  elem_cat_suscritas($texto);
					endforeach;
			$now = new DateTime('NOW');								

			if (sizeof($user_conceptos_seguimiento)>0){
				 if (sizeof($user_categories)>0){
						$pageposts = $wpdb->get_results($wpdb->prepare( $query_str,$date,$user_id,$user_id));
					/*error_log(print_r('---- LA QUERY---------------
					-------------------------------', TRUE),3,"C:\\log\\cron_log.log");*/
						error_log(print_r('---- LA QUERY------------'.$wpdb->last_query.'
					-------------------------------', TRUE),3,"C:\\log\\cron_log.log");
				 }
				else{
				 		error_log(print_r('---- '.$user->user_email.' NO TIENE CONCEPTOS DE BUSQUEDA------------
					', TRUE),3,"C:\\log\\cron_log.log");
				 	echo 'No tiene familias de producto configuradas, contacte con su administraddor tic@ainia.es';
				 }
			}else{
				error_log(print_r('---- '.$user->user_email.' NO TIENE CONCEPTOS DE SEGUIMIENTO------------
			', TRUE),3,"C:\\log\\cron_log.log");
				echo 'No dispone de conceptos personalizados, entre en <a href=""> Administración de conceptos</a> y cree sus conceptos';
				$enviar=false;
			}
			
				if ($pageposts){		
					//global $post; 
						error_log(print_r('---- if ($pageposts)------------
					-------------------------------', TRUE),3,"C:\\log\\cron_log.log");
						 foreach ($pageposts as $post): 				
									$cuerpo_correo = $cuerpo_correo . get_divider_table();
								
									$url=home_url($post->post_name);
									//$contenido_limpio=strip_tags ($post->post_content);
									//$contenido_limpio = $post->post_content;
									$post_content_highlight=marcar_conceptos($post,$user_conceptos_seguimiento);
									$post_title_highlight=marcar_conceptos_titulo($post,$user_conceptos_seguimiento);
									if ($cuantos%2==0){
										$cuerpo_correo = $cuerpo_correo . get_alerta_right($url,$post_title_highlight,$post_content_highlight);
											
									}else{
										$cuerpo_correo = $cuerpo_correo . get_alerta_left($url,$post_title_highlight,$post_content_highlight);
									}	
									$sent_posts[]=$post->ID;				
									$cuantos+=1;
						 endforeach;		
					/*$cuerpo_correo = $cuerpo_correo . inicio_categorias_suscritas('Categorías suscritas:');
					foreach ($user_categories as $category):
						$concepto=get_term($category);
						$cuerpo_correo = $cuerpo_correo .  elem_cat_suscritas($concepto->name);
					
					endforeach;*/
					
		
				}else{
							$enviar=false;
							$date= date('d/m/Y', strtotime($last_newsletter_date));
							$cuerpo_correo = $cuerpo_correo .'<br><br><span style="color: #333333;"><strong>'.'Desde el '.$date.' No hay nuevas alertas que coincidan con sus preferencias.'.'</strong></span>';
							error_log(print_r('
							- '.$user->user_email.' NO HAY NUEVAS Entradas------------
			', TRUE),3,"C:\\log\\cron_log.log");
				}
					$cuerpo_correo = $cuerpo_correo . get_end();
					wp_reset_postdata();	
					$buffer = ob_get_contents();
	
					ob_end_clean();	
		}
		if($enviar){
			//ENVIAR EL MAIL			
			//$headers = 'From: AINIA iWatch <'.strip_tags(get_option('ainia_newsletter_email')).'>' . "\r\n";
			$headers = 'From: Observatorio del envase <observatoriodelenvase@ecoembes.com>' . "\r\n";
			$headers .= 'Bcc: ralmarcha@ainia.es' . "\r\n";
			$headers .= "MIME-Version: 1.0\r\n";
			$headers .= "Content-Type: text/html; charset=utf-8\r\n";			
			//if(wp_mail($user->user_email, __('Foodalert Boletín Personalizado','ainia'), $buffer, $headers))
			//error_log(print_r('.................................. Cuerpo correo............................
			//'.$cuerpo_correo, TRUE),3,"C:\\log\\cron_log.log");
			//			error_log(print_r('
			//			..............................................................
			//', TRUE),3,"C:\\log\\cron_log.log");
			
						/*FIXME:falla envio en servidor - $user->user_email */
						try {
							if(wp_mail($user->user_email, __('Nuevas noticias para '.$user->display_name.': '.$cuantos.' nuevas coincidencias','ainia'), $cuerpo_correo, $headers))
							//if(wp_mail('ralmarcha@ainia', __('Nuevas noticias para '.$user->display_name.': '.$cuantos.' nuevas coincidencias','ainia'), $cuerpo_correo, $headers))
							
							{
									error_log(print_r('- '.sizeof($sent_posts).' (sizeof($sent_posts)------------
			', TRUE),3,"C:\\log\\cron_log.log");
				
								if (!(sizeof($sent_posts)>0)){
									$sent_posts=explode(',',$posts_enviados);
								}
											error_log(print_r('- '.sizeof($sent_posts).' (sizeof($sent_posts)------------
			', TRUE),3,"C:\\log\\cron_log.log");
							  add_extended_user_newsletter_sent($user->ID,$sent_posts);
							  $cuantos_mails+=1;
							}else{
								error_log(print_r('
										......................ELSE.......................................
							', TRUE),3,"C:\\log\\cron_log.log");
							}
							
						} catch (Exception $e) {
								error_log(print_r('
						..............................................................
			', TRUE),3,"C:\\log\\cron_log.log");
									error_log(print_r('
						.......................'.$e.'.......................................
			', TRUE),3,"C:\\log\\cron_log.log");
								
									error_log(print_r('
						..............................................................
			', TRUE),3,"C:\\log\\cron_log.log");
							
						}
		
			$usuarios_enviados .= $user->user_login.",";
		}
		
	}
	
	$admins = get_users( array( 'role' => 'administrator'));
	$admin_user_id = $admins[0]->ID;	
	if(!$usuarios_enviados)$usuarios_enviados="nadie";
	add_extended_user_note($admin_user_id,"El newsletter ha sido enviado a:".$usuarios_enviados);
	
    return $cuantos_mails;
}

function marcar_conceptos($post,$user_conceptos_seguimiento){
	
	$post_content=$post->post_content;
	$resultado =strip_tags($post_content);
	$resultado= wp_trim_words($resultado,$num_words =180, $more = '' );
		error_log(print_r('---- marcar_conceptos------------
					-------------------------------', TRUE),3,"C:\\log\\cron_log.log");
	//$resultado=$post_content;
	foreach ($user_conceptos_seguimiento as $concepto ):
		//$conc_eng = get_concepto_personalizado_eng($concepto->term_id);
				error_log(print_r('---- marcar_conceptos------CONCEPTO------'.$concepto->name.'--------post--'.$post->ID.'-----------------------', TRUE),3,"C:\\log\\cron_log.log");
				if(post_has_concepto_personalizado($post->ID,$concepto->term_id)){
					$pos=strpos($concepto->name,'+');
						if ($pos===false){
									/*error_log(print_r('---- marcar_conceptos A------------
										-------------------------------', TRUE),3,"C:\\log\\cron_log.log");*/
							$resultado=highlightStr($resultado,$concepto->name,'yellow');
						}else{	
									/*error_log(print_r('---- marcar_conceptos B------------
										-------------------------------', TRUE),3,"C:\\log\\cron_log.log");*/
							$palabras= explode('+',$concepto->name);
							$i=0;
							$palabras= explode('+',$concepto->name);
							
							foreach ($palabras as $palabra){
								$palabra_limpia=trim($palabra,' ');	
								$resultado=highlightStr($resultado,$palabra_limpia,'yellow');
								
							}
							
						}
				}else{
						error_log(print_r('---- NO MARCAR------------------------------------------', TRUE),3,"C:\\log\\cron_log.log");
				}	
					/*$resultado2 =str_ireplace($conc_eng, '<mark>'.$conc_eng.'</mark>', $resultado);
		$resultado = $resultado2;*/
		//$resultado =str_replace(strtolower ($conc_eng), '<mark>'.$conc_eng.'</mark>', $resultado);
	endforeach;
	//echo '/-- RESULTADO '.$resultado.'--/';
			//error_log(print_r('---- marcar_conceptos FIN-------------------------------------------', TRUE),3,"C:\\log\\cron_log.log");
	return $resultado;
}
function marcar_conceptos_titulo($post,$user_conceptos_seguimiento){
	
	$post_content=$post->post_title;
	$resultado =strip_tags($post_content);
	$resultado= wp_trim_words($resultado,$num_words =180, $more = '' );
		error_log(print_r('---- marcar_conceptos TITULO------------
					-------------------------------', TRUE),3,"C:\\log\\cron_log.log");
	//$resultado=$post_content;
	foreach ($user_conceptos_seguimiento as $concepto ):
		//$conc_eng = get_concepto_personalizado_eng($concepto->term_id);
				error_log(print_r('# marcar_conceptos------CONCEPTO------'.$concepto->name.'--------post--'.$post->ID.'-----------------------', TRUE),3,"C:\\log\\cron_log.log");
				if(post_has_concepto_personalizado($post->ID,$concepto->term_id)){
					$pos=strpos($concepto->name,'+');
						if ($pos===false){
									/*error_log(print_r('---- marcar_conceptos A------------
										-------------------------------', TRUE),3,"C:\\log\\cron_log.log");*/
							$resultado=highlightStr($resultado,$concepto->name,'yellow');
						}else{	
									/*error_log(print_r('---- marcar_conceptos B------------
										-------------------------------', TRUE),3,"C:\\log\\cron_log.log");*/
							$palabras= explode('+',$concepto->name);
							$i=0;
							$palabras= explode('+',$concepto->name);
							
							foreach ($palabras as $palabra){
								$palabra_limpia=trim($palabra,' ');	
								$resultado=highlightStr($resultado,$palabra_limpia,'yellow');
								
							}
							
						}
				}else{
						error_log(print_r('---- NO MARCAR------------------------------------------', TRUE),3,"C:\\log\\cron_log.log");
				}	
					/*$resultado2 =str_ireplace($conc_eng, '<mark>'.$conc_eng.'</mark>', $resultado);
		$resultado = $resultado2;*/
		//$resultado =str_replace(strtolower ($conc_eng), '<mark>'.$conc_eng.'</mark>', $resultado);
	endforeach;
	//echo '/-- RESULTADO '.$resultado.'--/';
			/*error_log(print_r('---- marcar_conceptos FIN------------
					-------------------------------', TRUE),3,"C:\\log\\cron_log.log");*/
	return $resultado;
}
function highlightStr($haystack, $needle, $highlightColorValue) {
     // return $haystack if there is no highlight color or strings given, nothing to do.
    if (strlen($highlightColorValue) < 1 || strlen($haystack) < 1 || strlen($needle) < 1) {
        return $haystack;
    }
    preg_match_all("/$needle+/i", $haystack, $matches);
    if (is_array($matches[0]) && count($matches[0]) >= 1) {
        foreach ($matches[0] as $match) {
            $haystack = str_replace($match, '<span style="background-color:'.$highlightColorValue.';">'.$match.'</span>', $haystack);
        }
    }
    return $haystack;
}

function update_terms(){
	
	$query_str='SELECT count(object_id) as cantidad,term_taxonomy_id as id FROM wp_term_relationships group by term_taxonomy_id';
		error_log(print_r('update_terms				
			'.$query_str, TRUE),3,"C:\\log\\cron_log.log");
		
	$conceptos = $wpdb->query($wpdb->prepare( $query_str,$query_str));
	error_log(print_r('***************************************************************************
						'. $wpdb->last_query.'
			***************************************************************************
			', TRUE),3,"C:\\log\\cron_log.log");
	
	foreach ($conceptos as $term){
		$query='update wp_term_taxonomy set count='.$term->cantidad.'where term_taxonomy_id='.$term->id;
			error_log(print_r('
			'.$query, TRUE),3,"C:\\log\\cron_log.log");

			
		$wpdb->query($wpdb->prepare( $query),$terms);
	}
}	
	
function ainia_get_users_with_terms($taxonomy){
	global $wpdb;
	
	//echo 'My_func'.$user_id;
	if(''!=$taxonomy){
		$query='select distinct u.* from wp_user_terms ut straight_join wp_users u on ut.user_id=u.ID straight_join wp_term_taxonomy tt on ut.term_id=tt.term_id and tt.taxonomy=%s straight_join wp_terms t on t.term_id=tt.term_id;';		
		$results=$wpdb->get_results( $wpdb->prepare( $query ,$taxonomy,$user_id));
	}else{
		return '';
	}
	
		
		return $results;
}
