<?php
/**
 * Created by mr2app.
 * User: Hani
 * Date: 3/19/2019
 * Time: 11:04 AM
 */

class woo2app_authentication extends WC_REST_Authentication {

	private $consumer_secret = '';
	private $consumer_key = '';
	private $consumer_enable = true;
	public function __construct() {
		$authentication = get_option('woo2app_authentication');
		if(isset($authentication['enable'])){
			$this->consumer_key = $authentication['consumer_key'];
			$this->consumer_secret = $authentication['consumer_secret'];
		}
		else{
			$this->consumer_enable = false;
		}
	}

	public function check_oauth_signature() {

		if($this->consumer_enable == false) return true;

		$params = $this->get_oauth_parameters();
		if($params['oauth_consumer_key'] != $this->consumer_key ){
			return false;
		}
		$consumer_secret = $this->consumer_secret;
		$http_method  = isset( $_SERVER['REQUEST_METHOD'] ) ? strtoupper( $_SERVER['REQUEST_METHOD'] ) : ''; // WPCS: sanitization ok.
		$request_path = isset( $_SERVER['REQUEST_URI'] ) ? wp_parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH ) : ''; // WPCS: sanitization ok.
		$wp_base      = get_home_url( null, '/', 'relative' );
		if ( substr( $request_path, 0, strlen( $wp_base ) ) === $wp_base ) {
			$request_path = substr( $request_path, strlen( $wp_base ) );
		}
		$base_request_uri = rawurlencode( get_home_url( null, $request_path, is_ssl() ? 'https' : 'http' ) );

		// Get the signature provided by the consumer and remove it from the parameters prior to checking the signature.
		$consumer_signature = rawurldecode( str_replace( ' ', '+', $params['oauth_signature'] ) );
		unset( $params['oauth_signature'] );

		// Sort parameters.
		if ( ! uksort( $params, 'strcmp' ) ) {
			return new WP_Error( 'woocommerce_rest_authentication_error', __( 'Invalid signature - failed to sort parameters.', 'woocommerce' ), array( 'status' => 401 ) );
		}

		// Normalize parameter key/values.
		//return $params;
		$params         = $this->normalize_parameters( $params );
		$query_string   = implode( '%26', $this->join_with_equals_sign( $params ) ); // Join with ampersand.
		$string_to_sign = $http_method . '&' . $base_request_uri . '&' . $query_string;

		if ( 'HMAC-SHA1' !== $params['oauth_signature_method'] && 'HMAC-SHA256' !== $params['oauth_signature_method'] ) {
			return new WP_Error( 'woocommerce_rest_authentication_error', __( 'Invalid signature - signature method is invalid.', 'woocommerce' ), array( 'status' => 401 ) );
		}

		$hash_algorithm = strtolower( str_replace( 'HMAC-', '', $params['oauth_signature_method'] ) );
		$secret         = $consumer_secret . '&';
		$signature      = base64_encode( hash_hmac( $hash_algorithm, $string_to_sign, $secret, true ) );
//		return array(
//			$consumer_signature,
//			$signature ,
//			$params,
//			$string_to_sign,
//			$wp_base
//			//$_SERVER['REQUEST_URI'],
//
//		);
		if ( ! hash_equals( $signature, $consumer_signature ) ) { // @codingStandardsIgnoreLine
			return new WP_Error( 'woocommerce_rest_authentication_error', __( 'Invalid signature - provided signature does not match.', 'woocommerce' ), array( 'status' => 401 ) );
		}

		return true;
	}
	private function normalize_parameters( $parameters ) {
		$keys       = wc_rest_urlencode_rfc3986( array_keys( $parameters ) );
		$values     = wc_rest_urlencode_rfc3986( array_values( $parameters ) );
		$parameters = array_combine( $keys, $values );

		return $parameters;
	}
	private function join_with_equals_sign( $params, $query_params = array(), $key = '' ) {
		foreach ( $params as $param_key => $param_value ) {
			//if($param_key == 'woocats') continue;
			if ( $key ) {
				$param_key = $key . '%5B' . $param_key . '%5D'; // Handle multi-dimensional array.
			}

			if ( is_array( $param_value ) ) {
				$query_params = $this->join_with_equals_sign( $param_value, $query_params, $param_key );
			} else {
				$string         = $param_key . '=' . $param_value; // Join with equals sign.
				if($param_value == '') $string = $param_key;
				$query_params[] = wc_rest_urlencode_rfc3986( $string );
			}
		}

		return $query_params;
	}
//	public function get_oauth_parameters() {
//		$params = array_merge( $_GET, $_POST ); // WPCS: CSRF ok.
//		$params = wp_unslash( $params );
//		$header = $this->get_authorization_header();
//
//		if ( ! empty( $header ) ) {
//			// Trim leading spaces.
//			$header        = trim( $header );
//			$header_params = $this->parse_header( $header );
//
//			if ( ! empty( $header_params ) ) {
//				$params = array_merge( $params, $header_params );
//			}
//		}
//
//		$param_names = array(
//			'oauth_consumer_key',
//			'oauth_timestamp',
//			'oauth_nonce',
//			'oauth_signature',
//			'oauth_signature_method',
//		);
//
//		$errors   = array();
//		$have_one = false;
//
//		// Check for required OAuth parameters.
//		foreach ( $param_names as $param_name ) {
//			if ( empty( $params[ $param_name ] ) ) {
//				$errors[] = $param_name;
//			} else {
//				$have_one = true;
//			}
//		}
//
//		// All keys are missing, so we're probably not even trying to use OAuth.
//		if ( ! $have_one ) {
//			return array();
//		}
//
//		// If we have at least one supplied piece of data, and we have an error,
//		// then it's a failed authentication.
//		if ( ! empty( $errors ) ) {
//			$message = sprintf(
//			/* translators: %s: amount of errors */
//				_n( 'Missing OAuth parameter %s', 'Missing OAuth parameters %s', count( $errors ), 'woocommerce' ),
//				implode( ', ', $errors )
//			);
//
//			$this->set_error( new WP_Error( 'woocommerce_rest_authentication_missing_parameter', $message, array( 'status' => 401 ) ) );
//
//			return array();
//		}
//
//		return $params;
//	}
//	public function parse_header( $header ) {
//		if ( 'OAuth ' !== substr( $header, 0, 6 ) ) {
//			return array();
//		}
//
//		// From OAuth PHP library, used under MIT license.
//		$params = array();
//		if ( preg_match_all( '/(oauth_[a-z_-]*)=(:?"([^"]*)"|([^,]*))/', $header, $matches ) ) {
//			foreach ( $matches[1] as $i => $h ) {
//				$params[ $h ] = urldecode( empty( $matches[3][ $i ] ) ? $matches[4][ $i ] : $matches[3][ $i ] );
//			}
//			if ( isset( $params['realm'] ) ) {
//				unset( $params['realm'] );
//			}
//		}
//
//		return $params;
//	}
//	public function get_authorization_header() {
//		if ( ! empty( $_SERVER['HTTP_AUTHORIZATION'] ) ) {
//			return wp_unslash( $_SERVER['HTTP_AUTHORIZATION'] ); // WPCS: sanitization ok.
//		}
//
//		if ( function_exists( 'getallheaders' ) ) {
//			$headers = getallheaders();
//			// Check for the authoization header case-insensitively.
//			foreach ( $headers as $key => $value ) {
//				if ( 'authorization' === strtolower( $key ) ) {
//					return $value;
//				}
//			}
//		}
//
//		return '';
//	}
}
