<?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_organize.php");

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

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

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

if ($_REQUEST['do'] != 'organize' || $_REQUEST['val'] == '') {
  header ("Location: /index.php");
  exit;
}

?>

<div align=center>
<table width='550' border=0 cellspacing=1 cellpadding=3 class='border'>
<tr>
  <td class='header' nowrap><B><?php echo ADMORG_HEADER ?></B></td>
</tr>
<tr>
  <td class='content' align=left>
	
<?

$val = rawurldecode ($_REQUEST['val']);

$dirs = explode (",", $val);

foreach ($dirs as $dir) {
	
	if ($dir != "") {
		
		if (is_dir (MUSIC_DIR . $dir)) {
	  	
			OrganizeDir (MUSIC_DIR . $dir);
			
		} elseif (is_file (MUSIC_DIR . '/' . $dir)) {
			
			OrganizeFile (MUSIC_DIR . '/' . $dir);
			
		}
		
	}
	
}

// Recursive organize function
function OrganizeDir ($dir) {

  GLOBAL $dbconn;
	
	echo "<br>&raquo;" . ADMORG_START_ORG . "&nbsp;" . $dir . "<br>\n";
	
  if ($dh = opendir ($dir)) {
  
  	while (($file = readdir ($dh)) !== false) {
	  
	  	if (($file != ".") && ($file != "..")) {
	  		
	    	if (is_dir ($dir . '/' . $file) 
				 || is_link ($path . '/' . $file)) {
		
		  		OrganizeDir ($dir . '/' . $file);
					$success = @rmdir ($dir . '/' . $file);
							
				} elseif (is_file ($dir . '/' . $file)) {
		
					OrganizeFile ($dir . '/' . $file);
		
				}
	  
	  	}
	
		}
		
		closedir($dh);
		$success = @rmdir ($dir);
  
  } else {
  
  	echo "&raquo;" . ADMORG_ERR_OPEN . "<br>\n";
  
  }

}

function OrganizeFile ($file) {

  GLOBAL $dbconn;
					
	// See if this is an eligible file before hitting database
	$ext = substr ($file, -3);
	if (in_array ($ext, explode (",", SUPPORTED_FORMATS))) {
					
		// Is file in database? If so, extract metadata and format
		$rel_path = separatorCleanup(substr ($file, strlen (MUSIC_DIR) + 1));
		$sql = "select id, al_id, ar_id, ge_id from netjuke_tracks"
				 . " where location = '" . specialUrlEncode ($rel_path) . "'";
		$dbrs = $dbconn->Execute ($sql);
						
		if ($dbrs->RecordCount() > 0) {
												  
			// Parse organize format and tokenize
			$sql = "select ar.name, al.name, ge.name, tr.name, tr.track_number"
					 . " from netjuke_tracks tr, netjuke_artists ar, netjuke_albums al"
					 . ", netjuke_genres ge where tr.id = ". $dbrs->fields[0] . " and "
					 . "al.id = " . $dbrs->fields[1] . " and ar.id = " . $dbrs->fields[2]
					 . " and ge.id = " . $dbrs->fields[3];
			$dbrows = $dbconn->Execute ($sql);
							
			if ($dbrows->RecordCount != -1) {							
								
				// Escape out all '/' characters to prevent subdir confusion
								
				$artist = $dbrows->fields[0];
				$album = $dbrows->fields[1];
				$genre = $dbrows->fields[2];
				$number = $dbrows->fields[4];
				$track = $dbrows->fields[3];
								
				$farray = array ($artist,
												 $album,
												 $genre,
												 $number,
												 $track);
																 
				$vals = preg_replace ('/\//', '\\', $farray);
								
				$replace_tokens = array ('/%a/',
																 '/%l/',
																 '/%g/',
																 '/%n/',
																 '/%t/',
																 '/%f/');
																				 
				$replace_fields = array ($vals[0],
																 $vals[1],
																 $vals[2],
																 $vals[3],
																 $vals[4],
																 $ext);
																				 
				$format = preg_replace ($replace_tokens, $replace_fields, ORGANIZE_FORMAT);															
								
				// Create directories if necessary, check permissions, move file
				$subdirs = split ('/', $format);
				array_pop ($subdirs);
								
				clearstatcache();
				$dpath = MUSIC_DIR;			
								
				foreach ($subdirs as $d) {
								
					$dpath .= '/' . $d;
					if (! @file_exists ($dpath)) {
									
						$success = @mkdir ($dpath);
									
					}
								
				}
								
				// Substitute back in the originals
				$patterns = array_map ("make_pattern", $vals);
				$format = preg_replace ($patterns, $farray, $format);
								
				// Everything looks good, copy the file
				if (!@is_writable ($dpath)) {
									
					echo "&raquo;" . ADMORG_ERR_COPY_1 . $file . ADMORG_ERR_COPY_2 . "<br>\n";
					exit;
									
				}
								
				if (@file_exists(MUSIC_DIR . '/' . $format)) {
								
					echo "&raquo;" . ADMORG_ERR_COPY_1 . '/' . $file . ADMORG_ERR_COPY_2 . "<br>\n";
									
				}
								
				//$success = @copy ($file, stripslashes (MUSIC_DIR . '/' . $format));
				$success = @copy ($file, stripslashes (MUSIC_DIR . '/' . $format));
				if ($success) {
									
					// Unlink original file, update db record with new location
					@unlink ($file);
					$sql = "UPDATE netjuke_tracks SET location = '".specialUrlEncode($format)."' WHERE id = '".$dbrs->fields[0]."'";
					$dbconn->Execute ($sql);										
									
					echo "&raquo;" . ADMORG_COPY_1 . $file . ADMORG_COPY_2 . htmlspecialchars(stripslashes($format)) . "<br>\n";
										
				} else {
									
				  echo "&raquo;" . ADMORG_ERR_COPY_1 . $file . ADMORG_ERR_COPY_2 . "<br>\n";
									
				}								
								
			 }
						
	 	 }
					
	 }
}

function make_pattern ($string) {
	return ('/'.preg_quote($string).'/');
}

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

?>

  </td>
</tr>
<tr>
  <td class='header' nowrap>
	<center><a href="file-browser.php"><?php echo ADMORG_BACK; ?></a></center>
	</td>
</tr>
</table>
