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

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

$dira = dirname(__FILE__);
$option = $argv[1];
$song = $argv[2];
$bit = @$argv[3];

switch ($option){

/**
* Получение главного трека
*/
case 'original':
$query = $mysqli -> query("SELECT * FROM `songs` WHERE `id` = " . (int)$song) -> fetch_assoc();

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

if($query['original'] == 'started'){
    @mkdir('files/'.$query['id'], 0777, true);
    @chmod('files/'.$query['id'], 0777);
    $output = runExternal("wget -O ".$dira."/files/".$query['id']."/".end($file)." ".$query['url']." &&
    mv ".$dira."/files/".$query['id']."/".end($file)." ".$dira."/".$file_path." &&
    mp3info2 -e binary -@p '@{APIC[]}' ".$dira."/".$file_path." > ".$dira."/files/".$query['id']."/picture.jpg &&
    ffmpeg -i ".$dira."/".$file_path." -ab 24K -ar 8000 -acodec libmp3lame -ss 00:00:00 -t 00:00:20 ".$dira."/".str_replace('.mp3', '_listen.mp3', $file_path));
    touch($dira.'/'.$file_path);

  	if(time() > (filemtime('files/delete.dat') + $config['time'])) {
		/**
		* Очистка ненужных записей
		*/
		$clear_time = time() - $config['time'];
		$query = $mysqli -> query('SELECT * FROM `query` WHERE `time` < ' . $clear_time);


		while($row = $query -> fetch_assoc()) {
			$mysqli -> query('DELETE FROM `songs` WHERE `sid` = ' . $row['id']);
		}

		$mysqli -> query('OPTIMIZE TABLE `query`');
		$mysqli -> query('OPTIMIZE TABLE `songs`');

		function removeDirRec($dir) {
			global $config;
   			if ($objs = glob($dir."/*")) {
    			foreach($objs as $obj) {
       				if(is_dir($obj)) {
       					removeDirRec($obj);
       				} elseif(time() > (filemtime($obj) + $config['time']) and $obj != 'files/delete.dat') {
       					unlink($obj);
       				}
      			}
			}

   			if($dir != 'files')
   				@rmdir($dir);
		}

		removeDirRec('files');

		touch('files/delete.dat');
	}

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

	$getID3 = new getID3;
	$getID3->encoding = 'cp1251';
	$getid = $getID3->analyze($dira."/".$file_path);

	require('system/getid3/write.php');

	$tagwriter = new getid3_writetags;
	$tagwriter->filename = $dira."/".$file_path;
	$tagwriter->tagformats = array('id3v1', 'id3v2.3');
	$tagwriter->tag_encoding = 'cp1251';

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

	if($tagexist) {
		$TagData['album'][0] = iconv('UTF-8', 'windows-1251', $config['site']);
	} else {
		$TagData['album'][0] = iconv('UTF-8', 'windows-1251', trim(preg_replace('![^0-9A-zА-яїЇіІєЄъЪёЁ&_-\s\.]!u', '', $config['site'])));
		$TagData['artist'][0] = iconv('UTF-8', 'windows-1251', trim(preg_replace('![^0-9A-zА-яїЇіІєЄъЪёЁ&_-\s\.]!u', '', $query['artist'])));
		$TagData['title'][0] = iconv('UTF-8', 'windows-1251', $query['title']);
	}

	$tagwriter->tag_data = $TagData;
	$tagwriter->WriteTags();

    if(filesize($dira."/files/".$query['id']."/picture.jpg") == 0){
		$output .= runExternal("rm ".$dira."/files/".$query['id']."/picture.jpg &&
		mp3info2 -@F 'APIC[]=@{I(fimb) ".$dira."/system/mp3_logo.gif}' ".$dira."/".$file_path." &&
		cp ".$dira."/system/mp3_logo.jpg ".$dira."/files/".$query['id']."/picture.jpg");
	}

	$output .= runExternal("php -f ".$dira."/img.php " . $query['id'] . " &&
	php -f ".$dira."/run.php change_status ".$query['id']." original &");
	print $output;
}

break;

/**
* Конвертирование в 320 кбит/сек
*/

case 'mp3_320':
$query = $mysqli -> query("SELECT * FROM `songs` WHERE `id` = " . (int)$song) -> fetch_assoc();
$file_path = 'files/' . $query['id'] . '/' . (($config['writable'] == true) ? '[' . $config['site'] . ']_' : '') . tr($query['artist'] . ' - ' . $query['title']) . '.mp3';

if($query['mp3_320'] == 'started'){

	$output = runExternal("ffmpeg -i ".$dira."/".$file_path." -ab 320K -ar 44100 -acodec libmp3lame ".$dira."/".str_replace('.mp3', '_320.mp3', $file_path)." &&
	id3cp ".$dira."/".$file_path." ".$dira."/".str_replace('.mp3', '_320.mp3', $file_path)." &&
	php -f ".$dira."/run.php change_status ".$query['id']." mp3_320 &");

	print $output;
}

break;

/**
* Конвертирование в 256 кбит/сек
*/

case 'mp3_256':
$query = $mysqli -> query("SELECT * FROM `songs` WHERE `id` = " . (int)$song) -> fetch_assoc();
$file_path = 'files/' . $query['id'] . '/' . (($config['writable'] == true) ? '[' . $config['site'] . ']_' : '') . tr($query['artist'] . ' - ' . $query['title']) . '.mp3';

if($query['mp3_256'] == 'started'){

	$output = runExternal("ffmpeg -i ".$dira."/".$file_path." -ab 256K -ar 44100 -acodec libmp3lame ".$dira."/".str_replace('.mp3', '_256.mp3', $file_path)." &&
	id3cp ".$dira."/".$file_path." ".$dira."/".str_replace('.mp3', '_256.mp3', $file_path)." &&
	php -f ".$dira."/run.php change_status ".$query['id']." mp3_256 &");

	print $output;
}

break;

/**
* Конвертирование в 192 кбит/сек
*/

case 'mp3_192':
$query = $mysqli -> query("SELECT * FROM `songs` WHERE `id` = " . (int)$song) -> fetch_assoc();
$file_path = 'files/' . $query['id'] . '/' . (($config['writable'] == true) ? '[' . $config['site'] . ']_' : '') . tr($query['artist'] . ' - ' . $query['title']) . '.mp3';

if($query['mp3_192'] == 'started'){

	$output = runExternal("ffmpeg -i ".$dira."/".$file_path." -ab 192K -ar 44100 -acodec libmp3lame ".$dira."/".str_replace('.mp3', '_192.mp3', $file_path)." &&
	id3cp ".$dira."/".$file_path." ".$dira."/".str_replace('.mp3', '_192.mp3', $file_path)." &&
	php -f ".$dira."/run.php change_status ".$query['id']." mp3_192 &");

	print $output;
}

break;

/**
* Конвертирование в 160 кбит/сек
*/

case 'mp3_160':
$query = $mysqli -> query("SELECT * FROM `songs` WHERE `id` = " . (int)$song) -> fetch_assoc();
$file_path = 'files/' . $query['id'] . '/' . (($config['writable'] == true) ? '[' . $config['site'] . ']_' : '') . tr($query['artist'] . ' - ' . $query['title']) . '.mp3';

if($query['mp3_160'] == 'started'){

	$output = runExternal("ffmpeg -i ".$dira."/".$file_path." -ab 160K -ar 44100 -acodec libmp3lame ".$dira."/".str_replace('.mp3', '_160.mp3', $file_path)." &&
	id3cp ".$dira."/".$file_path." ".$dira."/".str_replace('.mp3', '_160.mp3', $file_path)." &&
	php -f ".$dira."/run.php change_status ".$query['id']." mp3_160 &");

	print $output;
}

break;

/**
* Конвертирование в 128 кбит/сек
*/

case 'mp3_128':
$query = $mysqli -> query("SELECT * FROM `songs` WHERE `id` = " . (int)$song) -> fetch_assoc();
$file_path = 'files/' . $query['id'] . '/' . (($config['writable'] == true) ? '[' . $config['site'] . ']_' : '') . tr($query['artist'] . ' - ' . $query['title']) . '.mp3';

if($query['mp3_128'] == 'started'){

	$output = runExternal("ffmpeg -i ".$dira."/".$file_path." -ab 128K -ar 44100 -acodec libmp3lame ".$dira."/".str_replace('.mp3', '_128.mp3', $file_path)." &&
	id3cp ".$dira."/".$file_path." ".$dira."/".str_replace('.mp3', '_128.mp3', $file_path)." &&
	php -f ".$dira."/run.php change_status ".$query['id']." mp3_128 &");

	print $output;
}

break;

/**
* Конвертирование в 64 кбит/сек
*/

case 'mp3_64':
$query = $mysqli -> query("SELECT * FROM `songs` WHERE `id` = " . (int)$song) -> fetch_assoc();
$file_path = 'files/' . $query['id'] . '/' . (($config['writable'] == true) ? '[' . $config['site'] . ']_' : '') . tr($query['artist'] . ' - ' . $query['title']) . '.mp3';

if($query['mp3_64'] == 'started'){

	$output = runExternal("ffmpeg -i ".$dira."/".$file_path." -ab 64K -ar 22050 -acodec libmp3lame ".$dira."/".str_replace('.mp3', '_64.mp3', $file_path)." &&
	id3cp ".$dira."/".$file_path." ".$dira."/".str_replace('.mp3', '_64.mp3', $file_path)." &&
	php -f ".$dira."/run.php change_status ".$query['id']." mp3_64 &");

	print $output;
}

break;

/**
* Конвертирование в 32 кбит/сек
*/

case 'mp3_32':
$query = $mysqli -> query("SELECT * FROM `songs` WHERE `id` = " . (int)$song) -> fetch_assoc();
$file_path = 'files/' . $query['id'] . '/' . (($config['writable'] == true) ? '[' . $config['site'] . ']_' : '') . tr($query['artist'] . ' - ' . $query['title']) . '.mp3';

if($query['mp3_32'] == 'started'){

	$output = runExternal("ffmpeg -i ".$dira."/".$file_path." -ab 32K -ar 22050 -acodec libmp3lame ".$dira."/".str_replace('.mp3', '_32.mp3', $file_path)." &&
	id3cp ".$dira."/".$file_path." ".$dira."/".str_replace('.mp3', '_32.mp3', $file_path)." &&
	php -f ".$dira."/run.php change_status ".$query['id']." mp3_32 &");

	print $output;
}

break;

/**
* Изменение статуса MP3-файла
*/

case 'change_status':
$mysqli -> query("UPDATE `songs` SET `".$bit."` = 'yes' WHERE `id` = ".(int)$song);
break;
}
?>