<?php
include('../inc/mysqli.php');
include '../inc/functions.php';

include('../getid3/getid3.php');

if($_COOKIE['a'] != md5(set('admin', $db))){
	exit();
}

//Данные для ведения логов
$result = array();
 
$result['time'] = date('r');
$result['addr'] = substr_replace(gethostbyaddr($_SERVER['REMOTE_ADDR']), '******', 0, 6);
$result['agent'] = $_SERVER['HTTP_USER_AGENT'];
 
if (count($_GET)) {
	$result['get'] = $_GET;
}
if (count($_POST)) {
	$result['post'] = $_POST;
}
if (count($_FILES)) {
	$result['files'] = $_FILES;
}
 

if (file_exists('script.log') && filesize('script.log') > 102400) {
	unlink('script.log');
}
//Запись данных в лог файл 
$log = @fopen('script.log', 'a');
if ($log) {
	fputs($log, print_r($result, true) . "\n---\n");
	fclose($log);
}
 

//Изначально у нас нет ошибок 
$error = false;

//Определяем, был ли файл загружен при помощи HTTP POST 
if (!isset($_FILES['Filedata']) || !is_uploaded_file($_FILES['Filedata']['tmp_name'])) {
	$error = 'Invalid Upload';
}
 

//Проверяем размер загружаемых файлов 
if (!$error && $_FILES['Filedata']['size'] > 100 * 1024 * 1024){
	$error = 'Размер загружаемого файла не должен превышать 100 Мб';
}

//При желание вы можете добавить другие проверки


function str2lang2($str) {
	$str = mb_strtolower($str, 'UTF-8');
	$str = preg_replace('~[^a-zA-Zа-яА-Я]+~u', '', $str);
	return $str;
}
 

	$getID3 = new getID3;
	$ThisFileInfo = $getID3->analyze($_FILES['Filedata']['tmp_name']);
	
	$_FILES['Filedata']['name'] = str_replace('.mp3', '', $_FILES['Filedata']['name']);
	
	$file_n = explode(' - ', $_FILES['Filedata']['name']);
	
	if(empty($file_n[0]) or empty($file_n[1])){
		$file_n = explode('-', $_FILES['Filedata']['name']);
	}
	if(empty($file_n[0]) or empty($file_n[1])){
		$file_n = explode(' — ', $_FILES['Filedata']['name']);
	}
	
	$file_n[0] = str_ireplace('vk.com/vkmyz', '', $file_n[0]);
	$file_n[1] = str_ireplace('vk.com/vkmyz', '', $file_n[1]);
			
	$file_n[1] = str_ireplace('Telegram: @europaplusmusic - ', '', $file_n[1]);
	$file_n[0] = str_ireplace('Telegram: @europaplusmusic - ', '', $file_n[0]);
	
	$file_n[1] = str_ireplace('(PrimeMusic.cc)', '', $file_n[1]);
	$file_n[0] = str_ireplace('(PrimeMusic.cc)', '', $file_n[0]);
	
	$file_n[1] = str_ireplace('(zaycev.net)', '', $file_n[1]);
	$file_n[0] = str_ireplace('(zaycev.net)', '', $file_n[0]);
	
	$file_n[1] = str_ireplace('(mp3crazy.me)', '', $file_n[1]);
	$file_n[0] = str_ireplace('(mp3crazy.me)', '', $file_n[0]);
	
		if(!empty($ThisFileInfo['tags']['id3v2']['artist'][0])){
			$title = trim($ThisFileInfo['tags']['id3v2']['title'][0]);
			$artist = trim($ThisFileInfo['tags']['id3v2']['artist'][0]);
		}else{
			$title = $ThisFileInfo['tags']['id3v1']['title'][0];
			$artist = $ThisFileInfo['tags']['id3v1']['artist'][0];
		}
		
		$title = str_ireplace('vk.com/vkmyz', '', $title);
		$artist = str_ireplace('vk.com/vkmyz', '', $artist);
		
		$title = str_ireplace('(zaycev.net)', '', $title);
		$artist = str_ireplace('(zaycev.net)', '', $artist);
		
		$title = str_ireplace('(mp3crazy.me)', '', $title);
		$artist = str_ireplace('(mp3crazy.me)', '', $artist);
		
		$title = str_ireplace('(PrimeMusic.cc)', '', $title);
		$artist = str_ireplace('(PrimeMusic.cc)', '', $artist);
			
		$title = str_ireplace('Telegram: @europaplusmusic - ', '', $title);
		$artist = str_ireplace('Telegram: @europaplusmusic - ', '', $artist);
		
		if(!empty($ThisFileInfo['tags']['id3v2']['genre'][0])){
			$genre = $ThisFileInfo['tags']['id3v2']['genre'][0];
		}else{
			$genre = $ThisFileInfo['tags']['id3v1']['genre'][0];
		}
		
		$genre = str_ireplace('Prime Music', '', $genre);
		
		if(!empty($ThisFileInfo['tags']['id3v2']['year'][0])){
			$year = $ThisFileInfo['tags']['id3v2']['year'][0];
		}else{
			$year = $ThisFileInfo['tags']['id3v1']['year'][0];
		}
		
		if(empty($year)){
			$year = '0';
		}
		
		if(!empty($ThisFileInfo['tags']['id3v2']['album'][0])){
			$album = $ThisFileInfo['tags']['id3v2']['album'][0];
		}else{
			$album = $ThisFileInfo['tags']['id3v1']['album'][0];
		}
		
		$album = str_ireplace('WWW.FM-CHARTS.RU', '', $album);
		$album = str_ireplace('Zaycev.Net', '', $album);
		$album = str_ireplace('mp3crazy.me', '', $album);
		
		if(!empty($title)){
			
			$check  = $db->getAll("SELECT `id` FROM `files` WHERE `title` = ?s and `artist` = ?s", $title, $artist);
			
			if(count($check) > 0){
				$error = 'Такой файл уже существует';
			}
			
		}else{
			
			$file_n[0] = preg_replace('~^([0-9\.]+\s)~sU', '', $file_n[0]);
			$artist = trim($file_n[0]);
			$title = trim($file_n[1]);
			$artist = trim($artist, '.');
			$title = trim($title, '.');
			
			$check  = $db->getAll("SELECT `id` FROM `files` WHERE `title` = ?s and `artist` = ?s", $title, $artist);
			
			if(count($check) > 0){
				$error = 'Такой файл уже существует';
			}
			
			if(empty($title) or empty($artist)){
				$error = 'Не удалось определить имя файла';
			}
			
		}
 
