<?php

 
//wp-load : remove this
@include('../../../wp-load.php');

/*
 * main code class
 */
class pinterest {
	
	/*
	 * public variables
	 */
		public $ch='';
		public $db='';
		public $pid ;
	/* 
	 * Class Constructor
	 */
	
	function __construct(){

		
		
		//db
		global $wpdb;
		$this->db=$wpdb;
		//$this->db->show_errors();
		@$this->db->query("set session wait_timeout=28800");
	
	
		$this->ch = curl_init();
	
		/*verboxe	
		$verbose=fopen( dirname(__FILE__).'/verbose.txt', 'w');
		curl_setopt($this->ch, CURLOPT_VERBOSE , 1);
		curl_setopt($this->ch, CURLOPT_STDERR,$verbose);
		*/
	
		curl_setopt($this->ch, CURLOPT_HEADER,0);
		curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($this->ch, CURLOPT_CONNECTTIMEOUT, 10);
		curl_setopt($this->ch, CURLOPT_TIMEOUT,20);
		curl_setopt($this->ch, CURLOPT_REFERER, 'https://pinterest.com/login/');
		curl_setopt($this->ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.8) Gecko/2009032609 Firefox/3.0.8');
		curl_setopt($this->ch, CURLOPT_MAXREDIRS, 5); // Good leeway for redirections.
		curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, 0); // Many login forms redirect at least once.
		@curl_setopt($this->ch, CURLOPT_COOKIEJAR , "cookie.txt");
		curl_setopt($this->ch, CURLOPT_HEADER, 1);
		curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, false);
	 
		//log
		$this->log('ini','Curl initialized ...');
		
	}//end class constructor

	/*
	 * function get boards: get boards for specific user
	 * @user: the username to get boards to .
	 */
		function boards_get($usr){
			
			//log
			$this->log('Job initiated',"Fetching boards for user:$usr ...");
			
			$url = 'https://www.pinterest.com/resource/UserResource/get/?source_url=%2F'.$usr.'%2Fpins%2F&data=%7B%22options%22%3A%7B%22username%22%3A%22'.$usr.'%22%2C%22invite_code%22%3Anull%7D%2C%22context%22%3A%7B%7D%2C%22module%22%3A%7B%22name%22%3A%22UserProfileContent%22%2C%22options%22%3A%7B%22tab%22%3A%22boards%22%7D%7D%2C%22render_type%22%3A1%2C%22error_strategy%22%3A0%7D&module_path=App()%3EUserProfilePage(resource%3DUserResource(username%3D'.$usr.'))%3EUserInfoBar(tab%3Dboards%2C+spinner%3D%5Bobject+Object%5D%2C+resource%3DUserResource(username%3D'.$usr.'%2C+invite_code%3Dnull))&_=1418036527901';
			$url ="https://www.pinterest.com/resource/ProfileBoardsResource/get/?source_url=%2Fshandaz%2Fboards%2F&data=%7B%22options%22%3A%7B%22field_set_key%22%3A%22grid_item%22%2C%22username%22%3A%22shandaz%22%7D%2C%22context%22%3A%7B%7D%7D&module_path=App()%3EUserProfilePage(resource%3DUserResource(username%3Dshandaz))%3EUserInfoBar(tab%3Dboards%2C+spinner%3D%5Bobject+Object%5D%2C+resource%3DUserResource(username%3Dshandaz))&_=1432729040592";
			$url ="https://nl.pinterest.com/resource/BoardsResource/get/?source_url=%2Fmainecoonnl%2F&data=%7B%22options%22%3A%7B%22filter%22%3A%22public%22%2C%22sort%22%3A%22profile%22%2C%22field_set_key%22%3A%22grid_item%22%2C%22skip_board_create_rep%22%3Atrue%2C%22username%22%3A%22mainecoonnl%22%7D%2C%22context%22%3A%7B%22advertiser%22%3Anull%7D%7D&_=1477825134163";
			$url = str_replace('mainecoonnl', trim($usr), $url);
			
			$x='error';
			curl_setopt($this->ch, CURLOPT_HTTPGET, 1);
			curl_setopt($this->ch, CURLOPT_URL, trim($url));
			
			curl_setopt($this->ch, CURLOPT_HEADER,0);
			curl_setopt($this->ch,CURLOPT_HTTPHEADER,array('Referer: https://www.pinterest.com/','X-NEW-APP: 1','X-Requested-With: XMLHttpRequest'));
			curl_setopt ( $this->ch, CURLOPT_ENCODING, "" );
			
			$exec=curl_exec($this->ch);

			 
			$boards_links = array ();
			$boards_names = array ();
			$boards_imgs = array ();
			$ids = array ();
			
			@$json = json_decode ( $exec );
			
		 
			
			$boards = $json->resource_data_cache[0]->data;
			
			if(count($boards) == 0){
				$boards = $json->resource_response->data;
			}
			 
			foreach($boards as $board){
				$ids[]= $board->id;
				$boards_names[] = $board->name;
				$boards_links[] = $board->url;
				
				$boardimgs = (Array)$board->cover_images;
				$boardimg = current($boardimgs);
				
				$boards_imgs[] = $boardimg->url;
 				
				
				
			}
			
			$boards=array($ids,$boards_names,$boards_links,$boards_imgs);
			 
			
			return $boards;
			
		}//end function boards_get
		
		/*
		 *boards update : function to chek if the items needs to be updated if so it updates them
		 */
		function boards_update($pid,$usr){
			
			//check if need update or not 
			$wp_pinterest_to_wp_ops=get_post_meta($pid,'wp_pinterest_to_wp_ops',1);
			
			if(!is_array($wp_pinterest_to_wp_ops)) $wp_pinterest_to_wp_ops=array();
			
			if(!in_array('OPT_UPDATE',$wp_pinterest_to_wp_ops)) return false;
			
			//last update date
			$last_update=get_post_meta($pid,'last_update',1);
			
			$gallery_update=get_post_meta($pid,'gallery_update',1);
			$gallery_unit=get_post_meta($pid,'gallery_unit',1);
			$updae_every=$gallery_unit * $gallery_update;
			
			$difference=$this->get_time_difference($last_update,time('now'));
			//echo '<br>minutes passed:'.$difference; 
			//echo '<br>update every:'.$updae_every.'<br>';
			
			//distroy data of the pins and call wp_pins_get so it get's them from pintest again
			if($difference > $updae_every ){
				$query="delete from wp_pinterest_to_wp_pins where pin_gallery='$pid'";
				$this->db->query($query);	
				
				//distroy boards
				$query="delete from wp_pinterest_to_wp_boards where board_gallery='$pid'";
				$this->db->query($query);	
			}
			

			
		}//end function pins_update		
		
		
	/*
	 * wp_boards_get : get boards wordpress wraper with caching
	 * @pid: cutom post id 
	 */
	function wp_boards_get($pid,$usr){
		
		//get the boards from db first if not get them from pinterest
		$query="select * from wp_pinterest_to_wp_boards where board_gallery=$pid";
		
		$rows=$this->db->get_results($query);
	 
		if(count($rows) == 0){
				
				
			// no boards in the db lets get from pinterest
			$boards=$this->boards_get($usr);
			  
			if(count($boards[0]) > 0 ){
		
				//more than board found let's cache
				$ids=$boards[0];
				$titles=$boards[1];
				$links=$boards[2];
				$imgs=$boards[3];
		
				foreach($imgs as $key=>$value ) {
					$imgs[$key] = str_replace('https', 'http', $imgs[$key]);
				}
				
		
				$i=0;
				foreach($ids as $idn){
					$titles[$i] = addslashes($titles[$i]);
					$query="insert into wp_pinterest_to_wp_boards(board_gallery,board_id,board_link,board_img,board_name) values ($pid,'$idn','$links[$i]','$imgs[$i]','$titles[$i]')";
					$this->db->query($query);
					$i++;
				}
				
				//update last update date
			 	update_post_meta($pid,'last_update',time('now'));
			 	
			 	$gallery_itms = get_post_meta($pid,'gallery_itms',1);

			 	//add them all if none is selected
			 	if(! is_array($gallery_itms) || count($gallery_itms) == 0 || $gallery_itms[0] == ''){
			 		update_post_meta($pid,'gallery_itms',$ids);
			 		 
			 	} 
			 	 
		
				return $boards;
		
			}else{
				//no pins
				return false;
			}
				
		}else{
				
				
			//found in db return
			$return = array();
			foreach ($rows as $row){
				
				$ids[]=$row->board_id;
				$names[]=$row->board_name;
				$links[]=$row->board_link;
				$imgs[]=$row->board_img;
				
		
		
			}
			
			//check update
			$this->boards_update($pid,$usr);
		
			$return = array($ids,$names,$links,$imgs);
 
			
			return $return;
				
		}
		
	}//end function wp_boards_get
		
		
	/*
	 * function get pins : get pins for specific user
	 * 
	 */	
		function pins_get($key , $board = false,$board_id = false){
			 			  	
			//prepare
			curl_setopt($this->ch,CURLOPT_HTTPHEADER,array('Referer: https://www.pinterest.com/','X-NEW-APP: 1','X-Requested-With: XMLHttpRequest'));
				
			
			//get: http://pinterest.com/resource/UserPinsResource/get/?data=%7B%22options%22%3A%7B%22username%22%3A%22mganna%22%7D%2C%22module%22%3A%7B%22name%22%3A%22Grid%22%2C%22options%22%3A%7B%22scrollable%22%3Atrue%2C%22show_grid_footer%22%3Atrue%2C%22item_options%22%3A%7B%22show_rich_title%22%3Afalse%2C%22squish_giraffe_pins%22%3Afalse%2C%22show_board%22%3Atrue%2C%22show_via%22%3Afalse%2C%22show_pinner%22%3Afalse%2C%22show_pinned_from%22%3Afalse%7D%2C%22layout%22%3A%22variable_height%22%7D%2C%22append%22%3Afalse%2C%22errorStrategy%22%3A0%7D%2C%22context%22%3A%7B%22app_version%22%3A%225ad1cd0%22%7D%7D&source_url=%2Fmganna%2Fpins%2F&_=1373387862916
				
				if($board == false){
					
					//now key contains the user id like mganna
					$url="https://www.pinterest.com/resource/UserPinsResource/get/?source_url=%2Fwelkerpatrick%2Fpins%2F&data=%7B%22options%22%3A%7B%22username%22%3A%22welkerpatrick%22%7D%2C%22context%22%3A%7B%7D%7D&module_path=App()%3EUserProfilePage(resource%3DUserResource(username%3Dwelkerpatrick))%3EUserInfoBar(tab%3Dpins%2C+spinner%3D%5Bobject+Object%5D%2C+resource%3DUserResource(username%3Dwelkerpatrick%2C+invite_code%3Dnull))&_=1430667298559";
					$url = str_replace('welkerpatrick', $key, $url);
					$surl = $url;
 				
				
				}else{
					
					
					if($board_id != false){
						$wp_pinterest_board_id = $board_id;
					}else{
						$wp_pinterest_board_id = get_post_meta($this->pid,'wp_pinterest_board_id', 1);
					}
					
					 
					
					if(trim($wp_pinterest_board_id) == ''){
							
						//must get board id from it's page
						//curl get
						$x='error';
						$url='https://api.pinterest.com/v3/pidgets/boards/'.trim($key).'/pins/';
						
						$url = str_replace('//', '/', $url);
						$url = str_replace('https:/', 'https://', $url);
						
						 
						curl_setopt($this->ch, CURLOPT_HEADER,0);
						curl_setopt($this->ch, CURLOPT_HTTPGET, 1);
						curl_setopt($this->ch, CURLOPT_URL, trim($url));
						$exec=curl_exec($this->ch);
						$x=curl_error($this->ch);
							
						 
						//extract id
						$exIDjson = json_decode($exec);
						$exID = $exIDjson->data->board->id;
							
				 	
						if(is_numeric($exID)){
							
							$boards_ids[$key] = $exID;
							update_post_meta($this->pid, 'wp_pinterest_boards_ids', $boards_ids);
							
							$wp_pinterest_board_id = $exID;
						}else{
							return false;
						}
					 
					}
					
					$url ="https://www.pinterest.com/resource/BoardFeedResource/get/?source_url=%2Fwelkerpatrick%2Frecipes%2F&data=%7B%22options%22%3A%7B%22board_id%22%3A%221266774834151486%22%2C%22board_url%22%3A%22%2Fwelkerpatrick%2Frecipes%2F%22%2C%22board_layout%22%3A%22default%22%2C%22prepend%22%3Atrue%2C%22page_size%22%3Anull%2C%22access%22%3A%5B%5D%7D%2C%22context%22%3A%7B%7D%7D&module_path=App()%3EUserProfilePage(resource%3DUserResource(username%3Dwelkerpatrick))%3EUserProfileContent(resource%3DUserResource(username%3Dwelkerpatrick))%3EUserBoards()%3EGrid(resource%3DProfileBoardsResource(username%3Dwelkerpatrick))%3EGridItems(resource%3DProfileBoardsResource(username%3Dwelkerpatrick))%3EBoard(show_board_context%3Dfalse%2C+show_user_icon%3Dfalse%2C+view_type%3DboardCoverImage%2C+component_type%3D1%2C+resource%3DBoardResource(board_id%3D1266774834151486))&_=1430694254166";
					//replacing board id
					$url = str_replace('1266774834151486', $wp_pinterest_board_id, $url);
					$surl = $url;
					
				}
				
				   
				curl_setopt($this->ch, CURLOPT_HEADER,0);
				curl_setopt($this->ch, CURLOPT_HTTPGET, 1);
				curl_setopt($this->ch, CURLOPT_URL, trim($surl));
				 
				$exec=curl_exec($this->ch);
				$x=curl_error($this->ch);
			 
				 
				if(stristr($exec, 'request_identifier')){
				 	//valid reply
				 
				 	//json to array
				 	$arr = json_decode($exec);

				 	 
			 	 	//pins objects
			 		$pins = $arr->resource_response->data;
			 		
			 		 
			 		//bookmark
					$new_bookmark = $arr->resource->options->bookmarks[0];
					
					//if($board != false) unset($pins[0]);
					
				 	//extract data
				 	$pins_ids = array();
				 	$pins_imgs= array(); 
				 	$pins_text = array(); 
				 	$pins_imgs_big = array();
				 	
				 	foreach ($pins as $pin){
					 	
				 		$pins_ids[] = $pin->id;
				 		$pins_text[] = $pin->description_html;
				 		
				 		$pinimgs = (Array)$pin->images;
				 		$pin_img = current( $pinimgs );
				 		
				 		 
				 		$pins_imgs_big[] = $pin_img->url ;
				 		$pins_imgs[] = $pinimgs['236x']->url;
  
				 	}
				 	  
				 
				}
					 
				 	 
				$pins=array($pins_ids,$pins_imgs,$pins_text,$pins_imgs_big);
				
				 
				return $pins;
				
		}// end function pins_get
		
		/*
		 * update : function to chek if the items needs to be updated if so it updates them
		 */
		function pins_update($pid,$key,$boards=false){
			
			//check if need update or not 
			$wp_pinterest_to_wp_ops=get_post_meta($pid,'wp_pinterest_to_wp_ops',1);
			
			if(!is_array($wp_pinterest_to_wp_ops)) $wp_pinterest_to_wp_ops=array();
			
			if(!in_array('OPT_UPDATE',$wp_pinterest_to_wp_ops)) return false;
			
			//last update date
			$last_update=get_post_meta($pid,'last_update',1);
			
			$gallery_update=get_post_meta($pid,'gallery_update',1);
			$gallery_unit=get_post_meta($pid,'gallery_unit',1);
			$updae_every=$gallery_unit * $gallery_update;
			
			$difference=$this->get_time_difference($last_update,time('now'));
			//echo '<br>minutes passed:'.$difference; 
			//echo '<br>update every:'.$updae_every.'<br>';
			
			//distroy data of the pins and call wp_pins_get so it get's them from pintest again
			if($difference > $updae_every ){
				$query="delete from wp_pinterest_to_wp_pins where pin_gallery='$pid'";
				$this->db->query($query);	
			}
			
		}//end function pins_update
		
		/*
		 * wp_pins_get: pins_get with caching
		* @pid: the custom post type id
		* @key: board link if $boards = true or username if $boards=false , pin_board is the db field for the key
		* @boards: true if key is a board id 
		*/
		function wp_pins_get($pid,$key,$boards=false,$board_id=false){

			//echo '   pid:'.$pid.' '.$key.' '.$boards.' board:'.$board_id;
			
			 
			
			$this->pid = $pid;
			
			//get the pins from db first if not get them from pinterest
			if($boards == false){
				$query="select * from wp_pinterest_to_wp_pins where pin_board='$pid' and pin_gallery='$pid'";
			}else{
				$query="select * from wp_pinterest_to_wp_pins where pin_board='$key'  and pin_gallery='$pid' ";
			
				 
			}
			
			 
			 $rows=$this->db->get_results($query);
			 
			 
			 
 
			 if(count($rows) == 0){
			 	
			  
			 	// no pins in the db lets get from pinterest
			 	if($boards == false){
			 		$pins=$this->pins_get($key); // key is a user 
			 	}else{
			 		$pins=$this->pins_get($key,true,$board_id); //key is board link
			 	}
			 	 
			 	if(count($pins[0]) > 0 ){
			 		
			 		//more than a pin found let's cache
			 		$ids=$pins[0];
			 		$imgs=$pins[1];
			 		$ttls=$pins[2];
			 		$pins_imgs_big=$pins[3];
			 		
			 		if($boards == false){
			 			$pid_field=$pid;
			 		}else{
			 			$pid_field=$key;
			 		}
 
			 		 
			 		$i=0;
			 		foreach($ids as $idn){
			 			$query="insert into wp_pinterest_to_wp_pins(pin_id,pin_board,pin_img,pin_text,pin_img_big,pin_gallery) values ('$idn', '$pid_field','$imgs[$i]','".urlencode($ttls[$i])."','$pins_imgs_big[$i]','$pid')";
			 			$this->db->query($query);
			 			$i++;
			 		}
			 		
			 		//update last update date
			 		
			 		update_post_meta($pid,'last_update',time('now'));
			 		
			 		$type=get_post_meta($pid,'gallery_type',1);
			 		
			 		
			 		 
			 		if($type != 'boards'){
			 			@update_post_meta($pid,'gallery_itms',$ids);
			 		} 
			 		
			 		return $pins;
			 		
			 	}else{
			 		//no pins 
			 		return false;
			 	}
			 	
			 }else{
			 	
			 	 
			 	//found in db return
			 	$return = array();
			 	foreach ($rows as $row){
			 		$ids[]=$row->pin_id;
			 		$imgs[]=$row->pin_img;
			 		$ttls[]=$row->pin_text;
			 		$pin_imgs_big[]=$row->pin_img_big;
			 		
			 		
			 	}

			 	$return = array($ids,$imgs,$ttls,$pin_imgs_big);
			 	
			 	//check to update
			 	$this->pins_update($pid,$key,$boards);
			 	
			 	return $return;
			 	
			 }
				
		}
		
		/*
		 * function : pin_get 
		 * get the big image src , original link from the id of the pin
		 */
		function pin_get($pin_id){
			
			//get http://pinterest.com/resource/PinResource/get/?data={%22options%22%3A{%22id%22%3A%221266706118120650%22%2C%22view_type%22%3A%22detailed%22}%2C%22module%22%3A{%22name%22%3A%22CloseupContent%22%2C%22options%22%3A{%22id%22%3A%22content%22%2C%22resource%22%3A{%22name%22%3A%22PinResource%22%2C%22options%22%3A{%22id%22%3A%221266706118120650%22%2C%22view_type%22%3A%22detailed%22}}}%2C%22append%22%3Afalse}%2C%22context%22%3A{%22app_version%22%3A%225ad1cd0%22}}&source_url=%2Fpin%2F1266706118120653%2F&module_path=App%28%29%3EUserProfilePage%28resource%3DUserResource%28username%3Dwelkerpatrick%29%29%3EUserProfileContent%28resource%3DUserResource%28username%3Dwelkerpatrick%29%29%3EGrid%28resource%3DUserPinsResource%28username%3Dwelkerpatrick%29%29%3EGridItems%28resource%3DUserPinsResource%28username%3Dwelkerpatrick%29%29%3EPin%28show_rich_title%3Dfalse%2C+show_via%3Dfalse%2C+pin_id%3D1266706118120653%2C+show_board%3Dtrue%2C+squish_giraffe_pins%3Dfalse%2C+show_pinner%3Dfalse%2C+show_pinned_from%3Dfalse%2C+resource%3DPinResource%28id%3D1266706118120653%29%29&_=1373391535254
			$url="http://pinterest.com/resource/PinResource/get/?data={%22options%22%3A{%22id%22%3A%22$pin_id%22%2C%22view_type%22%3A%22detailed%22}%2C%22module%22%3A{%22name%22%3A%22CloseupContent%22%2C%22options%22%3A{%22id%22%3A%22content%22%2C%22resource%22%3A{%22name%22%3A%22PinResource%22%2C%22options%22%3A{%22id%22%3A%22$pin_id%22%2C%22view_type%22%3A%22detailed%22}}}%2C%22append%22%3Afalse}%2C%22context%22%3A{%22app_version%22%3A%225ad1cd0%22}}&source_url=%2Fpin%2F1266706118120653%2F&module_path=App%28%29%3EUserProfilePage%28resource%3DUserResource%28username%3Dwelkerpatrick%29%29%3EUserProfileContent%28resource%3DUserResource%28username%3Dwelkerpatrick%29%29%3EGrid%28resource%3DUserPinsResource%28username%3Dwelkerpatrick%29%29%3EGridItems%28resource%3DUserPinsResource%28username%3Dwelkerpatrick%29%29%3EPin%28show_rich_title%3Dfalse%2C+show_via%3Dfalse%2C+pin_id%3D1266706118120653%2C+show_board%3Dtrue%2C+squish_giraffe_pins%3Dfalse%2C+show_pinner%3Dfalse%2C+show_pinned_from%3Dfalse%2C+resource%3DPinResource%28id%3D1266706118120653%29%29&_=1373391535254";
			
			//curl get
			$x='error';
			
			curl_setopt($this->ch, CURLOPT_HTTPGET, 1);
			curl_setopt($this->ch, CURLOPT_URL, trim($url));
			while (trim($x) != ''  ){
				$exec=curl_exec($this->ch);
				 $x=curl_error($this->ch);
			}
			
			
			 
			//extract link : <a href=\"http://www.morenailpolish.com/2012/03/nail-art-challenge-judges-top-eight-and.html\">\n\n\n\n\n\n\n    <div class=\"imageContainer
			preg_match_all('/<a href=\\\"(.*?)\\\">\\\n\\\n\\\n\\\n\\\n\\\n\\\n    <div class=\\\"imageContainer\\\" style=.*<img src=\\\"(.*?)\\\" class=\\\"pinImage/s',$exec,$matches,PREG_PATTERN_ORDER);
			
			$pin_img=$matches[2];
			$pin_link=$matches[1];
			
			$pin=array($pin_img[0],$pin_link[0]);
			
			return $pin;
			
		}
		
		
		
	/* 
	 * Logging Function
	 */
	function log($type,$data){
		 
		$now = date( 'Y-m-d H:i:s');
		$data=addslashes($data);
		$query="INSERT INTO wp_pinterest_to_wp_log (action,date,data) values('$','$now','$data')";
		 
		$this->db->query($query);
	}
	
	/*
	 * function get_time_difference: get the time difference in minutes.
	 * @start: time stamp
	 * @end: time stamp
	 */
	
	function get_time_difference( $start, $end )
	{
	 
    $uts['start']      =     $start ;
    $uts['end']        =      $end ;
    
    
    
    if( $uts['start']!==-1 && $uts['end']!==-1 )
    {
        if( $uts['end'] >= $uts['start'] )
        {
            $diff    =    $uts['end'] - $uts['start'];

            return round($diff/60,0);
            
        }
        
    }
    
    
}//end function
	
	
		
	
}//end class

/*
 * class test
 */

$pinterest=new pinterest();

//echo '<pre>'; //testings
//print_r($pinterest->boards_get('ThaGawddess1'));
 
//print_r($pinterest->boards_get('welkerpatrick'));


//print_r($pinterest->pins_get('/alisyntaege/home/',true)); // ('welkerpatrick'));

//print_r($pinterest->pins_get('welkerpatrick')); // ('welkerpatrick'));