<?php
// +------------------------------------------------------------------------+
// | PHP Melody
// +------------------------------------------------------------------------+
// | PHP Melody IS FREE SOFTWARE
// | If you have downloaded this software from a website other
// | than Google or if you have otherwise received
// | this software from someone who is not a representative of
// | this site you are NOT involved in an illegal activity.
// | ---
// | In such case, please contact us.
// +------------------------------------------------------------------------+
// | Developed by: PHPSUGAR
// | Copyright: (c) 2004-2013 PHPSUGAR. All rights reserved.
// +------------------------------------------------------------------------+

namespace phpmelody\sources\src_youtube;

if ( ! class_exists('PhpmelodyYouTube'))
{
	include(ABSPATH . _ADMIN_FOLDER .'/src/youtube-sdk/autoload.php');
}

if ( ! is_object($youtube_api))
{
	$google_client = new \Google_Client();
	$google_client->setDeveloperKey($config['youtube_api_key']);

	$youtube_api = new \PhpmelodyYouTube($google_client);
}


function do_main(&$video_details, $url, $show_warnings = true)
{
	global $youtube_api;

	preg_match("/v=([^(\&|$)]*)/", $url, $matches);
	$yt_id = $matches[1];

	$item = $youtube_api->pm_get_video($yt_id);

	if (array_key_exists('error', $item) && $item['error']['message'] != '')
	{
		echo ($show_warnings) ? pm_alert_error($item['error']['message']) : '';
		return false;
	}
	$item = $item[0];

	// map details to older version
	$video_details = array( 'video_title' => $item['title'],
							'description' => $item['description'],
							'yt_length' => $item['duration'],
							'yt_id' => $item['id'],
							'direct' => $item['url'],
							'url_flv' => ($item['url_flv'] != '') ? $item['url_flv'] : $item['url'],
							'yt_thumb' => $item['thumbs'][0]['medium'],
							'keywords' => '',
							'embeddable' => $item['embeddable'],
							'geo-restriction' => $item['geo-restriction'],
							'private' => $item['private'],
							'embed_url' => $item['embed_url'],
							'mp4' => ''
						);
}

function download_thumb($thumbnail_link, $upload_path, $video_uniq_id, $overwrite_existing_file = false) {
	
	if (strpos($thumbnail_link, '//') === 0)
	{
		$thumbnail_link = 'http:'. $thumbnail_link;
	}
	
	if (strpos($thumbnail_link, 'http') !== 0)
	{
		$thumbnail_link = 'http://'. $thumbnail_link;
	}
	
	$last_ch = substr($upload_path, strlen($upload_path)-1, strlen($upload_path));
	if($last_ch != "/")
		$upload_path .= "/"; 

	$ext = ".jpg";
	
	$thumb_name = $video_uniq_id . "-1" . $ext;
	
	if(is_file( $upload_path . $thumb_name ) && ! $overwrite_existing_file) {
		return FALSE;
	}
	
	$error = 0;

	if ( function_exists('curl_init') ) 
	{

		$ch = curl_init();
		$timeout = 0;
		curl_setopt ($ch, CURLOPT_URL, $thumbnail_link);
		curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
		
		// Getting binary data
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		
		$image = curl_exec($ch);
		curl_close($ch);
		
		//	create & save image;
		$img_res = @imagecreatefromstring($image);
		if($img_res === false)
			return FALSE;
		
		$img_width = imagesx($img_res);
		$img_height = imagesy($img_res);
		
		$resource = @imagecreatetruecolor($img_width, $img_height);
		
		if( function_exists('imageantialias'))
		{
			@imageantialias($resource, true); 
		}
		
		@imagecopyresampled($resource, $img_res, 0, 0, 0, 0, $img_width, $img_height, $img_width, $img_height);
		@imagedestroy($img_res);
	
		switch($ext)
		{
			case ".gif":
				//GIF
				@imagegif($resource, $upload_path . $thumb_name);
			break;
			case ".jpg":
				//JPG
				@imagejpeg($resource, $upload_path . $thumb_name);
			break;  
			case ".png":
				//PNG
				@imagepng($resource, $upload_path . $thumb_name);
			break;
		}
	}
	else if( ini_get('allow_url_fopen') == 1 )
	{
		// try copying it... if it fails, go to backup method.
		if(!copy($thumbnail_link, $upload_path . $thumb_name ))
		{
			//	create a new image
			list($img_width, $img_height, $img_type, $img_attr) = @getimagesize($thumbnail_link);

			$image = '';

			switch($img_type)
			{
				case 1:
					//GIF
					$image = imagecreatefromgif($thumbnail_link);
					$ext = ".gif";
				break;
				case 2:
					//JPG
					$image = imagecreatefromjpeg($thumbnail_link);
					$ext = ".jpg";
				break;  
				case 3:
					//PNG
					$image = imagecreatefrompng($thumbnail_link);
					$ext = ".png";
				break;
			}
			
			$resource = @imagecreatetruecolor($img_width, $img_height);
			if( function_exists('imageantialias'))
			{
				@imageantialias($resource, true); 
			}
			
			@imagecopyresampled($resource, $image, 0, 0, 0, 0, $img_width, $img_height, $img_width, $img_height);
			@imagedestroy($image);
		}
		
		$thumb_name = $video_uniq_id . "-1" . $ext;
		
		$img_type = 2;
		switch($img_type)
		{
			default:
			case 1:
				//GIF
				@imagegif($resource, $upload_path . $thumb_name);
			break;
			case 2:
				//JPG
				@imagejpeg($resource, $upload_path . $thumb_name);
			break;  
			case 3:
				//PNG
				@imagepng($resource, $upload_path . $thumb_name);
			break;
		}
		
		if($resource === '')
			$error = 1;
	} 

	return $upload_path . $thumb_name;
}

// deprecated @since v2.3.1
function get_info($url = '') {}
function get_flv($url, $hq = 0) {}
function fetch_headers($url = '') {}
function get_thumb_link($video_data = '') {}
function video_details($video_data = array(), $url = '', &$info, $show_warnings = true) {}