<?php
include('include/autoloader.php');
set_time_limit(60000*60);


$sql = "SELECT * FROM channels WHERE auto_update='1' ORDER BY id ASC";
$query = $mysqli->query($sql);
if ($query->num_rows > 0) {
while ($row = $query->fetch_assoc()) {
	$latest_activity = $row['latest_activity']+$row['auto_update_period'];
	if ($latest_activity <= time()) {
	$id = $row['id'];
	$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) == 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 ('1','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'] == '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'));
	$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) == 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 ('1','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) == 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 ('1','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'");
}
}
}
?>