<?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_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'));
	   
    }

    /**
     * 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 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)){
							$selected_cats = wp_get_object_terms($user->ID, $this->taxonomy, array('fields'=>'ids'));											  						  
							wp_terms_checklist(0, array('taxonomy' => $this->taxonomy, 'selected_cats'=>$selected_cats));
							}
						  else {
							$selected_cats = wp_get_object_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]);						
		wp_set_object_terms($user_id, $terms, $this->taxonomy, false);
		clean_object_term_cache($user_id, $this->taxonomy);		
	}
	
    
	function filtrar_por_concepto( $query ) 
	{   		
		if( !is_admin() ) 
		{				
			if ( $query->query['post_type'] || !$query->is_home ) {
				//Solo filtra la home
				//Esta funcion la he desactivado del resto de paginas porque tiene efectos raros cuando no es la home
				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;
			}       			
					
			$query->set('tax_query', array(
				'relation' => 'OR',
				array('taxonomy' => 'scope','field' => 'id','terms' =>get_user_scopes($user_ID)),
				array('taxonomy' => 'category','field' => 'id','terms' =>get_user_categories($user_ID)),								
				));
		
			return $query;
		}
		return $query;
	}
    
}

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

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 = wp_get_object_terms($user_id, 'category');
		$conceptos = array();
		foreach($terms as $term)$conceptos[]=$term->term_id;
		return $conceptos;
	}
	
}

function get_user_scopes($user_id=0){
	if(!$user_id)$user_id = get_current_user_id();
	$terms = wp_get_object_terms($user_id, 'scope');	
	$conceptos = array();
	foreach($terms as $term)$conceptos[]=$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_scopes = wp_get_post_terms($post_id, 'scope', array("fields" => "ids"));  
	$user_scopes = get_user_scopes($user_id);
	foreach($post_scopes as $scope)
	 if(in_array($scope,$user_scopes))
	  return true;
	  
  //No permitir	  
	return false;
}


