<?php
session_start();
header("Content-type: text/html; charset=utf8");
set_time_limit(60000*60);
error_reporting(E_ERROR);
if(!isset($_SESSION['media_cms_user']) OR $_SESSION['super_admin'] == 0) {
header("location:login.php");
}
include('../include/config.php');
include('../include/connect.php');
include('include/functions.php');
include('include/general.class.php');
$general = new General;
$general->set_connection($mysqli);
$options = $general->get_all_options();
$case = make_safe(xss_clean($_GET['case']));
$action = make_safe(xss_clean($_POST['action'])); 
if ($action == "sort_category"){
	$records = $_POST['records'];
	$counter = 1;
	foreach ($records as $record) {
		$sql = "UPDATE categories SET category_order='$counter' WHERE id='$record'";
		$query = $mysqli->query($sql);
		$counter = $counter + 1;	
	}
}
if ($action == "sort_pages"){
	$records = $_POST['records'];
	$counter = 1;
	foreach ($records as $record) {
		$sql = "UPDATE pages SET page_order='$counter' WHERE id='$record'";
		$query = $mysqli->query($sql);
		$counter = $counter + 1;	
	}
}
if ($case == "ajax_remove_from_list"){
if (isset($_GET)) {
$id = make_safe(xss_clean($_GET['id']));
$delete = $mysqli->query("DELETE FROM lists_media WHERE id='$id'");
if ($delete) {
echo 1;	
} else {
echo 0;	
}
}
}

if ($case == "media_details"){
$id = make_safe(xss_clean($_GET['id']));
$site = make_safe(xss_clean($_GET['site']));
?>
<div class="modal-dialog" id="media-details">
		<div class="modal-content">
		<div class="modal-header">
			<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
			<h4 class="modal-title">Video Details</h4>
		</div>
		<div class="modal-body">
			<div class="embed-responsive embed-responsive-16by9">
			<?php if ($site == 'youtube') { ?>
			<iframe src="http://www.youtube.com/embed/<?php echo $id; ?>"></iframe>
			<?php } elseif ($site == 'vimeo') { ?>
			<iframe src="https://player.vimeo.com/video/<?php echo $id; ?>"></iframe>
			<?php } elseif ($site == 'facebook') { ?>
			<iframe src="https://www.facebook.com/video/embed?video_id=<?php echo $id; ?>"></iframe>
			<?php } else { ?>
			<div class="alert alert-warning">DailyMotion Videos Can't Load in Ajax Modals. you can watch the selected video by clicking dailymotion.com link <a href="http://www.dailymotion.com/video/<?php echo $id; ?>" class="alert-link" target="_BLANK">Watch Video</a></div>
			<?php } ?>
			</div>
		</div>
		<div class="modal-footer">
			<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
		</div>
		</div>
</div>
<?php
}

