<?php /*
Plugin Name: User Categories
Plugin URI: http://wordpress.org/extend/plugins/user-categories-2
Description:  Allows users to assign categories to user with a clean and simplified, filterable category meta box and use shortcodes to display category galleries
Version: 1.5
Author: Eddie Moya
Author URL: http://eddiemoya.comcategory

Author URL: http://eddiemoya.com
*/

define('EDIT_USER_CATEGORIES_CAP','edit_posts');

class User_Categories {
    public static $version = 1.5;
    public static $instances;
    public $taxonomy;
    
    /**
     * While normally run statically, this allows 
     * @param type $taxonomy 
     */
    public function __construct($taxonomy) {
        global $wp_version;
        // Store each instance of this class (for use when localizing scripts)
        $this->taxonomy = $taxonomy;
        self::$instances[] = $this;
        
        add_action('init', array(&$this, 'register_user_categories'));
		add_filter('pre_get_posts', array(__CLASS__, 'filtrar_por_concepto'));
	//	add_filter('pre_get_posts', array(__CLASS__, 'bloquear_queries_archive'));	
		//add_filter('posts_where', array(__CLASS__,'filter_where'));
		add_action('admin_menu', array($this, 'add_user_menu_categories'));
        add_action('wp_enqueue_media', array(__CLASS__, 'enqueue_user_categories_scripts'));
               
		add_action('show_user_profile',	array(&$this, 'user_categories_metabox'));
		add_action('edit_user_profile', array(&$this, 'user_categories_metabox'));
		add_action('personal_options_update',	array($this, 'save_profile'));
		add_action('edit_user_profile_update',	array($this, 'save_profile'));
	   
    }
	function filter_where($where = ''){
		global $wpdb;
		//if (  $query->is_main_query() ){
    				
			if(is_search()){
				$fecha_ini=get_query_var('date_ini');
				$fecha_fin=get_query_var('date_end');
				//echo $fecha_ini.'--'.$fecha_fin;
				if ($fecha_ini<>null && $fecha_fin<>null){
					$where .= " AND post_date >= '".$fecha_ini."' AND post_date <= '".$fecha_fin."'";
				}else if($fecha_ini<>null){
					$where .= " AND post_date >= '".$fecha_ini."'";
				}else if($fecha_fin<>null){
					$where .= " AND post_date <= '".$fecha_fin."'";
				}
			}
		//}
		//echo 'WHERE '.$where;
		 
    return $where;
	}
    
    /**
     * Enqueue javascript
     */
    function enqueue_user_categories_scripts() {
        global $wp_version;

        if (is_admin()) {
            
            // Get each instance of this class, and pass each taxonomy in to javascript
            foreach (self::$instances as $instance){
                $tax[] = apply_filters('mc_taxonomy', $instance->taxonomy);
            }
                
            $filename = 'user-categories-script.js';

            wp_register_script('user_categories_metabox_script', plugins_url($filename, __FILE__));
            wp_enqueue_script('user_categories_metabox_script');
            
            wp_localize_script('user_categories_metabox_script', 'taxonomy',  $tax);
        }
    }
    

    function bloquear_queries_archive($query){
    		//echo  '------------';
		 	global $wpdb;
		 	if( !is_admin() ) {
		 	//echo is_archive();
		 		//echo '**********';
		 		//echo is_tax();
		 	if(is_search()){
		 		if ( ! $query->is_main_query() )
    				return $query;
				//echo 'SEARCH';
				$query->set( 'posts_per_page', '1000' );
				/*$query->set('tax_query', array(
						array('taxonomy' => 'producto','field' => 'id','terms' =>get_user_products($user_ID)),
						
				));*/
				 $taxquery = array(
			        array(
			            'taxonomy' => 'producto',
			            'field' => 'id',
			            'terms' => get_user_products($user_ID),
			            'operator'=> 'IN'
			        )
			    );

  				  $query->set( 'tax_query', $taxquery );
				//echo 'aaaaaaa'.$GLOBALS['wp_query']->request.'bbbbb';
				
					return $query;
			}
    		if (  $query->query['post_type'] || !is_archive() && !is_tax() ){
					//echo 'RRRR';
				//echo $query;
				return $query;
			
			}else 
			//checks the context before altering the query
			$query->set( 'post_type', 'ZZZZZZ' );
			//echo 'aaaaaaa'.$GLOBALS['wp_query']->request.'bbbbb';
			return $query;
		
    }
		
    }
    
