<?php

// defines if this script requires to be logged in
define( "PRIVATE", true );

##################################################

# Call common libraries
require_once('../lib/inc-admin.php');
require_once(FS_PATH."/etc/locale/".LANG_PACK."/inc-admin_dup-finder.php");

#################################################

$section = "sysadmin";
include (INTERFACE_HEADER);

if ($_REQUEST['do'] == '') {

?>

<div align=center>
<table width='625' border=0 cellspacing=1 cellpadding=3 class='border'>
  <tr>
  <td class='header' nowrap>
    <table border=0 cellpadding=0 cellspacing=0 width=100%><tr>
      <td class='header'><B><?php echo  DTFINDER_HEADER ?></B></td>
    </tr></table>
  </tr>
  <tr>
  <td class='content'>
  <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
  <input type="hidden" name="do" value="process">
  <?php echo  DTFINDER_CAPTION_1 ?><br><br>
  <input type="checkbox" name="check_album" value="1" title="<?php echo DTFINDER_OPTION_1_HELP ?>" CHECKED> <?php echo DTFINDER_OPTION_1?>
  <input type="checkbox" name="check_artist" value="1" title="<?php echo DTFINDER_OPTION_2_HELP ?>" CHECKED> <?php echo DTFINDER_OPTION_2?>
  <input type="checkbox" name="check_genre" value="1" title="<?php echo DTFINDER_OPTION_3_HELP ?>"> <?php echo DTFINDER_OPTION_3?>
  <input type="checkbox" name="check_time" value="1" title="<?php echo DTFINDER_OPTION_4_HELP ?>"> <?php echo DTFINDER_OPTION_4?>
  <input type="checkbox" name="check_md5" value="1" title="<?php echo DTFINDER_OPTION_5_HELP ?>"> <?php echo DTFINDER_OPTION_5?>
  <input type="checkbox" name="show_paths" value="1" title="<?php echo DTFINDER_OPTION_6_HELP ?>"> <?php echo DTFINDER_OPTION_6?>
  <br><br><input type="submit" name="submit" value="<?php echo  DTFINDER_BTN ?>" class='btn_content'>
  </form>

<?php

} elseif ($_REQUEST['do'] == 'process') {

	$tracks = GetUniqueLocalTracks ($_REQUEST['check_album'], $_REQUEST['check_artist'], $_REQUEST['check_genre'], $_REQUEST['check_time']);
	
	$fields = implode (", ", array_keys ($tracks[0]));
	
	$duplicates = array ();
	$found = array ();		// maintain a list of id's already added
	$total_size = 0;
	$total_time = 0;
	$total_dups = 0;
	
	// Iterate the tracks, find duplicates
	foreach ($tracks as $track) {

		// Construct the SQL clause
		$clause = "";
		$from = "netjuke_tracks tr";
		
		foreach (array_keys ($track) as $field) {
		
			if ($field != 'tr.location') {
		
				if (substr ($field, 0, 3) == 'al.') {
				
					$from .= ", netjuke_albums al";					
				
				} elseif (substr ($field, 0, 3) == 'ar.') {
				
					$from .= ", netjuke_artists ar";
					
				} elseif (substr ($field, 0, 3) == 'ge.') {
				
					$from .= ", netjuke_genres ge";
				
				}
				
				$clause .= " AND $field = '" . $track[$field] . "'";
				
			}
			
		}
		
		$sql = "SELECT ".$fields.", tr.id FROM ".$from." WHERE location not like '%://%' ".$clause;
		$dbrs = $dbconn->Execute($sql);
		
		if ($dbrs->_numOfRows > 1) {
			
			$indices = array_keys ($track);
			$indices[] = 'tr.id';
			
  			$dups = array ();
			$pdups = array ();
			
  			while (!$dbrs->EOF) {
	
				$t = array ();
				
				for ($i = 0; $i < count ($indices); $i++) {
	
					$t[$indices[$i]] = $dbrs->fields[$i];
		
				}
				
				$t['tr.location'] = MUSIC_DIR.'/'.rawurldecode($t['tr.location']);
				$pdups[] = $t;
				$dbrs->MoveNext();
				
			}
			
			$dbrs->Close();
			
			if ($_REQUEST['check_md5'] == '1') {
				
				$original = array_shift ($pdups);
				$original['md5'] = md5_file ($original['tr.location']);
				
			}
			
			foreach ($pdups as $track) {
				
				if (! in_array ($track['tr.id'], $found)) {
				
					$track['tr.location'] = rawurldecode ($track['tr.location']);
					
					if ($_REQUEST['check_md5'] == '1') {
					
						$track['md5'] = md5_file ($track['tr.location']);
						if ($track['md5'] == $original['md5']) {
						
							$found[] = $track['tr.id'];
							$total_size += filesize ($track['tr.location']);
							$total_dups++;
							array_push ($dups, $track);							
							
							if ($_REQUEST['check_time'] == '1') {
							
								$total_time += $track['tr.time'];
								
							}
						}
					
					} else {
					
						$found[] = $track['tr.id'];
						$total_size += filesize ($track['tr.location']);
						$total_dups++;
						array_push ($dups, $track);
						
						if ($_REQUEST['check_time'] == '1') {
							
							$total_time += $track['tr.time'];
								
						}
						
					}
					
				}
				
			}
			
			if (count ($dups)) {
			
				// Push the original track back onto the array since we found matches
				if ($_REQUEST['check_md5'] == '1') {
				
					$total_dups++;
					array_unshift ($dups, $original);
					
				}
				
				array_push ($duplicates, $dups);
				
			}
			
		}
	
	}
	
	// Now present the duplicates in a nice table
//	echo "<PRE>Found ".$total_dups." tracks with possible duplicates. Total of ".$total_size." and ".$total_time." playing time...\n";
//	print_r ($duplicates); 

?>

<table width='100%' border=0 cellspacing=1 cellpadding=3 class='border'>
<tr>
    <td class="header" nowrap colspan=7>
    <B><?php echo  DTFINDER_RESULT_HEADER ?></B>
    </td>
</tr>
<tr>
	<td class="content" align=center nowrap>
		<?php echo $total_dups." ".DTFINDER_ROWCNT_1.". " ?>
	</td>
	<td class="content" align=center nowrap>
		<?php if ($total_time) { echo  myTimeFormat($total_time)." ".DTFINDER_ROWCNT_2." ";} echo myFilesizeFormat($total_size) ?>
	</td>
	<td class="content" align=center nowrap>
		<B><A HREF="Javascript:SelectAll();" title="<?php echo DTFINDER_SELECT_HELP ?>"><?php echo DTFINDER_SELECT ?></A></B>
	</td>
    <td class="content" align=center nowrap>
		<B><A HREF="Javascript:ResetAll();" title="<?php echo DTFINDER_RESET_HELP ?>"><?php echo DTFINDER_RESET ?></A></B>
	</td>
    <td class="content" align=center nowrap>
		<B><A HREF="Javascript:Plist('play');" title="<?php echo DTFINDER_PLAYSEL_HELP ?>"><?php echo DTFINDER_PLAYSEL ?></A></B><input type="checkbox" name='random' align='center' title="<?php echo DTFINER_RANDOMIZE_HELP ?>"><?php echo DTFINDER_RANDOMIZE ?>
	</td>
	<?php if (BATCH_DOWNLOAD == 't') { ?>
	<td class="content" align=center nowrap>
		<B><A HREF="Javascript:Plist('batch');" title="<?php echo  DTFINDER_BATCH_HELP ?>"><?php echo  DTFINDER_BATCH ?></A></B>
    </td>
	<?php } ?>
</tr>
</table>

<?php echo  SpecialEditTB() ?>

<BR>

<table width='100%' border=0 cellspacing=1 cellpadding=3 class='border'>   
<form name='playForm'>
<tr>
      <td class='header' width='5%' nowrap>
        <b><?php echo DTFINDER_OPTIONS_HEADER ?></b>
      </td>
      <td class='header' width='30%' nowrap>
        <b><?php echo DTFINDER_TRACK_HEADER ?></b>
      </td>
	  <?php if ($_REQUEST['check_time'] == '1') { ?>
      <td class='header' width='5%' nowrap>
        <b><?php echo DTFINDER_TIME_HEADER ?></b>
     </td>
	  <? } ?>
	  <?php if ($_REQUEST['check_artist'] == '1') { ?>
      <td class='header' width='20%' nowrap>
        <b><?php echo DTFINDER_ARTIST_HEADER ?></b>
      </td>
	  <? } ?>
	  <?php if ($_REQUEST['check_album'] == '1') { ?>
      <td class='header' width='28%' nowrap>
        <b><?php echo DTFINDER_ALBUM_HEADER ?></b>
      </td>
	  <? } ?>
	  <?php if ($_REQUEST['check_genre'] == '1') { ?>
      <td class='header' width='10%' nowrap>
        <b><?php echo DTFINDER_GENRE_HEADER ?></b>
      </td>
	  <? } ?>
	  <?php if ($_REQUEST['check_md5'] == '1') { ?>
      <td class='header' width='10%' nowrap>
        <b><?php echo DTFINDER_MD5_HEADER ?></b>
      </td>
	  <? } ?>
	  <?php if ($_REQUEST['show_paths'] == '1') { ?>
      <td class='header' width='10%' nowrap>
        <b><?php echo DTFINDER_PATH_HEADER ?></b>
      </td>
	  <? } ?>
</tr>

<?php

// Populate the table
foreach ($duplicates as $dups) {

		// Each $dups is a set of duplicate tracks (2 or more)
		foreach ($dups as $track) {
			
			$select = "<input type=checkbox name='val[]' value='".$track['tr.id']."' title=\"".DTFINDER_CHCK_HELP."\">";
			$play = "<a href='../play.php?do=play&val=".$track['tr.id']."' title=\"".DTFINDER_PLAY_HELP."\"><img alt='".DTFINDER_PLAY_HELP."' src='".$ICONS['play']."' border=0 width=8 height=8 align=absmiddle hspace=0 vspace=0></a>";
			$play_ar = "<a href='../play.php?do=play_all&type=ar&id=".$track['tr.ar_id']."' title=\"".DTFINDER_PLAY_AR_HELP."\"><img alt='".DTFINDER_PLAY_AR_HELP."' src='".$ICONS['play']."' border=0 width=8 height=8 align=absmiddle hspace=0 vspace=0></a>";
			$play_al = "<a href='../play.php?do=play_all&type=al&id=".$track['tr.al_id']."' title=\"".DTFINDER_PLAY_AL_HELP."\"><img alt='".DTFINDER_PLAY_AL_HELP."' src='".$ICONS['play']."' border=0 width=8 height=8 align=absmiddle hspace=0 vspace=0></a>";
			$play_ge = "<a href='../play.php?do=play_all&type=ge&id=".$track['tr.ge_id']."' title=\"".DTFINDER_PLAY_GE_HELP."\"><img alt='".DTFINDER_PLAY_GE_HELP."' src='".$ICONS['play']."' border=0 width=8 height=8 align=absmiddle hspace=0 vspace=0></a>";
			$get_info = "<a href=\"".WEB_PATH."/tr-info.php?id=".$track['tr.id']."\" target=\"NetJukeGetInfo\" onClick=\"window.open('','NetJukeGetInfo','width=500,height=575,top=0,left=0,menubar=no,scrollbars=yes,resizable=yes');\" title=\"".DTFINDER_INFO_HELP."\"><img alt=\"".DTFINDER_INFO_HELP."\" src='".$ICONS['info']."' border=0 width=8 height=8 align=absmiddle hspace=0 vspace=0></a>";
			
			if (ENABLE_DOWNLOAD == 't') {
            
   	        	$tr_location = rawurlencode ($track['tr.location']);
    	        if (substr_count($tr_location,"://") < 1) $tr_location = STREAM_SRVR."/".$tr_location;
            	if (substr_count($tr_location,"://") < 1) $tr_location  = WEB_PATH."/".$tr_location;
            	$dload = "<a href='".$tr_location."' title=\"".DTFINDER_DLOAD_HELP."\"><img alt='".DTFINDER_DLOAD_HELP."' src='".$ICONS['dload']."' border=0 width=7 height=8 align=absmiddle hspace=0 vspace=0></a>";
          
          	} else {
          
            	$dload = "";
          
          	}
			
			if ($_REQUEST['check_time'] == '1') {
			
				$time = myTimeFormat($track['tr.time']);
				
			}
			
			$track['tr.name'] = format_for_display ($track['tr.name']);
			$track['ar.name'] = format_for_display ($track['ar.name']);
			$track['al.name'] = format_for_display ($track['al.name']);
			$track['ge.name'] = format_for_display ($track['ge.name']);
			$track['md5'] = format_for_display ($track['md5']);
			$location = format_for_display ($track['tr.location']);
			
			// Construct the html
			$html .= "
          <tr valign=top>
            <td class='content' nowrap>$select $play $dload $get_info</td>
            <td class='content'>".$track['tr.name']."&nbsp;".$tr_img."</td>";
			if ($_REQUEST['check_time'] == '1') {
            
				$html .= "<td class='content' align=right>".$track['tr.time']."&nbsp;</td>";
				
			}
			if ($_REQUEST['check_artist'] == '1') {
            	
				$html .= "<td class='content'>$play_ar <A HREF=\"../search.php?do=list.tracks&col=ar.id&val=".$track['tr.ar_id']."&sort=ar\" title=\"".SRCH_AR_HELP."\">".$track['ar.name']."</A>&nbsp;".$ar_img."</td>";
            
			}
			if ($_REQUEST['check_album'] == '1') {
			
				$html .= "<td class='content'>$play_al <A HREF=\"../search.php?do=list.tracks&col=al.id&val=".$track['tr.al_id']."&sort=al\" title=\"".SRCH_AL_HELP."\">".$track['al.name']."</A>&nbsp;".$al_img."</td>";
			
			}
			if ($_REQUEST['check_genre'] == '1') {
           
			   $html .= "<td class='content'>$play_ge <A HREF=\"../search.php?do=list.tracks&col=ge.id&val=".$track['tr.ge_id']."&sort=ge\" title=\"".SRCH_GE_HELP."\">".$track['ge.name']."</A>&nbsp;</td>";
			   
			}
			if ($_REQUEST['check_md5'] == '1') {
           
			   $html .= "<td class='content'>".$track['md5']."&nbsp;</td>";
			   
			}
			if ($_REQUEST['show_paths'] == '1') {
			
				$html .= "<td class='content'>".$location."&nbsp;</td>";
				
			}
          	$html .= "</tr>";
			
		}
		
	}
	
	echo $html;
	echo "</form>";
	
}

