<?php
/*
	WPRS Video - extract video info
	
	WARNING: This file is part of the core WPRichSnippets plugin. DO NOT edit
	this file under any circumstances.
    */
	
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
	

//add_filter('wprs_entry_before', 'wprs_video_markup_output');
/**
 * Use WPRS filter to output video markup
 *
 * @param array $content
 * @since 1.3.8
 * @return array
 */
function wprs_video_markup_output($content) {
	global $post;
	if (!wprs_is_enabled($post->ID)) return $content;
	$template = wprs_template();
	$description = $template['description_raw'] != '' ? '<meta content="'.$template['description_raw'].'" itemprop="description">': ''; 
		
	$videoURL	= get_post_meta($post->ID, '_wprs_post_youtube', true);
	$videoId	= wprs_get_video_id_by_url($videoURL);
	$videoInfo	= wprs_get_video_details($videoURL);
		
	//echo '<pre>'; print_r($videoInfo); echo'</pre>'; exit;
	
	$content = $videoInfo . $content;
	
	return $content;
}



/**
 * Get video details by video URL
 *
 * @link https://gist.github.com/djekl/5832149
 * @param string $video_url The video url (YouTube, Vimeo)
 * @since 1.3.8
 * @return array 
 */
function wprs_get_video_details( $video_url ) {
	
	$host = explode('.', str_replace('www.', '', strtolower(parse_url($video_url, PHP_URL_HOST))));
	$host = isset($host[0]) ? $host[0] : $host;
	
	switch ( $host ) {
		
		case 'vimeo':
			
			$video_id	= wprs_get_video_id_by_url( $video_url );
			$vimeo		= wprs_get_vimeo_json_decode( $video_id );
 			
			//header("Content-Type: text/plain");
			//print_r($hash);
			//exit;
			return array(
                    'provider'          => 'Vimeo',
                    'title'             => $vimeo[0]->title,
                    'description'       => str_replace(array("<br>", "<br/>", "<br />"), NULL, $vimeo[0]->description),
                    'description_nl2br' => str_replace(array("\n", "\r", "\r\n", "\n\r"), NULL, $vimeo[0]->description),
                    'thumbnail'         => $vimeo[0]->thumbnail_large,
                    'video'             => "https://vimeo.com/" . $vimeo[0]->id,
                    'embed_video'       => "https://player.vimeo.com/video/" . $vimeo[0]->id,
					'duration'      	 => $vimeo[0]->duration,
                );
            break;
		
		case 'youtube' || 'youtu' :
			
			$video_id	= wprs_get_video_id_by_url( $video_url );
            $youtube	= wprs_get_youtube_json_decode( $video_id );
			
			return $youtube;
			
           /* return array(
                    'provider'          => 'YouTube',
                    'title'             => $hash->data->title,
                    'description'       => str_replace(array("<br>", "<br/>", "<br />"), NULL, $hash->data->description),
                    'description_nl2br' => str_replace(array("\n", "\r", "\r\n", "\n\r"), NULL, nl2br($hash->data->description)),
                    'thumbnail'         => $hash->data->thumbnail->hqDefault,
                    'video'             => "http://www.youtube.com/watch?v=" . $hash->data->id,
                    'embed_video'       => "http://www.youtube.com/v/" . $hash->data->id,
                );*/
            break;
    } // End switch
}



/**
 * Get video ID by URL
 *
 * @link https://gist.github.com/ckchaudhary/8629242#file-get-youtube-video-id-from-url
 * @param string $url The video url (YouTube, Vimeo)
 * @since 1.3.8
 * @return string , the video ID
 */