    function register_user_categories() {
        $tax_name = apply_filters('mc_taxonomy', $this->taxonomy);        
        register_taxonomy_for_object_type($tax_name, 'user');		
    }
	
	function add_user_menu_categories(){
		$tx = get_taxonomy( $this->taxonomy );
		add_users_page(
				$tx->label, 
				$tx->label, 
				'manage_options', 
				"edit-tags.php?taxonomy=".$this->taxonomy
			);	
	}

   
   
    function user_categories_metabox($user) {
                
        $tax = get_taxonomy($this->taxonomy);
        ?>
		<div class="user-category user-category-<?php echo $this->taxonomy; ?>" style="margin:20px">
        
        <div id="taxonomy-<?php echo $this->taxonomy; ?>" class="categorydiv">
		
			<?php if(current_user_can(EDIT_USER_CATEGORIES_CAP)):?>
			<div class="taxonomy-metabox-field-container">
				<label class='category-filter' for="category-filter"><?php echo __('Search').' '.$tax->labels->name; ?>:</label>
				<input id='<?php echo $this->taxonomy?>-search' name="category-filter" type='text' />
			</div>
			<?php else:?>
				 <h4><?php _e("You has been assigned these categories:","ainia")?></h4>
			<?php endif;?>
            
            <div id="<?php echo $this->taxonomy; ?>-all" >
                <?php $name = ( $this->taxonomy == 'category' ) ? 'post_category' : 'tax_input[' . $this->taxonomy . ']'; ?>
                
                <ul id="<?php echo $this->taxonomy; ?>checklist" class="list:<?php echo $this->taxonomy ?> <?php echo $this->taxonomy; ?>checklist form-no-clear">
                    <?php if(current_user_can(EDIT_USER_CATEGORIES_CAP)){
							echo 'user'.$user->ID;
										  						 						
							$selected_cats = ainia_get_user_terms($user->ID, $this->taxonomy, array('fields'=>'ids'));									  						  
							wp_terms_checklist(0, array('taxonomy' => $this->taxonomy, 'selected_cats'=>$selected_cats));
							//ainia_get_user_terms($user_id=0,$taxonomy,$fields)
							
							}
						  else {
							
							$selected_cats = ainia_get_user_terms($user->ID, $this->taxonomy, array('fields'=>'all'));											  						  							
							foreach($selected_cats as $cat)echo "<li>".$cat->name."</li>";														
							}
						
						?>
                </ul>
            </div>
        </div>		
		</div>
            <?php
    }

    
    public function save_profile($user_id) 
	{
		
		if(!current_user_can(EDIT_USER_CATEGORIES_CAP)) return false;								
		$terms = ( $this->taxonomy == 'category' ) ? $_POST['post_category'] : $_POST['tax_input'][$this->taxonomy];								
		for($t=0;$t<count($terms);$t++)$terms[$t]=intval($terms[$t]);							
		ainia_set_user_terms($user_id, $terms);
		
	}
	
    
	function filtrar_por_concepto( $query ) 
	{   		
			//echo '---- filtrar_por_concepto---';
		if( !is_admin() ) 
		{				
			if ( $query->query['post_type']|| !$query->is_home   && !is_archive() && !is_search()) {
				//Solo filtra la home
				//Esta funcion la he desactivado del resto de paginas porque tiene efectos raros cuando no es la home
				//echo 'opcion 1';
				return $query;
			}       			
					
			$user_ID = get_current_user_id();  // get the current user ID
			if ( !is_user_logged_in() || !$user_ID || $user_ID < 1) {
				return $query;
			}   
			
			if (is_search()){
			$query->set('tax_query', array(
				/*TODO: ATENCION: arreglar para food alert
						'relation' => 'OR',
						 array('taxonomy' => 'producto','field' => 'id','terms' =>get_user_products($user_ID)),*/
						array('taxonomy' => 'category','field' => 'id','terms' =>get_user_categories2($user_ID)),
				));
				$query->set( 'post_type', 'post' );
				echo $GLOBALS['wp_query']->request;
				return $query;	
			}
		
			if (is_archive() && is_tax('riesgo')){
				//echo 'opcion 2';
				//echo 'ENTRA';
				$query->set('tax_query', array(
						'relation' => 'AND',
						array('taxonomy' => 'riesgo','field' => 'slug','terms' =>get_query_var('riesgo')),
						array('taxonomy' => 'producto','field' => 'id','terms' =>get_user_products($user_ID)),
						
				));
			//	//echo $GLOBALS['wp_query']->request;
				$query->set( 'post_type', 'alert' );
			
				return $query;
			}
			if (is_archive() && is_tax('pais')){
				//echo 'ENTRA';
				$query->set('tax_query', array(
						'relation' => 'AND',
						array('taxonomy' => 'pais','field' => 'slug','terms' =>get_query_var('pais')),
						array('taxonomy' => 'producto','field' => 'id','terms' =>get_user_products($user_ID)),
			
				));
				//	echo $GLOBALS['wp_query']->request;
				$query->set( 'post_type', 'alert' );
					
				return $query;
			}
			if (is_archive() && is_tax('pais_notificacion')){
				//echo 'ENTRA';
				$query->set('tax_query', array(
						'relation' => 'AND',
						array('taxonomy' => 'pais_notificacion','field' => 'slug','terms' =>get_query_var('pais_notificacion')),
						array('taxonomy' => 'producto','field' => 'id','terms' =>get_user_products($user_ID)),
							
				));
				//	echo $GLOBALS['wp_query']->request;
				$query->set( 'post_type', 'alert' );
					
				return $query;
			}
			if (is_archive() && is_tax('fuente')){
				//echo 'ENTRA-fuente';
				$pagina_anterior=get_query_var('previous_page').'XX';
				//echo $pagina_anterior.'...';
				$pos=strpos($pagina_anterior,'noticias');
				if ($pos!==false){
					
						$query->set('tax_query', array(
						'relation' => 'AND',
						array('taxonomy' => 'fuente','field' => 'slug','terms' =>get_query_var('fuente')),
						array('taxonomy' => 'category','field' => 'id','terms' =>get_user_categories($user_ID)),
							
				));
				
					$query->set( 'post_type', 'post' );
					
				}else{
					
							$query->set('tax_query', array(
							'relation' => 'AND',
							array('taxonomy' => 'fuente','field' => 'slug','terms' =>get_query_var('fuente')),
							array('taxonomy' => 'producto','field' => 'id','terms' =>get_user_products($user_ID)),
								
					));
						//echo $GLOBALS['wp_query']->request;
					$query->set( 'post_type', 'alert' );
				}
		
					//echo $GLOBALS['wp_query']->request;
				return $query;
			}
			if (is_archive() && is_tax('producto')){
				//echo 'ENTRA-fuente';
				$query->set('tax_query', array(
											array('taxonomy' => 'producto','field' => 'id','terms' =>get_user_products($user_ID)),
							
				));
				//	echo $GLOBALS['wp_query']->request;
				$query->set( 'post_type', 'alert' );
					
				return $query;
			}
			//echo 'CAT__'. is_category();
			//echo 'ARCH-----------'.is_archive();
			if (is_archive() && is_category()){
			/*	echo 'ENTRA-category';
				$query->set('tax_query', array(
											array('taxonomy' => 'category','field' => 'id','terms' =>get_query_var('cat')),
							
				));*/
					//echo $GLOBALS['wp_query']->request;
				//$query->set( 'post_type', 'alert' );
					
				return $query;
			}
			else{
			//	echo 'opcion 25';
				$query->set('tax_query', array(
				/*TODO: ATENCION: arreglar para food alert
						'relation' => 'OR',
						 array('taxonomy' => 'producto','field' => 'id','terms' =>get_user_products($user_ID)),*/
						array('taxonomy' => 'category','field' => 'id','terms' =>get_user_categories2($user_ID)),
				));
				$query->set( 'post_type', 'post' );
				echo $GLOBALS['wp_query']->request;
				return $query;
			}
		
		}
	//	echo $GLOBALS['wp_query']->request;
		return $query;
	}
    
}

