<?php
/*
*	Plugin Name: Textoptimizer
*	Plugin URI: http://textoptimizer.com
*	Description: Search engine will love you ! Give them what they want, for a better ranking.
*	Version: 2.3
*	Author: Webinfo LTD
*	Author URI: http://textoptimizer.com
*	Text Domain: textoptimizer
*/

/**
*	@package	Textoptimizer WordPress Plugin
*	@author		Webinfo LTD
*/

// Textoptimizer Plugin Folder Url.
if ( ! defined( 'TEXTOPTIMIZER_PLUGIN_URL' ) ) :
	define( 'TEXTOPTIMIZER_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
endif;

Class Textoptimizer {
	// Define Global Variables and Other Public, Private or Protected Variables.
	public $textOptimizerApiUrl = "https://api.textoptimizer.com/api/";
	public $textOptimizerSuggestionsLink = "https://textoptimizer.com/m?q=";
	public $textOptimizerBuyMoreLink = "https://textoptimizer.com/s/order";

	/** Textoptimizer Constructor
	*	@no-argument
	*	@no-return
	*	set all default action and hook calling
	**/
	public function __construct() {
		add_action( 'init', array(&$this, 'TextoptimizerTextDomain'));
		add_action( 'admin_enqueue_scripts', array(&$this, 'TextoptimizerAdminEnqueue'));
		add_action( 'add_meta_boxes', array(&$this, 'TextoptimizerRegisterMetaBox'));

		/** Post Data Optimize **/
		add_action('wp_ajax_TextoptimizerPostDataOptimize', array(&$this, 'TextoptimizerPostDataOptimize'));
		add_action('wp_ajax_nopriv_TextoptimizerPostDataOptimize', array(&$this, 'TextoptimizerPostDataOptimize'));

		/** Login **/
		add_action('wp_ajax_TextoptimizerLoginUser', array(&$this, 'TextoptimizerLoginUser'));
		add_action('wp_ajax_nopriv_TextoptimizerLoginUser', array(&$this, 'TextoptimizerLoginUser'));

		/** Registration **/
		add_action('wp_ajax_TextoptimizerRegistrationUser', array(&$this, 'TextoptimizerRegistrationUser'));
		add_action('wp_ajax_nopriv_TextoptimizerRegistrationUser', array(&$this, 'TextoptimizerRegistrationUser'));

		/** Logout **/
		add_action('wp_ajax_TextoptimizerLogoutUser', array(&$this, 'TextoptimizerLogoutUser'));
		add_action('wp_ajax_nopriv_TextoptimizerLogoutUser', array(&$this, 'TextoptimizerLogoutUser'));
	}

	/** Textoptimizer Text Domain
	*	@access only init for the plugin setup
	*	@no-argument
	*	@no-return
	*	set the textoptimizer text domain with plugin relative path
	**/
	public function TextoptimizerTextDomain() {
		load_plugin_textdomain('textoptimizer', false, basename(dirname(__FILE__)) . '/languages');
	}

	/** Textoptimizer Register Metabox Add In Post 
	*	@no-argument
	*	@no-return
	**/
	public function TextoptimizerRegisterMetaBox() {
		add_meta_box( 'textoptimizer-metabox', __( 'TextOptimizer', 'textoptimizer' ), array(&$this, 'TextoptimizerFields'), array('post', 'page'), 'side', 'high');
	}

	/** Textoptimizer Metabox Fields
    *   @no-argument
    *   @no-return
    **/
	public function TextoptimizerFields() {
		global $post;
		$textOptimizerValues = get_post_custom( $post->ID );
		include_once('textoptimizer-meta.php');
	}

	/** Textoptimizer Admin Enqueue Files
	*	@no-argument
	*	@no-return
	**/
	public function TextoptimizerAdminEnqueue(){
		wp_enqueue_script( 'jquery' );
		wp_enqueue_style( 'textoptimizer-google-fonts', 'https://fonts.googleapis.com/css?family=Lato:100,100i,300,300i,400,400i,700,700i,900,900i', false );
		wp_enqueue_script( 'textoptimizer-admin-script', plugins_url('/assets/js/textoptimizer-admin-script.js',__FILE__), array('jquery'), false, true );
		wp_enqueue_script( 'copytoclipboard-script', plugins_url('/assets/js/tabulous.js',__FILE__), array('jquery'), false, true );
		wp_enqueue_script( 'copytoclipboard12-script', plugins_url('/assets/js/jquery.qtip.js',__FILE__), array('jquery'), false, true );
		$textoptimizer = array(
			'ajaxUrl' => admin_url( 'admin-ajax.php' ),
			'pluginUrl' =>	TEXTOPTIMIZER_PLUGIN_URL,
			'howToAddLabel' => __('Words to add', 'textoptimizer'),
			'howToRemoveLabel' => __('Word to remove', 'textoptimizer'),
			'errorMessage' => __('Please use standard characters', 'textoptimizer'),
			'blankKeyWordMessage' => __('Please enter keywords', 'textoptimizer'),
			'blankContentMessage' => __('Please enter content in post content area.', 'textoptimizer'),
		);
		wp_localize_script('textoptimizer-admin-script', 'textoptimizerJS', $textoptimizer);
		wp_enqueue_style( 'textoptimizer-admin-css', plugins_url('/assets/css/textoptimizer-backend.css', __FILE__) );
	}

	/** Textoptimizer Improve Content.
	*	access - Only For AJAX
	*	@no-argument
	*	@return json encode string in ajax jquery
	**/
	public function TextoptimizerPostDataOptimize(){
		$limitInTextWord = 7;
		$limitWord = 35;
		if(isset($_POST['keyWords'])): $keyWords = $_POST['keyWords']; else: $keyWords = ''; endif;
		if(isset($_POST['content'])): $content = $_POST['content']; else: $content = ''; endif;
		$apiDatas = $this->TextoptimizerGetUserDetails();
		$apiKey = '';
		if(isset($apiDatas['success']) && $apiDatas['success']==1) :
			$apiKey = $apiDatas['apiKey'];
		endif;
		$content = wp_filter_nohtml_kses($content);
		$url = $this->textOptimizerApiUrl.'optimize_text';
		$datas = array('query' => $keyWords, 'content' => $content, 'api_key'=>$apiKey);
		$result =json_decode($this->TextoptimizerAPICall($datas, 'postdata', $url));

		if(is_array($result) && isset($result[0])){

			$results['resultCount'] = $count." ".$resultCount;
			if((!isset($result[0]->error)) && ($result[0]->error=='') && (isset($result[0]->score))) :
				$results['success'] = true;
				$resultCount = __("semantics relationships analysed.", "textoptimizer");
				$array = json_decode(json_encode($result), true);
				$count = count($array, COUNT_RECURSIVE);
				if(isset($result[0]->credits)) :
					$results['credits']	= $result[0]->credits;
				else :
					$results['credits']	= "null";
				endif;
				if(isset($result[0]->score)) :
					$results['score'] = esc_html($result[0]->score);
					$score = $results['score'];
					if( $score < 30 ){
						$imgSrc = esc_url(TEXTOPTIMIZER_PLUGIN_URL.'assets/images/bot_result1.png');
					}else if( $score < 40 ){
						$imgSrc = esc_url(TEXTOPTIMIZER_PLUGIN_URL.'assets/images/bot_result2.png');
					}else if( $score < 70 ){
						$imgSrc = esc_url(TEXTOPTIMIZER_PLUGIN_URL.'assets/images/bot_result3.png');
					}else{
						$imgSrc = esc_url(TEXTOPTIMIZER_PLUGIN_URL.'assets/images/bot_result4.png');
					}
					$results['scoreImage'] = $imgSrc;
				else :
					$results['scoreImage'] = '';
					$results['score'] = __('Score Not Found!', 'textoptimizer');
				endif;

				$btnNameCopy = __("Copy to clipboard", "textoptimizer");
				$btnNameSuggestion = __("More suggestions", "textoptimizer");

				/* BOX-2 Green Tab Title & Content */
				if(isset($result[0]->lexical_fields_ok) && !empty($result[0]->lexical_fields_ok)) :
					$box2 = $result[0]->lexical_fields_ok;
					$box2TabTitle = ''; $box2TabContent = '';
					$labelCurrently = __("Currently in your text:", "textoptimizer"); 
					$labelAddSuggestions = __("Optionally, you could add some of the following suggestions:", "textoptimizer"); 
					$i = 1;
					foreach($box2 as $key=>$values){
						$tabActiveClass = '';
						$suggestionsButtonLink = $this->textOptimizerSuggestionsLink.$values->name;
						if($key==0) :
							$tabActiveClass = 'tabulous_active';
						endif;
						$box2TabTitle .= '<li><a class="'.$tabActiveClass.'" href="#tabs-'.$i.'" title="'.$values->name.'">'.$values->name.'</a></li>';

	    				$in_text = $this->TextoptimizerLimitText($values->in_text, $limitInTextWord);
	    				$you_could_add = $this->TextoptimizerLimitText($values->you_could_add, $limitWord);

						$box2TabContent .= '<div id="tabs-'.$i.'">';
						// Currently in your text
						$box2TabContent .= '<p><strong class="textoptimizer-" style="font-size:14px;color:#009531;display:block">';
						$box2TabContent .= $labelCurrently;
						$box2TabContent .= '</strong>'.$in_text.'</p>';
						$box2TabContent .= '<p>';

						// Add more Suggestions
						$box2TabContent .= '<p><strong class="textoptimizer-" style="font-size:14px;color:#009531;display:block">';
						$box2TabContent .= $labelAddSuggestions;
						$box2TabContent .= '</strong>'.$you_could_add.'</p>';
						$box2TabContent .= '<p>';

						$box2TabContent .= '<a class="textoptimizer_button clipboard-btn" style="margin-bottom:5px" href="#" onclick="return copyTextToClipboard(\''.$in_text.'\');">'.$btnNameCopy.'</a>';
						$box2TabContent .= '<a class="textoptimizer_button suggestion_btn box2_suggestion_btn" href="'.$suggestionsButtonLink.'" onclick="return textoptimizerOpenLink(this);" target="_new" rel="nofollow" >'.$btnNameSuggestion.'</a>';
						$box2TabContent .= '</p></div>';
						$i++;
					} 
					$box2TabTitle .= '<span class="tabulousclear"></span>';
					$results['titleBox2'] = $box2TabTitle;
					$results['contentBox2'] = $box2TabContent;
				else :
					$results['titleErrorBox2'] = '';
					$results['contentErrorBox2'] = '';
				endif;

				/* BOX-3 Blue Tab Title & Content */
				if(isset($result[0]->lexical_fields_more) && $result[0]->lexical_fields_more != NULL) :
					$box3 = $result[0]->lexical_fields_more; $i = 2;
					$label = __("If possible, improve your text by adding some of the following suggestions", "textoptimizer");
					$label2 = __("Currently in your text", "textoptimizer");
					$box3TabTitle = '<li><a href="#tabs-1" >'.__("COMMON WORDS", "textoptimizer").'</a></li>';

					if(isset($result[0]->summary_add)) :
						$optimizerSuggestion = $this->TextoptimizerLimitText($result[0]->summary_add, $limitWord);
						$box3TabContent = '<div id="tabs-1" style="top: 40px;" class="showscale"><p><strong style="font-size:14px;color:#01658f;display:block">'.$label.':</strong>'.$optimizerSuggestion.'</p><p><a class="textoptimizer_button clipboard-btn" style="margin-bottom:5px" href="#" onclick="return copyTextToClipboard(\''.$optimizerSuggestion.'\');">'.$btnNameCopy.'</a></p></div>';
					endif;

					foreach($box3 as $key=>$values){
						$you_could_add = $this->TextoptimizerLimitText($values->you_could_add, $limitWord);
						$in_text = $this->TextoptimizerLimitText($values->in_text, 10);
						$copyClipboardContent = "Currently in your text: \u000A".$in_text."\u000AIf possible, improve your text by adding some of the following suggestions: \u000A".$you_could_add;
						$tabActiveClass = '';
						$suggestionsButtonLink = $this->textOptimizerSuggestionsLink.$values->name;
						if($key==0) :
							$tabActiveClass = 'tabulous_active';
						endif;
						$box3TabTitle .= '<li><a href="#tabs-'.$i.'" title="'.$values->name.'" class="'.$tabActiveClass.'">'.$values->name.'</a></li>';
						$box3TabContent .= '<div id="tabs-'.$i.'" style="top: 40px;" class="hidescale">';
						$box3TabContent .= '<p><strong style="font-size:14px;color:#01658f;display:block">';
						$box3TabContent .= $label2;
						$box3TabContent .= '</strong>'.$in_text.'</p>';
						$box3TabContent .= '<p><strong style="font-size:14px;color:#01658f;display:block">'.$label.':</strong>';
						$box3TabContent .= $you_could_add.'</p>';
						$box3TabContent .= '<p><a class="textoptimizer_button clipboard-btn" style="margin-bottom:5px" href="#" onclick="return copyTextToClipboard(\''.$copyClipboardContent.'\');">'.$btnNameCopy.'</a>';
						$box3TabContent .= '<a class="textoptimizer_button suggestion_btn box3_suggestion_btn" href="'.$suggestionsButtonLink.'" target="_blank" onclick="return textoptimizerOpenLink(this);" rel="nofollow">'.$btnNameSuggestion.'</a>';
						$box3TabContent .= '</p></div>';
						$i++;
					} 
					$box3TabTitle .= '<span class="tabulousclear"></span>';
					$results['titleBox3'] = $box3TabTitle;
					$results['contentBox3'] = $box3TabContent;
				else :
					$results['titleErrorBox3'] = '';
					$results['contentErrorBox3'] = '';
				endif;

				/* BOX-4 RED Tab Title & Content */
				if(isset($result[0]->lexical_fields_less) && !empty($result[0]->lexical_fields_less)) :
					$box4 = $result[0]->lexical_fields_less;
					$box4TabTitle = ''; $box4TabContent = '';
					$label = __("Currently in your text", "textoptimizer"); 
					$label2 = __("If possible, remove from your text some of the following suggestions", "textoptimizer");
					$i = 2;

					if(isset($result[0]->summary_remove)) :
						$summary_remove = $this->TextoptimizerLimitText($result[0]->summary_remove, $limitWord);
						$box4TabContent = '<div id="tabs-1" style="top: 40px;" class="showscale"><p><strong style="font-size:14px;color:#ae0001;display:block">'.$label2.':</strong>'.$summary_remove.'</p><p><a class="textoptimizer_button clipboard-btn" style="margin-bottom:5px" href="#" onclick="return copyTextToClipboard(\''.$summary_remove.'\');">'.$btnNameCopy.'</a></p></div>';
						$box4TabTitle = '<li><a href="#tabs-1" title="">'.__("COMMON WORDS", "textoptimizer").'</a></li>';
					endif;

					foreach($box4 as $values){
						$tabActiveClass = '';
						$suggestionsButtonLink = $this->textOptimizerSuggestionsLink.$values->name;
						if($key==0) :
							$tabActiveClass = 'tabulous_active';
						endif;
						$box4TabTitle .= '<li><a class="'.$tabActiveClass.'" href="#tabs-'.$i.'" title="'.$values->name.'">'.$values->name.'</a></li>';
						$you_could_remove = $this->TextoptimizerLimitText($values->you_could_remove, $limitWord);
						$box4TabContent .= '<div id="tabs-'.$i.'"><p><strong style="font-size:14px;color:#ae0001;display:block">';
						$box4TabContent .= $label;
						$box4TabContent .= '</strong>'.$you_could_remove.'</p>';
						$box4TabContent .= '<p><a class="textoptimizer_button clipboard-btn" style="margin-bottom:5px" href="#" onclick="return copyTextToClipboard(\''.$you_could_remove.'\');">'.$btnNameCopy.'</a>';
						$box4TabContent .= '<a class="textoptimizer_button suggestion_btn box4_suggestion_btn" rel="nofollow" href="'.$suggestionsButtonLink.'" target="_blank" onclick="return textoptimizerOpenLink(this);" >'.$btnNameSuggestion.'</a>';
						$box4TabContent .= '</p></div>';				
						$i++;
					} 
					$box4TabTitle .= '<span class="tabulousclear"></span>';
					$results['titleBox4'] = $box4TabTitle;
					$results['contentBox4'] = $box4TabContent;
				else :
					$results['titleErrorBox4'] = '';
					$results['contentErrorBox4'] = '';
				endif;
			else :
				$results['success'] = false;
				$results['credits']	= $result[0]->credits;
				$results['statuses'] = $result[0]->status;
				$results['errors'] = $result[0]->error;
			endif;

		} else {
			$results['statuses'] = $result->status;
			$results['errors'] = $result->error;
		}
		echo json_encode($results); exit;
	}

	/** Textoptimizer For Login User.
	*	@$url argument
	*	@return $results in JSON format
	**/
	public function TextoptimizerLoginUser() {
		$this->TextOptimizerResetUser(); // reset user
		$resultDatas = array();
		$user['user[email]'] = $_POST['userEmail'];
		$user['user[password]'] = $_POST['userPassword'];
		$url = $this->textOptimizerApiUrl.'signin';
		$getResponse = json_decode($this->TextoptimizerAPICall($user, 'getdata', $url));
		if(isset($getResponse->success) && $getResponse->success==true) {
			$resultDatas['success'] = true;
			$resultDatas['notification'] = $getResponse->notification;
			$resultDatas['userName'] = $_POST['userEmail'];
			$resultDatas['buyMore'] = $this->textOptimizerBuyMoreLink.'?api_key='.base64_encode($getResponse->api_key);
			$resultDatas['credits'] = $getResponse->credits;
			$datas = $this->TextoptimizerEncryption(array('success'=>true, 'userName'=>$_POST['userEmail'], 'userPassword'=>$_POST['userPassword'], 'apiKey'=>$getResponse->api_key));
			setcookie('TextoptimizerUserSession', $datas, time()+86400*30);
		} else{
			$resultDatas['success'] = false;
			$resultDatas['notification'] = $getResponse->notification;
			$resultDatas['errors'] = $getResponse->error;
			$datas = $this->TextoptimizerEncryption(array('success'=>false, 'userName'=>$_POST['userEmail'], 'password'=>'', 'apiKey'=>null));
		}
		echo json_encode($resultDatas); exit;
	}

	/** Textoptimizer For Registration User.
	*	@$url argument
	*	@return $results in JSON format
	**/
	public function TextoptimizerRegistrationUser() {
		$this->TextOptimizerResetUser(); // reset user
		$resultDatas = array();
		$user['user[email]'] = $_POST['userEmail'];
		$user['user[password]'] = $_POST['userPassword'];
		$user['user[terms]'] = $_POST['userAgree'];

		$url = $this->textOptimizerApiUrl.'signup';
		$getResponse = json_decode($this->TextoptimizerAPICall($user, 'getdata', $url));
		if(isset($getResponse->success) && $getResponse->success==true) {
			$resultDatas['success'] = true;
			$resultDatas['notification'] = $getResponse->notification;
			$resultDatas['userName'] = $_POST['userEmail'];
			$resultDatas['buyMore'] = $this->textOptimizerBuyMoreLink.'?api_key='.base64_encode($getResponse->api_key);
			$datas = $this->TextoptimizerEncryption(array('success'=>true, 'userName'=>$_POST['userEmail'], 'userPassword'=>$_POST['userPassword'], 'apiKey'=>$getResponse->api_key));
			setcookie('TextoptimizerUserSession', $datas, time()+86400*30);
		} else {
			$resultDatas['success'] = false;
			$resultDatas['notification'] = $getResponse->notification;
			$resultDatas['errors'] = explode(",", $getResponse->error);
			$datas = $this->TextoptimizerEncryption(array('success'=>false, 'userName'=>'', 'password'=>'', 'apiKey'=>null));
		}
		echo json_encode($resultDatas); exit;
	}

	/** Textoptimizer For Logout User.
	*	@$url argument
	*	@return $results in JSON format
	**/
	public function TextoptimizerLogoutUser() {
		$resultDatas = array();	
		$resultDatas['success'] = true;
		$datas = $this->TextoptimizerEncryption(array('success'=>false, 'userName'=>'', 'password'=>'', 'apiKey'=>null));
		$this->TextOptimizerResetUser(); // reset user
		echo json_encode($resultDatas); exit;
	}

	public function TextOptimizerResetUser() {
		unset($_COOKIE['TextoptimizerUserSession']); setcookie('TextoptimizerUserSession', null, -1);
		return true;
	}

	/** Textoptimizer check user login or not 
	*	@no-arguments
	*	@retrun login user datas array formate
	*/
	public function TextoptimizerGetUserDetails(){
		if(isset($_COOKIE["TextoptimizerUserSession"]) && $_COOKIE["TextoptimizerUserSession"]!='') :
			return $this->TextoptimizerDecryption($_COOKIE["TextoptimizerUserSession"]);
		else :
			return false;
		endif;
	}

	/** For Get Response From Curl Using API.
	*	@$url argument
	*	@return $results in JSON format
	**/
	public function TextoptimizerAPICall($curlFields, $method='postdata', $url){		
		$postdatastring = http_build_query($curlFields);
		if($method=='getdata') :
			$url = $url.'?'.$postdatastring;
		endif;
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HEADER, false);
		
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
		curl_setopt($ch, CURLOPT_TIMEOUT_MS, 10000); //10000		
		if($method=='getdata') {
			curl_setopt($ch, CURLOPT_HTTPGET, 1);
		} else {
			curl_setopt($ch, CURLOPT_POST, count($postdatastring));
			curl_setopt($ch, CURLOPT_POSTFIELDS, $postdatastring);
		}
		$serverResponse = curl_exec($ch);
		$httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		$curlErrNo = curl_errno($ch);

		if($httpStatusCode >= 400 and $httpStatusCode < 500 ) {
			$errorCode = $httpStatusCode; $errorMessage = '';
		} else if($curlErrNo==28){
			$errorCode = $curlErrNo;
			$errorMessage = __('Server did not responded in a timely fashion. Please try again', 'textoptimizer');
		} else {
			$errorCode = 0; $errorMessage = '';
		}
		if($errorCode!=0) {
			$serverTimeOut['status']	= $errorCode;
			$serverTimeOut['error']		= $errorMessage;
			$serverResponse = json_encode((object)$serverTimeOut);
		}
		curl_close ($ch);
		return $serverResponse;
	}

	public function TextoptimizerLimitText($wordArray, $limit) {
		if(is_array($wordArray)) :
			if(count($wordArray)>$limit) {
				$limitedArray = array_slice($wordArray, 0, $limit, true);
				$wordString = implode(", ",$limitedArray).'...';
			} else {
				$limitedArray = $wordArray;
				$wordString = implode(", ", $limitedArray);
			}
			return $wordString;
		endif;
		return false;
	}

	public function TextoptimizerCheckProtocol() {
		$siteUrl = site_url();
		$protocol = current(explode('//', $siteUrl));
		if($protocol=='https:') : return true;
		else : return false; endif;
	}

	/** Textoptimizer encryption settings datas
	*   @access for relative the family
	*   @one argument datas is array formate $originalDatas
	*   @return Encryption data string result.
	*   call for the Textoptimizer any datas encryption formate using serialize & base64_encode
	*   first of array data convert to serialize string after then this string encryption using base64_encode
	**/
    public function TextoptimizerEncryption($originalDatas) {
        return base64_encode(serialize($originalDatas));
    }

    /** Textoptimizer decryption settings datas
	*   @access for relative the family
	*   @one argument datas is encrypted formate string $encryptionDatas
	*   @return Decryption data array result.
	*   call for the Textoptimizer any original datas encryption formate using base64_decode & unserialize
	*   first of encrypted string data convert to decoding using base64_decode string after then this string encryption using base64_decode
	**/
    public function TextoptimizerDecryption($encryptionDatas) {
        return unserialize(base64_decode($encryptionDatas));
    }
}
/* Create Textoptimizer Class Object */
$textoptimizer = new Textoptimizer();
?>