//Если появились ошибки возвращаем их 
if ($error) {
 
	$return = array(
		'status' => '0',
		'error' => $error
	);
 
} else {//Если ошибок нет
 
	$return = array(
		'status' => '1',
		'name' => $artist.' - '.$title
	);

	$new = md5(date("Ymd")."_".rand(10000,99999)).'.mp3';
	
	$return['new'] = $new;
	$return['genre'] = (!empty($genre) ? $genre : 'null');
	$return['album'] = (!empty($album) ? $album : 'null');
	

	if(!move_uploaded_file($_FILES['Filedata']['tmp_name'], '../mp3/'.$new)){
		$return = array(
		'status' => '0',
		'error' => 'Загрузка не удалась'
		);
	}else{
		
		if (preg_match("/[а-я]+/iu", str2lang2($title.$artist))) {
			$lang = 'ru';
		}else{
			$lang = 'en';
		}
		
		if(empty($ThisFileInfo['bitrate'])) $ThisFileInfo['bitrate'] = '0';
		if(empty($ThisFileInfo['playtime_string'])) $ThisFileInfo['playtime_string'] = '00:00';
		if(empty($ThisFileInfo['audio']['channels'])) $ThisFileInfo['audio']['channels'] = '0';
		if(empty($ThisFileInfo['audio']['sample_rate'])) $ThisFileInfo['audio']['sample_rate'] = '0';
		if(empty($ThisFileInfo['audio']['channelmode'])) $ThisFileInfo['audio']['channelmode'] = '0';

		$db->query("INSERT INTO `files` SET 
		`title` = ?s,`artist` = ?s,`name_full` = ?s,
		`first_letter_a` = ?s,`first_letter_t` = ?s,
		`filename` = ?s,`genre` = ?s,`year` = ?s,
		`album` = ?s,`date_add` = ?s,`bitrate` = ?s,
		`filesize` = ?s,`playtime_string` = ?s,
		`channels` = ?s,`sample_rate` = ?s,
		`channelmode` = ?s,`lang` = ?s", 
		$title,$artist,$artist.' - '.$title,
		mb_strtolower(mb_substr($artist, -mb_strlen($artist, 'UTF-8'), 1, 'UTF-8')),
		mb_strtolower(mb_substr($title, -mb_strlen($title, 'UTF-8'), 1, 'UTF-8')),
		$new,$genre,$year,$album,time(),$ThisFileInfo['bitrate'],$_FILES['Filedata']['size'],$ThisFileInfo['playtime_string'],
		$ThisFileInfo['audio']['channels'],$ThisFileInfo['audio']['sample_rate'],$ThisFileInfo['audio']['channelmode'],$lang);
		
	}
	
}


 
if (isset($_REQUEST['response']) && $_REQUEST['response'] == 'xml') {
	// header('Content-type: text/xml');
 
	// Really dirty, use DOM and CDATA section!
	echo '<response>';
	foreach ($return as $key => $value) {
		echo "<$key><![CDATA[$value]]></$key>";
	}
	echo '</response>';
} else {
	// header('Content-type: application/json');
 
	echo json_encode($return);

}
 
?>