$mc_category_metabox = new User_Categories('category');
$mc_scope_metabox = new User_Categories('producto');

function get_user_categories($user_id=0){
	if(!$user_id)$user_id = get_current_user_id();	
	if(user_can($user_id,'manage_options')){
		//Administrador, puede ver todo
		$categories = get_categories(); 		
		$conceptos = array();
		foreach ($categories as $category) $conceptos[]=$category->term_id;
		return $conceptos;
	}
	else{
		//Resto usuarios
		$terms = ainia_get_user_terms($user_id, 'category',array(fields=>'all'));
		$conceptos = array();
		foreach($terms as $term)$conceptos[]=$term->term_id;
		return $conceptos;
	}
	
}
function get_user_categories2($user_id=0){
	if(!$user_id)$user_id = get_current_user_id();	

		//Resto usuarios
		
		$terms = ainia_get_user_terms($user_id, 'category','all');
		$conceptos = array();
		foreach($terms as $term)$conceptos[]=$term->term_id;
		return $conceptos;
	
}

function get_user_products($user_id=0){
	//echo 'user-products';
	if(!$user_id)$user_id = get_current_user_id();

	$terms = ainia_get_user_terms($user_id, 'producto','all');	
	$conceptos = array();
	foreach($terms as $term)$conceptos[]=$term->term_id;
	//echo implode("",$conceptos);
	return $conceptos;
}
function get_user_conceptos_seguimiento($user_id=0){
	//echo 'user-products';
	if(!$user_id)$user_id = get_current_user_id();
	
	$terms = ainia_get_user_terms($user_id, 'concepto_seguimiento','all');
	
	global $wpdb;
	//echo  'SEGUMIMIENTO.....'.$wpdb->last_query;
	$conceptos = array();
	foreach($terms as $term)$conceptos[]=$term->term_id;
	//echo "--".implode(",",$conceptos);
	return $conceptos;
}

