<?php
/*
 * @package lh_fap
 */
/**
 * The importer class that handles the sideloading of the images from the api endpoint.
 */
class LH_Fap_Import {
	private $_apiUrl = "http://www.free-images.cc/wp-json";
	/**
	 * The constructor of this class.
	 *
	 * @access public
	 * @return void
	 */
	public function __construct(){
		$this->action_dispatcher();
		$this->filter_dispatcher();
	}
	/**
	 * The function that dispatches all used actions by this class.
	 *
	 * @access private
	 * @return void
	 */
	private function action_dispatcher(){
		add_action('wp_ajax_import_image', 		array( $this, 'import_image' ) );
		add_action('wp_ajax_list_images', 		array( $this, 'list_images' ) );
	}
	/**
	 * The function that dispatches all used filters by this class.
	 *
	 * @access private
	 * @return void
	 */
	private function filter_dispatcher(){
	}
	/**
	 * The ajax call, that actually imports the image.
	 *
	 * @access public
	 * @return void
	 */
	public function import_image(){
		$image_id = isset($_GET['image_id']) ? intval($_REQUEST['image_id']) : null;
		$post_id = isset($_GET['post_id']) ? intval($_REQUEST['post_id']) : null;
		$response = array(
			"error"	=> true,
			"msg"	=> __("An unknown error occured!", "lhf"),
		);
		// If the current user cannot upload files, die with an error message
		if(!current_user_can("upload_files")){
			http_response_code(401);
			$response['msg'] = __("I'm sorry Dave, I'm afraid I can't do that. (Insufficient permissions!)", "lhf");
			$this->json_response($response);
			die();
		}
		if(!$image_id){
			http_response_code(401);
			$this->json_response($response);
			die();
		}
		if($image_id){
			// Check if we already have an image with that FAP ID in the database
			$qry = new WP_Query(array(
				"post_type"		=> 'attachment',
				'post_status' 	=> 'any',
				"meta_query"	=> array(
					array(
						"key"	=> '_fap_id',
						"value"	=> $image_id,
					),
				),
			));
			// If that query returns any results, die with the error message, including
			if($qry->have_posts()){
				http_response_code(400);
				$response['msg'] = __("An image with that ID is already in the database!", "lhf");
				$response['attachment_id'] = $qry->posts[0]->ID;
				$this->json_response($response);
				die();
			}
			// Download the data from the api
			$json_data = $this->curl_download($this->_apiUrl . "/image/" . $image_id . "/");
			if($json_data['header']['http_code'] !== 200){
				http_response_code($json_data['header']['http_code']);
				$response['msg'] = __("An image with that ID could not be retrieved!", "lhf");
				$this->json_response($response);
				die();
			}
			// At this point we should have working data from our API
			$body = json_decode($json_data['body']);
			$id = $this->add_to_library($body->data[0], $post_id);
			if($id){
				$response = array(
					"error"		=> false,
					"msg"		=> __("The image has been successfully added.", "lhf"),
					"image_id"	=> $id,
				);
			}
		}
		$this->json_response($response);
		die();
	}
	public function list_images(){
		$response = array(
			"success"	=> false,
		);
		$search_term = isset($_GET['s']) ? ($_REQUEST['s']) : null;
		$paged = isset($_GET['paged']) ? intval($_REQUEST['paged']) : null;
		$api_url = $this->_apiUrl . "/image/";
		$api_url = add_query_arg(array(
			"paged"		=> $paged,
			"s"			=> $search_term,
		), $api_url);
		$json_data = $this->curl_download($api_url);
		if($json_data){
			$response = json_decode($json_data['body']);
		}
		$this->json_response($response);
		die();
	}
	/**
	 * add_to_library function.
	 *
	 * @access private
	 * @param mixed $data
	 * @return void
	 */
	private function add_to_library($data, $post_id){
		if(isset($data->url) && !filter_var($data->url, FILTER_VALIDATE_URL) === false){
			// The download URL is legal
			$tmp = download_url( $data->url );
			if( is_wp_error( $tmp ) ){
				// download failed, handle error
			}
			$desc = $data->title;
			$file_array = array();
			// Set variables for storage
			// fix file filename for query strings
			preg_match('/[^\?]+\.(jpg|jpeg|gif|png)/i', $data->url, $matches);
			$file_array['name'] = basename($matches[0]);
			$file_array['tmp_name'] = $tmp;
			// If error storing temporarily, unlink
			if ( is_wp_error( $tmp ) ) {
				@unlink($file_array['tmp_name']);
				$file_array['tmp_name'] = '';
			}
			$post_data = array(
				'post_content'	=> sprintf(__("by %s via free-images.cc", "lhf"), $data->author),
			);
			// do the validation and storage stuff
			$id = media_handle_sideload( $file_array, $post_id, $desc, $post_data );
			// If error storing permanently, unlink
			if ( is_wp_error($id) ) {
				@unlink($file_array['tmp_name']);
				return $id;
			} else {
				$res = update_post_meta($id, '_fap_id', $data->id);
			}
			return $id;
		}
		return false;
	}
	/**
	 * Make sure we have a legal json response.
	 *
	 * @access private
	 * @param mixed $response
	 * @return void
	 */
	private  function json_response($response){
		header('Content-Type: application/json');
		echo json_encode($response);
	}
	/**
	 * Handle the downloading of the url.
	 *
	 * @access private
	 * @param mixed $url
	 * @return void
	 */
	private function curl_download($url){
	    // is cURL installed yet?
	    if (!function_exists('curl_init')){
	        die('Sorry cURL is not installed!');
	    }
	    // OK cool - then let's create a new cURL resource handle
	    $ch = curl_init();
	    // Now set some options (most are optional)
	    // Set URL to download
	    curl_setopt($ch, CURLOPT_URL, $url);
	    // Set a referer
	    curl_setopt($ch, CURLOPT_REFERER, get_bloginfo("url"));
	    // User agent
	    curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");
	    // Include header in result? (0 = yes, 1 = no)
	    curl_setopt($ch, CURLOPT_HEADER, 0);
	    // Should cURL return or print out the data? (true = return, false = print)
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	    // Timeout in seconds
	    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
	    // Download the given URL, and return output
	    $output = curl_exec($ch);
		// Get the connection info
		$info = curl_getinfo($ch);
	    // Close the cURL resource, and free system resources
	    curl_close($ch);
	    return array(
	    	"body"		=> $output,
	    	"header"	=> $info,
	    );
	}
	}