function wprs_get_video_id_by_url( $video_url ){
    /*
    * type1: http://www.youtube.com/watch?v=9Jr6OtgiOIw
    * type2: http://www.youtube.com/watch?v=9Jr6OtgiOIw&feature=related
    * type3: http://youtu.be/9Jr6OtgiOIw
	* type4: https://vimeo.com/136757205
    */
    $vid_id = "";
    $flag = false;
    if(isset($video_url) && !empty($video_url)){
        /*case1 and 2*/
        $parts = explode("?", $video_url);
        if(isset($parts) && !empty($parts) && is_array($parts) && count($parts)>1){
            $params = explode("&", $parts[1]);
            if(isset($params) && !empty($params) && is_array($params)){
                foreach($params as $param){
                    $kv = explode("=", $param);
                    if(isset($kv) && !empty($kv) && is_array($kv) && count($kv)>1){
                        if($kv[0]=='v'){
                            $vid_id = $kv[1];
                            $flag = true;
                            break;
                        }
                    }
                }
            }
        }

        /*case 3*/
        if(!$flag){
            $needle = "youtu.be/";
            $pos = null;
            $pos = strpos($video_url, $needle);
            if ($pos !== false) {
                $start = $pos + strlen($needle);
                $vid_id = substr($video_url, $start, 11);
                $flag = true;
            }
        }
		
		/*case vimeo 4*/
        if(!$flag){
            $needle = "vimeo.com/";
            $pos = null;
            $pos = strpos($video_url, $needle);
            if ($pos !== false) {
                $start = $pos + strlen($needle);
                $vid_id = substr($video_url, $start, 9);
                $flag = true;
            }
        }
		
    }
    return $vid_id;
}



/**
 * Get YouTube JSON decode info by ID 
 *
 * @param string $video_id
 * @since 1.3.8
 * @return array
 */
function wprs_get_youtube_json_decode( $video_id ) {

	$youtube = "http://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=". $video_id ."&format=json";
	
	$curl = curl_init($youtube);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	$return = curl_exec($curl);
	curl_close($curl);
	
	return json_decode($return, true);
}



/**
 * Get Vimeo JSON decode info by ID 
 *
 * @param string $video_id
 * @since 1.3.8
 * @return array
 */
function wprs_get_vimeo_json_decode( $video_id ) {

	return json_decode(file_get_contents("http://vimeo.com/api/v2/video/".$video_id.".json"));
}


add_filter('oembed_dataparse','wprs_oembed_dataparse', 10, 3);
/**
 * Add Schema VideoObject to oembed
 *
 * @param string $video_id
 * @since 1.3.8
 * @return array
 */
