<?php 
function ayi_get_image_type($file) {
     if (!$f = @fopen($file, 'rb')) {
         return false;
     }
 
     $data = fread($f, 8);
     fclose($f);
 
     if (
         @array_pop(unpack('H12', $data)) == '474946383961' ||
         @array_pop(unpack('H12', $data)) == '474946383761'
     ) {
         return 'GIF';
     } else if (
         @array_pop(unpack('H4', $data)) == 'ffd8'
     ) {
         return 'JPEG';
     } else if (
         @array_pop(unpack('H16', $data)) == '89504e470d0a1a0a'
     ) {
         return 'PNG';
     } 
 
     return false;
 }
 
 
 
 
function ayi_set_featured_image( $post_id, $image_url ){
		require_once(ABSPATH . "wp-admin" . '/includes/image.php');
		require_once(ABSPATH . "wp-admin" . '/includes/file.php');
		require_once(ABSPATH . "wp-admin" . '/includes/media.php');
		
		$upload_dir = wp_upload_dir();
		$image_data = file_get_contents($image_url);
		$filename = basename($image_url);
		
		$filename_ar = explode('.', $filename);
		$filename = '_'.md5( rand(1, 10000).rand(1, 10000) ).sanitize_file_name( $filename_ar[0] ).'.'.$filename_ar[1];
		if(wp_mkdir_p($upload_dir['path']))
			$file = $upload_dir['path'] . '/' . $filename;
		else
			$file = $upload_dir['basedir'] . '/' . $filename;
		file_put_contents($file, $image_data);

		$wp_filetype = wp_check_filetype($filename, null );
		$attachment = array(
			'post_mime_type' => $wp_filetype['type'],
			'post_title' => sanitize_file_name($filename),
			'post_content' => '',
			'post_status' => 'inherit'
		);
		$attach_id = wp_insert_attachment( $attachment, $file, $post_id );
		require_once(ABSPATH . 'wp-admin/includes/image.php');
		$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
		wp_update_attachment_metadata( $attach_id, $attach_data );

		set_post_thumbnail( $post_id, $attach_id );
	
}

function ayi_get_back_object( $keyword = null ){

	$config = get_option('ayi_options'); 
	
	$public_key = $config['access_key'];
	$private_key = $config['secret_key'];
	
	for($i=0; $i<=5; $i++){
		$params = array();

		$host = "webservices.amazon.".$config['country']; 
		$uri = "/onca/xml";
		
		##################################
		$params["Service"] = "AWSECommerceService";
		$params["Operation"] = "ItemSearch";
		$params["Version"] ="2011-08-01";
		$params["AWSAccessKeyId"] = $public_key;
		$params["AssociateTag"] = $config['tracking_id'];
		$params["ResponseGroup"] = "Medium,Offers";
		$params["SearchIndex"] = "All";
		$params["Keywords"] = $keyword;
		$params["Timestamp"] = gmdate("Y-m-d\TH:i:s\Z");
		$params["ItemPage"] = $i;
		$method = "GET"; 
		##########################################
		
		ksort($params);
		$canonicalized_query = array();
		foreach ($params as $param=>$value)
		{
			$param = str_replace("%7E", "~", rawurlencode($param));
			$value = str_replace("%7E", "~", rawurlencode($value));
			$canonicalized_query[] = $param."=".$value;
		}
		

		$canonicalized_query = implode("&", $canonicalized_query);
		$string_to_sign = $method."\n".$host."\n".$uri."\n".$canonicalized_query;

		$signature = base64_encode(hash_hmac("sha256", $string_to_sign, $private_key, True));
		$signature = str_replace("%7E", "~", rawurlencode($signature));
		$request = "http://".$host.$uri."?".$canonicalized_query."&Signature=".$signature;

		#var_dump( $request );
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$request);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_TIMEOUT, 60);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

		$response = curl_exec($ch);
		$res[] = simplexml_load_string($response);
	}
	
    return $res;
	
}