if ($action == "sort_media_list"){
	$records = $_POST['records'];
	$counter = 1;
	foreach ($records as $record) {
		$sql = "UPDATE lists_media SET media_order='$counter' WHERE id='$record'";
		$query = $mysqli->query($sql);
		$counter = $counter + 1;	
	}
}
if ($action == "media_channel_import") {
	
	$id = abs(intval($_POST['id']));
	if (empty($id)) {
	header("location:login.php");
	}
	$sql = "SELECT * FROM channels WHERE id='$id' LIMIT 1";
	$query = $mysqli->query($sql);
	$row = $query->fetch_assoc();
	$category_id = $row['category_id'];
	$channel_id = $row['id'];
	$channel_link = $row['link'];
	$media_number = $row['media_number'];
	$day = date('j');
	$month = date('n');
	$year = date('Y');
	
	if ($row['video_site'] == 'youtube') {
	$u = parse_url($channel_link);
	if (strpos($channel_link,'/user/') != false) {
	$youtube_username = str_replace('/user/','',$u['path']);
	$baseUrl = 'https://www.googleapis.com/youtube/v3/';
	$apiKey = $options['api_youtube_apikey'];
	$link = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/channels?key='.$apiKey.'&forUsername='.$youtube_username.'&part=id'), true);
	$channelId = $link['items'][0]['id'];
	} else {
	$baseUrl = 'https://www.googleapis.com/youtube/v3/';
	$apiKey = $options['api_youtube_apikey'];
	$youtube_username = str_replace('/channel/','',$u['path']);	
	$channelId = $youtube_username;
	}
	$url = $baseUrl .'channels?' .
    'id=' . $channelId .
    '&part=contentDetails' . 
    '&key=' . $apiKey;
	$json = json_decode(file_get_contents($url), true);
	 
	$playlist = $json['items'][0]['contentDetails']['relatedPlaylists']['uploads'];
	 
	$url = $baseUrl .'playlistItems?' .
	 'part=snippet' .
	 '&maxResults=' .$media_number.
	 '&playlistId=' . $playlist .
	 '&key=' . $apiKey;
	$json = json_decode(file_get_contents($url), true);
	foreach(array_reverse($json['items']) as $video) {
		$video_id = $video['snippet']['resourceId']['videoId'];
		$video_title = htmlspecialchars($video['snippet']['title'],ENT_QUOTES);
		$video_details = htmlspecialchars($video['snippet']['description'],ENT_QUOTES);
		if (!empty($video['snippet']['thumbnails']['standard']['url'])) {
		$video_thumbnail = $video['snippet']['thumbnails']['standard']['url'];
		} else {
		$video_thumbnail = $video['snippet']['thumbnails']['high']['url'];	
		}
		$video_youtube_url = 'http://www.youtube.com/watch?v='.$video_id;
		if (check_video_id($video_id,'youtube') == 0) {
		$videt = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/videos?id='.$video_id.'&part=contentDetails&key='.$apiKey), true);
		$video_duration = $videt['items'][0]['contentDetails']['duration'];
		$duration = youtube_duration($video_duration);
		$datetime = time();
		if (!empty($video_thumbnail)) {
		$thumb = 'youtube_'.$video_id.'.jpg';
		$up = file_put_contents('../upload/media/'.$thumb,file_get_contents($video_thumbnail));	
		} else {
		$thumb = '';	
		}
		if (count($video['snippet']['tags']) > 0) {
			$tags = implode(',',$video['snippet']['tags']);
		} else {
			$tags = title_to_keywords($video['snippet']['title']);
		}
		$publish_time = youtube_date_to_unix($video['snippet']['publishedAt']);
		$insert = $mysqli->query("INSERT INTO media (user_id,video_site,video_id,channel_id,category_id,title,details,permalink,datetime,thumbnail,duration,tags,day,month,year,published,publish_time) VALUES ('$_SESSION[media_cms_user]','youtube','$video_id','$channel_id','$category_id','$video_title','$video_details','$video_youtube_url','$datetime','$thumb','$duration','$tags','$day','$month','$year','1','$publish_time')");
		}
	}	
	}
	
	if ($row['video_site'] == 'facebook') {
	$u = parse_url($channel_link);
	$u = parse_url($row['link']);
	$username = $u['path'];
	$token = $options['api_facebook_extended_token'];
	$graph = 'https://graph.facebook.com/v2.0/'.$username.'/videos?fields=embed_html,tags,length,picture,description,name,source,id,created_time,from,icon,thumbnails,updated_time&access_token='.$token.'&limit='.$media_number;
	$url = json_decode(file_get_contents($graph),true);
	foreach(array_reverse($url['data']) as $video) {
		$video_id = $video['id'];
		$video_title = htmlspecialchars($video['name'],ENT_QUOTES);
		$video_details = htmlspecialchars($video['description'],ENT_QUOTES);
		if (!empty($video['data']['thumbnails']['data'][1]['uri'])) {
		$video_thumbnail = $video['data']['thumbnails']['data'][1]['uri'];
		} else {
		$video_thumbnail = $video['data']['thumbnails']['data'][0]['uri'];
		}
		$video_facebook_url = 'https://www.facebook.com/'.$username.'/videos/'.$video_id.'/';
		if (check_video_id($video_id,'facebook') == 0) {
		$datetime = time();
		if (!empty($video_thumbnail)) {
		$thumb = 'facebook_'.$video_id.'.jpg';
		$up = file_put_contents('../upload/media/'.$thumb,file_get_contents($video_thumbnail));	
		} else {
		$thumb = '';	
		}
		if (count($video['tags']) > 0) {
			$tags = implode(',',$video['tags']);
		} else {
			$tags = title_to_keywords($video['name']);
		}
		$publish_time = youtube_date_to_unix($video['created_time']);
		$insert = $mysqli->query("INSERT INTO media (user_id,video_site,video_id,channel_id,category_id,title,details,permalink,datetime,thumbnail,duration,tags,day,month,year,published,publish_time) VALUES ('$_SESSION[media_cms_user]','facebook','$video_id','$channel_id','$category_id','$video_title','$video_details','$video_facebook_url','$datetime','$thumb','$duration','$tags','$day','$month','$year','1','$publish_time')");
		}
	}	
	}
	
	
	if ($row['video_site'] == 'vimeo') {
	$u = parse_url($channel_link);
	$user = str_replace('/','',$u['path']);
	$api_endpoint = 'http://vimeo.com/api/v2/' . $user;
	$user = simplexml_load_string(curl_get($api_endpoint . '/info.xml'));
	// if this user isn't updated before then import all his videos
	if ($row['latest_activity'] == 0) {
	$user_videos = $user->user->total_videos_uploaded;
	$pages = $user_videos/20;
	if (is_float($pages)) {
	$pages_number = ceil($pages);	
	} else {
	$pages_number = $pages;	
	}
	if ($pages_number >= 3) {
	$page_number = 3;	
	} else {
	$page_number = $pages_number;	
	}
	for ($i=$page_number;$i>0;$i--) {
	$videos = simplexml_load_string(curl_get($api_endpoint . '/videos.xml?page='.$i));
	$vid = object_to_array($videos);
	$vids = array_reverse($vid['video']);
	foreach ($vids as $video) {
	$title = htmlspecialchars($video['title'],ENT_QUOTES);	
	$description = htmlspecialchars($video['description'],ENT_QUOTES);
    if (count(explode(',',$video['tags'])) > 0) {
	$tags = $video['tags'];		
	} else { 	
	$tags = title_to_keywords($title);	
	}
	$permalink = $video['url'];	
	$duration = $video['duration'];	
	$vimeo_id = $video['id'];	
	$vimeo_user_id = $video['user_id'];
	$thumbnail = $video['thumbnail_large'];	
	$privacy = $video['embed_privacy'];
    $date_time = explode(' ',$upload_date);
	$dmy = explode('-',$date_time[0]);
	$hms = explode(':',$date_time[1]);
	$upload_unix = mktime($hms[0], $hms[1], $hms[2], $dmy[1], $dmy[0], $dmy[2]);	
	if (check_video_id($vimeo_id,'vimeo') == 0) {
	
	$datetime = time();
	$day = date('j');
	$month = date('n');
	$year = date('Y');
	if ($privacy == 'anywhere') {
	if (!empty($thumbnail)) {
	$filetype = strtolower(substr(strrchr($thumbnail,'.'),1));
	$thumb = 'vimeo_'.$vimeo_id.'.'.$filetype;
	$up = file_put_contents('../upload/media/'.$thumb,file_get_contents($thumbnail));	
	} else {
	$thumb = '';	
	}
	$publish_time = vimeo_date_to_unix($video['upload_date']);
	$insert = $mysqli->query("INSERT INTO media (user_id,video_site,video_id,channel_id,category_id,title,details,permalink,datetime,thumbnail,duration,tags,day,month,year,published,publish_time) VALUES ('$_SESSION[media_cms_user]','vimeo','$vimeo_id','$channel_id','$category_id','$title','$description','$permalink','$datetime','$thumb','$duration','$tags','$day','$month','$year','1','$publish_time')");
	}
	}
	}
	}
	// if this user is updated before then import only new videos
	} else {
	$videos = simplexml_load_string(curl_get($api_endpoint . '/videos.xml'));
	$vid = object_to_array($videos);
	$vids = array_reverse($vid['video']);
	foreach ($vids as $video) {
	$title = addslashes(htmlspecialchars($video['title'],ENT_QUOTES));	
	$description = addslashes(htmlspecialchars($video['description'],ENT_QUOTES));	
	if (count(explode(',',$video['tags'])) > 0) {
	$tags = $video['tags'];		
	} else { 	
	$tags = title_to_keywords($title);	
	}
	$permalink = $video['url'];	
	$duration = $video['duration'];	
	$vimeo_id = $video['id'];	
	$vimeo_user_id = $video['user_id'];
	$thumbnail = $video['thumbnail_large'];	
	$privacy = $video['embed_privacy'];	
	$date_time = explode(' ',$upload_date);
	$dmy = explode('-',$date_time[0]);
	$hms = explode(':',$date_time[1]);
	$upload_unix = mktime($hms[0], $hms[1], $hms[2], $dmy[1], $dmy[0], $dmy[2]);
	if (check_video_id($vimeo_id,'vimeo') == 0) {	
	$datetime = time();
	$day = date('j');
	$month = date('n');
	$year = date('Y');
	if ($privacy == 'anywhere') {
	if (!empty($thumbnail)) {
	$filetype = strtolower(substr(strrchr($thumbnail,'.'),1));
	$thumb = 'vimeo_'.$vimeo_id.'.'.$filetype;
	$up = file_put_contents('../upload/media/'.$thumb,file_get_contents($thumbnail));	
	} else {
	$thumb = '';	
	}
	$publish_time = vimeo_date_to_unix($video['upload_date']);
	$insert = $mysqli->query("INSERT INTO media (user_id,video_site,video_id,channel_id,category_id,title,details,permalink,datetime,thumbnail,duration,tags,day,month,year,published,publish_time) VALUES ('$_SESSION[media_cms_user]','vimeo','$vimeo_id','$channel_id','$category_id','$title','$description','$permalink','$datetime','$thumb','$duration','$tags','$day','$month','$year','1','$publish_time')");
	}
	}
	}
	}		
	}
	
	
	
	if ($row['video_site'] == 'dailymotion') {
	$u = parse_url($channel_link);
	$user = str_replace('/','',$u['path']);
	$url = 'https://api.dailymotion.com/user/'.$user.'/videos?fields=allow_embed,description,duration,embed_url,id,thumbnail_720_url,thumbnail_url,title,created_time,tags,url&limit='.$media_number;
	$videos = json_decode(file_get_contents($url), true);	
	foreach(array_reverse($videos['list']) as $video) {
		if ($video['allow_embed'] == 1) {
		$video_id = $video['id'];
		if (check_video_id($video_id,'dailymotion') == 0) {
		$video_title = htmlspecialchars($video['title'],ENT_QUOTES);
		$video_details = htmlspecialchars($video['description'],ENT_QUOTES);
		if (isset($video['thumbnail_720_url']) AND !empty($video['thumbnail_720_url'])) {
		$video_thumbnail = $video['thumbnail_720_url'];
		} else {
		$video_thumbnail = $video['thumbnail_url'];	
		}
		$video_dailymotion_url = $video['url'];
		$duration = $video['duration'];
		$datetime = time();
		if (!empty($video_thumbnail)) {
		$filetype = strtolower(substr(strrchr($video_thumbnail,'.'),1));
		$thumb = 'dailymotion_'.$video_id.'.'.$filetype;
		$up = file_put_contents('../upload/media/'.$thumb,file_get_contents($video_thumbnail));	
		} else {
		$thumb = '';	
		}
		if (count($video['tags']) > 0) {
			$tags = implode(',',$video['tags']);
		} else {
			$tags = title_to_keywords($video['title']);
		}
		$publish_time = $video['created_time'];
		$insert = $mysqli->query("INSERT INTO media (user_id,video_site,video_id,channel_id,category_id,title,details,permalink,datetime,thumbnail,duration,tags,day,month,year,published,publish_time) VALUES ('$_SESSION[media_cms_user]','dailymotion','$video_id','$channel_id','$category_id','$video_title','$video_details','$video_dailymotion_url','$datetime','$thumb','$duration','$tags','$day','$month','$year','1','$publish_time')");
		}
		}
	}
	}	
	$now = time();
	$mysqli->query("UPDATE channels SET latest_activity='$now' WHERE id='$id'");
}


