<?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);

// Reset any variables
ensure_defined_REQUEST('check_album');
ensure_defined_REQUEST('check_artist');
ensure_defined_REQUEST('check_genre');
ensure_defined_REQUEST('check_time');
ensure_defined_REQUEST('check_md5');
ensure_defined_REQUEST('show_paths');

if (! isset ($_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?>
  <br>
  <input type="checkbox" name="check_artist" value="1" title="<?php echo DTFINDER_OPTION_2_HELP ?>" CHECKED> <?php echo DTFINDER_OPTION_2?>
  <br>
  <input type="checkbox" name="check_genre" value="1" title="<?php echo DTFINDER_OPTION_3_HELP ?>"> <?php echo DTFINDER_OPTION_3?>
  <br>
  <input type="checkbox" name="check_time" value="1" title="<?php echo DTFINDER_OPTION_4_HELP ?>"> <?php echo DTFINDER_OPTION_4?>
  <br>
  <input type="checkbox" name="check_md5" value="1" title="<?php echo DTFINDER_OPTION_5_HELP ?>"> <?php echo DTFINDER_OPTION_5?>
  <br>
  <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);
				$info = GetAllFileInfo($original['tr.location'], '', false, true, true);
				$original['md5'] = $info['md5_data'];
				
			}
			
			foreach ($pdups as $track) {
				
				if (! in_array ($track['tr.id'], $found)) {
				
					$track['tr.location'] = rawurldecode ($track['tr.location']);
					
					if ($_REQUEST['check_md5'] == '1') {
					
						$info = GetAllFileInfo($track['tr.location'], '', false, true, true);
						$track['md5'] = $info['md5_data'];
						
						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='1%' nowrap>
        <b><?php echo DTFINDER_OPTIONS_HEADER ?></b>
      </td>
      <td class='header' nowrap>
        <b><?php echo DTFINDER_TRACK_HEADER ?></b>
      </td>
	  <?php if ($_REQUEST['check_time'] == '1') { ?>
      <td class='header' nowrap>
        <b><?php echo DTFINDER_TIME_HEADER ?></b>
     </td>
	  <?php } ?>
	  <?php if ($_REQUEST['check_artist'] == '1') { ?>
      <td class='header' nowrap>
        <b><?php echo DTFINDER_ARTIST_HEADER ?></b>
      </td>
	  <?php } ?>
	  <?php if ($_REQUEST['check_album'] == '1') { ?>
      <td class='header' nowrap>
        <b><?php echo DTFINDER_ALBUM_HEADER ?></b>
      </td>
	  <?php } ?>
	  <?php if ($_REQUEST['check_genre'] == '1') { ?>
      <td class='header' nowrap>
        <b><?php echo DTFINDER_GENRE_HEADER ?></b>
      </td>
	  <?php } ?>
	  <?php if ($_REQUEST['check_md5'] == '1') { ?>
      <td class='header' nowrap>
        <b><?php echo DTFINDER_MD5_HEADER ?></b>
      </td>
	  <?php } ?>
	  <?php if ($_REQUEST['show_paths'] == '1') { ?>
      <td class='header' nowrap>
        <b><?php echo DTFINDER_PATH_HEADER ?></b>
      </td>
	  <?php } ?>
</tr>

<?php

$first = '';
$html = '';
		
// Populate the table
foreach ($duplicates as $dups) {

		$first = '';
		
		// Each $dups is a set of duplicate tracks (2 or more)
		foreach ($dups as $track) {		
				
			$select = "<input type=checkbox class=\"nomargin\" name='val[]' $first value='".$track['tr.id']."' title=\"".DTFINDER_CHCK_HELP."\">";
			$play = buildButton("../play.php?do=play&val=".$track['tr.id'],  DTFINDER_PLAY_HELP, 'play');
			if (isset ($track['tr.ar_id'])) $play_ar = buildButton("../play.php?do=play_all&type=ar&id=".$track['tr.ar_id'], DTFINDER_PLAY_AR_HELP, 'play');
			if (isset ($track['tr.al_id'])) $play_al = buildButton("../play.php?do=play_all&type=al&id=".$track['tr.al_id'], DTFINDER_PLAY_AL_HELP, 'play');
			if (isset ($track['tr.ge_id'])) $play_ge = buildButton("../play.php?do=play_all&type=ge&id=".$track['tr.ge_id'], DTFINDER_PLAY_GE_HELP, 'play');
			$get_info = buildButton(WEB_PATH."/tr-info.php?id=".$track['tr.id'], DTFINDER_INFO_HELP, 'info', "NetJukeGetInfo");

		        $first = 'CHECKED';
			
			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 = buildButton($tr_location, DTFINDER_DLOAD_HELP, 'dload');
          
          	} else {
          
                        $dload = "";
          
          	}
			
			if ($_REQUEST['check_time'] == '1') {
			
				$time = myTimeFormat($track['tr.time']);
				
			}
			
			if (isset ($track['tr.name'])) $track['tr.name'] = format_for_display ($track['tr.name']);
			if (isset ($track['ar.name'])) $track['ar.name'] = format_for_display ($track['ar.name']);
			if (isset ($track['al.name'])) $track['al.name'] = format_for_display ($track['al.name']);
			if (isset ($track['ge.name'])) $track['ge.name'] = format_for_display ($track['ge.name']);
			if (isset ($track['md5'])) $track['md5'] = format_for_display ($track['md5']);
			if (isset ($track['tr.location'])) $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;</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=\"".DTFINDER_AR_HELP."\">".$track['ar.name']."</A>&nbsp;</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=\"".DTFINDER_AL_HELP."\">".$track['al.name']."</A>&nbsp;</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=\"".DTFINDER_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></td></tr></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;

}

?>