echo "</table><BR>";

include (INTERFACE_FOOTER);

?>

<?php

// FUNCTIONS
function GetUniqueLocalTracks ($album, $artist, $genre, $duration) {

  GLOBAL $dbconn, $fields;
          
  flush();
  
  $fields = "tr.name,tr.location";
  $from = "netjuke_tracks tr";
  $clause = "";
  
  if ($album == '1') {
  
  	$fields .= ",tr.al_id,al.name";
	$from .= ",netjuke_albums al";
	$clause .= " and al.id = tr.al_id";
	
  }
  
  if ($artist == '1') {
  
  	$fields .= ",tr.ar_id,ar.name";
	$from .= ",netjuke_artists ar";
	$clause .= " and ar.id = tr.ar_id";
	
  } 
  
  if ($genre == '1') {
  
  	$fields .= ",tr.ge_id,ge.name";
	$from .= ",netjuke_genres ge";
	$clause .= " and ge.id = tr.ge_id";
	
  }
  
  if ($duration == '1') {
  
  	$fields .= ",tr.time";
	
  }
  
  $sql = "SELECT ".$fields." FROM ".$from." WHERE location not like '%://%'".$clause;
  //echo $sql;
  $dbrs = $dbconn->Execute($sql);
  
  $tracks = array();
  $indices = explode (',', $fields);
  
  while (!$dbrs->EOF) {
	
	for ($i = 0; $i < count ($indices); $i++) {
	
		if ($indices[$i] == 'tr.location') {
		
			$track[$indices[$i]] = rawurldecode(str_replace('//', '/', MUSIC_DIR.'/'.$dbrs->fields['location']));
			
		} else {
		
			$track[$indices[$i]] = $dbrs->fields[$i];
			
		}
		
	}
	
    $tracks[] = $track;    
    $dbrs->MoveNext();
  
  }
  
  $dbrs->Close();
  
  return $tracks;

}

?>
