<?php

/*
Plugin Name: P1 Content Magnet
Plugin URI: http://www.p1contentmagnet.com
Description:  P1 Content Magnet is the most in-depth and valuable onPage optimization system to get you P1 rankings in Google and free, targeted traffic. If you have some questions, please contact our support via the link <a href="http://petergaretysupport.zendesk.com/anonymous_requests/new?ticket[fields][20944601]=p1_content_magnet" target="_blank">here</a>
Version: 2.0.1
Author: Peter Garety
Author URI: http://www.petergaretypublishing.com
*/

// Require the plugin functionality from WP since it's not always loaded
require_once( ABSPATH . 'wp-admin/includes/plugin.php' );

// This filter has to be in the main plugin file and the plugin file named after
// the directory that contains it or it won't work
add_filter( 'plugins_url', 'p1cm_plugins_url', 10, 3 );

// Allow symlinking this plugin
function p1cm_plugins_url( $url, $path, $plugin ) {
	// Do it only for this plugin
	if ( strstr( $plugin, 'p1-content-magnet' ) ) {
		return str_replace( str_replace( '\\', '/', dirname( __FILE__ ) ), '/p1-content-magnet', $url );
	}

	return $url;
}

add_action( 'plugins_loaded', 'P1CM::Loaded' );

// We have to explicitly name the file rather than using __FILE__
// because of the symlink in the dev environment
register_activation_hook( 'p1-content-magnet/p1-content-magnet.php', 'P1CM::Activate' );


// Setup the constants we will use throughout the plugin
// to provide base urls/dirs etc
define( 'P1CM_PLUGIN_URL', plugins_url( '', __FILE__ ) );
define( 'P1CM_FILE', __FILE__ );
define( 'P1CM_PLUGIN_DIR', dirname( __FILE__ ) );
define( 'P1CM_OPTION_KEY', '_p1cm_option_key' );
define( 'P1CM_META_KEY', '_p1cm_meta_key' );
define( 'P1CM_NEXT_META_KEY', '_p1cm_next_meta_key' );
define( 'P1CM_PLUGIN_SLUG', 'p1-content-magnet/p1-content-magnet.php');
define( 'P1CM_APP_CODE', 'p1cm' );

require_once( P1CM_PLUGIN_DIR . '/p1cm-meta-seo.php' );

add_filter( 'dashnex_register_models', 'p1cm_register_models' );
function p1cm_register_models( $paths ) {
	//$paths[] = __DIR__ . '/P1CM/Model';
	return $paths;
}

add_filter( 'dashnex_register_query_handlers', 'p1cm_register_query_handlers' );
function p1cm_register_query_handlers( $query_handlers ) {
	if (dashnex_check_license( 'p1cm' )) {
		$query_handlers[] = 'p1cm_progress_tracker_query';
		$query_handlers[] = 'p1cm_proxy_test_query';
	}
	return $query_handlers;
}

add_filter('dashnex_autoload', 'p1cm_autoload');
function p1cm_autoload($defs)
{
    $defs['P1CM\\'] = __DIR__ . '/P1CM';
    return $defs;
}

add_filter('dashnex_config', 'p1cm_config');
function p1cm_config( $configs ) {
	$configs[] = json_decode( file_get_contents( dirname( __FILE__ ) . '/config/services.json' ), true );
	$configs[] = json_decode( file_get_contents( dirname( __FILE__ ) . '/config/meta.json' ), true );
	$configs[] = json_decode( file_get_contents( dirname( __FILE__ ) . '/config/columns.json' ), true );
	$configs[] = json_decode(file_get_contents(dirname(__FILE__) . '/config/query.json'), TRUE);

	if ( WP_DEBUG ) {
		$configs[] = json_decode( file_get_contents( dirname( __FILE__ ) . '/config/debug.json' ), true );
	}

    return $configs;
}

add_filter( 'dashnex_register_templates', 'p1cm_register_templates' );
function p1cm_register_templates( $paths ) {
    $paths[ 'p1cm' ] = __DIR__ . '/view';
    return $paths;
}