function wprs_oembed_dataparse( $return, $data, $url ) {
	
	global $post;
	
	if ( ! wprs_is_enabled($post->ID) ) return $return;
	
	//print_r($data); exit;
	
	$video_id		= '';		
	$name			= '';
	$description	= '';
	$thumbnail_url	= '';
	$upload_date	= '';		
	$duration 		= '';
			
	$host 			= isset($data->provider_name) ? $data->provider_name : '';
	
	$supported_hosts = array ( 'TED', 'Vimeo', 'Dailymotion', 'VideoPress', 'Vine', 'YouTube' );
	
	if ( ! in_array( $host, $supported_hosts) ) return $return;
	
	// Get values from post meta
	$meta_name			= get_post_meta( $post->ID, '_wprs_post_embed_title', true );
	$meta_description	= get_post_meta( $post->ID, '_wprs_post_embed_description', true );
	$meta_upload_date	= get_post_meta( $post->ID, '_wprs_post_embed_upload_date', true );
	$meta_duration		= get_post_meta( $post->ID, '_wprs_post_embed_duration', true );
	
	// Override values if found via parsing the data
	$video_id		= isset($data->video_id) ? $data->video_id : '';
	$name			= isset($data->title) ? $data->title : $meta_name;
	$description	= isset($data->description) ? $data->description : $meta_description;
	$thumbnail_url	= isset($data->thumbnail_url) ? $data->thumbnail_url : '';
	$upload_date	= isset($data->upload_date) ? $data->upload_date : $meta_upload_date;
	$duration		= isset($data->duration) ? wprs_get_time_second_to_iso8601_duration( $data->duration ) : $meta_duration;
			
			
	$schema_array = array (
						
							'title'			=> $name,
							'description'	=> $description,
							'thumbnailUrl'	=> $thumbnail_url,
							'uploadDate'	=> $upload_date,
							'duration'		=> $duration,
					);
	
	$schema = '<div itemprop="video" itemscope itemtype="http://schema.org/VideoObject">';
	
	if($name)								$schema .= '<meta itemprop="name" content="'.$name.'"/>';
	if($description)						$schema .= '<meta itemprop="description" content="'.$description.'"/>';
	if($thumbnail_url)						$schema .= '<meta itemprop="thumbnailUrl" content="'. $thumbnail_url.'"/>';
	if($upload_date)						$schema .= '<meta itemprop="uploadDate" content="'.$upload_date.'"/>';
	if($duration)							$schema .= '<meta itemprop="duration" content="'.$duration.'"/>';
	if($video_id && $host == 'Vimeo')		$schema .= '<meta itemprop="embedUrl" content="https://player.vimeo.com/video/'.$video_id.'"/>';
	
	$schema .= '</div>';
	
	// Use video thumbnail as main page image
	if($thumbnail_url)						$schema .= wprs_get_video_thumb_mageObject($thumbnail_url);
	
	// Return Schema
	return $data->html . $schema;
	
	///
	/// What's below is not needed at theis time!
	///
	switch ( $host ) {
		
		case 'YouTube':
			
			// Try remove related videos
			$data->html = str_replace('feature=oembed', 'feature=oembed&#038;rel=0', $data->html);
		
			$name			= $data->title;
			$description	= '';
			$thumbnail_url	= $data->thumbnail_url;
			$upload_date	= '';
		
			$schema = '<div itemscope itemtype="http://schema.org/VideoObject">';
			$schema .= '<meta itemprop="name" content="'.$name.'"/>';
			$schema .= '<meta itemprop="description" content="Some description"/>';
			$schema .= '<meta itemprop="thumbnailUrl" content="'. $thumbnail_url.'"/>';
			$schema .= '<meta itemprop="uploadDate" content="2015-02-05T08:00:00+08:00"/>';
			$schema .= '</div>';
		
        	return $data->html . $schema;
            break;
			
		case 'Vimeo':
			
			$video_id		= $data->video_id;
			$name			= $data->title;
			$description	= $data->description;
			$thumbnail_url	= $data->thumbnail_url;
			$upload_date	= $data->upload_date;
			$duration		= wprs_get_time_second_to_iso8601_duration( $data->duration );
			
			
			$schema = '<div itemscope itemtype="http://schema.org/VideoObject">';
			$schema .= '<meta itemprop="name" content="'.$name.'"/>';
			$schema .= '<meta itemprop="description" content="'.$description.'"/>';
			$schema .= '<meta itemprop="thumbnailUrl" content="'. $thumbnail_url.'"/>';
			$schema .= '<meta itemprop="uploadDate" content="'.$upload_date.'"/>';
			$schema .= '<meta itemprop="duration" content="'.$duration.'"/>';
			$schema .= '<meta itemprop="embedUrl" content="https://player.vimeo.com/video/'.$video_id.'"/>';
			$schema .= '</div>';
			
			return $data->html . $schema;
            break;
			
		case 'Dailymotion':
			
			$name			= $data->title;
			$description	= $data->description;
			$thumbnail_url	= $data->thumbnail_url;
			$upload_date	= '';
			
			$schema = '<div itemscope itemtype="http://schema.org/VideoObject">';
			$schema .= '<meta itemprop="name" content="'.$name.'"/>';
			$schema .= '<meta itemprop="description" content="'.$description.'"/>';
			$schema .= '<meta itemprop="thumbnailUrl" content="'. $thumbnail_url.'"/>';
			$schema .= '<meta itemprop="uploadDate" content="2015-02-05T08:00:00+08:00"/>';
			$schema .= '</div>';
			
			return $data->html . $schema;
            break;		
		
		case 'VideoPress':
			
			$name			= $data->title;
			$description	= '';
			$thumbnail_url	= $data->thumbnail_url;
			$upload_date	= '';
			
			$schema = '<div itemscope itemtype="http://schema.org/VideoObject">';
			$schema .= '<meta itemprop="name" content="'.$name.'"/>';
			$schema .= '<meta itemprop="description" content="Some description"/>';
			$schema .= '<meta itemprop="thumbnailUrl" content="'. $thumbnail_url.'"/>';
			$schema .= '<meta itemprop="uploadDate" content="2015-02-05T08:00:00+08:00"/>';
			$schema .= '</div>';
			
			return $data->html . $schema;
            break;	
    
		// Example
		/*
		<div itemscope itemtype="http://schema.org/VideoObject">
			<span itemprop="name">'.$name .'</span>
			<span itemprop="description">Video description</span>
			<img itemprop="thumbnailUrl" src="https://www.example.com/thumbnail1.jpg" alt="thumbnail text"/>
			<meta itemprop="uploadDate" content="2015-02-05T08:00:00+08:00"/>
			<meta itemprop="duration" content="PT1M33S" />
			<link itemprop="contentUrl" href="http://www.example.com/video123.flv" />
			<link itemprop="embedUrl" href="http://www.example.com/videoplayer.swf?video=123" />
			<meta itemprop="interactionCount" content="2347" />
		</div>
		*/
		
    }
	
	return $return;
}
