<?php
/*
Plugin Name: WP Extended Users 
Description: Provide a new user CRM Functions (metadata,tracking, notes). 
Version: 0.1
License: GPL
Author: Aurelio Pons
Author URI: http://www.a3p.es
Text Domain: wp-extended-users
Domain Path: /lang/

Some parts of this code are based on User Object Framework of Jennifer M. Dodd

================================================================================

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
	
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/


if ( !defined( 'ABSPATH' ) ) exit;

if ( !class_exists( 'WP_Extended_Users' ) ) {
class WP_Extended_Users 
{
	public static $instance;
	public static $version;
	public static $plugin_dir;
	public static $plugin_url;
	
	public function __construct() 
	{
		self::$instance = $this;
		$this->version = '20121216';
		$this->plugin_dir   = plugin_dir_path( __FILE__ );
		$this->plugin_url   = plugins_url( __FILE__ );

		// Database creation and maintenance.
		register_activation_hook( __FILE__, array( &$this, 'install' ) );
		add_action( 'plugins_loaded', array( &$this, 'update_check' ), 9 );

		// Load class and function definitions.
		add_action('plugins_loaded', array( &$this, 'init' ), 10 );
			
		//Enlace "ajustes" en pagina plugins
		//add_filter('plugin_action_links', array( &$this,'plugin_settings_link'), 10, 2);
					
	}
	
	public function install() 
	{
		global $wpdb;

		$installed_version = get_option( 'wp_extended_users_version' );
		if ( $installed_version != $this->version ) {
			global $wpdb;
			require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );

			if ( !empty( $wpdb->charset ) )
				$charset_collate = "DEFAULT CHARACTER SET {$wpdb->charset}";
			else
				$charset_collate = "";

			if ( !$wpdb->get_var( $wpdb->prepare( "SHOW TABLES LIKE '{$wpdb->prefix}user_relations'" ) ) ) {
				$sql = "CREATE TABLE {$wpdb->prefix}user_relations (
						relationship_id bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY,
						user_id bigint(20) NOT NULL DEFAULT 0,
						user_ip bigint(20) NOT NULL DEFAULT 0,
						object_id bigint(20) NOT NULL,
						object_type varchar(32) NOT NULL,
						date timestamp ON UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
						count bigint(20) NOT NULL DEFAULT 1,
					KEY user_id (user_id),
					KEY user_ip (user_ip),
					KEY object (object_id, object_type),
					KEY relationship (user_id, user_ip, object_id, object_type)
				) {$charset_collate};";
				dbDelta( $sql );
			}

			if ( !$wpdb->get_var( $wpdb->prepare( "SHOW TABLES LIKE '{$wpdb->prefix}user_relationsmeta'" ) ) ) {
				$sql = "CREATE TABLE {$wpdb->prefix}user_relationsmeta (
						meta_id bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY,
						user_relations_id bigint(20) NOT NULL,
						meta_key varchar(255) NOT NULL, 
						meta_value longtext,
						meta_date timestamp ON UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
					KEY relationship (user_relations_id),
					KEY meta_key (meta_key)
				) {$charset_collate};";
				dbDelta( $sql );
			}

			update_option( 'wp_extended_users_version', $this->version );
		}
	}

	public function update_check() {
		if ( get_option( 'wp_extended_users_version' ) != $this->version ) {
			$this->install();
		}
	}

	public function init() 
	{
		if ( get_option( 'wp_extended_users_version' ) == $this->version ) { 
			// Add tables to $wpdb for metadata functions.
			global $wpdb;
			$wpdb->user_relations = $wpdb->prefix . 'user_relations';
			$wpdb->user_relationsmeta = $wpdb->prefix . 'user_relationsmeta';
			
			$this->includes();
								
			if(current_user_can('edit_users'))
			{
				wp_enqueue_script( 'jquery-ui-core' );
				wp_enqueue_script( 'jquery-ui-dialog' );
				wp_enqueue_style ( 'jquery-ui-css', plugin_dir_url( __FILE__ ).'css/jquery-ui-fresh.css' );
		
				add_action('admin_menu', array( &$this, 'add_menu_items' ) );
				
				add_action('admin_head','add_thickbox');
				add_action('admin_head','a3p_extended_user_tabs_css');
				add_action('admin_head','a3p_extended_user_tabs_js');
							
				add_action('wp_ajax_save_note_meeting_call', 'save_note_meeting_call_callback');	
			}
			
						
		} else {
			// Failed to find tables.
		}
		
		//load_plugin_textdomain( 'wp-extended-users', false, dirname( plugin_basename( __FILE__ ) ).'/lang' ); 
		
		add_filter('set-screen-option', array($this,'set_screen_options'), 10, 3);
		
		if(false){
			add_extended_user_email_from (2,"hoy","info@a3p.es","Este es el asunto","Este es el cuerpo del mail")  ;
			add_extended_user_email_to   (2,"hoy","info@a3p.es","Este es el asunto","Este es el cuerpo del mail")  ;
			add_extended_user_note		 (2,"hoy");
			add_extended_user_phone_call (2,"Ha llamado para comentar que...");
			add_extended_user_meeting    (2,"Reunion el dia 18 para...");
			add_extended_user_form	     (2,'{"Formulario":"Contacto","ID":"Wordpress Form Manager ID:1","Nombre":"Aurelio","Comentario":"Hola"}');
			add_extended_user_user	     (2,1,"Relacion entre dos usuarios");
			register_user_login();
			register_user_post(12);
			register_user_comment(1);		
		}
		
	}

	public function includes() {
		
		require( $this->plugin_dir . 'user_hooks.php' ); 			
		require( $this->plugin_dir . 'user_ui.php' );		
		require( $this->plugin_dir . 'user_relations.php' ); 
		require( $this->plugin_dir . 'user_relations_list_table.php' ); 
	
	
	}
	
	function add_menu_items(){
	/*
		$hook = add_users_page( __('Tracking','ainia'), __('Tracking','ainia'), 'read', 
								'user_relations', array($this,'users_relations_page') );
		add_action("load-".$hook,array($this,'add_screen_options'));	
	*/	
		add_filter( 'user_row_actions',array( $this, 'user_row' ), 10, 2 );
		
		//Registra Página oculta
		global $_registered_pages;  
        $hookname = get_plugin_page_hookname('historial-usuario', 'users.php');
		add_action("load-".$hookname,array($this,'add_screen_options'));
	
	    if (!empty($hookname)) add_action($hookname, array($this,'user_relations_page'));  
		$_registered_pages[$hookname] = true; 
	}
	
	
	function user_row( $actions, $user ) {
		if ( current_user_can( 'edit_users', $user->ID ) )
			$actions[] = '<a href="users.php?page=historial-usuario&user_id='.$user->ID.'">' . __('Tracking','ainia') . '</a>';
		return $actions;
	}
		
	function add_screen_options() 
	{
		$option = 'per_page';
		$args = array(
			'label' => __('Tracking','ainia'),
			'default' => 15,
			'option' => 'user_relations_per_page'
			);
		add_screen_option( $option, $args );
		
    }
		
    function set_screen_options($status, $option, $value) {			
		if($option=="user_relations_per_page")return $value;
    }
			
	public function users_relations_page()
	{			
		a3p_extended_user_tabs_html($user);	
	}
	
	public function user_relations_page()
	{			
		if(current_user_can('edit_users')){
			$user_id = intval($_REQUEST['user_id']);
			$user=get_userdata( $user_id );
			a3p_extended_user_tabs_html($user);				
		}
	}
	
	
	
	//Configuracion del plugin

	
	public function config_page()
	{		
		echo '<div class="wrap"><div id="icon-users" class="icon32"><br /></div><h2>'.__('WP Extended Users','ainia').'</h2>';
		echo '</div>';
	}
	

	function plugin_settings_link($links, $file) {
		if ( $file == plugin_basename(__FILE__) ) {
			/* Insert the link at the end*/
			$links['settings'] = sprintf( '<a href="%s"> %s </a>', admin_url( 'options-general.php?page=options' ), __( 'Settings' ) );
		}
		return $links;
	}
	
} }


new WP_Extended_Users;


?>