add_filter( 'dashnex_assets', 'p1cm_assets' );
function p1cm_assets( $namespaces ) {
	$namespaces[ 'p1cm' ] = P1CM_PLUGIN_URL . '/P1CM/Assets';
	return $namespaces;
}

add_filter('dashnex_register_ajax_handlers', 'p1cm_register_ajax_handlers');
function p1cm_register_ajax_handlers($handlers) 
{
	if (dashnex_check_license( 'p1cm' )) {
		$handlers['p1cm-proxies-add-proxy'] = array(
			'service' => '\\P1CM\\Ajax\\Proxies',
			'method' => 'AddProxy'
		);
		$handlers['p1cm-proxies-delete-proxy'] = array(
			'service' => '\\P1CM\\Ajax\\Proxies',
			'method' => 'DeleteProxy'
		);
		$handlers['p1cm-proxies-test-proxy'] = array(
			'service' => '\\P1CM\\Ajax\\Proxies',
			'method' => 'TestProxy'
		);

		$handlers[ 'p1cm_content_data' ] = array(
			'service' => '\\P1CM\\Column\\ContentData',
			'method'  => 'ContentData'
		);
    
		$handlers['p1cm-meta-load-data'] = array(
			'service' => '\\P1CM\\Ajax\\Meta',
			'method' => 'LoadData'
		);    
	}
	if (dashnex_check_license( 'p1am' )) {
		$handlers[ 'p1cm_delete_report' ] = array(
			'service' => '\\P1CM\\Page\\AuthorityMagnet',
			'method'  => 'DeleteReport'
		);
		$handlers[ 'p1cm_keyword_report' ] = array(
			'service' => '\\P1CM\\Page\\AuthorityMagnet',
			'method'  => 'KeywordReport'
		);
		$handlers[ 'p1cm_site_report' ] = array(
			'service' => '\\P1CM\\Page\\AuthorityMagnet',
			'method'  => 'SiteReport'
		);
    
		$handlers['p1cm-content-builder-process'] = array(
			'service' => '\\P1CM\\Ajax\\ContentBuilder',
			'method' => 'Process'
		);

		$handlers['p1cm-authority-magnet-get-report'] = array(
			'service' => '\\P1CM\\Ajax\\AuthorityMagnet',
			'method' => 'GetReport'
		);
	}

    return $handlers;
}

add_filter( 'dashnex_register_columns', 'p1cm_register_columns');
function p1cm_register_columns( $columns ) {
	if (dashnex_check_license( 'p1cm' )) {
		$columns[] = 'p1cm_content_column';
	}
	return $columns;
}

add_action('wp_enqueue_scripts', '\\P1CM\\Assets\\Register::ScriptsStyles');
add_action('admin_enqueue_scripts', '\\P1CM\\Assets\\Register::AdminScriptsStyles');

add_filter( 'dashnex_register_licenses', 'p1cm_register_licenses' );
function p1cm_register_licenses( $licenses ) {
	$licenses[ 'p1cm' ] = array(
			'name' => 'P1 Content Magnet',
			'description' => 'P1 Content Magnet is the most in-depth and valuable onPage optimization system to get you P1 rankings in Google and free, targeted traffic.',
			'logo' => array(
				'namespace' => 'p1cm',
				'path' => '/img/p1cm.png'	
			),
			'upgrades' => array(
					'p1am' => array(
							'name' => 'P1 Authority Magnet',
							'description' => 'P1 Authority Magnet allows you to gather your competition data to precisely target your website in Google for TOP rankings.'
					)
			)
	);
	return $licenses;
}

// This is a simple helper class to create our basic view system
class P1CM {
	const AUTHORITY_REPORTS_TABLE_NAME = 'p1cm_authority_reports';

	const DEFAULT_STOP_WORDS = 'a,able,about,across,after,all,almost,also,am,among,an,
		and,any,are,as,at,be,because,been,but,by,can,cannot,could,
		dear,define,did,do,does,either,else,ever,every,for,from,get,got,
		had,has,have,he,her,hers,him,his,how,however,i,if,in,into,
		is,it,its,just,least,let,like,likely,may,me,might,more,most,must,
		my,neither,no,nor,not,of,off,often,on,only,or,other,our,own,
		rather,said,say,says,she,should,since,so,some,tags,than,that,the,
		their,them,then,there,these,they,this,tis,to,too,twas,tweet,us,wants,
		was,we,were,what,when,where,which,while,who,whom,why,will,
		with,would,yet,you,your';