function ayi_check_api(){
	$config = get_option('ayi_options'); 
	if( $config['access_key'] != ''   ){
		$pxml_arr = ayi_get_back_object( null );
	
		if( $pxml_arr[0]->Error ){ 
		$out .= '
			<div class="control-group err_msg">  
            <label class="control-label" for="optionsCheckbox">&nbsp;</label>  
            <div class="controls">  
              <div class="alert alert-error">  
				  '.$pxml_arr[0]->Error->Message.' 				
				</div>   
            </div>  
          </div>';
	
		}else{ 
			$out .= '
			<div class="control-group err_msg">  
            <label class="control-label" for="optionsCheckbox">&nbsp;</label>  
            <div class="controls">  
              <div class="alert alert-success">  				   
				  Your API key is valid
				</div>   
            </div>  
          </div>';		
		}
	}
	return $out;
}

function ayi_api_curl_post($url, $data, &$info){

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, ayi_api_curl_postData($data));
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_REFERER, $url);
  $html = trim(curl_exec($ch));
  curl_close($ch);

  return $html;
}

function ayi_api_curl_postData($data){

  $fdata = "";
  foreach($data as $key => $val){
    $fdata .= "$key=" . urlencode($val) . "&";
  }

  return $fdata;

}

function ayi_api_get_spinned_text( $in_text ){
	$config = get_option('ayi_options'); 
	$result = array();
	

	
			if( $config['use_spinner'] == 'sr' ){
				set_time_limit(150);

				$data = array();
				
				// Spin Rewriter API settings - authentication:
				$data['email_address'] = $config['sr_login'];				// your Spin Rewriter email address goes here
				$data['api_key'] = $config['sr_pass'];		// your unique Spin Rewriter API key goes here
				
				// Spin Rewriter API settings - request details:
				$data['action'] = "unique_variation";						// possible values: 'api_quota', 'text_with_spintax', 'unique_variation', 'unique_variation_from_spintax'
				$data['text'] =  $in_text;
				$data['protected_terms'] = "";		// protected terms: John, Douglas Adams, then
				$data['auto_protected_terms'] = "false";					// possible values: 'false' (default value), 'true'
				$data['confidence_level'] = "high";							// possible values: 'low', 'medium' (default value), 'high'
				$data['auto_sentences'] = "false";							// possible values: 'false' (default value), 'true'
				$data['auto_paragraphs'] = "false";							// possible values: 'false' (default value), 'true'
				$data['auto_new_paragraphs'] = "false";						// possible values: 'false' (default value), 'true'
				$data['auto_sentence_trees'] = "false";						// possible values: 'false' (default value), 'true'
				$data['use_only_synonyms'] = "false";						// possible values: 'false' (default value), 'true'
				$data['reorder_paragraphs'] = "false";						// possible values: 'false' (default value), 'true'
				$data['nested_spintax'] = "true";							// possible values: 'false' (default value), 'true'
				
				



				// Don't change anything below this comment.
				
				// Make the actual API request and save the JSON response.
				$api_response = ayi_api_spinrewriter_api_post($data);
				
			
				// Output interpreted JSON response (as a native PHP array).
				$api_response_interpreted = json_decode( $api_response, true);
			
				//var_dump( $api_response_interpreted );
				
				if( $api_response_interpreted['status'] == 'OK' ){
					$result['success'] = true;
					$result['text'] = $api_response_interpreted['response'];			  
					$result['msg'] = 'Spinned via Spin Rewriter';	
				}else{
					$result['success'] = false;
					$result['msg'] = 'Spin Rewriter Error: '.$api_response_interpreted['response'];
				}
			
				
			}
	
	if( $config['use_spinner'] == 'bs' ){
		$url = 'http://thebestspinner.com/api.php';

		#$testmethod = 'identifySynonyms';
		$testmethod = 'rewriteText';


		# Build the data array for authenticating.

		$data = array();
		$data['action'] = 'authenticate';
		$data['format'] = 'php'; # You can also specify 'xml' as the format.

		# The user credentials should change for each UAW user with a TBS account.

		$data['username'] = $config['bs_login'];
		$data['password'] = $config['bs_pass'];

		# Authenticate and get back the session id.
		# You only need to authenticate once per session.
		# A session is good for 24 hours.
		$output = unserialize(ayi_api_curl_post($url, $data, $info));

		if($output['success']=='true'){
		  # Success.
		  $session = $output['session'];
		  
		  # Build the data array for the example.
		  $data = array();
		  $data['session'] = $session;
		  $data['format'] = 'php'; # You can also specify 'xml' as the format.
		  $data['text'] = $in_text;
		  $data['action'] = $testmethod;
		  $data['maxsyns'] = '3'; # The number of synonyms per term.
		  
		  if($testmethod=='replaceEveryonesFavorites'){
			# Add a quality score for this method.
			$data['quality'] = '1';
		  }

		  # Post to API and get back results.
		  $output = ayi_api_curl_post($url, $data, $info);
		  $output = unserialize($output);
		  
		  

			  $result['success'] = true;
			  $result['text'] = $output['output'];			  
			  $result['msg'] = 'Spinned via BestSpinner';	

		  /*
		  # Show results.
		  echo "<p><b>Method:</b><br>$testmethod</p>";
		  echo "<p><b>Text:</b><br>$data[text]</p>";
		  
		  $data['action'] = 'apiQuota';
		  $quota = ape_api_curl_post($url, $data, $info);
		  $quota = unserialize($quota);
		  
		  if($output['success']=='true'){
			echo "<p><b>Output:</b><br>" . str_replace("\r", "<br>", $output['output']) . "</p><p>Remaining quota: $quota[output]</p>";
		  }
		  else{
			echo "<p><b>Error:</b><br>$output[error]</p>";
		  }
		  */
		}
		else{
		  # There were errors.
		  //echo "<p><b>Error:</b><br>$output[error]</p>";
			$result['success'] = false;
			$result['msg'] = 'BestSpin Error: '.$output['error'];
		}
	}
	
	if( $config['use_spinner'] == 'sb' ){
		$result = array();
		$url = 'http://spinnerbros.com/api/turningarticlev2';

	 
		$data = array(
			'quality' => 5,
			'apikey' => $config['sb_token'],
			'originaltext' => $in_text
		);
	 
		$output = wp_Remote_post(
			$url, 
			array(
				'timeout'     => 45,
				'body' => $data
			)

		); 
		
 
		if( !is_wp_error( $output )  ){
		  # Success.
		 
		 	if( wp_remote_retrieve_response_code($output) == '200'  ){

				$resp = wp_remote_retrieve_body( $output );
				$resp = json_decode( $resp );
			 
				if( $resp->status == 'success' ){
					$result['success'] = true;
					$result['text'] = $resp->uniqearticle;			  
					$result['msg'] = 'Spinned via Spinner Bros';
				}else{
					$result['success'] = false;
					$result['msg'] = 'Spinner Bros Error: '.$resp->message;
				}
				

			 }else{
				$result['success'] = false;
				$result['msg'] = 'Spinner Bros Error: '.$output['error'];
			 }
		  
		  

			  	

	 
		}
		else{
 
			$result['success'] = false;
			$result['msg'] = 'Spinner Bros Error: '.$output->get_error_message();
		}
	}


	return $result;
}

