<?php
/**
 * @package    WPRS
 * @subpackage Admin
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly


add_action('init', 'wprs_load_tracking');
/**
	* Load tracking
	*/
function wprs_load_tracking() {
	
	$options = get_option('wprs_options');
	
	if ( isset($options['wprs_chk_allow_tracking']) !='' ) $GLOBALS['wprs_tracking'] = new WPRS_Tracking;
}

/**
 * Class that creates the tracking functionality for WPRS, as the core class might be used in more plugins,
 * it's checked for existence first.
 *
 * NOTE: this functionality is opt-in. Disabling the tracking in the settings or saying no when asked will cause
 * this file to not even be loaded.
 *
 */
class WPRS_Tracking {

	/**
	 * @var    object    Instance of this class
	 */
	public static $instance;


	/**
	 * Class constructor
	 */
	function __construct() {
		
		// Constructor is called from WPRS
		if ( current_filter( 'wprs_tracking' ) ) {
			$this->tracking();
		} // Backward compatibility - constructor is called from other WPRS plugin
		elseif ( ! has_action( 'wprs_tracking', array( $this, 'tracking' ) ) ) {
			add_action( 'wprs_tracking', 		array( $this, 'tracking' ) );
		}
		add_action( 'template_redirect', 	array( $this, 'wprs_tracking_process_api_request' ), -1 );
	}