// import single video
if ($action == "import_single_youtube_video") {
	$id = make_safe($_POST['id']);
	$category = make_safe($_POST['category']);
	if (empty($id)) {
	header("location:login.php");
	}
		$baseUrl = 'https://www.googleapis.com/youtube/v3/';
		$apiKey = $options['api_youtube_apikey'];
		$url = $baseUrl .'videos?' .
				'id=' .$id.
				'&part=snippet' . 
				'&key=' . $apiKey;
		$json = json_decode(file_get_contents($url), true);

		if (count($json['items']) == 0) {
		echo 'failure';	
		} else {			
		$video_title = htmlspecialchars($json['items'][0]['snippet']['title'],ENT_QUOTES);
		$video_details = htmlspecialchars($json['items'][0]['snippet']['description'],ENT_QUOTES);
		if (!empty($json['items'][0]['snippet']['thumbnails']['standard']['url'])) {
		$video_thumbnail = $json['items'][0]['snippet']['thumbnails']['standard']['url'];
		} else {
		$video_thumbnail = $json['items'][0]['snippet']['thumbnails']['high']['url'];	
		}
		$video_youtube_url = 'http://www.youtube.com/watch?v='.$id;
		$videt = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/videos?id='.$id.'&part=contentDetails&key='.$apiKey), true);
		$video_duration = $videt['items'][0]['contentDetails']['duration'];
		$duration = youtube_duration($video_duration);
		if (check_video_id($id,'youtube') == 0) {
		$datetime = time();
		$day = date('j');
		$month = date('n');
		$year = date('Y');
		if (!empty($video_thumbnail)) {
		$thumb = 'youtube_'.$id.'.jpg';
		$up = file_put_contents('../upload/media/'.$thumb,file_get_contents($video_thumbnail));	
		} else {
		$thumb = '';	
		}
		if (count($json['items'][0]['snippet']['tags']) > 0) {
			$tags = implode(',',$json['items'][0]['snippet']['tags']);
		} else {
			$tags = title_to_keywords($json['items'][0]['snippet']['title']);
		}
		$publish_time = youtube_date_to_unix($json['items'][0]['snippet']['publishedAt']);
		$insert = $mysqli->query("INSERT INTO media (user_id,video_site,video_id,channel_id,category_id,title,details,permalink,datetime,thumbnail,duration,tags,day,month,year,published,publish_time) VALUES ('$_SESSION[media_cms_user]','youtube','$id','0','$category','$video_title','$video_details','$video_youtube_url','$datetime','$thumb','$duration','$tags','$day','$month','$year','1','$publish_time')");
		if ($insert) {
		echo 'success';	
		} else {
		echo 'failure';	
		}
		} else {
		echo 'failure';	
		}
		}
}


