<?php
include_once (plugin_dir_path( __FILE__ ).'simple_html_dom.php');
	class Affi_aliexpress {
		function __construct()
		{
			global $wpdb;
		}

		public static function get_products($keyword='',$acategory='',$aCountry='',$page='',$per_page= '',$info=array())
		{
			$TrackingId = '';	
			$request    = '';
			$appKey     = '29109';
			if ($appKey != '') {
				$page = (isset($page) && !empty($page) && intval($page) > 0)?$page:1;
				$per_page = (isset($per_page) && !empty($per_page) && intval($per_page) > 0)?$per_page:12;
				
				$filter = $info;

				$filter['keyword'] = (isset($keyword)) ? urlencode(utf8_encode($keyword)) : "";
				$filter['productId'] = (isset($filter['ab_sku']))?$filter['ab_sku']:"";
				$filter['category_id'] = (isset($acategory) && $acategory) ? $acategory : "";


				$result = array("total" => 0, "per_page" => $per_page, "items" => array(), "error" => "");
				if ((isset($filter['productId']) && !empty($filter['productId'])) || (isset($filter['keyword']) && !empty($filter['keyword'])) || (isset($filter['category_id']) && $filter['category_id'] != 0)) {
					$single_product_id = (isset($filter['productId']) && $filter['productId']) ? $filter['productId'] : "";
					$query = (isset($filter['keyword'])) ? urlencode(utf8_encode($filter['keyword'])) : "";
					$category_id = (isset($filter['category_id']) && $filter['category_id']) ? $filter['category_id'] : "";
					$sortby = (isset($filter['sortby']) && $filter['sortby']) ? $filter['sortby'] : "sellerRateDown";
					$link_category_id = (isset($filter['link_category_id']) && IntVal($filter['link_category_id'])) ? IntVal($filter['link_category_id']) : 0;
					
					$priceFrom = (isset($info['ab_minprice']) && !empty($info['ab_minprice']) && floatval($info['ab_minprice']) > 0.009) ? "&originalPriceFrom=".$info['ab_minprice']: '';
					$priceTo   = (isset($info['ab_maxprice']) && !empty($info['ab_maxprice']) && floatval($info['ab_maxprice']) > 0.009) ? "&originalPriceTo=".$info['ab_maxprice'] : '';

					$commissionRateFrom = (isset($_GET['commission_rate_from']) && !empty($_GET['commission_rate_from']) && floatval($filter['commission_rate_from']) > 0.009) ? "&commissionRateFrom={$_GET['commission_rate_from']}" : '';
					$commissionRateTo = (isset($_GET['commission_rate_to']) && !empty($_GET['commission_rate_to']) && floatval($filter['commission_rate_to']) > 0.009) ? "&commissionRateTo={$_GET['commission_rate_to']}" : '';

					$volumeFrom = (isset($info['ab_orderfrom']) && !empty($info['ab_orderfrom']) && intval($info['ab_orderfrom']) > 0) ? "&volumeFrom=".$info['ab_orderfrom']:'';
					$volumeTo   = (isset($info['ab_orderto']) && !empty($info['ab_orderto']) && intval($info['ab_orderto']) > 0) ? "&volumeTo=".$info['ab_orderto']:'';

					$feedback_min = (isset($info['ab_scorefrom']) && intval($info['ab_scorefrom']) > 0) ? intval($info['ab_scorefrom']) : 0;
					$feedback_max = (isset($info['ab_scoreto']) && intval($info['ab_scoreto']) > 0) ? intval($info['ab_scoreto']) : 0;
					if ($feedback_max < $feedback_min) {
						$feedback_max = 0;
					}
					/*Custom code*/

					$feedback_max = $feedback_max * 2000;
					/*End of Custom code*/
					$startCredit = ($feedback_min) ? "&startCreditScore={$feedback_min}" : '';
					$endCredit = ($feedback_max) ? "&endCreditScore={$feedback_max}" : '';

					$request_sort = '';
					if(isset($sortby)){
						$request_sort = '&sort='.$sortby;		
					}

					$ab_curr = 'USD';
					$ab_lang = 'en';
					/* // <--------------------------- */

					if ($single_product_id) {
						/* // search by product id */
						$request_param = "http://gw.api.alibaba.com/openapi/param2/2/portals.open/api.getPromotionProductDetail/{$appKey}";
						$request_param .= "?fields=productId,productTitle,productUrl,imageUrl,originalPrice,salePrice,discount,evaluateScore,commission,commissionRate,30daysCommission,volume,packageType,lotNum,validTime,storeName,storeUrl,localPrice,allImageUrls";
						$request_param .= "&productId=$single_product_id";
						$request_param .= "&localCurrency=$ab_curr";
						$request_param .= "&language=$ab_lang"; 
						$request_sort = "";
					} else {
						/* // search by query and params */
						$request_url = "http://gw.api.alibaba.com/openapi/param2/2/portals.open/api.listPromotionProduct/{$appKey}";
						$request_param = "?fields=totalResults,productId,productTitle,productUrl,imageUrl,originalPrice,salePrice,discount,evaluateScore,commission,commissionRate,30daysCommission,volume,packageType,lotNum,validTime,localPrice,allImageUrls";

						$request_param .= "&categoryId={$category_id}&pageNo={$page}&keywords={$query}&pageSize={$per_page}";
						 
						$request_param .= $volumeFrom . $volumeTo . $priceFrom . $priceTo . $startCredit . $endCredit;
						$request_param .= "&localCurrency=$ab_curr";
						$request_param .= "&language=$ab_lang";
						$request_sort = "";
						$request_param .= '&highQualityItems=true';
					}
					
					/* echo"<pre>";print_r($request_url . $request_param . $request_sort);echo"</pre>"; */
					//return $request_url;
					$request = file_get_contents($request_url . $request_param . $request_sort);
					//return $request;
					/* echo"<pre>";print_r($request);echo"</pre>"; */
					if(empty($request)){
						if (!function_exists('curl_init')){ 
							die('CURL is not installed!');
						}
						$ch = curl_init();
						curl_setopt($ch, CURLOPT_URL, $request_url . $request_param . $request_sort);
						curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
						$request = curl_exec($ch);
						curl_close($ch);
					}					
					//echo"<pre>";print_r($request);echo"</pre>";
					$items = json_decode($request, true);

					if (isset($items['result']['products']) && !empty($items['result']['products'])) {
						$data = $items['result']['products'];
						foreach ($data as $k=>$item) {

							$item["CustomerReviews"]["IFrameURL"] = isset($item["CustomerReviews"]["IFrameURL"]) && $item["CustomerReviews"]["IFrameURL"] != ''  ? $item["CustomerReviews"]["IFrameURL"] : '';

							$goods = array(
								   'title'      =>strip_tags($item["productTitle"]),
								   'external_id'=>$item["productId"],
								   'image'      => (isset($item["imageUrl"])) ? $item["imageUrl"] : '',
								   'product_url'=>$item["productUrl"],
								   'orig_url'   =>$item["productUrl"],
								   'reviews'    =>'',
								   'rating'     =>$item["evaluateScore"],
								   'old_price'  =>round(self::get_normalize_price($item["originalPrice"]),2),
								   'tmp_price'  =>round(self::get_normalize_price($item["salePrice"]),2),
								   'currency'   =>getCurrencySymbol('USD'),
								   'Subtitle'=>''
							);	

							$data1[]=$goods;
							unset($product_data);
						}
	
						$result["total"] = IntVal($items['result']['totalResults']) > 10240 ? 10240 : $items['result']['totalResults'];
					}if ($error_code == 20010000 && empty($items['result']['products'])) {
						$result["error"] = 'There is no product to display!';
					} elseif ($error_code == 400) {
						$result["error"] = $items['error_message'];
					} elseif ($error_code == 20030000) {
						$result["error"] = 'Required parameters';
					} elseif ($error_code == 20030010) {
						$result["error"] = 'Keyword input parameter error';
					} elseif ($error_code == 20030020) {
						$result["error"] = 'Category ID input parameter error or formatting errors';
					} elseif ($error_code == 20030030) {
						$result["error"] = 'Commission rate input parameter error or formatting errors';
					} elseif ($error_code == 20030040) {
						$result["error"] = 'Unit input parameter error or formatting errors';
					} elseif ($error_code == 20030050) {
						$result["error"] = '30 days promotion amount input parameter error or formatting errors';
					} elseif ($error_code == 20030060) {
						$result["error"] = 'Tracking ID input parameter error or limited length';
					} elseif ($error_code == 20030070) {
						$result["error"] = 'Unauthorized transfer request';
					} elseif ($error_code == 20020000) {
						$result["error"] = 'System Error';
					} elseif ($error_code == 20030100) {
						$result["error"] = 'Error! Input parameter Product ID';
					}
				} else {
					$result["error"] = 'Please enter some search keywords or select item from category list!';
				}
				$total_row = 	$result["total"]/$per_page;	
				return $data1;
		}
		return '';
	}
		
		public static function get_affiliate_goods($goods_list=array()) {
		
		
		$single_url = isset($goods_list['productUrl']) && (!empty($goods_list['productUrl'])) ? $goods_list['productUrl'] :'';

		$TrackingId = '';	
        $appKey     = '29109';
			
			$result = $goods_list;
			$urls = "";
			//return $count;
			if(!empty($single_url)) {
				$result = $goods_list;
				$urls.=($urls ? "," : "") . $result['productUrl'];
				//return $urls;
			}
			else {
				foreach ($result as $goods) {
					$urls.=($urls ? "," : "") . $goods['productUrl'];
				}
			}
			
		//	return $urls;
			$request_url = "http://gw.api.alibaba.com/openapi/param2/2/portals.open/api.getPromotionLinks/{$appKey}?fields=&trackingId={$TrackingId}&urls={$urls}";
          //  return $request_url;
								$request = file_get_contents($request_url);
								if(empty($request)){
										if (!function_exists('curl_init')){ 
											die('CURL is not installed!');
										}
									$ch = curl_init();
									curl_setopt($ch, CURLOPT_URL, $request_url);
									curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
									$request = curl_exec($ch);
									curl_close($ch);
								}			
			if ($request) {
			$data  = json_decode($request, true);
				//return $data;
				if (isset($data['errorCode']) && $data['errorCode'] == 20010000) {

				
				
				
					if(!empty($single_url)){
						//foreach ($result as $key => $goods) {
						$new_promo_url = "";
						foreach ($data['result']['promotionUrls'] as $pu) {
							if ($pu[0]['url'] == $result[$key]['productUrl']) {
								$new_promo_url = $pu['promotionUrl'];
								break;
							}
						}
						if ($new_promo_url) {
							$result['productUrl'] = $new_promo_url;
						}
						$result['ordersCount'] = $ordercount;
						$result['noofvariations'] = $novariation;
						
					//}
					}
					else{
					foreach ($result as $key => $goods) {
						$new_promo_url = "";
						foreach ($data['result']['promotionUrls'] as $pu) {
							if ($pu['url'] == $result[$key]['productUrl']) {
								$new_promo_url = $pu['promotionUrl'];
								break;
							}
						}
						if ($new_promo_url) {
							$result[$key]['productUrl'] = $new_promo_url;
						}
						//$result[$key]['ordersCount'] = $ordercount;
						//$result[$key]['noofvariations'] = $novariation;

					}
				}
				
				
				
				} else 
					$result = '';   
            } 				
			
			
			
			return $result;
	}
	public static function get_normalize_price($price) {
            return (isset($price) && $price) ? sprintf("%01.2f", str_replace(array('US $', 'RUB', '$', 'GPB', 'BRL', 'CAD', 'AUD', 'EUR', 'INR', 'UAH', 'JPY', 'MXN', 'IDR', 'TRY', 'SEK', '.00'), '', $price)) : "0.00";
    }

    public static function getproductbyid($productid){
		$url = 'https://www.aliexpress.com/item/'.$productid.'.html';
		$html = file_get_contents($url);
		if(empty($html)){
			if (!function_exists('curl_init')){ 
				die('CURL is not installed!');
			}
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			$html = curl_exec($ch);
			curl_close($ch);
		}
		$scriptDocument = new DOMDocument();
		//disable libxml errors
		libxml_use_internal_errors(TRUE); 
		//check if any html is actually returned
		if(!empty($html)){ 
			$scriptDocument->loadHTML($html);
			libxml_clear_errors(); 
			$scriptDOMXPath = new DOMXPath($scriptDocument);
			$scriptRow = $scriptDOMXPath->query('//script');
			if($scriptRow->length > 0){
				foreach($scriptRow as $row){
					//echo"<pre>";print_r($row);echo"</pre>";
					$hh = trim($row->textContent);
					$jj = substr($hh,0,16);
					//echo"<pre>";print_r($jj);echo"</pre>";
					if('window.runParams'==$jj){
						$textContent = trim($row->nodeValue);	
						$parsed = self::get_string_between($textContent, '{', '};');
						$parsed1 = self::get_string_between($parsed, 'data:', 'csrfToken');
						//$ghj = explode('data:',$textContent);
						$parsed1 = str_replace(array("\r", "\n"), '',$parsed1);
						$parsed1 = substr(trim($parsed1),0,-1);


						$result = json_decode(trim($parsed1));
						//echo"<pre>";print_r($result);echo"</pre>";

						$data['title'] = $result->titleModule->subject;
						$data['averageStar'] = $result->titleModule->feedbackRating->averageStar;
						$data['totalValidNum'] = $result->titleModule->feedbackRating->totalValidNum;
						$data['image'] = $result->pageModule->imagePath;
						$data['DetailUrl'] = $result->pageModule->itemDetailUrl;
						$data['productId'] = $result->pageModule->productId;
						
						$data['sale_price'] = $result->priceModule->minActivityAmount->value;
						$data['orig_price'] = $result->priceModule->maxAmount->value;
						
						$data['storeName'] = $result->storeModule->storeName;
						
						$data['stock'] = $result->actionModule->totalAvailQuantity;
						
						$data['currency'] = getCurrencySymbol($result->commonModule->currencyCode);
                        return $data;						
					}
				}
			}
		}		
	}
    public static function get_product_by_id($product_id='',$aCountry='',$acategory='',$page='',$count_product='',$site=''){

    		$currency_conversion_factor = 1;
			global $wpdb;
			$productId = $product_id;

            $appKey     = '29109';			
			
			$request_url = "http://gw.api.alibaba.com/openapi/param2/2/portals.open/api.getPromotionProductDetail/{$appKey}";
			$request_url .= "?fields=productId,productTitle,productUrl,imageUrl,originalPrice,salePrice,discount,evaluateScore,volume,validTime,storeName,storeUrl,localPrice,allImageUrls";
			$request_url .= "&productId=$productId";
			if (false) {
				$request_url .= "&localCurrency=$localCurrency";
			}

			$full_request_url = apply_filters('wpeae_get_localized_url', $request_url, array('type' => 'aliexpress_request'));
            //echo $full_request_url;
			$request = wp_remote_get($full_request_url);
			
			//echo '<br>';
            //echo"<pre>";print_r($request);echo"</pre>";
			if (is_wp_error($request)) {
				return array('state' => 'error', 'message' => 'alibaba.com not response!');
			}
			//DEBUG

			$data = json_decode($request['body'], true);
			//echo "<pre>";print_r($data);echo "</pre>";
			//return $data;
			//$data['result']['description'] = "#debug_hide#";
			//echo $full_request_url."<br/>";
			/* echo "<pre>";print_r($data['result']);echo "</pre>"; */

			if (isset($data['errorCode']) && $data['errorCode'] == 20010000) {
				if (isset($data['result']['productId']) && $data['result']['productId'] == $productId) {
						$item = self::get_affiliate_goods($data['result']);
						return $item;
						//echo "<pre>";print_r($item);echo "</pre>";
				} else {
					return false;
				}
				
			} elseif (isset($data['errorCode']) && $data['errorCode'] == 20010000 && isset($data['result']['productId']) && $data['result']['productId'] != $goods->external_id) {
				return array('state' => 'error', 'message' => 'System Error');
			} elseif (isset($data['errorCode']) && ($data['errorCode'] == 20130000 || $data['errorCode'] == 20030100)) {
				return array('state' => 'error', 'message' => 'Input parameter Product ID is error');
			} elseif (isset($data['error_code']) && $data['error_code'] == 400) {
				return array('state' => 'error', 'message' => "{$data['error_message']}");
			} elseif (isset($data['errorCode']) && $data['errorCode'] == 20030000) {
				return array('state' => 'error', 'message' => 'Required parameters');
			} elseif (isset($data['errorCode']) && $data['errorCode'] == 20030010) {
				return array('state' => 'error', 'message' => 'Keyword input parameter error');
			} elseif (isset($data['errorCode']) && $data['errorCode'] == 20030020) {
				return array('state' => 'error', 'message' => 'Category ID input parameter error or formatting errors');
			} elseif (isset($data['errorCode']) && $data['errorCode'] == 20030030) {
				return array('state' => 'error', 'message' => 'Commission rate input parameter error or formatting errors');
			} elseif (isset($data['errorCode']) && $data['errorCode'] == 20030040) {
				return array('state' => 'error', 'message' => 'Unit input parameter error or formatting errors');
			} elseif (isset($data['errorCode']) && $data['errorCode'] == 20030050) {
				return array('state' => 'error', 'message' => '30 days promotion amount input parameter error or formatting errors');
			} elseif (isset($data['errorCode']) && $data['errorCode'] == 20030060) {
				return array('state' => 'error', 'message' => 'Tracking ID input parameter error or limited length');
			} elseif (isset($data['errorCode']) && $data['errorCode'] == 20030070) {
				return array('state' => 'error', 'message' => 'Unauthorized transfer request');
			} elseif (isset($data['errorCode']) && $data['errorCode'] == 20020000) {
				return array('state' => 'error', 'message' => 'System Error');
			} else {
				return array('state' => 'error', 'message' => 'Unknown Error');
			}


    }	
    public static function image_http_to_https($image_url) {
			return preg_replace("/http:\/\/g(\d+)\.a\./i", "https://ae$1.", strval($image_url));
		}

	public static function image_https_to_http($image_url) {
			return preg_replace("/https:\/\/ae(\d+)\./i", "http://g$1.a.", strval($image_url));
	}

	public static function get_ali_description($url) {
		$html='';
		if(!empty($url)){
			$desc_content = file_get_contents($url);
			if(empty($desc_content)){
				if (!function_exists('curl_init')){ 
					die('CURL is not installed!');
				}
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				$desc_content = curl_exec($ch);
				curl_close($ch);
			}			
			$desc_content = str_replace(array("window.productDescription='", "';"), '', $desc_content);
			$desc_content = htmlspecialchars_decode(utf8_decode(htmlentities($desc_content, ENT_COMPAT, 'UTF-8', false)));    
			
			$dom = new DOMDocument();
			libxml_use_internal_errors(true);
			$dom->loadHTML($desc_content);
			libxml_use_internal_errors(false);

			$finder = new DOMXPath($dom);
							
			$html = preg_replace('~<(?:!DOCTYPE|/?(?:html|body))[^>]*>\s*~i', '', $dom->saveHTML());
		}
		return $html; 
	}
	
	public static function get_ali_description_old($product_id = '') {
				$request = '';
		  		$result = array();
			if ($product_id) {
				$result["description"] = "";
				$result["description_images"] = array();
				$result["m_description"] = "";
				$result["images"] = array();
				$result["attribute"] = array();
				$result["keywords"] = "#empty#";
				$result["quantity"] = "";
			    //$request_url  ="https://aeproductsourcesite.alicdn.com/product/description/pc/v2/en_US/desc.htm?productId=32910149680&key=HTB1uBETU5rpK1RjSZFhM7NSdXXa2.zip&token=57365df140c703a006dde57a6e530673";
				$request_url  = "http://desc.aliexpress.com/getDescModuleAjax.htm?productId=" . $product_id . "&t=";
				$desc_content = file_get_contents($request_url);
				if(empty($desc_content)){
					if (!function_exists('curl_init')){ 
						die('CURL is not installed!');
					}
					$ch = curl_init();
					curl_setopt($ch, CURLOPT_URL, $request_url);
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
					$desc_content = curl_exec($ch);
					curl_close($ch);
				}

				$data = json_decode($request, true);	   
				$desc_content = str_replace(array("window.productDescription='", "';"), '', $desc_content);
                $desc_content = htmlspecialchars_decode(utf8_decode(htmlentities($desc_content, ENT_COMPAT, 'UTF-8', false)));    
    				$dom = new DOMDocument();
					libxml_use_internal_errors(true);
					$dom->loadHTML($desc_content);
					libxml_use_internal_errors(false);

					$finder = new DOMXPath($dom);

					$items = $finder->query('//div[@style="max-width: 650.0px;overflow: hidden;font-size: 0;clear: both;"]');
					foreach ($items as $item) {
						$item->parentNode->removeChild($item);
					}
										
					$html = preg_replace('~<(?:!DOCTYPE|/?(?:html|body))[^>]*>\s*~i', '', $dom->saveHTML());
					return $html;								
					$html = self::alli_clear_html($html);
					$dom->preserveWhiteSpace = false;
					$images = $dom->getElementsByTagName('img');
					$images_url = array();

					foreach ($images as $image) {
						$img = $image->getAttribute('src');
						$pos = strpos($img, '?');
						$img = $pos === true ? substr($img, 0, $pos) : $img;

						if (strrpos($img, '.jpg')) {
							$images_url[] = $img;
						}
					}

					$result["description"] = $html;
					$result["description_images"] = $images_url;
				
								$response = file_get_contents('http://m.aliexpress.com/item-desc/' . $product_id . '.html?site=en');
								if(empty($response)){
										if (!function_exists('curl_init')){ 
											die('CURL is not installed!');
										}
									$ch = curl_init();
									curl_setopt($ch, CURLOPT_URL, 'http://m.aliexpress.com/item-desc/' . $product_id . '.html?site=en');
									curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
									$response = curl_exec($ch);
									curl_close($ch);
								}
				if (!$response) {
					$html_str = $response;
                    $html_str = htmlspecialchars_decode(utf8_decode(htmlentities($html_str, ENT_COMPAT, 'UTF-8', false)));    

					$dom = new DOMDocument();
					libxml_use_internal_errors(true);
					$dom->loadHTML($html_str);
					libxml_use_internal_errors(false);
					$finder = new DOMXPath($dom);

					//get attributes
					$rows = $finder->query("//*[contains(@class, 'prop-table')]/tbody/tr");
					foreach ($rows as $row) {
						$key = $value = "";
						foreach ($row->childNodes as $td) {
							if (XML_ELEMENT_NODE == $td->nodeType) {
								if ("key" === $td->getAttribute('class')) {
									$key = $td->nodeValue;
								} else if ("value" === $td->getAttribute('class')) {
									$value = $td->nodeValue;
								}
							}
						}
						if ($value && $value !== "NA" && $value !== "None") {
							$result["attribute"][] = array("name" => $key, "value" => $value);
						}
					}
				}
			} else {
				$result = '';
				
			}
			//echo"<pre>";print_r($result);echo"</pre>";
			return $result;

	}
	public static function alli_clear_html($in_html) {
			if (!$in_html)
				return "";
			$html = preg_replace('~<(?:!DOCTYPE|/?(?:html|body))[^>]*>\s*~i', '', $in_html);
			$html = preg_replace('/(<[^>]+) style=".*?"/i', '$1', $html);
			$html = preg_replace('/(<[^>]+) class=".*?"/i', '$1', $html);
			$html = preg_replace('/(<[^>]+) width=".*?"/i', '$1', $html);
			$html = preg_replace('/(<[^>]+) height=".*?"/i', '$1', $html);
			$html = preg_replace('/(<[^>]+) alt=".*?"/i', '$1', $html);
			$html = preg_replace('/^<!DOCTYPE.+?>/', '$1', str_replace(array('<html>', '</html>', '<body>', '</body>'), '', $html));
			$html = preg_replace("/<\/?div[^>]*\>/i", "", $html);

			$html = preg_replace('#(<a.*?>).*?(</a>)#', '$1$2', $html);
			$html = preg_replace('/<a[^>]*>(.*)<\/a>/iU', '', $html);
			$html = preg_replace("/<\/?h1[^>]*\>/i", "", $html);
			$html = preg_replace("/<\/?strong[^>]*\>/i", "", $html);
			$html = preg_replace("/<\/?span[^>]*\>/i", "", $html);

			$html = str_replace(' &nbsp; ', '', $html);
			$html = str_replace('&nbsp;', ' ', $html);

			$pattern = "/<[^\/>]*>([\s]?)*<\/[^>]*>/";
			$html = preg_replace($pattern, '', $html);

			$html = str_replace(array('<img', '<table'), array('<img class="img-responsive"', '<table class="table table-bordered'), $html);
			return $html;
		}

		public static function get_aliexpress_categories() {
			$result = json_decode(file_get_contents(PLUGIN_PATH.'/api/data/ali_categories.xml'), true);
			$result = $result["categories"];
			array_unshift($result, array("id" => "", "name" => "-- Select category --", "level" => 1));
			return $result;
		}

	public static function get_product_for_import($pid){
		ini_set('max_execution_time', '0');
		$result = $product =$product_images= $product_attributes = array();
		$product_desc = '';
		try{

			

			$product_info = self::get_product_by_id($pid);
			//echo"<pre>";print_r($product_info);echo"</pre>";

			//$p_url = isset($product_info['additional_meta']['detail_url']) ? $product_info['additional_meta']['detail_url'] : '';
            $p_url = 'https://www.aliexpress.com/item/'.$pid.'.html';

			if(!empty($product_info)){
				if(isset($product_info['error'])){
					throw new \Exception($product_info['message'], 1);
				}

				//images
				if(isset($product_info['additional_meta']['images']) && !empty($product_info['additional_meta']['images'])){
					$img_arr = explode(",",$product_info['additional_meta']['images']);
					$product_images = $img_arr;
				}
				else{
					$product_images = self::get_product_images($pid);
				}


				//preparing product array
				$product['sku'] = $product_info['external_id'];
				$product['url'] = $product_info['additional_meta']['detail_url'];
				$product['title'] = base64_encode(apply_filter_to_text($product_info['title']));
				$product['thumb'] = $product_info['image'];
				$product['images'] = serialize($product_images);
				$product['skip_images'] = serialize(array());
				$product['skip_vars'] = serialize(array());
				$product['affiliate_url'] = $product_info['additional_meta']['detail_url'];
				$product['seller_url'] = $product_info['seller_url'];
				$product['dimensions'] = serialize(array());
				$product['lotNum'] = 1;
				$product['packageType'] = 'piece';
				$product['category_id'] = $product_info['category_id'];
				$product['category_name'] = '';
				$product['categories'] = serialize(array());

				$product['orders'] = 0;
				$product['tags'] = serialize(array());
				$status = get_option('ab_product_status',false);
				$product_status = (isset($status) && $status) ? $status :'publish';
				$product['status'] = $product_status;
				$product['price_min'] = $product_info['price'];
				$product['price_max'] = $product_info['old_price'];
				$product['regular_price_min'] = $product_info['old_price'];
				$product['regular_price_max'] = $product_info['old_price'];

				//variations
				$skuproducts = self::get_product_variations($pid,$p_url);
				$sku_products = $skuproducts['product_sku'];
				$descriptions = $skuproducts['description'];

				//attributes
				if( get_option('ab_import_attributes','no') =='yes'){
					$product_attributes = self::get_product_attributes($pid,$p_url);
					$product_desc .= '<table class="content_attributes"><tbody>';
					foreach ($product_attributes as $attribute) {
						$product_desc .= '<tr><th>' . apply_filter_to_text($attribute['name']) . '</th><td><p>' . (is_array($attribute['value']) ? implode(", ", apply_filter_to_text($attribute['value'])) : apply_filter_to_text($attribute['value'])) . "</p></td></tr>";
					}
					$product_desc .= '</tbody></table>';
				}	
				//description
				if( get_option('ab_import_description','no') =='yes'){
					//$product_desc = self::get_ali_description($pid);
					$product_desc .= clean_description($descriptions);
				}				
				
				$product['description'] = base64_encode(apply_filter_to_text($product_desc));
				//var_dump($sku_products);exit;
				if(!empty($sku_products) && !empty($sku_products['variations'])){
					$vars = $sku_products['variations'];
					$min = $product['price_min'];
					$max = $product['price_max'];
					foreach ($vars as $key => $value) {
						if($value['price'] > 0 && $value['price'] < $min){
							$min = $value['price'];
						}
						if($value['price'] > 0 && $value['price'] > $max){
							$max = $value['price'];
						}
					}
					$product['price_max'] = $max;
					$product['price_min'] = $min;
				}



				//randomize quantity
				if (get_option('ab_random_stock',false)=='yes') {
					$product['disable_var_quantity_change'] = true;
					foreach ($sku_products['variations'] as &$variation) {
						$variation['original_quantity'] = intval($variation['quantity']);
						$tmp_quantity = rand(intval(get_option('ab_random_from')), intval(get_option('ab_random_to')));
						$tmp_quantity = ($tmp_quantity > $variation['original_quantity']) ? $variation['original_quantity'] : $tmp_quantity;
						$variation['quantity'] = $tmp_quantity;
					}
				}

				//update pricing 
				$product['sku_products'] = $sku_products;
				$product = wpab_price_formula($product, $round = 2, $type = 'all');

				$product['detail'] = base64_encode(serialize($product['sku_products']));
				unset($product['disable_var_quantity_change']);
				unset($product['calc_price']);
				unset($product['calc_regular_price']);
				unset($product['sku_products']);
				$product['attribute'] = serialize($product_attributes);
				$result['product'] = $product;


			/*var_dump($product);
			die('END');*/

			}
			else{
				throw new \Exception("Error while fetching product details!", 1);
			}
		}
		catch(\Exception $e){
			return array('state' => 'error', 'message' => $e->getMessage());
		}
	return array('state' => 'ok', 'message' => 'Product data fetched successfully!','data'=>$result);
	}

	public static function get_product_variations($pid,$url) {
		ini_set('max_execution_time', '0');
		$variations = $combinations = $list = array();
		$p_attributes = array();
		try{
			if($pid) 
			{
//include('dom.php');
//$url = $_GET['url'];
$html = file_get_contents($url);
if(empty($html)){
	if (!function_exists('curl_init')){ 
		die('CURL is not installed!');
	}
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$html = curl_exec($ch);
	curl_close($ch);
}
$scriptDocument = new DOMDocument();
//disable libxml errors
libxml_use_internal_errors(TRUE); 
//check if any html is actually returned
if(!empty($html)){ 
	$scriptDocument->loadHTML($html);
	libxml_clear_errors(); 
	$scriptDOMXPath = new DOMXPath($scriptDocument);
	$scriptRow = $scriptDOMXPath->query('//script');
	if($scriptRow->length > 0){
		foreach($scriptRow as $row){
			//echo"<pre>";print_r($row);echo"</pre>";
			$hh = trim($row->textContent);
			$jj = substr($hh,0,16);
			//echo"<pre>";print_r($jj);echo"</pre>";
			if('window.runParams'==$jj){
			    $textContent = trim($row->nodeValue);	
				$parsed = self::get_string_between($textContent, '{', '};');
				$parsed1 = self::get_string_between($parsed, 'data:', 'csrfToken');
				//$ghj = explode('data:',$textContent);
				$parsed1 = str_replace(array("\r", "\n"), '',$parsed1);
				$parsed1 = substr(trim($parsed1),0,-1);


				$result = json_decode(trim($parsed1));
				//print_r(json_decode($parsed));
				//echo "</pre>";

				if(isset($result->descriptionModule->descriptionUrl)){
					$descurl = $result->descriptionModule->descriptionUrl;
					$description = self::get_ali_description($descurl);
				}
				
				if(isset($result->skuModule->productSKUPropertyList)){
					foreach($result->skuModule->productSKUPropertyList as $attr){
						 
						//echo"<pre>";print_r($attr);echo"</pre>";
						$id = $attr->order;
						$name = $attr->skuPropertyName;
						$value=array();
						if(isset($attr->skuPropertyValues)){
							foreach($attr->skuPropertyValues as $attr2){
								$valu['name']=$attr2->propertyValueDisplayName;
								$valu['id']=$attr2->propertyValueId;
								$pimage='';
								if(isset($attr2->skuPropertyImagePath)){
								$valu['image']=$attr2->skuPropertyImagePath;
                                $pimage=$attr2->skuPropertyImagePath;								
								}
								if(isset($attr2->skuPropertyImageSummPath)){
								$valu['thumb']=$attr2->skuPropertyImageSummPath;	
								}
								$value[$valu['id']] = $valu;
								$attri[$valu['id']] =array('name'=>$valu['name'],'image'=>$pimage); 
								unset($valu);
							}	
						}
						$attributes[] = array('id'=>$id,'name'=>$name,'value'=>$value);
						unset($value);
					}
					
				}
				$product_sku['attributes'] = $attributes;
				//echo"<pre>";print_r($product_sku);echo"</pre>";
				if(isset($result->skuModule->skuPriceList)){
					foreach($result->skuModule->skuPriceList as $k=>$attr){
						
						

						//echo"<pre>";print_r($attr);echo"</pre>";

						$skuPropIds =explode(',',$attr->skuPropIds);
						$pimg ='';
						foreach($skuPropIds as $skuPropId){
							//echo"<pre>";print_r($skuPropId);echo"</pre>";
							$attribut[] = $skuPropId;
							$attribut_name[] = $attri[$skuPropId]['name'];
							if(isset($attri[$skuPropId]['image']) && $attri[$skuPropId]['image']!=''){
							$pimg = $attri[$skuPropId]['image'];
							}
						}
						//echo"<img src=".$pimg." />";
						//echo"<pre>";print_r($attri);echo"</pre>";
						//$id = $attr->skuAttr;
						$id = $attr->skuId;
						$sku =$attr->skuId;
						$price = $attr->skuVal->skuActivityAmount->value;
						$regular_price = $attr->skuVal->skuAmount->value;
						$quantity = $attr->skuVal->availQuantity;
						//echo $attr->skuAttr;
						$variation = array(
						'id'=>$id,
						'sku'=>$sku,
						'attributes'=>$attribut,
						'attributes_names'=>$attribut_name,
						'quantity'=>$quantity,
						'currency'=>'USD',
						'discount'=>'0',
						'regular_price'=>$regular_price,
						'price'=>$price,
						'image'=>$pimg
						);
                        $variations[] =$variation;
						unset($attribut);
						unset($attribut_name);
					}
					
				}
                $product_sku['variations'] = $variations;				
                //echo"<pre>";print_r($product_sku);echo"</pre>";				
			}
		}
	}
}
			}
		}
		catch(\Exception $e){
			//do nothing
			//echo $e->getMessage();exit;
		}
	$sku_products = ['product_sku'=>$product_sku,'description'=>$description];
	//echo"<pre>";print_r($product_sku);echo"</pre>";
	return $sku_products;		
	}
	
	public static function get_product_variations_old($pid,$url) {
		ini_set('max_execution_time', '0');
		$variations = $combinations = $list = array();
		$p_attributes = array();
		try{
			if($pid) 
			{
				$html = file_get_html($url);
				$product_info_sku = '';
	            if($html->find('#j-product-info-sku', 0)) 
	            {
				    $product_info_sku = $html->getElementById('j-product-info-sku');
				}
				else if(($html->find('#product-info-sku', 0))) 
	            {
				    $product_info_sku = $html->getElementById('product-info-sku');
				}

				if($product_info_sku == '')
				{
					//echo 'Product does not have variations';exit;
				}
				else
				{
					$types = $list = array();
					if($product_info_sku->hasChildNodes())
					{
						//find attributes
						foreach($product_info_sku->find('dl.p-property-item') as $item) 
						{	
							$name = '';
							//get variation types options
							foreach($item->find('dt.p-item-title') as $title) 
							{
									$text = $title->plaintext;
									$name = trim(str_replace(array(':'), '', $text));
					            	array_push($types, $name);
							}

					       	//build lists
			       			$options = array();
							foreach ($item->find('ul.sku-attr-list') as $ul) 
							{
					       		$vals = array();
						       	foreach ($ul->find('li') as $li) 
						       	{

						       		if (isset($li->attr['class'])) 
						       		{
						       			$classes = explode(' ', $li->attr['class']);
						       			if(in_array('disabled', $classes))
						       			{
						       				continue;
						       			}
						       			$innertext = $li->find('a',0)->outertext;
							       		$h = str_get_html($innertext);
							       		$a = $h->find('a',0);
							       		$attr = $a->attr;
							       		$sku = $attr['data-sku-id'];
							       		$attrVal = $attr['title'];
							       		$attrVal = apply_filter_to_text($attrVal);

							       		$i = 2;
							       		while(in_array($attrVal, $vals))
							       		{
							       			$attrVal.= '#'.$i;
							       			$i++;
							       		}
							       		array_push($vals, trim($attrVal));

								    	$options[$sku]['name'] = trim($attrVal);
								    	$options[$sku]['id'] = $sku;

								    	$classname = str_replace(' ', '', $li->attr['class']);
								    	if($classname == 'item-sku-image')
								    	{
								    		$i = $a->find('img',0);
								       		$options[$sku]['image'] = $i->bigpic;
								       		$options[$sku]['thumb'] = $i->bigpic;
								    	}
								  	}
								  	else
								  	{
								  		$a = $li->find('a',0);
								  		$attr = $a->attr;
								  		$sku = $attr['data-sku-id'];

								  		$attrVal = $li->find('a',0)->find('span',0)->plaintext;
							       		$attrVal = apply_filter_to_text($attrVal);
								  		//$attrVal = str_replace(' ', '', $attrVal);

										$i = 2;
							       		while(in_array($attrVal, $vals))
							       		{
							       			$attrVal.= '#'.$i;
							       			$i++;
							       		}
								    	array_push($vals, trim($attrVal));

								    	$options[$sku]['name'] = trim($attrVal);
								    	$options[$sku]['id'] = $sku;
								  	}
							  	}
					       	}

					       $list[$name] = $options;  
						}
						$cust_ct = 0;
						foreach ($list as $name => $values) {
							$p_attributes[$cust_ct]['id'] = $cust_ct+1;
							$p_attributes[$cust_ct]['name'] = $name;
							$p_attributes[$cust_ct]['value'] = $values;
							$cust_ct++;
						}

						//find prices and prepare variations
			            $prices_url = "https://m.ru.aliexpress.com/item/".$pid.".html";
			            $prices_html = file_get_html($prices_url);

			            //skuIds
			            $skuPropertyIdList = $prices_html->find('amp-state#skuPropertyIdList',0);
			            $scripts = $skuPropertyIdList->find('script',0);
			            $innertext = $scripts->innertext;
			            $skuIds = json_decode($innertext, true);
			            
			            //PriceList
			            $skuPriceList = $prices_html->find('amp-state#skuPriceList',0);
			            $scripts = $skuPriceList->find('script',0);
			            $innertext = $scripts->innertext;
			            $priceList = json_decode($innertext, true);

			            //create new pricelisting
			            $priceListing = array();
			            foreach ($skuIds as $i => $ids) 
			            {
			            	$key = implode("", $ids);
			            	$newKey = implode("#", $ids);
			            	$key = "u".$key;
			            	if(isset($priceList[$key]))
			            	{
			            		$priceListing[$newKey] = $priceList[$key];
			            	}
			            }
			            //process variations
			            $combinations = self::get_combinations($list);
			            foreach ($combinations as $v => $comb) 
			            {
			            	$single_item = array();
			            	$skuList = $options = array();
			            	$price = $stock = 0;
			            	$att_names = array();
			            	$att_image = '';
							foreach ($comb as $k=>$item) 
							{
								$skuList[] = $item['id'];
								$options[$k]=$item['name'];
								$att_names[] =$item['name'];
								if(isset($item['image']) && $item['image']!='')
									$att_image = $item['image'];
							}

							//get price & stock
							$skuKey = implode('#', $skuList);
							if(isset($priceListing[$skuKey]))
							{
			            		$single_item['id'] = $skuKey;
			            		$single_item['sku'] = $skuKey;
			            		$single_item['attributes'] = $skuList;
			            		$single_item['attributes_names'] = $att_names;
								$stock = $priceListing[$skuKey]['skuStock'];
								$price = $priceListing[$skuKey]['skuPriceValue'];
								$price = round(self::get_normalize_price($price),2);
							}
							if($price==0)
							{
								continue;
							}
							$single_item['currency'] = 'USD';
							$single_item['discount'] = '0';
							$single_item['price'] = $price;
							$single_item['regular_price'] = $price;
							$single_item['quantity'] = $stock;
							$single_item['sku'] = $skuKey;
							$single_item['image'] = $att_image;

						$combinations[$v] = $single_item;
			            }
					}
				}
			}
		}
		catch(\Exception $e){
			//do nothing
			//echo $e->getMessage();exit;
		}
	$sku_products = ['attributes'=>$p_attributes,'variations'=>$combinations];
	return $sku_products;		
	}	
	public static function get_product_attributes_old($pid,$url) {
		$attributes = array();
		try{
			if($pid) 
			{
				$html = file_get_contents($url);
				$dom = new DOMDocument();
				libxml_use_internal_errors(true);
				$dom->loadHTML($html);
				libxml_use_internal_errors(false);
				$finder = new DOMXPath($dom);
				$items = $finder->query("//*[contains(@class, 'product-property-list')]/li");
				if($items->length > 0){
					foreach ($items as $row) {
						$key = $value = "";
						foreach ($row->childNodes as $span) {
							if (XML_ELEMENT_NODE == $span->nodeType) {
								if ("propery-title" === $span->getAttribute('class')) {
									$key = str_replace(array(':','-'), '', strip_tags($span->nodeValue));
								} else if ("propery-des" === $span->getAttribute('class')) {
									$value = $span->nodeValue;
								}
							}
						}
						if ($value && $value !== "NA" && $value !== "None") {
							$attributes[] = array("name" => $key, "value" => $value);
						}
					}
				}
			}
		}
		catch(\Exception $e){
			//do nothing
		}
	return $attributes;		
	}
	public static function get_product_attributes($pid,$url) {
		$attributes = array();
		try{
			if($pid) 
			{
				//include('dom.php');
				//$url = $_GET['url'];
				$html = file_get_contents($url);
				if(empty($html)){
					if (!function_exists('curl_init')){ 
						die('CURL is not installed!');
					}
					$ch = curl_init();
					curl_setopt($ch, CURLOPT_URL, $url);
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
					$html = curl_exec($ch);
					curl_close($ch);
				}				
				//echo"<pre>";print_r($html);echo"</pre>";
				$scriptDocument = new DOMDocument();
				//disable libxml errors
				libxml_use_internal_errors(TRUE); 
				//check if any html is actually returned
				if(!empty($html)){ 
					$scriptDocument->loadHTML($html);
					libxml_clear_errors(); 
					$scriptDOMXPath = new DOMXPath($scriptDocument);
					$scriptRow = $scriptDOMXPath->query('//script');
					if($scriptRow->length > 0){
						foreach($scriptRow as $row){
							//echo"<pre>";print_r($row);echo"</pre>";
							$hh = trim($row->textContent);
							$jj = substr($hh,0,16);
							//echo"<pre>";print_r($jj);echo"</pre>";
							if('window.runParams'==$jj){
								$textContent = trim($row->nodeValue);	

								$parsed = self::get_string_between($textContent, '{', '};');
								$parsed1 = self::get_string_between($parsed, 'data:', 'csrfToken');
								//$ghj = explode('data:',$textContent);
								$parsed1 = str_replace(array("\r", "\n"), '',$parsed1);
								$parsed1 = substr(trim($parsed1),0,-1);

								//$parsed1 = str_replace("{number}","number",$parsed1);
								
								//$output = preg_match_all('/data:/', $textContent, $matches,PREG_SET_ORDER );
					//display
								//echo "<pre>";
								//print_r($parsed1);
								//echo '{'.trim($parsed1).'};';
								$result = json_decode(trim($parsed1));
								//print_r(json_decode($parsed));
								//echo "</pre>";
								$attributes=array();
								if(isset($result->specsModule->props)){
									foreach($result->specsModule->props as $attr3){
										$attributes[]=array('name'=>$attr3->attrName,'value'=>$attr3->attrValue);
									}
								}
								//echo"<pre>";print_r($attributes);echo"</pre>";
							
							}
						}
					}
				}
			}
		}
		catch(\Exception $e){
			//do nothing
		}
	    return $attributes;			
	}
	public static function get_product_images($pid) {
		$images_url = array();
		try{
			if ($pid) 
			{
				$result["description"] = "";
				$result["description_images"] = array();
				$result["m_description"] = "";
				$result["images"] = array();
				$result["attribute"] = array();
				$result["keywords"] = "#empty#";
				$result["quantity"] = "";
			   
			   	$request_url = "http://desc.aliexpress.com/getDescModuleAjax.htm?productId=" . $pid . "&t=";
				$desc_content = file_get_contents($request_url);
				if(empty($desc_content)){
						if (!function_exists('curl_init')){ 
							die('CURL is not installed!');
						}
					$ch = curl_init();
					curl_setopt($ch, CURLOPT_URL, $request_url);
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
					$desc_content = curl_exec($ch);
					curl_close($ch);
				}
				$data = json_decode($request, true);	   
				$desc_content = str_replace(array("window.productDescription='", "';"), '', $desc_content);
	            $desc_content = htmlspecialchars_decode(utf8_decode(htmlentities($desc_content, ENT_COMPAT, 'UTF-8', false)));
	            $dom = new DOMDocument();
				libxml_use_internal_errors(true);
				$dom->loadHTML($desc_content);
				libxml_use_internal_errors(false);
				$finder = new DOMXPath($dom);

				$items = $finder->query('//div[@style="max-width: 650.0px;overflow: hidden;font-size: 0;clear: both;"]');
				foreach ($items as $item) {
					$item->parentNode->removeChild($item);
				}				
				$html = preg_replace('~<(?:!DOCTYPE|/?(?:html|body))[^>]*>\s*~i', '', $dom->saveHTML());
				$html = self::alli_clear_html($html);
				$dom->preserveWhiteSpace = false;
				$images = $dom->getElementsByTagName('img');
				foreach ($images as $image) {
					$img = $image->getAttribute('src');
					$pos = strpos($img, '?');
					$img = $pos === true ? substr($img, 0, $pos) : $img;

					if (strrpos($img, '.jpg')) {
						$images_url[] = $img;
					}
				}
			}
		}
		catch(\Exception $e){
			//do nothing
		}
		if(!empty($images_url)){
			$images_url = array_unique($images_url);
		}
	return $images_url;		
	}


    public static function get_combinations($arrays) {
		$result = array(array());
		foreach ($arrays as $property => $property_values) 
		{
			$tmp = array();
			foreach ($result as $result_item) 
			{
				foreach ($property_values as $sku => $property_value) 
				{
					$tmp[] = array_merge($result_item, array($property => $property_value));
				}
			}
			$result = $tmp;
		}
		return $result;
	}
	
	public static function get_string_between($string, $start, $end){
		$string = ' ' . $string;
		$ini = strpos($string, $start);
		if ($ini == 0) return '';
		$ini += strlen($start);
		$len = strpos($string, $end, $ini) - $ini;
		return substr($string, $ini, $len);
	}	
}