<HTML>
<HEAD>
	<STYLE>
	BODY, TD {
		font-family: sans-serif;
		font-size: 10pt;
	}
	</STYLE>
</HEAD>
<BODY>
<?php

require_once('getid3.functions.php');

if (!mysql_connect('localhost', 'getid3', 'getid3')) {
	die('Could not connect to MySQL host');
}
if (!mysql_select_db('getid3')) {
	die('Could not select database');
}

function safe_mysql_query($SQLquery) {
	$result = @mysql_query($SQLquery);
	if (mysql_error()) {
		die('<FONT COLOR="red">'.mysql_error().'</FONT>');
	}
	return $result;
}

function mysql_table_exists($tablename) {
	return (bool) safe_mysql_query('DESCRIBE '.$tablename);
}


if (!mysql_table_exists('files')) {
	$SQLquery  = 'CREATE TABLE files (';
	$SQLquery .= '  ID mediumint(8) unsigned NOT NULL auto_increment,';
	$SQLquery .= '  filename text NOT NULL,';
	$SQLquery .= '  md5_file varchar(32) NOT NULL default "",';
	$SQLquery .= '  md5_data varchar(32) NOT NULL default "",';
	$SQLquery .= '  md5_data_source varchar(32) NOT NULL default "",';
	$SQLquery .= '  filesize int(10) unsigned NOT NULL default "0",';
	$SQLquery .= '  fileformat varchar(255) NOT NULL default "",';
	$SQLquery .= '  audio_dataformat varchar(255) NOT NULL default "",';
	$SQLquery .= '  video_dataformat varchar(255) NOT NULL default "",';
	$SQLquery .= '  audio_bitrate float NOT NULL default "0",';
	$SQLquery .= '  video_bitrate float NOT NULL default "0",';
	$SQLquery .= '  playtime_seconds varchar(255) NOT NULL default "",';
	$SQLquery .= '  tags varchar(255) NOT NULL default "",';
	$SQLquery .= '  artist varchar(255) NOT NULL default "",';
	$SQLquery .= '  title varchar(255) NOT NULL default "",';
	$SQLquery .= '  album varchar(255) NOT NULL default "",';
	$SQLquery .= '  genre varchar(255) NOT NULL default "",';
	$SQLquery .= '  comment varchar(255) NOT NULL default "",';
	$SQLquery .= '  track tinyint(3) unsigned NOT NULL default "0",';
	$SQLquery .= '  PRIMARY KEY  (ID)';
	$SQLquery .= ') TYPE=MyISAM;';
	safe_mysql_query($SQLquery);
}