if ($action == "import_single_dailymotion_video") {
	$id = make_safe($_POST['id']);
	$category = make_safe($_POST['category']);
	if (empty($id)) {
	header("location:login.php");
	}
		$url = 'https://api.dailymotion.com/video/'.$id.'?fields=allow_embed,description,duration,embed_url,id,thumbnail_720_url,thumbnail_url,title,created_time,tags,url';
		$json = json_decode(file_get_contents($url), true);

		if (count($json) == 0) {
		echo 'failure';	
		} else {
		if ($json['allow_embed'] == 1) {
		$video_id = $json['id'];			
		$video_title = htmlspecialchars($json['title'],ENT_QUOTES);
		$video_details = htmlspecialchars($json['description'],ENT_QUOTES);
		if (!empty($json['thumbnail_720_url'])) {
		$video_thumbnail = $json['thumbnail_720_url'];
		} else {
		$video_thumbnail = $json['thumbnail_url'];	
		}
		$video_youtube_url = $json['url'];	
		if (check_video_id($id,'dailymotion') == 0) {
		$datetime = time();
		$day = date('j');
		$month = date('n');
		$year = date('Y');
		if (!empty($video_thumbnail)) {
		$thumb = 'dailymotion_'.$id.'.jpg';
		$up = file_put_contents('../upload/media/'.$thumb,file_get_contents($video_thumbnail));	
		} else {
		$thumb = '';	
		}
		$duration = $json['duration'];	
		if (count($json['tags']) > 0) {
			$tags = implode(',',$json['tags']);
		} else {
			$tags = title_to_keywords($json['title']);
		}
		$video_dailymotion_url = $json['url'];
		$publish_time = $json['created_time'];
		$insert = $mysqli->query("INSERT INTO media (user_id,video_site,video_id,category_id,title,details,permalink,datetime,thumbnail,duration,tags,day,month,year,published,publish_time) VALUES ('$_SESSION[media_cms_user]','dailymotion','$id','$category','$video_title','$video_details','$video_dailymotion_url','$datetime','$thumb','$duration','$tags','$day','$month','$year','1','$publish_time')");
		if ($insert) {
		echo 'success';	
		} else {
		echo 'failure';	
		}
		} else {
		echo 'failure';	
		}
		}
		}
}