	/**
	 * Get the singleton instance of this class
	 *
	 * @return object
	 */
	public static function get_instance() {
		if ( ! ( self::$instance instanceof self ) ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	/**
	 * Main tracking function.
	 */
	public function tracking() {
		
		$transient_key = 'wprs_tracking_cache';
		$data          = get_transient( $transient_key );

		// bail if transient is set and valid
		if ( $data !== false ) {
		
			return;
		
		} else {
		
			$data = $this->get_tracking_data();
			$sl = trim( get_option( 'wprs_license_key' ) );
			$site_name= str_replace(" ", "-", get_bloginfo('name'));
			$site_url= get_bloginfo( 'url' );
		
			$args = array(
				//'body'      => $data,
				'blocking'  => false,
				'sslverify' => false,
			);

			wp_remote_post( 'http://wprichsnippets.com/?wprs-tracking=true&license-key='.$sl.'&site-name='.$site_name.'&site-url='.$site_url, $args );
		
		}

	}
	
	
	/**
	 * Get tracking data function.
	 */
	public function get_tracking_data() {

		$transient_key = 'wprs_tracking_cache';
		$data          = get_transient( $transient_key );

		// bail if transient is set and valid
		if ( $data !== false ) {
			return $data;
		}

		// Start of Metrics
		global $blog_id, $wpdb;

		$hash = get_option( 'WPRS_Tracking_Hash', false );

		if ( ! $hash || empty( $hash ) ) {
			// create and store hash
			$hash = md5( site_url() );
			update_option( 'WPRS_Tracking_Hash', $hash );
		}

		$pts        = array();
		$post_types = get_post_types( array( 'public' => true ) );
		if ( is_array( $post_types ) && $post_types !== array() ) {
			foreach ( $post_types as $post_type ) {
				$count             = wp_count_posts( $post_type );
				$pts[ $post_type ] = $count->publish;
			}
		}
		unset( $post_types );

		$comments_count = wp_count_comments();

		$theme_data     = wp_get_theme();
		$theme          = array(
			'name'       => $theme_data->display( 'Name', false, false ),
			'theme_uri'  => $theme_data->display( 'ThemeURI', false, false ),
			'version'    => $theme_data->display( 'Version', false, false ),
			'author'     => $theme_data->display( 'Author', false, false ),
			'author_uri' => $theme_data->display( 'AuthorURI', false, false ),
		);
		$theme_template = $theme_data->get_template();
		if ( $theme_template !== '' && $theme_data->parent() ) {
			$theme['template'] = array(
				'version'    => $theme_data->parent()->display( 'Version', false, false ),
				'name'       => $theme_data->parent()->display( 'Name', false, false ),
				'theme_uri'  => $theme_data->parent()->display( 'ThemeURI', false, false ),
				'author'     => $theme_data->parent()->display( 'Author', false, false ),
				'author_uri' => $theme_data->parent()->display( 'AuthorURI', false, false ),
			);
		}
		else {
			$theme['template'] = '';
		}
		unset( $theme_template );


		$plugins       = array();
		$active_plugin = get_option( 'active_plugins' );
		foreach ( $active_plugin as $plugin_path ) {
			if ( ! function_exists( 'get_plugin_data' ) ) {
				require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
			}

			$plugin_info = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin_path );

			$slug           = str_replace( '/' . basename( $plugin_path ), '', $plugin_path );
			$plugins[ $slug ] = array(
				'version'    => $plugin_info['Version'],
				'name'       => $plugin_info['Name'],
				'plugin_uri' => $plugin_info['PluginURI'],
				'author'     => $plugin_info['AuthorName'],
				'author_uri' => $plugin_info['AuthorURI'],
			);
		}
		unset( $active_plugins, $plugin_path );
		
		// Server data
		$server_data = array();

		if ( isset( $_SERVER['SERVER_SOFTWARE'] ) && ! empty( $_SERVER['SERVER_SOFTWARE'] ) ) {
			$server_data['software'] = $_SERVER['SERVER_SOFTWARE'];
		}

		if ( function_exists( 'phpversion' ) ) {
			$server_data['php_version'] = phpversion();
		}

		if ( function_exists( 'ini_get' ) ) {
			$server_data['php_post_max_size'] = size_format( wprs_let_to_num( ini_get( 'post_max_size' ) ) );
			$server_data['php_time_limt'] = ini_get( 'max_execution_time' );
			$server_data['php_max_input_vars'] = ini_get( 'max_input_vars' );
			$server_data['php_suhosin'] = extension_loaded( 'suhosin' ) ? 'Yes' : 'No';
		}

		$server_data['mysql_version'] = $wpdb->db_version();

		$server_data['php_max_upload_size'] = size_format( wp_max_upload_size() );
		$server_data['php_default_timezone'] = date_default_timezone_get();
		$server_data['php_soap'] = class_exists( 'SoapClient' ) ? 'Yes' : 'No';
		$server_data['php_fsockopen'] = function_exists( 'fsockopen' ) ? 'Yes' : 'No';
		$server_data['php_curl'] = function_exists( 'curl_init' ) ? 'Yes' : 'No';
		
		
		// Construct data array
		$data = array(
			'site'		=> array(
				'hash'			=> $hash,
				//'license_key'	=> $sl,
				'url' 			=> home_url(),
				'version'   	=> get_bloginfo( 'version' ),
				'multisite' 	=> is_multisite() ? 'Yes' : 'No',
				'users'     	=> $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->users INNER JOIN $wpdb->usermeta ON ({$wpdb->users}.ID = {$wpdb->usermeta}.user_id) WHERE 1 = 1 AND ( {$wpdb->usermeta}.meta_key = %s )", 'wp_' . $blog_id . '_capabilities' ) ),
				'debug_mode'    => ( defined('WP_DEBUG') && WP_DEBUG ) ? 'Yes' : 'No',
				'lang'      	=> get_locale(),
			),
			'pts'		=> $pts,
			'comments'	=> array(
				'total'    => $comments_count->total_comments,
				'approved' => $comments_count->approved,
				'spam'     => $comments_count->spam,
				'pings'    => $wpdb->get_var( "SELECT COUNT(comment_ID) FROM $wpdb->comments WHERE comment_type = 'pingback'" ),
			),
			'options'	=> apply_filters( 'wprs_tracking_filters', array() ),
			'theme'		=> $theme,
			'plugins'	=> $plugins,
			'server'	=> $server_data,
		);

		$args = array(
			'body'      	=> $data,
			'blocking'		=> false,
			'sslverify'		=> false,
			'user-agent'	=> 'WPRS',
			'headers'		=> array(),
			'cookies'		=> array()
		);
		
		// Make sure to only send tracking data once a week
		set_transient( $transient_key, 1, WEEK_IN_SECONDS );
		// For debug
		//set_transient( $transient_key, $data, 1000 );
		
		return $data;

	}
	
	function wprs_tracking_process_api_request() {
    
		global $wp_query;
     
    	// If our endpoint isn't hit, just return
    	if ( ! isset( $wp_query->query_vars['wprs-tracking-api'] ) ) {
			return;
    	}
 
    	// If they didn't supply a key, return
    	if ( ! isset( $wp_query->query_vars['wprs-tracking-check-license-key'] ) ) {
       		wprs_tracking_output( array( 'error' => 'No License Key Provided' ) );
    	}
 
 		// Get license key
    	//$sl = edd_software_licensing();
		$sl = trim( get_option( 'wprs_license_key' ) );
	
 
    	define( 'EDD_BYPASS_NAME_CHECK', true );
    	//$status = $sl->check_license( array( 'key' => $wp_query->query_vars['wprs-tracking-check-license-key'] ) );
 		$status = '';
    	// If the key isn't invalid or disabled, return our API data
    	if ( $status != 'invalid' && $status != 'disabled' ) {
			// get data
			$data = $this->get_tracking_data();
			// output data
			wprs_tracking_output( $data );
		
    	} else {
		
        	wprs_tracking_output( array( 'error' => 'Invalid License Key. Cheetin\' eh?' ) );
    
		}
     
	}

} /* End of class */


add_filter( 'wprs_tracking_filters', 'wprs_tracking_additions' );
/**
 * Adds tracking parameters for WPRS plugin settings. Outside of the main class as the class could also be in use in other plugins.
 *
 * @param array $options
 *
 * @return array
 */
function wprs_tracking_additions( $options ) {
	
	// Get WPRS plugin settings
	$options['wprs'] = get_option('wprs_options');
	return $options;
	
}


add_action( 'init', 'wprs_tracking_add_endpoint' );
/*
	Add end point
	*/
function wprs_tracking_add_endpoint( $rewrite_rules ) {
	
	// add a rewrite for endpoint
    add_rewrite_endpoint( 'wprs-tracking-api', EP_ALL );
	
	// flush rewrite rules
	// Not sure if this should be preformed here,
	// but I will leave it here for now!
	flush_rewrite_rules();

}
 

add_filter( 'query_vars', 'wprs_tracking_query_vars' );
/*
	Set query var 
	*/
function wprs_tracking_query_vars( $vars ) {
    
	$vars[] = 'wprs-tracking-check-license-key';
 
    return $vars;

}


/*
	End point ouput
	*/
function wprs_tracking_output( $output ) {
    
	// Helps us exit any output buffers started by plugins or themes
    $ob_status = ob_get_level();
    while ( $ob_status > 0 ) {
        ob_end_clean();
        $ob_status--;
    }

    // Output the data for the endpoint
    header( 'Content-Type: application/json' );
    echo json_encode( $output );
    exit;

}


/**
* let_to_num function.
 *
* This function transforms the php.ini notation for numbers (like '2M') to an integer.
*
* @param $size
@return int
*/
function wprs_let_to_num( $size ) {
	
	$l   = substr( $size, -1 );
	$ret = substr( $size, 0, -1 );
    
	switch ( strtoupper( $l ) ) {
        case 'P':
            $ret *= 1024;
        case 'T':
            $ret *= 1024;
        case 'G':
            $ret *= 1024;
        case 'M':
            $ret *= 1024;
        case 'K':
            $ret *= 1024;
    }
	
    return $ret;
	
}

