<?php


/**
 * Description of Instagram
 *
 * @author Nexthon
 */

/*
 {source_info}{"name":"Instagram.com","website":"https:\/\/www.instagram.com\/"}{end_source_info}
 */
class Instagram 
{
    //put your code here
    /*** Get Instagaram video Info ***/
	 function getMediaInfo($url) 
        {
		$data = array();
		$data['found'] = 0;
		$urlParts = parse_url($url);
		if(isset($urlParts['path'])) {
			$pathArr = explode("/",rtrim($urlParts['path'],"/"));
			if(count($pathArr) == 3 && $pathArr[1] == "p") {
				$id = $pathArr[2];
				$result = getRemoteContents($url);
				if($result) {
					$result = getStringBetween($result,'window._sharedData = ',';</script>');
					if(!empty($result)) {
						$result = json_decode($result,true);
						if(isset($result['entry_data']) && isset($result['entry_data']['PostPage'][0]['graphql']['shortcode_media'])) {
							$result = $result['entry_data']['PostPage'][0]['graphql']['shortcode_media'];
							if($result['is_video'] == 1 && isset($result['video_url'])) {
								$data['found'] = 1;
								$data['id'] = $id;
								$title = "Video by Instagaram - ".$result['owner']['username'];
								$data['title'] = $title;
								if(isset($result['edge_media_to_caption']['edges'][0]['node']['text'])) {
									$description = $result['edge_media_to_caption']['edges'][0]['node']['text'];
									$data['description'] = htmlentities(truncate(trim(preg_replace('/[\s]+/',' ',preg_replace("/\r|\n/", " ", $description))),250),ENT_QUOTES);
								}
								else {
									$data['description'] = "Download ".$title." From Instagaram";
								}
								$data['image'] = end($result['display_resources'])['src'];
								$data['script'] = '$(document).on("click",".video-thumb",function() { window.open("'.$url.'", "_blank");});';
								
								$videos = array();
								
								$height = $result['dimensions']['height'];
								$formatId = $height;
								$link = array();
								$formatData = array();
								$formatData['order'] = 1;
								$formatData['height'] = $height;
								$formatData['ext'] = "mp4";
								$formatData['resolution'] = $height."p";
								$formatData['video'] = "true";
								$formatData['video_only'] = "false";
								$link['data'] = $formatData;
								$link['formatId'] = $formatId;
								$link['order'] = 1;
								$link['url'] = $result['video_url'];
								$link['title'] = $title.".".$formatData['ext'];
								$link['size'] = "unknown";
								
								array_push($videos,$link);
								$data['videos'] = $videos;
							}
						}
					}
				}
			}
		}
		return $data;
	}
}