if ($action == "import_channel_single_video") {
if (isset($_POST)) {
		$site = make_safe(xss_clean($_POST['site']));
		$category = make_safe(xss_clean(intval($_POST['category'])));
		$channel = make_safe(xss_clean(intval($_POST['channel'])));			
		$id = make_safe(xss_clean($_POST['id']));
		$datetime = time();
		$day = date('j');
		$month = date('n');
		$year = date('Y');
		if (empty($id)) {
		echo 'failure';	
		} else {
			switch ($site) {
				case 'youtube';
				if (check_video_id($id,'youtube') > 0) {
				echo 'failure';	
				} else {
				$baseUrl = 'https://www.googleapis.com/youtube/v3/';
				$apiKey = $options['api_youtube_apikey'];
				$url = $baseUrl.'videos?'.
						'id='.$id.
						'&part=snippet'. 
						'&key='.$apiKey;
				$json = json_decode(file_get_contents($url), true);
				if (count($json['items']) == 0) {
				echo 'failure';	
				} else {
				$video_title = htmlspecialchars($json['items'][0]['snippet']['title'],ENT_QUOTES);
				$video_details = htmlspecialchars($json['items'][0]['snippet']['description'],ENT_QUOTES);
				if (!empty($json['items'][0]['snippet']['thumbnails']['standard']['url'])) {
				$video_thumbnail = $json['items'][0]['snippet']['thumbnails']['standard']['url'];
				} else {
				$video_thumbnail = $json['items'][0]['snippet']['thumbnails']['high']['url'];	
				}
				$video_youtube_url = 'http://www.youtube.com/watch?v='.$id;
				$videt = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/videos?id='.$id.'&part=contentDetails&key='.$apiKey), true);
				$video_duration = $videt['items'][0]['contentDetails']['duration'];
				$duration = youtube_duration($video_duration);
				if (!empty($video_thumbnail)) {
				$thumb = 'youtube_'.$id.'.jpg';
				$up = file_put_contents('../upload/media/'.$thumb,file_get_contents($video_thumbnail));	
				} else {
				$thumb = '';	
				}
				if (count($json['items'][0]['snippet']['tags']) > 0) {
					$tags = implode(',',$json['items'][0]['snippet']['tags']);
				} else {
					$tags = title_to_keywords($json['items'][0]['snippet']['title']);
				}
				$publish_time = youtube_date_to_unix($json['items'][0]['snippet']['publishedAt']);
				$insert = $mysqli->query("INSERT INTO media (video_site,video_id,user_id,category_id,channel_id,title,details,permalink,datetime,thumbnail,duration,day,month,year,published,tags,publish_time) VALUES ('youtube','$id','$_SESSION[media_cms_user]','$category','$channel','$video_title','$video_details','$video_youtube_url','$datetime','$thumb','$duration','$day','$month','$year','1','$tags','$publish_time')");
				if ($insert) {
					echo 'success';	
				} else {
					echo 'failure';	
				}
				} 
				}
				break;
				case 'vimeo';
				if (check_video_id($id,'vimeo') > 0) {
				echo 'failure';	
				} else {
				$video = simplexml_load_string(curl_get('http://vimeo.com/api/v2/video/'.$id.'.xml'));
				if (!isset($video->video->id)) {				
					echo 'failure';	
				} else {
					$video_id = $video->video->id;
					$video_title = htmlspecialchars(str_replace("'",'',$video->video->title),ENT_QUOTES);
					$video_details = htmlspecialchars(str_replace("'",'',$video->video->description),ENT_QUOTES);
					$video_thumbnail = $video->video->thumbnail_large;
					$video_url = $video->video->url;
					$duration = $video->video->duration;
					if (!empty($video->video->tags)) {
						$tags = $video->video->tags;
					} else {
						$tags = title_to_keywords($video->video->title);
					}
					$publish_time = vimeo_date_to_unix($video->video->upload_date);
					if (!empty($video_thumbnail)) {
					$thumb = 'vimeo_'.$video_id.'.jpg';
					$up = file_put_contents('../upload/media/'.$thumb,file_get_contents($video_thumbnail));	
					} else {
					$thumb = '';	
					}
				$insert = $mysqli->query("INSERT INTO media (video_site,video_id,user_id,category_id,channel_id,title,details,permalink,datetime,thumbnail,duration,day,month,year,published,tags,publish_time) VALUES ('vimeo','$video_id','$_SESSION[media_cms_user]','$category','$channel','$video_title','$video_details','$video_url','$datetime','$thumb','$duration','$day','$month','$year','1','$tags','$publish_time')");
				if ($insert) {
					echo 'success';	
				} else {
					echo 'failure';	
				}
				}
				}
				break;
				case 'dailymotion';
				if (check_video_id($id,'dailymotion') > 0) {
				echo 'failure';	
				} else {
				$url = 'https://api.dailymotion.com/video/'.$id.'?fields=allow_embed,description,duration,embed_url,id,thumbnail_720_url,thumbnail_url,title,created_time,tags,url';
				$video = json_decode(file_get_contents($url), true);
				if (count($video) == 0) {
					echo 'failure';	
				} else {
					$video_id = $video['id'];
					$video_title = htmlspecialchars($video['title'],ENT_QUOTES);
					$video_details = htmlspecialchars($video['description'],ENT_QUOTES);
					if (!empty($video['thumbnail_720_url'])) {
					$video_thumbnail = $video['thumbnail_720_url'];
					} else {
					$video_thumbnail = $video['thumbnail_url'];	
					}
					$video_url = $video['url'];
					$duration = $video['duration'];
					if (count($video['tags']) > 0) {
						$tags = implode(',',$video['tags']);
					} else {
						$tags = title_to_keywords($video['title']);
					}
					$publish_time = $video['created_time'];
					if (!empty($video_thumbnail)) {
					$thumb = 'dailymotion_'.$video_id.'.jpg';
					$up = file_put_contents('../upload/media/'.$thumb,file_get_contents($video_thumbnail));	
					} else {
					$thumb = '';	
					}
				$insert = $mysqli->query("INSERT INTO media (video_site,video_id,user_id,category_id,channel_id,title,details,permalink,datetime,thumbnail,duration,day,month,year,published,tags,publish_time) VALUES ('dailymotion','$video_id','$_SESSION[media_cms_user]','$category','$channel','$video_title','$video_details','$video_url','$datetime','$thumb','$duration','$day','$month','$year','1','$tags','$publish_time')");
				if ($insert) {
					echo 'success';	
				} else {
					echo 'failure';	
				}
				}
				}
				break;
				default;
			}
		}	 	
		}
}