/* TODO: modificar query para Foodalert con nueva tabla user_terms.*/
function get_user_risks($user_id=0){
	global $wpdb;
	if(!$user_id)$user_id = get_current_user_id();
	$user_categories=  get_user_products($user_id);
	$date=date('Y-m-d', strtotime('-90 days'));
	$query='SELECT distinct risk_term.term_id
FROM
(SELECT
		*
		FROM
		wp_posts
		WHERE
		post_date > %s) AS posts
		STRAIGHT_JOIN
		wp_term_relationships AS rel_prod ON posts.ID = rel_prod.object_id
		STRAIGHT_JOIN
		wp_term_taxonomy AS prod_tax ON rel_prod.term_taxonomy_id = prod_tax.term_taxonomy_id
		AND prod_tax.term_id in ('. implode(",",$user_categories).')
		AND prod_tax.taxonomy = \'producto\'
				STRAIGHT_JOIN
				wp_terms AS prod_term ON prod_term.term_id = prod_tax.term_id
				STRAIGHT_JOIN
				wp_term_relationships AS rel_riesgo ON rel_riesgo.object_id = posts.ID
				STRAIGHT_JOIN
				wp_term_taxonomy AS risk_tax ON risk_tax.term_taxonomy_id = rel_riesgo.term_taxonomy_id
				AND risk_tax.taxonomy = \'riesgo\'
						STRAIGHT_JOIN
						wp_terms AS risk_term ON risk_term.term_id = risk_tax.term_id
						GROUP BY prod_term.name , risk_term.name;';
	
	$results=$wpdb->get_results( $wpdb->prepare( $query ,$date,$producto->term_id));
	$conceptos = array();
	echo 'RIESGOS:'.$wpdb->last_query.'----';
	foreach($results as $term){
		$conceptos[]=$term->term_id;
		//echo '*'.$term->term_id.'*';
	}
	return $conceptos;

}