function ayi_get_full_descr( $video_id, $default_content ){
	$config = get_option('ayi_options'); 
	$res = wp_remote_get( 'https://www.googleapis.com/youtube/v3/videos?part=snippet&id='.$video_id.'&key='.$config['youtube_api_key'] );
	if( !is_wp_error( $res ) ){
		$content = json_decode( $res['body'], true );
		$content = $content['items'][0]['snippet']['description'];
		return $content;
	}else{
		return $default_content;
	}
	
}

function ayi_api_spinrewriter_api_post($data){
		$data_raw = "";
		foreach ($data as $key => $value){
			$data_raw = $data_raw . $key . "=" . urlencode($value) . "&";
		}
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, "http://www.spinrewriter.com/action/api");
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data_raw);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$response = trim(curl_exec($ch));
		curl_close($ch);
		return $response;
	}



 

	
	function wyi_run_import(){
		global $wpdb;
		
		set_time_limit(0);
		
		$config = get_option( 'ayi_options'); 
 

		$values_tmp_channel = (array)$config['channel_id']; 
		$values_tmp_cat = (array)$config['import_cat'];
		
		$out_arr_ids = array();
		for( $i=1; $i < count($values_tmp_cat); $i++ ){
			$out_arr_ids[] = array( 'id' => $values_tmp_channel[$i], 'cat' => $values_tmp_cat[$i] );
		}
		 
		//if( trim( $config['channel_id'] ) == '' || count( $all_ids ) == 0 ){ return false; }

		 

		if( count($out_arr_ids) > 0 ){
			foreach( $out_arr_ids as $single_chanel ){
			 
				$url = 'https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=50&channelId='.$single_chanel['id'].'&key='.$config['youtube_api_key'].'';
				$response = wp_remote_get( $url  );
			 
				if( !is_wp_error( $response ) ){
					
					if( wp_remote_retrieve_response_code( $response ) == 200 ){
						
						
						
						$body = json_decode( wp_remote_retrieve_body( $response )  );
						
						// get total pages
						$total_items = $body->pageInfo->totalResults;
			
						if( $body->nextPageToken ){
							$next_page_token = $body->nextPageToken;
						}else{
							$next_page_token = null;
						}

						//calc pages num
						if( $total_items % 50 == 0 ){
							$pages =  $total_items / 50;
						}else{
							$pages =  (int)( $total_items / 50 ) + 1;
						}
							

						for( $i=1; $i<=$pages; $i++ ){
						
							if( $next_page_token ){
								$string_prefix = '&pageToken='.$next_page_token;
							}else{
								$string_prefix = '';
							}

							// pagi patch
							$string_prefix = '';
							 
							$url = 'https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=50&channelId='.$single_chanel['id'].'&key='.$config['youtube_api_key'].''.$string_prefix;
							
							 
	
							$videos = wp_remote_get( $url  );
							;
							
							
							if( wp_remote_retrieve_response_code( $videos ) == 200 ){
								$video_list = json_decode( wp_remote_retrieve_body( $videos )  );
								//var_dump( $video_list );
								if( $video_list->nextPageToken ){
									$next_page_token = $video_list->nextPageToken;
								}else{
									$next_page_token = null;
								}
								
							 
							 
								// process posts
								foreach( $video_list->items as $single_item ){
									 
								
									$video_id = $single_item->id->videoId;
									
									if( !$video_id ){ continue; }
						
									$processed_ids[] = $video_id;
									$single_line = $video_id;
								
									$video_title = $single_item->snippet->title;
									$video_description = $single_item->snippet->description;
									$video_date = $single_item->snippet->publishedAt;
									$video_image = $single_item->snippet->thumbnails->high->url;
									 
									 
									

									// check if pos exists
									$args = array(
										'post_type' => 'post',
										'post_status' => 'any',
										'meta_query' => array(
											array(
												'key' => 'youtube_id',
												'value' => $video_id
											)
										)

									);
									$all_posts = get_posts( $args );
								 
									if( count($all_posts) > 0 ){ continue; }
									// process posts 
									#############


									$post_stat = 'publish';
									
						
									
									$video_player = '<div class="video_block"><iframe  src="//www.youtube.com/embed/'.$single_line.'" frameborder="0" allowfullscreen></iframe></div>';
									if( $config['add_descr'] == 'yes' ){
										
										
										// spinning
										
										// remote get content
										
										$vide_content = ayi_get_full_descr( $single_line, $video_description );

								
										if( $config['use_spinner'] == 'bs' || $config['use_spinner'] == 'sr' || $config['use_spinner'] == 'sb' ){
											$result = ayi_api_get_spinned_text( $vide_content );
											if( $result['success'] == true ){
												$vide_content = $result['text'];
												$spin_msg = '<div class="tw-bs">
													<div class="alert alert-success">  
													  '.$result['msg'].' 
													</div>  
												</div>';
											}else{
												$vide_content = $video_description;
												$spin_msg = '<div class="tw-bs">
												<div class="alert alert-danger">  
													   '.$result['msg'].'
													</div>  
												</div>';;
											}
											//echo $spin_msg;
											
										}
										
										
										if( strlen( $config['descr_limit'] ) > 0 ){
											$vide_content = substr($vide_content, 0, (int)$config['descr_limit'] );
										}
							
										$cntnt2use = $video_player.'<!-- social_share --> <!-- ads_place --> <div class="post_content_bl">'.$vide_content.'</div>';
									}
									
									// automaticaly add products
									
									if( $config['add_auto_prod'] == 'yes' ){
										$modifiers = array( 'best', 'top', 'cheap', 'discount', 'buy', 'purchase', 'get', 'compare', 'good', 'premium', 'cool', 'greatest', 'finest', 'perfect' );
									
								
										$out_arr = ayi_get_product_action( $modifiers[rand(0, count($modifiers)-1)].' '.get_option('latest_search') );
										
										
										if( $config['content_order'] == 'vda' || $config['content_order'] == '' ){
											$cntnt2use = $cntnt2use.'<div class="prod_block">'.$out_arr.'</div>';
										}
										if( $config['content_order'] == 'vad' ){
											$cntnt2use = str_replace( '<!-- ads_place -->', '<div class="prod_block">'.$out_arr.'</div>', $cntnt2use );
										}
										
										
									}
									
						
									$my_post = array(
									  'post_title'    => $video_title,
									  'post_content'  => $cntnt2use,
									  'post_status'   => $post_stat,
									  'post_type' => 'post',
									  'post_author'   => 1,
									  'post_category' => ( $single_chanel['cat'] && $single_chanel['cat'] != '-1' ? array( $single_chanel['cat']  ) : array() )
									);
									 
									/*
									if( $_POST['post_date'][$single_line] != '' ) {				
										$post_future_date = date( 'Y-m-d H:i:s' , strtotime( $_POST['post_date'][$single_line] ) );
										$my_post['post_date'] = $post_future_date;
										$my_post['post_date_gmt'] = $post_future_date;
									}
									*/
							
									// Insert the post into the database		
									$new_id = wp_insert_post( $my_post );
									update_post_meta( $new_id, 'youtube_id', $single_line );
									update_post_meta( $new_id, 'youtube_descr', $video_description  );
									
									ayi_set_featured_image( $new_id,   $video_image  );
									
									
									// posting to OnlyWire
									if( $config['use_ow'] == 'yes' ){
										$ch = curl_init();
						
										$url = urlencode( get_permalink($new_id) );
										$title = urlencode( $video_title );
										$comments = urlencode( $video_title );
										$tags = urlencode("");
										//$servicelogins = urlencode("my-facebook,my-folkd,my-bibsonomy");
						
										$username= $config['ow_login'];
										$password= $config['ow_pass'];
						
										$params = "url={$url}&title={$title}&tags={$tags}&comments={$comments}";
										//&service_logins={$servicelogins}&schedule_date=2013-01-01 12:59:59
						
										$query = "https://www.onlywire.com/api/add?{$params}";
										curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
										curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
										curl_setopt($ch, CURLOPT_URL, $query);
										curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
										curl_setopt($ch, CURLOPT_USERPWD, $username.":".$password);
						
										$output = curl_exec($ch);
						
										curl_close ($ch);
						
									
										
									}
									
									
									
									#############
								
								}
								
							
							}else{
								$is_dump_error = 1;
							}
							
							
						}
					}else{
						$is_dump_error = 1;
					} 
				}else{
					$is_dump_error = 1;
				}
			}
		}
		 
	}

?>