if ($action == 'fetch_facebook_video') {
				$link = make_safe($_POST['facebook_video_link']);
				$category = make_safe($_POST['category']);
				if (empty($link)) {
				echo notification('warning','Please Insert Valid Facebook Video Link');	
				} else {
				$u = parse_url($link);
				$paths = explode('/',$u['path']);
				$video_id = $paths[3];
				if (check_video_id($video_id,'facebook') > 0) {
				echo notification('warning','This Video is Inserted Before.');
				} else {
				$token = $options['api_facebook_extended_token'];
				$graph = 'https://graph.facebook.com/v2.0/'.$video_id.'?fields=embed_html,tags,length,picture,description,name,source,id,created_time,from,icon,thumbnails,updated_time&access_token='.$token;
				$url = json_decode(file_get_contents($graph),true);
				if (!isset($url['id'])) {
				echo notification('warning','Not Valid Video Link');
				} else {
				if (isset($url['name'])) {
				$video_title = htmlspecialchars($url['name'],ENT_QUOTES);
				$tags = title_to_keywords($video_title);
				} else {
				if (isset($url['description'])) {
				$video_title = htmlspecialchars(mb_substr($url['description'],0,100,'UTF-8'),ENT_QUOTES);
				$tags = title_to_keywords($video_title);
				} else {
				$video_title = $url['id'];	
				$tags = '';
				}
				}
				if (isset($url['description'])) {
				$video_details = htmlspecialchars($url['description'],ENT_QUOTES);
				} else {
				$video_details = '';	
				}
				
				$video_thumbnail = $url['picture'];
				$video_facebook_url = 'https://www.facebook.com/'.$url['from']['id'].'/videos/'.$url['id'].'/';
				$duration = round($url['length']);
				if (!empty($video_thumbnail)) {
				$thumb = 'facebook_'.$video_id.'.jpg';
				$up = file_put_contents('../upload/media/'.$thumb,file_get_contents($video_thumbnail));	
				} else {
				$thumb = '';	
				}
				if (isset($options['users_media_publishing']) AND $options['users_media_publishing'] == 1) {
					$published = 1;
				} else {
					$published = 0;
				}
				$publish_time = youtube_date_to_unix($url['created_time']);
				$datetime = time();
				$insert = $mysqli->query("INSERT INTO media (video_site,video_id,user_id,category_id,title,details,permalink,datetime,thumbnail,duration,day,month,year,published,tags,publish_time) VALUES ('facebook','$video_id','$_SESSION[media_cms_user]','$category','$video_title','$video_details','$video_facebook_url','$datetime','$thumb','$duration','$day','$month','$year','$published','$tags','$publish_time')");
				if ($insert) {
					echo notification('success','Video Imported Successfully.');
					echo '<div class="embed-responsive embed-responsive-16by9">
							<iframe src="https://www.facebook.com/video/embed?video_id='.$url['id'].'"></iframe>
						</div>';
				} else {
					echo notification('danger','Error Happened');
				}
					
				} 
				}
				}

}