function get_all_user_risks($user_id=0){
	global $wpdb;
	if(!$user_id)$user_id = get_current_user_id();
	$user_categories=  get_user_products($user_id);
	$date=date('Y-m-d', strtotime('-90 days'));
	$query='select * from wp_terms t straight_join wp_term_taxonomy tt on t.term_id=tt.term_id and taxonomy=\'riesgo\'';
	
	
	$results=$wpdb->get_results( $wpdb->prepare( $query ,$date,$producto->term_id));
	$conceptos = array();
	//echo 'RIESGOS:'.$wpdb->last_query.'----';
	foreach($results as $term){
		$conceptos[]=$term->term_id;
		//echo '*'.$term->term_id.'*';
	}
	return $conceptos;

}



function is_post_in_user_categories($post_id,$user_id=0)
{
	if(user_can($user_id,'manage_options'))return true;
	if(get_post_type($post_id)=="project")return true;

  //Comprobar categorias
	$post_cats = wp_get_post_categories( $post_id );
	$user_cats = get_user_categories($user_id);
	foreach($post_cats as $cat)
	 if(in_array($cat,$user_cats))
	  return true;

  //Comprobar �mbitos	  
	$post_products = wp_get_post_terms($post_id, 'producto', array("fields" => "ids"));  
	$user_products = get_user_products($user_id);
	foreach($post_products as $product)
	 if(in_array($product,$user_products))
	  return true;
	  
  //No permitir	  
	return false;
}
/**
 * 	Recupera los términos de la nueva tabla user_terms.
	ainia_get_user_terms, user_id obligatorio, $taxonomy puede ser '', fields: 'all','ids','names','slugs'.
	@param $user_id user_id
	@param $taxonomy taxonomy
	@param $fields fields

 */
function ainia_get_user_terms($user_id,$taxonomy,$fields){
	global $wpdb;
	
	//echo 'My_func'.$user_id;
	if(''!=$taxonomy){
		$query='select t.* from wp_user_terms ut straight_join wp_term_taxonomy tt on ut.term_id=tt.term_id and tt.taxonomy=%s and ut.user_id=%d straight_join wp_terms t on t.term_id=tt.term_id;';		
		$results=$wpdb->get_results( $wpdb->prepare( $query ,$taxonomy,$user_id));
	}else{
		$query='select t.* from {$wpdb->prefix}user_terms ut straight_join {$wpdb->prefix}term_taxonomy tt on ut.term_id=tt.term_id and ut.user_id=%d straight_join {$wpdb->prefix}terms t on t.term_id=tt.term_id;';	
		$results=$wpdb->get_results( $wpdb->prepare( $query ,$user_id));
	}
		if(strcmp($fields,'ids')== 0){
			$results=getIds($results);
		}else{
		if (strcmp($fields,'slug')==0){
			$results=getSlugs($results);
		}
		} 
		
		return $results;
}
function getIds($result){
	$conceptos = array();
		foreach ($result as $category) $conceptos[]=$category->term_id;
		return $conceptos;
	
}
function getSlugs($result){
	$conceptos = array();
		foreach ($result as $category) $conceptos[]=$category->slug;
		return $conceptos;
}

function ainia_set_user_terms($user_id=0,$term_ids){
	global $wpdb;
	
		//	$result2 = $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->prefix}user_terms WHERE user_id = %d", $user_id ) );
		
			$query_string="INSERT into {$wpdb->prefix}user_terms (user_id,term_id) values(%d, %d)";
			
			foreach ($term_ids as $term_id){
					$wpdb->query( $wpdb->prepare($query_string,$user_id,$term_id ) );
			}
	
}


