<?php
/**
 * Поиск MP3 (ВКонтакте)
 *
 * Автор: byvlad
 * Версия: 2.12
 * Стоимость: 400 WMR
 */

require_once ('system/core.php');			// Ядро скрипта
require_once ('system/functions.php');		// Функции скрипта
require_once ('system/pages.class.php');	// Пагинатор

if (!empty($_GET['search'])) {
	$ses = protect(urldecode($_GET['search']));
	$sort = (!in_array($_GET['sort'], array('0', '1', '2'))) ? '2' : (int)$_GET['sort'];
	$lyrics = (isset($_GET['only']) and $_GET['only'] == 1) ? '1' : '0';

	if ($mysqli -> result($mysqli -> query("SELECT COUNT(*) FROM `query` WHERE `query` = '" . $ses . "' AND `sort` = ".$sort." AND `lyrics` = ".$lyrics)) == 0) {
		$mysqli -> query("INSERT INTO `query` (`query`, `time`, `obr`, `sort`, `lyrics`) VALUES('" . $ses . "', " . time() . ", '1', " . $sort . ", " . $lyrics . ")");
		$sid = $mysqli -> insert_id;
	} else {
		$da = $mysqli -> query("SELECT * FROM `query` WHERE `query` = '" . $ses . "' AND `sort` = " . $sort . " AND `lyrics` = " . $lyrics) -> fetch_array();

		$mysqli -> query("UPDATE `query` SET
			`time` = '" . time() . "',
			`obr` = `obr`+1
		WHERE `id` = " . $da['id']);

		if($da['time'] < time() - 3600)
			$mysqli -> query("DELETE FROM `songs` WHERE `sid` = " . $da['id']);

		$sid = $da['id'];
	}

	if($sid == $mysqli -> insert_id or $da['time'] < time() - 3600) {
		$api = md5('762677api_id=2129685auto_complete=' . $config['auto_complete'] . 'count=' . $config['track'] . 'lyrics=' . $lyrics . 'method=audio.searchoffset=0q=' . $ses . 'sort=' . $sort . 'test_mode=1v=2.039Z6Hqk28r');
		$xml = LoadPage('http://api.vk.com/api.php', 'api_id=2129685&auto_complete=' . $config['auto_complete'] . '&count=' . $config['track'] . '&lyrics=' . $lyrics . '&method=audio.search&offset=0&q=' . $ses . '&sort=' . $sort . '&test_mode=1&v=2.0&sig=' . $api, 'http://vkontakte.ru/app2129685');

		$parse = simplexml_load_string(str_replace('<?xml version="1.0" encoding="utf-8"?>', '', $xml));

		$sqlStart = "INSERT INTO `songs` (`sid`, `artist`, `title`, `duration`, `url`, `lyrics`) VALUES";
		$sqlForeach = '';

		foreach ($parse->audio as $song)
			$sqlForeach.= "\n('" . $sid . "','" . $mysqli -> real_escape_string($song -> artist) . "','" . $mysqli -> real_escape_string($song -> title) . "','" . $song -> duration . "','" . $song -> url . "','" . $song -> lyrics_id . "'),";

		$sqlForeach = substr($sqlForeach,0,-1);
		$mysqli -> query($sqlStart.$sqlForeach);
    }

	header('Location: search_' . $sid . '.html');
	exit;
}

switch(ACTION) {
	case 'list':
	/**
	* Список треков
	*/
	if (!empty($_GET['sid']) and is_numeric($_GET['sid'])) {
		$inquiry = $mysqli -> query("SELECT `query` FROM `query` WHERE `id` = " . $_GET['sid']) -> fetch_row();
		$title = $inquiry[0];

		require_once ('system/head.php');	// Шапка скрипта

		$total = $mysqli -> result($mysqli -> query("SELECT COUNT(*) FROM `songs` WHERE `sid` = " . $_GET['sid']));
		$pages = new Pages($total, $config['page'],  'search_' . $_GET['sid']);
		$query = $mysqli -> query("SELECT * FROM `songs` WHERE `sid` = " . $_GET['sid'] . " ORDER BY `id` LIMIT " . $pages -> sql() . "," . $config['page']);
		if($total == 0) {
			echo '<div class="padding">Ничего не найдено!<br /></div>';
		}

		echo '<div class="padding">Поиск ' . $inquiry[0] . '</div>';

		if($query -> num_rows > 0) {
			while ($row = $query -> fetch_assoc()) {
				echo '<div class="katalog"><img src="../style/img/dot.gif" alt="" /><a href="view_' . $row['id'] . '.html"><b>' . $row['artist'] . '</b> - ' . $row['title'] . '</a> [' . gmdate('i:s', $row['duration']) . ']';

				if($row['lyrics'] != 0)
					echo ' [<a href="lyrics_' . $row['id'] . '_' . $_GET['sid'] . '_' . (int)@$_GET['page'] . '.html">Текст песни</a>]';

				echo '</div>';
			}

			if ($total > $config['page']) {
				echo '<div class="padding">';
				$pages -> run();
				echo '</div>';
			}
		}
	}
		break;

	/**
	* Просмотр трека
	*/
	case 'view':
	if (!empty($_GET['view']) and is_numeric($_GET['view'])) {
		$extdir = dirname($_SERVER['REQUEST_URI'])=='/' ? dirname($_SERVER['REQUEST_URI']) : dirname($_SERVER['REQUEST_URI']).'/';
    	$query = $mysqli -> query("SELECT * FROM `songs` WHERE `id` = " . $_GET['view']) -> fetch_assoc();
    	if(!$query) {
    		header('Location: http://' . $_SERVER['SERVER_NAME'] . $extdir . 'error.html');
			exit;
   		}
    	$title = $query['artist'] . ' - ' . $query['title'];
   		require_once ('system/head.php');    // Шапка скрипта
    	$rand = rand(0, 100);

    	$file = 'files/' . $query['id'] . '/' . (($config['writable'] == true) ? '[' . $config['site'] . ']_' : '') . tr($query['artist'] . ' - ' . $query['title']) . '.mp3';

		$rFilesize = 0;
		foreach(glob("files/*/*.mp3") as $rFile) {
			$rFilesize += filesize($rFile);
		}
		$rFilesize = round($rFilesize/1048576*100) / 100;

		if($rFilesize >= $config['restrict']) {
			header('Location: error_size.html');
			exit;
		}

    	if (!file_exists($file)) {
        	echo '<div class="padding"><b>Скачивание песни</b><br/>
                 	 Файл подготавливается к скачиванию,<br/>пожалуйста <a href="view_' . $query['id'] . '.html?' . $rand . '">обновите</a> страницу через 5-10 секунд!</b><br />';
        	if($query['size'] == 0) {
            	$query['size'] = getSizeFile($query['url']);
            	$mysqli -> query("UPDATE `songs` SET `size` = " . $query['size'] . " WHERE `id` = " . $query['id']);
        	}
        	if($query['original'] == 'no') {
        		if(!is_dir('files/' . $query['id']))
    				@mkdir('files/'  .$query['id'], 0777, true);

            	$mysqli -> query("UPDATE `songs` SET `original` = 'started' WHERE `id` = " . $query['id']);
            	runExternal("php -f ".dirname(__FILE__)."/run.php original ".$query['id']."  >/dev/null 2>/dev/null &", &$code );
        	} else {
            	$percent = $query['size']/100;
            	$file = explode('/', $query['url']);
            	$file = 'files/' . $query['id'] . '/' . end($file);

              	echo 'Файл подготовлен на ' . round((filesize($file)/$percent), 2) . ' %.';
          	}
          	echo '</div>';
      	} else {
			echo '<div class="main2"><b>' . $query['artist'] . '</b> - ' . $query['title'] . '</div>';

			if(isset($_GET['repeat'])) {
				echo '<div class="main2">Ошибка! Такой файл уже подготовлен!</div>';
			}

			if(isset($_GET['captcha_error'])) {
				echo '<div class="padding">Ошибка! Вы ввели не верный код с картинки!</div>';
			}

			if(preg_match('#linux|windows|Yahoo|Rambler|Yandex|Google|bsd|unix|macos|macintosh#i', $_SERVER['HTTP_USER_AGENT'])) {
				echo '<div class="padding"><b>Воспроизвести</b><br/>
				<object type="application/x-shockwave-flash" data="dewplayer-rect.swf" width="240" height="20" id="dewplayermultirect" name="dewplayermultirect">
					<param name="movie" value="dewplayer-rect.swf" />
					<param name="flashvars" value="mp3=' . $file . '" />
				</object><br/></div>';
			}

			require_once ('system/getid3/getid3.php');

			$getID3 = new getID3;
			$getID3->encoding = 'cp1251';
			$getid = $getID3->analyze($file);

			$tagexist = true;

			if(!empty($getid['tags']['id3v2'])) $TagData = $getid['tags']['id3v2'];
			elseif(!empty($getid['tags']['id3v1'])) $TagData = $getid['tags']['id3v1'];
			else $tagexist = false;

			echo '<div class="padding">';

			if (file_exists('files/' . $query['id'] . '/picture.jpg') and filesize('files/' . $query['id'] . '/picture.jpg') != 0) {
        		echo '<img src="files/' . $query['id'] . '/picture.jpg" alt="Cover" /><br /><br />';
			}

			echo '<b>Каналы</b>: '.$getid['audio']['channels'].' ('.$getid['audio']['channelmode'].')<br/>
				<b>Частота</b>: '.ceil($getid['audio']['sample_rate']/1000).' КГц<br/>
				<b>Битрейт</b>: '.$Bitrate = ceil($getid['audio']['bitrate']/1000).' Кбит/с<br/>
				<b>Длительность</b>: '.date('i:s', $getid['playtime_seconds']).'<br />
				<b>Размер</b>: '.size(filesize($file)).'<br /><br />';

			if($tagexist){
				if(isset($TagData['artist'][0]))
					echo '<b>Исполнитель</b>: '.iconv('windows-1251','UTF-8', $TagData['artist'][0]).'<br/>';
				if(isset($TagData['title'][0]))
					echo '<b>Название</b>: '.iconv('windows-1251','UTF-8', $TagData['title'][0]).'<br/>';
				if(isset($TagData['album'][0]))
					echo '<b>Альбом</b>: '.iconv('windows-1251','UTF-8', $TagData['album'][0]).'<br/>';
				if(isset($TagData['year'][0]))
					echo '<b>Год</b>: '.$TagData['year'][0].'<br/>';
			}

			$arr_files = array('mp3_320', 'mp3_256', 'mp3_192', 'mp3_160', 'mp3_128', 'mp3_64', 'mp3_32');

			echo '</div><div class="kub"><img src="../style/img/kub.gif" alt="" /></div><div class="padding"><b>Файлы</b><br/>
			<strong>Прослушать</strong>:<br />
			[<a href="' . str_replace('.mp3', '_listen.mp3', $file) . '">Скачать</a> (<b>24Кб/с., 20 сек</b>, 61.41 Кб)]</div>
			<div class="padding">
			<strong>Оригинал</strong>:<br />
			[<a href="' . $file . '">Скачать</a>]';
   			if($query['lyrics'] != 0) {
      			echo ' | [<a href="lyrics_' . $query['id'] . '.shtml">Текст песни</a>]';
        	} else {
            	echo ' | [<a href="index.php?search=' . urlencode($query['artist'] . ' - ' . $query['title']) . '&amp;sort=0&amp;only=1">Искать текст песни</a>]';
        	}

			echo '</div>';

			foreach($arr_files as $aFile) {
				if($query[$aFile] == 'started') {
					$fBit = (int)str_replace('mp3_', '', $aFile);
					$percent = ((filesize($file) / $Bitrate) * $fBit/100);
					echo '<div class="padding">
					Скачать</a> (MP3, <b>' . str_replace('mp3_', '', $aFile) . ' КБит/Сек</b>, идет подготовка..., ' . round((filesize(str_replace('.mp3', '_' . str_replace('mp3_', '', $aFile) . '.mp3', $file))/$percent), 2) . ' %,<a href="view_' . $query['id'] . '.html?' . rand(0, 100) . '">Обновить</a>)</div>';
				} elseif ($query[$aFile] == 'yes') {
             		echo '<div class="padding">
					<strong>MP3 ' . str_replace('mp3_', '', $aFile) . ' КБит/Сек</strong>:<br />
					[<a href="' . str_replace('.mp3', '_' . str_replace('mp3_', '', $aFile) . '.mp3', $file) . '">Скачать</a>, ' . size(filesize(str_replace('.mp3', '_' . str_replace('mp3_', '', $aFile) . '.mp3', $file))) . ']</div>';
				}
			}

			echo '</div><div class="login"><b>Параметры</b><br/>
			
			<form action="convert.php?id=' . $query['id'] . '" method="post"><div>';
			if($config['captcha']) {
				echo '<img src="captcha.php" alt="Код с картинки" /><br/>
					<b>Код с картинки:</b><br/>
					<input class="button" name="submit" type="text" class="button" size="4" name="code" />
					<br/>';
			}
			echo '<b>Битрейт:</b><br />
			<select name="bitrate">';

			foreach($arr_files as $fFile) {
				$fBit = (int)str_replace('mp3_', '', $fFile);
				if($fBit < $Bitrate)
					echo '<option value="' . $fFile . '">MP3 ' . $fBit . ' КБит/Сек ~(' . size((filesize($file) / $Bitrate) * $fBit) . ')</option>';
			}

			echo '</select><br /><input value="Вперед!" type="submit" /></div></form></div>';
		}
	}
		break;

	/**
	* Просмотр текста
	*/
	case 'view_text':
	if (!empty($_GET['lyrics']) and is_numeric($_GET['lyrics'])) {
		$query = $mysqli -> query("SELECT * FROM `songs` WHERE `id` = " . $_GET['lyrics']) -> fetch_assoc();
		$title = 'Текст песни ' . $query['artist'] . ' - ' . $query['title'];
		require_once ('system/head.php');	// Шапка скрипта
		$api = md5('762677api_id=2129685lyrics_id='.$query['lyrics'].'method=audio.getLyricstest_mode=1v=2.039Z6Hqk28r');
		$xml = LoadPage('http://api.vkontakte.ru/api.php', 'api_id=2129685&lyrics_id='.$query['lyrics'].'&method=audio.getLyrics&test_mode=1&v=2.0&sig='.$api, 'http://vkontakte.ru/app2129685');

		echo '<div class="padding">Текст песни <b>' . $query['artist'] . '</b> - ' . $query['title'] . '</div>
		<div class="padding">'. nl2br(simplexml_load_string(str_replace('<?xml version="1.0" encoding="utf-8"?>', '', $xml))->lyrics->text) . '</div>
		<div class="padding">';
		if(@$_GET['page']) {
			echo '<a href="search_' . $_GET['id'] . '_' . $_GET['page'] . '.html">&lt;Назад</a></div>';
		} else {
			echo '<a href="view_' . $_GET['lyrics'] . '.html">&lt;Назад</a></div>';
		}

		require_once ('system/foot.php');	// Ноги скрипта
		exit;
	}
		break;

	/**
	* История запросов
	*/
	case 'history':
	$title = 'История запросов';
	require_once ('system/head.php');	// Шапка скрипта


 	$total = $mysqli -> result($mysqli -> query("SELECT COUNT(*) FROM `query`"));
	$pages = new Pages($total, $config['page'],  'history');
	$query = $mysqli -> query("SELECT * FROM `query` ORDER BY `obr` DESC LIMIT " . $pages -> sql() . "," . $config['page']);
	if($total == 0)
		echo '<div class="padding">Ничего не найдено!<br /></div>';

 	echo '<div class="padding">История запросов</div>';

	while ($row = $query -> fetch_assoc()) {
		echo '<div class="padding"><img src="../style/img/dot.gif" alt="" /><a href="index.php?action=search&amp;search=' . $row['query'] . '&amp;sort=' . $row['sort'] . '&amp;only=' . $row['lyrics'] . '">' . $row['query'] . '</a> [<b>Обр</b>: ' . $row['obr'] . ']</div>';
	}

	if ($total > $config['page']) {
		echo '<div class="padding">';
		$pages -> run();
		echo '</div>';
	}
		break;

	/**
	* Книга отзывов
	*/
	case 'comments':
	$title = 'Книга отзывов';
	require_once ('system/head.php');	// Шапка скрипта

	echo '<div class="padding">Книга отзывов</div>';

	if(!empty($_POST['name']) and !empty($_POST['msg']) and !empty($_POST['code'])) {
		if($_SESSION['code'] != $_POST['code']) {
			echo '<div class="padding">Проверочный код введен неверно!<br />Попробуйте ещё раз!</div>';
		} else {
			$check = $mysqli -> query("SELECT `time` FROM `comments` WHERE `name` = '" . protect($_POST['name']) . "' ORDER BY `id` DESC") -> fetch_assoc();

			if($check['time'] > time()-1) {
                 echo '<div class="padding">Ошибка! Слишком быстро!</div>';
			} else {
				echo '<div class="padding">Спасибо! Ваш комментарий добавлен!</div>';

				$mysqli -> query("INSERT INTO `comments` SET
				`name` = '" . protect($_POST['name']) . "',
				`text` = '" . BBcode(protect($_POST['msg'])) . "',
				`time` = " . time() . "");

				unset($_SESSION['code']);
				$ok = true;
			}
		}
	}

	$config['page'] = 5;

 	$total = $mysqli -> result($mysqli -> query("SELECT COUNT(*) FROM `comments`"));
	$pages = new Pages($total, $config['page'],  'comments');
	$query = $mysqli -> query("SELECT * FROM `comments` ORDER BY `time` DESC LIMIT " . $pages -> sql() . "," . $config['page']);

	if(!isset($ok)) {
		echo '<div class="login">
		<form action="comments.html" method="post">
		<div>
		Ваше имя:<br/>
		<input type="text" name="name" maxlength="32" value=""/><br/>
		Комментарий:<br/>
		<input type="text" name="msg" maxlength="250" value=""/><br/>
		<img src="captcha.php" alt=""/><br/>
		Код с картинки:<br/>
		<input type="text" size="4" name="code"/>
		<br/><input class="button" type="submit" value="Сказать"/></div></form>
		</div>';
	}

	if($total == 0) {
		echo '<div class="link2">Отзывов ещё нет...<br /></div>';
    } else {
		while ($row = $query -> fetch_assoc()) {
			echo '<div class="clouds_2"></div><div class="padding"><span style="color:#00bb00"><b>' . $row['name'] . '</b></span> написал(а) ' . clock($row['time']) . ':<br /><br />' . $row['text'] . '</div>';
		}

		if ($total > $config['page']) {
			echo '<div class="link1">';
			$pages -> run();
			echo '</div>';
		}
    }
		break;

	/**
	* Что сейчас качают?
	*/
	case 'loaded':
	$title = 'Что сейчас качают?';
	require_once ('system/head.php');	// Шапка скрипта


 	$total = $mysqli -> result($mysqli -> query("SELECT COUNT(*) FROM `songs` WHERE `original` = 'yes'"));
	$pages = new Pages($total, $config['page'],  'loaded');
	$query = $mysqli -> query("SELECT * FROM `songs` WHERE `original` = 'yes' ORDER BY `id` LIMIT " . $pages -> sql() . "," . $config['page']);
	if($total == 0)
		echo '<div class="padding">Ничего не найдено!<br /></div>';

 	echo '<div class="padding">Что сейчас качают?</div>';

		while ($row = $query -> fetch_assoc()) {
		echo '<div class="padding"><img src="../style/img/dot.gif" alt="" /><a href="view_' . $row['id'] . '.html"><b>' . $row['artist'] . '</b> - ' . $row['title'] . '</a> [' . gmdate('i:s', $row['duration']) . ']';

		if($row['lyrics'] != 0)
			echo ' [<a href="lyrics_' . $row['id'] . '_' . $row['sid'] . '_' . (int)@$_GET['page'] . '.html">Текст песни</a>]';

		echo '</div>';
	}

	if ($total > $config['page']) {
		echo '<div class="<div class="login_f">';
		$pages -> run();
		echo '</div>';
	}
		break;

	/**
	* Главная
	*/
	default:
	$title = 'Главная';
	require_once ('system/head.php');	// Шапка скрипта

	/**
	* Вывод ошибки
	*/
	if (isset($_GET['error']))
		echo '<div class="padding"><strong>Ошибка!</strong><br />Ничего не найдено!</div>';

	if (isset($_GET['error_size']))
		echo '<div class="padding"><strong>Ошибка!</strong><br />Размер папки файлов преувеличен!<br />Попробуйте позже!</div>';

	echo '<div class="login">
			<form action="index.php" method="get">
				<div>
					<b>Запрос</b>:<br />
					<input name="search" type="text" /><br />
						<b>Сортировать:</b><br/>
							<select name="sort">
								<option value="2">по популярности</option>
								<option value="0">по дате</option>
								<option value="1">по длительности</option>
							</select><br/>
						<input name="only" type="checkbox" value="1" /><b> Только с текстом</b><br />
					<input class="button" name="submit" type="submit" class="button" value="Искать"/>
				</div>
			</form>
		</div><div class="clouds_2"></div>
	
	<div class="katalog"><b>Последние запросы:</b><br/>';

	$result = $mysqli -> query("SELECT COUNT(*), (SELECT COUNT(*) FROM `query`),(SELECT COUNT(*) FROM `songs` WHERE `original` = 'yes') FROM `comments`") -> fetch_row();
	$query = $mysqli -> query("SELECT * FROM `query` ORDER BY `id` DESC LIMIT " . $config['limit']);
    if($query -> num_rows > 0) {
		while ($row = $query -> fetch_assoc()) {
			echo '<img src="../style/img/dot.gif" alt="" /><a href="index.php?search=' . $row['query'] . '&amp;sort=' . $row['sort'] . '&amp;only=' . $row['lyrics'] . '">' . $row['query'] . '</a> [<b>' . $row['obr'] . '</b>]<br />';
		}
	} else {
		echo 'Ещё никто, ничего не искал. Будь первым!';
	}

	echo '</div>

	
	<div class="kub"><img src="../style/img/kub.gif" alt="" /></div><div class="katalog"><b>Сервисы:</b><br/>
	<img src="../style/img/dot.gif" alt="" /><a href="history.html">История запросов</a> [<b>Зап</b>. ' . $result[1] . ']<br />
	<img src="../style/img/dot.gif" alt="" /><a href="loaded.html">Что сейчас качают</a> [<b>Зап</b>. ' . $result[2] . ']</div>';
		break;
}

require_once ('system/foot.php');	// Ноги скрипта
?>