if ($action == 'import_single_facebook_video') {
				$id = make_safe($_POST['id']);
				$category = make_safe($_POST['category']);
				if (empty($id)) {
				echo 'failure';	
				} else {
				if (check_video_id($id,'facebook') > 0) {
				echo 'failure';	
				} else {
				$token = $options['api_facebook_extended_token'];
				$graph = 'https://graph.facebook.com/v2.0/'.$id.'?fields=embed_html,tags,length,picture,description,name,source,id,created_time,from,icon,thumbnails,updated_time&access_token='.$token;
				$url = json_decode(file_get_contents($graph),true);
				if (!isset($url['id'])) {
				echo 'failure';
				} else {
				if (isset($url['name'])) {
				$video_title = htmlspecialchars($url['name'],ENT_QUOTES);
				$tags = title_to_keywords($video_title);
				} else {
				if (isset($url['description'])) {
				$video_title = htmlspecialchars(mb_substr($url['description'],0,100,'UTF-8'),ENT_QUOTES);
				$tags = title_to_keywords($video_title);
				} else {
				$video_title = $url['id'];	
				$tags = '';
				}
				}
				if (isset($url['description'])) {
				$video_details = htmlspecialchars($url['description'],ENT_QUOTES);
				} else {
				$video_details = '';	
				}
				$video_thumbnail = $url['picture'];
				$video_facebook_url = 'https://www.facebook.com/'.$url['from']['id'].'/videos/'.$url['id'].'/';
				$duration = round($url['length']);
				if (!empty($video_thumbnail)) {
				$thumb = 'facebook_'.$id.'.jpg';
				$up = file_put_contents('../upload/media/'.$thumb,file_get_contents($video_thumbnail));	
				} else {
				$thumb = '';	
				}
				if (isset($options['users_media_publishing']) AND $options['users_media_publishing'] == 1) {
					$published = 1;
				} else {
					$published = 0;
				}
				$publish_time = youtube_date_to_unix($url['created_time']);
				$datetime = time();
				$insert = $mysqli->query("INSERT INTO media (video_site,video_id,user_id,category_id,title,details,permalink,datetime,thumbnail,duration,day,month,year,published,tags,publish_time) VALUES ('facebook','$id','$_SESSION[media_cms_user]','$category','$video_title','$video_details','$video_facebook_url','$datetime','$thumb','$duration','$day','$month','$year','$published','$tags','$publish_time')");
				if ($insert) {
					echo 'success';
				} else {
					echo 'failure';
				}
					
				} 
				}
				}

}
?>