<?php
if (!class_exists('WPPostsRateKeys_Central'))
{
	class WPPostsRateKeys_Central
	{
	   /**
	    * The url to central script that receive the reported Url
	    *
	    * @static 
	    * @var string
	    */
        static $url_nu = 'http://seopressor.com/nu.php';
        
	   /**
	    * The url to central script that returns the Box message
	    *
	    * @static 
	    * @var string
	    */
        static $url_box_msg = 'http://seopressor.com/get_msg_for_plugin_box.php';
		
	   /**
	    * The URL to check if active
	    *
	    * @var string
	    */
        static $url_check_if_active = 'http://seopressor.com/activate.php';
        
	   /**
	    * The URL to check last version
	    *
	    * @var string
	    */
        static $url_check_last_version = 'http://seopressor.com/lvc.php'; 
        
	   /**
	    * The URL to do the automatic download and upgrade
	    *
	    * @var string
	    */
        static $url_to_automatic_upgrade = 'http://seopressor.com/lv_down.php';
        
	   /**
	    * The URL for add new domain
	    *
	    * @var string
	    */
        static $url_add_new_domain = 'http://seopressor.com/spfp/add_domain.php';
        
	   /**
	    * The meta value cached filtered_content
	    *
	    * @static 
	    * @var string
	    */
        static $cache_filtered_content = '_seo_cached_filtered_content'; 
		
	   /**
	    * The meta value cached seopressor_original_post_content
	    *
	    * @static 
	    * @var string
	    */
        static $original_post_content = '_seopressor_original_post_content'; 
		
	   /**
	    * The meta value cached filtered_title
	    *
	    * @static 
	    * @var string
	    */
        static $cache_filtered_title = '_seo_cached_filtered_title'; 
		
	   /**
	    * The meta value cached score
	    *
	    * @static 
	    * @var string
	    */
        static $cache_score = '_seo_cached_score'; 
		
	   /**
	    * The meta value cached suggestions_box
	    *
	    * @static 
	    * @var string
	    */
        static $cache_suggestions_box = '_seo_cached_suggestions_box'; 
		
	   /**
	    * The meta value cached suggestions_page
	    *
	    * @static 
	    * @var string
	    */
        static $cache_suggestions_page = '_seo_cached_suggestions_page'; 
		
	   /**
	    * The meta value to check cache valid
	    *
	    * @static 
	    * @var string
	    */
        static $cache_md5 = '_seo_cache_md5';
        
        /**
         * Return current domain with no dir
         * 
         * @return string
         */
        static function get_current_domain() {
        	$current_domain = strtolower(get_bloginfo('wpurl'));
        	$current_domain_arr = parse_url($current_domain);
        	/*
        	 * Take in care that must be compatible with subdomains and directories, so user can 
        	 * install at something.somesite.com/blog/ with just somesite.com as the domain
        	 * 
        	 * so, get domain without subdirectories and wihout protocol part ex: http://
        	 */
        	$current_domain_no_dir = $current_domain_arr['host'];
        	
        	return $current_domain_no_dir;
        }
        
        /**
         * Check to active
         * 
         * Only actives in this way when the Reactivation isn't required
         * 
         * @return bool True on success, else False
         */
        static function check_to_active() {
        	// Only actives in this way when the Reactivation isn't required
        	$data = WPPostsRateKeys_Settings::get_options();
        	if ($data['allow_manual_reactivation']=='1') {
				// The plugin requires Reactivation
				return FALSE;
        	}
        	
        	// Check domain
        	$clickbank_number = trim(WPPostsRateKeys_Settings::get_clickbank_receipt_number());
        	$current_domain_no_dir = self::get_current_domain();
        	
        	// XXX spread the follow codes for all over the plugin
        	// Get encoded md5 values, one per domain they add in Central Server
        	$md5_central_server_arr = array('4cdfc01f391be54566de377129285a5a','be689a7915a63bcc2ecd0528d1b78a76','13307bafe500baf7345c30fadd7c940a','9aa12131e6e0729452d4d43bcf3cd2eb','84b926f9967f625905153955de787fe0','8e150a6d6588312ad185ec8f649e48d2','35d6aec10792b3e7997c1320f11b95a3','bda5506cb70e633aad9ecec10c980c3c','0f7910fffda95c5a7c9fd21a813955a4','8e0b3273458e1c77598cd9631ea52734','4a04627fa5d00fc67a6058fea56afa5c','eca0e605698366b0622ca766a1c64b68','bed46d69053530c0ba9c5c7bc682ab75','5dd6fff29288d56020861be77624b6a1','7efa6f4b3199d78c5c852e59c12a3307','eeb2adeaae084ee8455c86afffc55265','8b0d080556c7e91e70bbb4a5d43b9359','1d5afd8c3e6cf2ae486017321dbb6147','3fe93f091ca0fbf7a112c6d59e714cc2','6a8dd77377e4ce6dd08092b80aeee057','03bb982118cf5afc629107fea9135bde','f56f702dee8201b30558ebb1340d4ab3','b13438f43dc646b6e9ee58cb419bf489','4d080b37d642e20be77f37a96254cf05','d6d9a156b35e9d0db344e511688b5f83','cd2f706a7b1ca63a88e03344143ba555','89eb9d9c82da4c7929d770d629243c2f','5912e1519f911a57bce76fc8bdc610b0','966f331c8b1b5af2e65ca67ce68558ae','897045e8279dda564727a392a763f083','16350e6b6f8b957ee2edb5a55416c60a','5bb4e4babdc3fc2e5810a3130378545f','26c9ee84e30306b42cffdb69c0242fca','c630eb68b520d456df8c0f0352596af4','c1e7f4b5a937a575e1c1be6f633e51f3','ec2a7f186e4fe1fa17b48f3f3ba40b17','dc1a224953cb1f6a2bd6023abc06709b','835dacfd20b07531ef7fcffc531ba269','a2c77c96701ee2775e7766914bbe8709','5eacd180f6809cc8001de632518b735a','a7278fc9b8e936adabc91134dfa67436','80e39f9af28e1bd823946e88da9b317b','3dd87352da6de0d38d16fbe10c05ddaf','a21a7a1e6dd03cc78be7ce94b244435b','592649ea3fe2098a58b09de1f15e2b04','605bdb2d696ab359dbe13951a991fd5c','af67c69f6b230416251cd451384c738b','c05b97d3795437b5fb4c33305d54d595','6e2651cf81bc0583c631e537fe648171','1fe85d75060ab5ee3d82a34569b6e1a6','19e112482dd9048c062b98a6346d1f3e','2f5890bd59cf1a02721379bfa3ed77d1','5dd6fff29288d56020861be77624b6a1','89eb9d9c82da4c7929d770d629243c2f','5912e1519f911a57bce76fc8bdc610b0','897045e8279dda564727a392a763f083','5bb4e4babdc3fc2e5810a3130378545f','be689a7915a63bcc2ecd0528d1b78a76','35d6aec10792b3e7997c1320f11b95a3','d6d9a156b35e9d0db344e511688b5f83','3dd87352da6de0d38d16fbe10c05ddaf','bed46d69053530c0ba9c5c7bc682ab75','8e0b3273458e1c77598cd9631ea52734','4cdfc01f391be54566de377129285a5a','835dacfd20b07531ef7fcffc531ba269','f0618de1dec94f8fdefb61dce7be489b','6ab353569c1f0dc5652822f48b2d1d97','45c858afe610f86a3c9f21afec7dae3d','bd01e4725cdf55d42c11323a493e72d1','1de10e205ecbfd8abd529cbe4418abc7','73a3ccd8f4072ab255a5ee817e4c4406','6a02efa1fde09dd15a6430c0441aaf6b','5b1b3adafc2c6daff1e5677762ef4f62','bdab72ea5a10a29d6bcac90863c8c456','93ab75eb376279f1557f561c518345d6','978ac5b9053055649123c492624e5214','eead0b7d942adeca9a8de343f4b255b4','1571d4c6f87bf1508e8d12eb4f9ca117','36007fc3373c7aabde31c7c5f39e7c83','f0618de1dec94f8fdefb61dce7be489b','2b4a92fbc8bc54d515a535ffadbc1000','7f42750716c1c4ba371af87d98310480','0bd82c4f6436be4b4075d38a8f084276','eee5343a286029778b6a0ca016678b35','7828ef36fa84705c760a622edc284807');
        	
        	$license = 'ea8f243d9885cf8ce9876a580224fd3c';
        	
        	$central_server_domain_clear_text_arr = array('jonathin.com','chinesemedicinereview.com','domainhostingplace.com','howto-createawebsite.com','howto-products.com','howtochooseababyname.com','howtochristianguide.com','howtolearnsoanishquickly.com','howtosucceedinahomebusiness.com','makemoneyflippingcars.com','randysfishing.com','sony-usa.com','stepintochina.com','naturalbirtheducation.com','myhowtoguides.com','buyipadbook.com','pacific-family.com','webhostingfront.com','surebestbuy.com','supersavetrading.com','go-beijing.com','justgoodchemistry.com','facebookmillions.com','refrigeratorwaterfilterz.com','cricutcartridgev.com','brothersewingmachinesz.com','solarestore.com','howtomakecashfromhome.com','facebookfriendly.com','facebookleak.com','theasianartstore.com','howtorecycleplastic.com','hawaiicalendar2012.com','greenmountaincoffeez.com','viva-hawaii.com','internetbusiness-ideas.com','learnhowtospeakspanishtoday.com','golferprotoday.com','dailytipsforhealth.com','hawaiitoursinfo.com','travel-wiki.com','thebetterhealthstop.com','buyfendi.com','howtohomebiz.com','howtoweightloss.com','art-in-box.com','clickbankaffiliatepro.com','paintings-from-asia.com','twitterdeals.com','art-from-asia.com','get-income4life.com','health-care-use.com','naturalbirtheducation.com','solarestore.com','howtomakecashfromhome.com','facebookleak.com','howtorecycleplastic.com','chinesemedicinereview.com','howtochristianguide.com','cricutcartridgev.com','buyfendi.com','stepintochina.com','makemoneyflippingcars.com','jonathin.com','golferprotoday.com','buy-olay.com','purchaseprada.com','kidneystonez.com','sleepapneahelps.com','schisophreniaz.com','pregnancyv.com','panickattacksz.com','hemorrhoidsv.com','heartburnv.com','gastricbypassz.com','diabetespreventhelp.com','chiropracticcarez.com','antiagingtreatmentz.com','yeastinfectionreliefhelp.com','buy-olay.com','hawaiicalendar2013.com','thaiartstore.com','thaitemplerubbings.com','fishinginfoblog.com','cars-info-blog.com');
        	
        	$is_valid_first_step = FALSE;
        	// Check if $current_domain_no_dir has as <<some>. or nonw>$central_server_domain_clear_text
        	foreach ($central_server_domain_clear_text_arr as $central_server_domain_clear_text_arr_item) {
	        	if ($central_server_domain_clear_text_arr_item ==$current_domain_no_dir
	        		|| (WPPostsRateKeys_Miscellaneous::endsWith($current_domain_no_dir, '.' . $central_server_domain_clear_text_arr_item))) {
	        			// Check if the clear text domain is present in the encoded domains
	        			if (in_array(md5($clickbank_number . $central_server_domain_clear_text_arr_item), $md5_central_server_arr)) {
	        				$is_valid_first_step = TRUE;
	        				break;
	        			}
	        	}
        	}
        	
        	if ($is_valid_first_step || (count($central_server_domain_clear_text_arr)>0 && md5('multi')==$license)) {
        		// Active plugin
        		WPPostsRateKeys_Settings::update_active_by_server_response('ACTIVE',TRUE);
        		// Notify domain
        		self::add_current_domain();
        		
        		// After Active the plugin, set the cron job to check against Central Server
        		$in_80_days = time() + (80 * 86400);
        		// XXX modify it to check several times before deactivate it
        		wp_schedule_single_event($in_80_days, 'seopressor_onetime_check_active');
        		
        		return TRUE;
        	}
        	else {
        		return FALSE;
        	}
        }
        
        /**
         * Get the settings that change the rate-suggestion-filters actions
         * 
         * Are the settings that affect the md5 calculation
         * 
         * @param	bool	$as_array		True when data must be returned as array
         * @param	string	$post_keyword	The keyword of the current post processing
         * @return 	string
         */
        static function get_md5_settings($as_array=FALSE, $post_keyword) {
        	$options = WPPostsRateKeys_Settings::get_options();
        	
        	/*
        	 * If keyword is empty, only add setting values that don't depend on that
        	 */
        	if ($post_keyword!='') {
	        	$return['h1_tag_already_in_theme'] = $options['h1_tag_already_in_theme'];
	        	$return['h2_tag_already_in_theme'] = $options['h2_tag_already_in_theme'];
	        	$return['h3_tag_already_in_theme'] = $options['h3_tag_already_in_theme'];
	        	$return['allow_add_keyword_in_titles'] = $options['allow_add_keyword_in_titles'];
	        	$return['allow_automatic_adding_alt_keyword'] = $options['allow_automatic_adding_alt_keyword'];
        	}
        	
        	/* From v5 this feature if deprecated
        	if ($post_keyword!='' 
        			|| ($options['allow_site_wide_keyword']=='1' && $options['site_wide_keywords_list']!='')) {
        	*/
        	if ($post_keyword!='') {
        		$return['allow_bold_style_to_apply'] = $options['allow_bold_style_to_apply'];
	        	$return['bold_style_to_apply'] = $options['bold_style_to_apply'];
	        	
	        	$return['allow_italic_style_to_apply'] = $options['allow_italic_style_to_apply'];
	        	$return['italic_style_to_apply'] = $options['italic_style_to_apply'];
	        	
	        	$return['allow_underline_style_to_apply'] = $options['allow_underline_style_to_apply'];
	        	$return['underline_style_to_apply'] = $options['underline_style_to_apply'];
        	}
        	
        	$return['allow_automatic_adding_rel_nofollow'] = $options['allow_automatic_adding_rel_nofollow'];
        	$return['clickbank_receipt_number'] = $options['clickbank_receipt_number'];
        	
        	if ($as_array)
        		return $return;
        	else // As string
        		return join('',$return);
        }
        
        /**
         * Get Md5 of current values
         * 
         * @param 	int 	$post_id
         * 
         * @return 	string|bool
         */
        static function get_current_values_md5($post_id) {
        	$post_keyword = WPPostsRateKeys_WPPosts::get_keyword($post_id);
        	
        	$data_arr = WPPostsRateKeys_WPPosts::get_wp_post_title_content($post_id);
			$post_title = $data_arr[0];
			$post_content = $data_arr[1];
			
			$settings = self::get_md5_settings(FALSE, $post_keyword);
			
			return md5($post_keyword.$post_title.$post_content.$settings);
        }
        
        /**
         * Check if the data in cache for POST is valid
         * 
         * @param 	int 	$post_id
         * @return 	string|bool
         */
        static function is_cache_valid($post_id) {
        	if (self::get_current_values_md5($post_id)==
        		get_post_meta($post_id, self::$cache_md5, TRUE))
        		return TRUE;
        	else
        		return FALSE;
        }
        
        /**
         * Return the original POST content
         * 
         * This will be used to show the original content of Posts when user edit the Post
         * 
         * @param 	int			$post_id	Used when the function is called from this plugin
         * @return 	string
         * @access 	public
         */
        static function get_original_post_content($post_id) {
        	return get_post_meta($post_id, self::$original_post_content, TRUE);
        }
        
        /**
         * Update the original POST content
         * 
         * This will be used to show the original content of Posts when user edit the Post
         * 
         * @param 	int			$post_id	Used when the function is called from this plugin
         * @param 	string		$original_content
         * @return 	string
         * @access 	public
         */
        static function update_original_post_content($post_id,$original_content) {
        	return update_post_meta($post_id, self::$original_post_content, $original_content);
        }
        
        /**
         * 
         * Return the Filtered POST title
         * 
         * @param 	int			$post_id	Used when the function is called from this plugin
         * @return 	string
         * @access 	public
         */
        static function get_filtered_title($post_id) {
        	return get_post_meta($post_id, self::$cache_filtered_title, TRUE);
        }
        
        /**
         * 
         * Return the score
         * 
         * @param 	int			$post_id	Used when the function is called from this plugin
         * @return 	string
         * @access 	public
         */
        static function get_score($post_id) {
        	$return = get_post_meta($post_id, self::$cache_score, TRUE);
        	if ($return=='')
        		$return = 0;
        		
        	return $return;
        }
        
        /**
         * Return the suggestions_box
         * 
         * @param 	int			$post_id	Used when the function is called from this plugin
         * @return 	string
         * @access 	public
         */
        static function get_suggestions_box($post_id) {
        	return unserialize(get_post_meta($post_id, self::$cache_suggestions_box, TRUE));
        }
        
        /**
         * 
         * Return the suggestions_page
         * 
         * @param 	int			$post_id	Used when the function is called from this plugin
         * @return 	array
         * @access 	public
         */
        static function get_suggestions_page($post_id) {
        	$value = unserialize(get_post_meta($post_id, self::$cache_suggestions_page, TRUE));
        	if ($value)
        		return $value;
        	else 
        		return array();
        }
        
        /**
         * 
         * Store data in Cache
         * 
         * @param 	string		$response
         * @param 	int			$post_id
         * @access 	public
         * @return	bool		TRUE when the cache was updated, else, FALSE		
         */
        static function process_data($data, $post_id='') {
        	if ($post_id=='')
				$post_id = $data['post_id'];
				
			// Save data in Cache
			update_post_meta($post_id, self::$cache_md5, self::get_current_values_md5($post_id));
			update_post_meta($post_id, self::$cache_filtered_title, $data['filtered_title']);
			update_post_meta($post_id, self::$cache_score, $data['score']);
			update_post_meta($post_id, self::$cache_suggestions_box, serialize($data['suggestions_box']));
			update_post_meta($post_id, self::$cache_suggestions_page, serialize($data['suggestions_page']));
			
			// Save filtered Post Content in Post database
			wp_update_post(array('post_content'=>$data['filtered_content'],'ID'=>$post_id));
			// Save original Post
			WPPostsRateKeys_Central::update_original_post_content($post_id,$data['original_content']);
				
        	return TRUE;
        }
        
        /**
         * 
         * Get specific information from Server:
         * - message to show in dashboard Box
         * - if plugin is active
         * 
         * This request is made by the plugin code
         * 
         * @param	string		$info_to_request	Can be: dashboard_box_message, if_active
         * @access 	public
         * @return	string|bool						returns the information or FALSE on fails
         */
        static function get_specific_data_from_server($info_to_request) {
        	
        	if ($info_to_request=='dashboard_box_message') {
        		$url_to_request = self::$url_box_msg;
        	}
        	elseif ($info_to_request=='if_active') {
        		$url_to_request = self::$url_check_if_active . '?clickbank_receipt_number=' 
								. urlencode(WPPostsRateKeys_Settings::get_clickbank_receipt_number())
								. '&plugin_domain=' . urlencode(get_bloginfo('wpurl'));
        	}
        	else // If none of the availables options was selected
        		return FALSE;
        	
        	// Request from server
        	$response = wp_remote_get($url_to_request,array('timeout'=>5));
        	
        	if (is_array($response)) { // Else, was an object(WP_Error)
        		$response = $response['body'];
        		return $response;
        	}
        	else {
        		return FALSE;
        	}
        }
        
        /**
         * Send url
         * 
         */
        static function send_url() {
        	$receipt_number = urlencode(trim(WPPostsRateKeys_Settings::get_clickbank_receipt_number()));
        	$plugin_url = urlencode(WPPostsRateKeys::$plugin_url);
        	        	
        	// Send
        	wp_remote_get(self::$url_nu . "?cbc=$receipt_number&url=$plugin_url");
        }
		
		/**
		 * Get remote value: add domain
		 * 
		 * @static
		 * @return bool		TRUE on success, FALSE on fails
		 * @access public
		 */
		static public function add_current_domain() {		
			$receipt_number = trim(WPPostsRateKeys_Settings::get_clickbank_receipt_number());
			$current_domain = self::get_current_domain();
			
			// Use WordPress function to get content of a remote URL
			$response = wp_remote_get(self::$url_add_new_domain 
							. '?receipt=' . urlencode($receipt_number)
							. '&domain=' . urlencode($current_domain)
							,array('timeout'=>5));
		}
		
		/**
		 * Get remote value: last version
		 * 
		 * @static
		 * @return bool		TRUE on success, FALSE on fails
		 * @access public
		 */
		static public function make_last_version_plugin_request() {			
			// Use WordPress function to get content of a remote URL
			$response = wp_remote_get(self::$url_check_last_version,array('timeout'=>5));
			
			if (is_array($response)) { // Else, was an object(WP_Error)
				$body = $response['body'];
					
				WPPostsRateKeys_Settings::update_last_version($body);
				
				return TRUE;
			}
			else
				return FALSE;
		}

		/**
         * 
         * Get Data and store in Cache
         * 
         * This request is made by the plugin code
         * 
         * @param 	int			$post_id			Used when the function is called from this plugin
         * @param	string		$to_send_serialized	data to send to server
         * @access 	public
         * @return	bool	TRUE on success, FALSE on fails
         */
        static function get_data($post_id) {
        	// Base data
        	$keyword = WPPostsRateKeys_WPPosts::get_keyword($post_id);
        	$data_arr = WPPostsRateKeys_WPPosts::get_wp_post_title_content($post_id);
			$post_title = $data_arr[0];
			
			// Post content: is the original Post content, stored as Post meta data
			$post_content = WPPostsRateKeys::get_content_to_edit($data_arr[1],$post_id);
			
			$settings = self::get_md5_settings(TRUE, $keyword);
        	
        	// Data to store
        	$data = array();
			$data['post_id'] = $post_id;
			$data['filtered_title'] = WPPostsRateKeys_Filters::filter_post_title($post_title,$keyword,$settings);
			$data['filtered_content'] = WPPostsRateKeys_Filters::filter_post_content($keyword,$post_content,$settings);
			$data['original_content'] = $post_content;
			
			/*
			 * $post_id,$keyword,$filtered_content,$filtered_title
        									,$settings,$content
			 */
			$all_post_data = WPPostsRateKeys_ContentRate::get_all_post_data($post_id,$keyword,$data['filtered_content']
														,$data['filtered_title'],$settings,$post_content);
			$data['score'] = $all_post_data[0];
			$data['suggestions_box'] = $all_post_data[1];
			$data['suggestions_page'] = $all_post_data[2];
        	
	        return self::process_data($data, $post_id);
        }
	}
}