	const DEFAULT_MIN_WORD_LENGTH = 4;

	const DEFAULT_LOCALE = 'US';

	
	public static function Activate() {
		if ( ! defined( 'DASHNEX_LOADED' ) ) {
			exit( 'You must install DashNex to activate P1 Content Magnet.  Please go here <a href="">DashNex</a> to download it for free.' );
		}
		self::setDefaultContentParameters();
        self::authorityReportManagerActivate();
        self::proxyManagerActivate();
	}
	
	public static function Loaded() {
		if ( ! defined( 'DASHNEX_LOADED' ) ) {
			
			$pluginPath = ABSPATH . 'wp-content/plugins/p1-content-magnet/p1-content-magnet.php';
			
			$reactivate_plugins = get_option('_dashnex_reactivate_plugins', array() );
			if ( ! in_array( $pluginPath, $reactivate_plugins ) ) {
				$reactivate_plugins[] = $pluginPath;
				update_option( '_dashnex_reactivate_plugins', $reactivate_plugins );
			}
			
			deactivate_plugins( $pluginPath );
			header( 'Location: ' . $_SERVER[ 'REQUEST_URI' ] );
		}
	}
	
	public static function Render( $view, $_data = array() ) {
		extract( $_data );
		require( P1CM_PLUGIN_DIR . '/view/' . $view . '.php' );
	}
	
	public static function RenderJson( $data ) {
		echo json_encode( $data );
		exit();
	}
	
	public static function Asset( $path , $return = FALSE) {
		$str = P1CM_PLUGIN_URL . '/P1CM/Assets/' . $path;
        if($return) {
            return $str;
        }
        echo $str;
	}
	
	public static function Route( $page, $args = array() ) {
		$route = 'admin.php?page=' . $page;

		foreach ( $args as $key => $value ) {
			$route .= '&' . $key . '=' . $value;
		}
		
		return $route; 
	}
    
    protected static function authorityReportManagerActivate() {
		global $wpdb;
		
		$table_name = self::GetAuthorityReportManagerTableName();
		$sql = "CREATE TABLE $table_name (
  			id int unsigned NOT NULL AUTO_INCREMENT,
  			report text NOT NULL,
  			PRIMARY KEY id (id)
		);";
		require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
		dbDelta( $sql );
	}
	
	public static function GetAuthorityReportManagerTableName() {
		global $wpdb;
		
		return $wpdb->prefix . self::AUTHORITY_REPORTS_TABLE_NAME;
	}
	
	protected static function proxyManagerActivate() {
		
	}

	protected static function setDefaultContentParameters() {
		$options = get_option( P1CM_OPTION_KEY );

		if ( ! isSet( $options[ 'stop_words' ] )
			|| strlen( $options[ 'stop_words' ] ) === 0 ) {
			$stopWords = str_replace( "\t", '', self::DEFAULT_STOP_WORDS );
			$options[ 'stop_words' ] = $stopWords;
			update_option( P1CM_OPTION_KEY, $options );
		}

		if ( ! isSet( $options[ 'min_word_length' ] )
			|| strlen( $options[ 'min_word_length' ] ) === 0 ) {
			$options[ 'min_word_length' ] = self::DEFAULT_MIN_WORD_LENGTH;
			update_option( P1CM_OPTION_KEY, $options );
		}

		if ( ! isSet( $options[ 'locale' ] )
			|| strlen( $options[ 'locale' ] ) ) {
			$options[ 'locale' ] = self::DEFAULT_LOCALE;
			update_option( P1CM_OPTION_KEY, $options );
		}
	}
}

// Everything we do from here on out is admin specific to only load it
// for an admin function
if ( is_admin() ) {
	require_once( "p1cm-admin.php" );
}