if (!empty($_REQUEST['scan'])) {
	$DirectoriesToScan	= array(realpath($_REQUEST['scan']));
	$DirectoriesScanned = array();
	while (count($DirectoriesToScan) > 0) {
		foreach ($DirectoriesToScan as $DirectoryKey => $startingdir) {
			if ($dir = @opendir($startingdir)) {
				while (($file = readdir($dir)) !== false) {
					if (($file != '.') && ($file != '..')) {
						$RealPathName = realpath($startingdir.'/'.$file);
						if (is_dir($RealPathName)) {
							if (!in_array($RealPathName, $DirectoriesScanned) && !in_array($RealPathName, $DirectoriesToScan)) {
								$DirectoriesToScan[] = $RealPathName;
							}
						} else if (is_file($RealPathName)) {
							$FilesInDir[] = $RealPathName;
						}
					}
				}
				closedir($dir);
			}
			$DirectoriesScanned[] = $startingdir;
			unset($DirectoriesToScan[$DirectoryKey]);
		}
	}

	$SQLquery = 'DELETE FROM files';
	safe_mysql_query($SQLquery);

	$FilesInDir = array_unique($FilesInDir);
	sort($FilesInDir);

	require_once('getid3.php');

	$starttime = time();
	$rowcounter = 0;
	$totaltoprocess = count($FilesInDir);

	$formatExtensions = array('mp3'=>'mp3', 'ogg'=>'ogg', 'zip'=>'zip', 'wav'=>'riff', 'avi'=>'riff', 'mid'=>'midi', 'mpg'=>'mpeg');
	foreach ($FilesInDir as $filename) {
		set_time_limit(30);

		echo date('H:i:s').' ['.number_format(++$rowcounter).' / '.number_format($totaltoprocess).'] '.$filename.'<BR>';

		$ThisFileInfo = GetAllFileInfo($filename, '', true, true, true);
		if (empty($ThisFileInfo['fileformat']) || ($ThisFileInfo['fileformat'] == 'id3')) {
			if (isset($formatExtensions[fileextension($filename)])) {
				$ThisFileInfo = GetAllFileInfo($filename, $formatExtensions[fileextension($filename)], true, true, true);
			}
		}

		$SQLquery  = 'INSERT INTO files (filename, md5_file, md5_data, md5_data_source, filesize, fileformat, audio_dataformat, video_dataformat, audio_bitrate, video_bitrate, playtime_seconds, tags, artist, title, album, genre, comment, track) VALUES (';
		$SQLquery .= '"'.addslashes(@$ThisFileInfo['filenamepath']).'", ';
		$SQLquery .= '"'.addslashes(@$ThisFileInfo['md5_file']).'", ';
		$SQLquery .= '"'.addslashes(@$ThisFileInfo['md5_data']).'", ';
		$SQLquery .= '"'.addslashes(@$ThisFileInfo['md5_data_source']).'", ';
		$SQLquery .= '"'.addslashes(@$ThisFileInfo['filesize']).'", ';
		$SQLquery .= '"'.addslashes(@$ThisFileInfo['fileformat']).'", ';
		$SQLquery .= '"'.addslashes(@$ThisFileInfo['audio']['dataformat']).'", ';
		$SQLquery .= '"'.addslashes(@$ThisFileInfo['video']['dataformat']).'", ';
		$SQLquery .= '"'.addslashes(@$ThisFileInfo['audio']['bitrate']).'", ';
		$SQLquery .= '"'.addslashes(@$ThisFileInfo['video']['bitrate']).'", ';
		$SQLquery .= '"'.addslashes(@$ThisFileInfo['playtime_seconds']).'", ';
		$SQLquery .= '"'.addslashes(@implode(',', @$ThisFileInfo['tags'])).'", ';
		$SQLquery .= '"'.addslashes(@implode(',', @$ThisFileInfo['comments']['artist'])).'", ';
		$SQLquery .= '"'.addslashes(@implode(',', @$ThisFileInfo['comments']['title'])).'", ';
		$SQLquery .= '"'.addslashes(@implode(',', @$ThisFileInfo['comments']['album'])).'", ';
		$SQLquery .= '"'.addslashes(@implode(',', @$ThisFileInfo['comments']['genre'])).'", ';
		$SQLquery .= '"'.addslashes(@implode(',', @$ThisFileInfo['comments']['comment'])).'", ';
		$SQLquery .= '"'.addslashes(@implode(',', @$ThisFileInfo['comments']['track'])).'")';
		safe_mysql_query($SQLquery);

	}

	echo '<HR>Done scanning!<HR>';

} elseif (!empty($_REQUEST['deadfilescheck'])) {

	$SQLquery  = 'SELECT filename FROM files';
	$result = safe_mysql_query($SQLquery);
	$totalchecked = 0;
	$totalremoved = 0;
	while ($row = mysql_fetch_array($result)) {
		$totalchecked++;
		set_time_limit(30);
		if (!file_exists($row['filename'])) {
			$totalremoved++;
			echo $row['filename'].'<BR>';
			flush();
			$SQLquery = 'DELETE FROM files WHERE (filename = "'.FixDBFields($row['filename']).'")';
			safe_mysql_query($SQLquery);
		}
	}

	echo number_format($totalremoved).' of '.number_format($totalchecked).' files in database no longer exist - removed from database.<HR>';

}

echo '<FORM ACTION="'.FixTextFields($_SERVER['PHP_SELF']).'">';
echo '<B>Warning:</B> Scanning a new directory will erase all previous entries in the database!<BR>';
echo 'Directory: <INPUT TYPE="TEXT" NAME="scan" VALUE="'.FixTextFields(!empty($_REQUEST['scan']) ? $_REQUEST['scan'] : '').'"> ';
echo '<INPUT TYPE="SUBMIT" VALUE="Go">';
echo '</FORM><HR>';

$SQLquery  = 'SELECT md5_data, filename, COUNT( * ) AS num';
$SQLquery .= ' FROM files';
$SQLquery .= ' GROUP BY md5_data';
$SQLquery .= ' ORDER BY num DESC';
$result = safe_mysql_query($SQLquery);
echo 'Duplicated MD5_DATA:<TABLE BORDER="1" CELLSPACING="0" CELLPADDING="2">';
while (($row = mysql_fetch_array($result)) && ($row['num'] > 1)) {
	set_time_limit(30);

	$filenames = array();
	$tags      = array();
	$md5_data  = array();
	$SQLquery  = 'SELECT filename, tags FROM files WHERE (md5_data = "'.$row['md5_data'].'") ORDER BY filename ASC';
	$result2 = safe_mysql_query($SQLquery);
	while ($row2 = mysql_fetch_array($result2)) {
		$filenames[] = $row2['filename'];
		$tags[]      = $row2['tags'];
		$md5_data[]  = $row['md5_data'];
	}

	echo '<TR>';
	echo '<TD VALIGN="TOP" STYLE="font-family: monospace;">'.implode('<BR>', $md5_data).'</TD>';
	echo '<TD VALIGN="TOP" NOWRAP>'.implode('<BR>', $tags).'</TD>';
	echo '<TD VALIGN="TOP">'.implode('<BR>', $filenames).'</TD></TR>';
}
echo '</TABLE>';

?>
</BODY>
</HTML>