<?php

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

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

require_once(FS_PATH."/lib/getid3/getid3.php");
require_once(FS_PATH."/lib/getid3/getid3.putid3.php");
require_once(FS_PATH."/lib/getid3/getid3.ogginfo.php");

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

# Security check. gr_id is intitialized as 1 in
# ../account.php upon login

if (    (substr($_SERVER['SCRIPT_NAME'],-11) == 'tr-edit.php')
     || (substr($_SERVER['SCRIPT_NAME'],-17) == 'tr-batch-edit.php')
     || (substr($_SERVER['SCRIPT_NAME'],-14) == 'radio-edit.php') ) {

  if (abs($NETJUKE_SESSION_VARS["gr_id"]) > 2) {
    alert(INCADM_DENIED);
    exit;
  }

} else {

  if (abs($NETJUKE_SESSION_VARS["gr_id"]) != 1) {
    header("Location: ".WEB_PATH);
    exit;
  }

}

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

function SavePrefFile($pref_file, $save = 0, $data = array()) {
  
  GLOBAL $NETJUKE_SESSION_VARS;
  
  $prefs = '';
  
  $const_ar = array (   'SECURITY_MODE' => ''
                      , 'SECURITY_KEY' => ''
                      , 'LANG_PACK' => ''
                      , 'DB_TYPE' => ''
                      , 'DB_HOST' => ''
                      , 'DB_USER' => ''
                      , 'DB_PASS' => ''
                      , 'DB_NAME' => ''
                      , 'SUPPORTED_FORMATS' => ''
                      , 'STREAM_SRVR' => ''
                      , 'MUSIC_DIR' => ''
                      , 'DATA_DIR_IMPORT' => ''
                      , 'DATA_DIR_BACKUP' => ''
                      , 'ARTWORK_DIR' => ''
                      , 'RES_PER_PAGE' => ''
                      , 'ENABLE_COMMUNITY' => ''
                      , 'ENABLE_DOWNLOAD' => ''
                      , 'PROTECT_MEDIA' => ''
                      , 'REAL_ONLY' => ''
                      , 'JUKEBOX_PLAYER' => ''
                      , 'JUKEBOX_PLAYER_PATH' => ''
                      , 'JUKEBOX_PLAYER_PID' => ''
                      , 'JUKEBOX_PLIST' => ''
                      , 'RADIO_TYPE' => ''
                      , 'RADIO_PLIST' => ''
                      , 'RADIO_URL' => ''
                      , 'INTERFACE_HEADER' => ''
                      , 'INTERFACE_FOOTER' => ''
                      , 'CUSTOM_HEADER' => ''
                      , 'CUSTOM_FOOTER' => ''
                      , 'USER_THEMES' => ''
                      , 'INV_ICN' => ''
                      , 'DEFAULT_BGCOLOR' => ''
                      , 'DEFAULT_TEXT' => ''
                      , 'DEFAULT_LINK' => ''
                      , 'DEFAULT_ALINK' => ''
                      , 'DEFAULT_VLINK' => ''
                      , 'DEFAULT_TD_BORDER' => ''
                      , 'DEFAULT_TD_HEADER' => ''
                      , 'DEFAULT_TD_HEADER_FC' => ''
                      , 'DEFAULT_TD_CONTENT' => ''
                      , 'DEFAULT_FONT_FACE' => ''
                      , 'DEFAULT_FONT_SIZE' => ''
					  , 'EDIT_MEDIA' => ''
					  , 'BATCH_DOWNLOAD' =>''
					  , 'BATCH_TAR_PATH' => ''
					  , 'BATCH_ZIP_PATH' => ''
					  , 'BATCH_SIT_PATH' => ''
					  , 'BATCH_TIME_LIMIT' => ''
					  , 'BATCH_SIZE_LIMIT' => ''
					  , 'DATA_DIR_TRASH' => ''
					  , 'ORGANIZE_FORMAT' => '');
  
  $prefs .= "<"."?php\r\n";
  $prefs .= "\r\n";
  $prefs .= "// ".ADMPREF_FILEINFO_1.": ".date("Y-m-d @ H:i:s")." ".ADMPREF_FILEINFO_2." ".$_SERVER['REMOTE_ADDR']."\r\n";
  $prefs .= "// ".ADMPREF_FILEINFO_3.": ".WEB_PATH."/etc/inc-prefs.php\r\n";
  $prefs .= "\r\n";
  
  foreach ($const_ar as $key => $val) {
    if (isset($data[$key])) {
      $prefs .= "define(  \"".$key."\", \"".str_replace('"','\"',$data[$key])."\"  );\r\n";
    } else {
      $prefs .= "define(  \"".$key."\", \"".str_replace('"','\"',constant($key))."\"  );\r\n";
    }
  }
  
  $prefs .=  "\r\n?".">";

  if ($save == 1) {
    
    if (@is_writable($pref_file)) {
    
      $fp = fopen($pref_file,'w');
    
      fwrite($fp,$prefs);
    
      fclose($fp);
    
      if ($data['USER_THEMES'] == 'f') {
    
        $NETJUKE_SESSION_VARS["inv_icn"] = $data['INV_ICN'];

        $NETJUKE_SESSION_VARS["bgcolor"] = $data['DEFAULT_BGCOLOR'];
        $NETJUKE_SESSION_VARS["text"] = $data['DEFAULT_TEXT'];
        $NETJUKE_SESSION_VARS["link"] = $data['DEFAULT_LINK'];
        $NETJUKE_SESSION_VARS["alink"] = $data['DEFAULT_ALINK'];
        $NETJUKE_SESSION_VARS["vlink"] = $data['DEFAULT_VLINK'];
        $NETJUKE_SESSION_VARS["td_border"] = $data['DEFAULT_TD_BORDER'];
        $NETJUKE_SESSION_VARS["td_header"] = $data['DEFAULT_TD_HEADER'];
        $NETJUKE_SESSION_VARS["td_header_fc"] = $data['DEFAULT_TD_HEADER_FC'];
        $NETJUKE_SESSION_VARS["td_content"] = $data['DEFAULT_TD_CONTENT'];
        $NETJUKE_SESSION_VARS["font_face"] = $data['DEFAULT_FONT_FACE'];
        $NETJUKE_SESSION_VARS["font_size"] = $data['DEFAULT_FONT_SIZE'];
      
        netjuke_session('update');
    
      } else {
    
        $NETJUKE_SESSION_VARS["bgcolor"] = '';
      
        netjuke_session('update');
      
      }
    
    } else {
    
      alert(ADMPREF_DENIED_1);
      
      exit;
    
    }
  
    header("Location: ".$_SERVER['PHP_SELF']);
  
  } else {
   
    header( "Content-Disposition: attachment; filename=inc-prefs.txt" ); 
    header( "Content-type: text/plain" );
    echo $prefs;
 
  }

}

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

function SaveNewImportFile($dir,$rows) {

  $new_file = $dir.'/bckp-'.str_replace(".","",str_replace(" ","",microtime()));
  
  $fp = fopen($new_file,'w');
  
  fwrite($fp,$rows);
  
  fclose($fp);
  
  rename($new_file, $new_file.'.txt');
  
  return $new_file.'.txt';

}

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

function groupSelect($selected) {

  GLOBAL $dbconn;
  
  $dbrs = $dbconn->Execute("SELECT id, name FROM netjuke_groups where id != 4 order by id desc");

  $html = "<SELECT NAME='gr_idField' class=input_content>";

  while (!$dbrs->EOF) {
    
    if ($dbrs->fields[0] == $selected) {
       $indeed = "SELECTED";
    } else {
       $indeed = "";
    }
    
    $html .= "<OPTION VALUE='".$dbrs->fields[0]."' $indeed>".$dbrs->fields[1]."</OPTION>";
    
    $dbrs->MoveNext();
  
  }
  
  $dbrs->Close();

  $html .= "</SELECT>";

  return $html;

}

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

function Update_Image($type = "", $id = 0, $img = "") {

  GLOBAL $dbconn;
  
  switch ($type) {
  
    case 'tr':
      $table = 'netjuke_tracks';
      break;
    case 'ar':
      $table = 'netjuke_artists';
      break;
    case 'al':
      $table = 'netjuke_albums';
      break;
    default:
      $table = FALSE;
  
  }
  
  if ( ($table) && (abs($id) != 0) ) {
  
    $dbconn->Execute( "update ".$table." set img_src = '".$img."' where id = ".abs($id) );
  
  }
  
  return $img;

}

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

function CheckDataDirPerm() {

  $path = str_replace('//','/',FS_PATH."/".DATA_DIR_IMPORT);
  
  if (  !file_exists($path) || !is_writable($path) ) {
    alert(INCADM_NOPERM);
    exit;
  }

}


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

function ImportTrackData($raw_values,$track_cache,$ar_cnt=0,$al_cnt=0,$ge_cnt=0) {

   GLOBAL $dbconn;
   
   //print_r($raw_values);

  $data = array();
          
  # The following fields can already be initialize
  # as they will be inserted as is in netjuke_tracks
  $data['size']           = $raw_values[4];
  $data['time']           = $raw_values[5];
  $data['track_number']   = $raw_values[6];
  $data['year']           = $raw_values[8];
  $data['date']           = $raw_values[10];
  $data['bit_rate']       = $raw_values[11];
  $data['sample_rate']    = $raw_values[12];
  $data['kind']           = $raw_values[14];

  $data['comments']       = raw_to_db(rawurldecode($raw_values[15])); // might be url encoded

  $data['img_src']        = $raw_values[17];

  $data['lyrics']         = raw_to_db(rawurldecode($raw_values[20])); // might be url encoded
          
  $data['name']           = raw_to_db($raw_values[0]);
  
  $temp_loc = $raw_values[16];
  
  $data['location']       = specialUrlEncode($temp_loc);
  
  // DEBUG echo "- '".$data['Location']."'<br>";
     
  if (substr($data['location'],0,1) == '/') $data['location'] = substr($data['location'],1);
  
  $dbrs = $dbconn->Execute("select id from netjuke_tracks where location = '".$data['location']."'");
   
  if ($dbrs->RecordCount() < 1) {
  
    $duplicate = false;
       
    # Get Artist, Album & Genre ID based on their respective names.
    list($data['ar_id'],$ar_cnt) = ImportTrackData_FindId('netjuke_artists',$raw_values[1],$ar_cnt,$raw_values[18]);
    list($data['al_id'],$al_cnt) = ImportTrackData_FindId('netjuke_albums',$raw_values[2],$al_cnt,$raw_values[19]);
    list($data['ge_id'],$ge_cnt) = ImportTrackData_FindId('netjuke_genres',$raw_values[3],$ge_cnt);
          
    $columns = array();
    $values = array();
    
    foreach ($data as $key => $value) {
      if (strlen($value) > 0) {
        array_push($columns, $key);
        array_push($values, "'$value'");
      }
    }
    
    $sql = 'INSERT INTO netjuke_tracks ('.join(', ',$columns).') VALUES ('.join(', ',$values).')';
    
    if (!$dbconn->Execute($sql)) {
     				
      // $status = 'did not work...';
      // print $status;
    
    } else {
    
      $track_cache['netjuke_artists'][$data['ar_id']]++;
      $track_cache['netjuke_albums'][$data['al_id']]++;
      $track_cache['netjuke_genres'][$data['ge_id']]++;
      
      $status = '|';
    
    }
  
  } else {
  
    $duplicate = true;
     	   
    $status = '';
  
  }
  
  return array($duplicate,$track_cache,$status,$ar_cnt,$al_cnt,$ge_cnt);

}

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

function ImportTrackData_FindId($table,$value,$cnt = 0,$img_src = "") {

   GLOBAL $dbconn;
   
   $value = raw_to_db($value);

   if (strlen($value) > 0) {

     $select_sql = "SELECT id FROM $table WHERE UPPER(name) = '".strtoupper($value)."'";
     $insert_sql = "INSERT INTO $table (name, img_src) VALUES ('$value', '$img_src')";

     $dbrs = $dbconn->Execute($select_sql);
		 
		 if ($dbrs == NULL) {
		 
		 	return array(1, $cnt);
			
		 }
		 
     if ($dbrs->RecordCount() < 1) {
       if ($dbconn->Execute($insert_sql) === false) {
	     // error
       } else {
         $dbrs = $dbconn->Execute($select_sql);
         $cnt++;
       }
     }

     return array($dbrs->fields[0],$cnt);

   } else {

     return array(1,$cnt);

   }

}

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

function track_cache($do, $table, $id = 0, $val = 0) {

  // $do: defines the action
  // expects: increment, decrement, reset

  // $table: defines the sql table
  // expects: netjuke_artists, netjuke_artists, netjuke_genres

  // $id: the record id
  // note: not needed in reset

  // $val: the number to in/decrement the counter by
  // note: not needed in reset
  
  GLOBAL $dbconn;
  
  if (    ($table == 'netjuke_artists') 
       || ($table == 'netjuke_albums')
       || ($table == 'netjuke_genres') ) {

    switch ($do) {

      case "increment":
        $dbconn->Execute(" update $table set track_cnt = track_cnt + $val where id = $id ");
        break;

      case "decrement":
        $dbconn->Execute(" update $table set track_cnt = track_cnt - $val where id = $id ");
        break;

      default:
        $do = 'reset';
        $dbconn->Execute(" update $table set track_cnt = 0 where track_cnt < 1 or track_cnt is null ");

    }

  }

}

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

function track_cache_batch($do, $tables) {
  
  GLOBAL $dbconn;

  // $do is as defined in track_cache()
  
  // Processes a multi-demensional array ($tables) described below.
  // [table name list][record id list] = a number to in/decrement by.
  
  // Used as proxy to track_cache() in most scripts.
  
  foreach ($tables as $table => $ids) {
  
    track_cache('reset', $table);
  
    foreach ($ids as $id => $val) {
    
      track_cache($do, $table, $id, $val);
    
    }
  
    track_cache('reset', $table);
  
  }

}

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

function CacheCleanUp() {

  GLOBAL $dbconn;

  $dbconn->Execute('delete from netjuke_artists where track_cnt = 0 and id != 1');
  $dbconn->Execute('delete from netjuke_albums where track_cnt = 0 and id != 1');
  $dbconn->Execute('delete from netjuke_genres where track_cnt = 0 and id != 1');

}

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

function FixMP3Info($path, $getid3array) {
  
  $filename = explode("/", $path);
  $filename = str_replace( "_", " ", substr(end($filename), 0, -4) );

  if (stristr($filename, ' ')) {
    $explode_str = ' - ';
  } else {
    $explode_str = '-';
  }
  
  // "artist - album - tracknum - title.*"
  list($artist, $album, $tracknumber, $trackname) = explode($explode_str, $filename, 4);

  if (!is_numeric(trim($tracknumber)) || empty($tracknumber)) {
    
    // "artist - album - title.*"
    list($artist, $album, $trackname) = explode($explode_str, $filename, 3);
    
    $tracknumber = 0;

    if (empty($trackname)) {
      
      // "tracknum - title.*" or "artist - title.*"
      list($tempval, $trackname) = explode($explode_str, $filename, 2);
      
      $album = "";
      
      if ( (is_numeric(trim($tempval))) && (!empty($trackname)) ) {

        // "tracknum - title.*" - would fail if the artist's name
        // happens to be numerical only though...
        $tracknumber = $tempval;
        $artist = "";

      } elseif ( !empty($trackname) ) {

        //"artist - title.*"
        $artist = $tempval;
        $tracknumber = "";

      } else {

        // title.*
        $trackname = $filename;

        $artist = "";
        $tracknumber = "";

      }
    
    }
  
  }

  $trackname = trim($trackname);
  $tracknumber = trim($tracknumber);
  $artist = trim($artist);
  $album = trim($album);

  if (empty($trackname)) $trackname = "N/A";
  if (empty($artist)) $artist = "N/A";
  if (empty($tracknumber)) $tracknumber = 0;
  if (empty($album)) $album = "N/A";

  if (empty($getid3array["name"])) $getid3array["name"] = $trackname;
  if (empty($getid3array["artist"])) $getid3array["artist"] = $artist;
  if (empty($getid3array["album"])) $getid3array["album"] = $album;
  if (empty($getid3array["tr_num"])) $getid3array["tr_num"] = $tracknumber;
  if (empty($getid3array["genre"])) $getid3array["genre"] = "N/A";

  return $getid3array;

}

function get_lang_in_639 () {
	switch (LANG_PACK) {
	  
	  	case 'en':
		  $lang = 'eng';
		  break;
		  
		case 'de':
		  $lang = 'deu';
		  break;
		
		case 'ca':
		  $lang = 'cat';
		  break;
		  
		case 'es':
		  $lang = 'spa';
		  break;
		  
		case 'fr':
		  $lang = 'fra';
		  break;
		
		default:
		  $lang = 'XXX';
		  break;
		  
	  }
	  
	return ($lang);
	
}

// Fetch all metadata from db and write back to tags
function WriteTags ($id) {

  GLOBAL $dbconn;

  foreach ($id as $this_id) {

    $sql = "select tr.name, ar.name, al.name, tr.track_number, ge.name,"
	       . " tr.year, tr.comments, tr.lyrics, tr.location, ge.id from netjuke_tracks tr,"
         . " netjuke_artists ar, netjuke_albums al, netjuke_genres ge"
		     . " WHERE tr.id = " . $this_id . " and al.id = tr.al_id"
		     . " and ge.id = tr.ge_id and ar.id = tr.ar_id" ;

    $dbrs = $dbconn->Execute ($sql);

    $lang = get_lang_in_639 ();

    if ($dbrs->RecordCount() != 0) {

      $data['id3']['id3v2']['TIT2']['data'] = $dbrs->fields[0];
		  $data['id3']['id3v2']['TPE1']['data'] = $dbrs->fields[1];
      $data['id3']['id3v2']['TALB']['data'] = $dbrs->fields[2];
      $data['id3']['id3v2']['TRCK']['data'] = $dbrs->fields[3];
      $data['id3']['id3v2']['TIT1']['data'] = $dbrs->fields[4];
      $data['id3']['id3v2']['COMM'][0]['data'] = $dbrs->fields[6];
      $data['id3']['id3v2']['COMM'][0]['language'] = $lang;
	  	$data['id3']['id3v2']['COMM'][0]['description'] = "Netjuke Comment";
      $data['id3']['id3v2']['USLT'][0]['data'] = $dbrs->fields[7];				
      $data['id3']['id3v2']['USLT'][0]['language'] = $lang;
      $data['id3']['id3v2']['USLT'][0]['description'] = "Netjuke Lyrics";

      $location = rawurldecode ($dbrs->fields[8]);

      if (is_writable (MUSIC_DIR . '/' . $location) && ! stristr($location, "://")) {
	  
	      $temp_vals = explode('.', MUSIC_DIR . '/' . $location);
      	$file_ext = strtolower(array_pop($temp_vals));
	    
        if (  ($file_ext == 'mp3')
           || ($file_ext == 'mp2') ) {		
		  	 
            if (! WriteID3v2 (MUSIC_DIR . '/' . $location, $data, 4, 0, FALSE, 0, TRUE)) {
			
                return (2);

            }
		  
            if (! WriteID3v1 (MUSIC_DIR . '/' . $location, $dbrs->fields[0], $dbrs->fields[1],
                              $dbrs->fields[2], '', '', $dbrs->fields[9], $dbrs->fields[4])) {
			 
                return (2);
			   
            }
						
						$sql = "update netjuke_track set size = ".filesize (MUSIC_DIR . '/' . $location)
								 . " where id = " . $this_id;
						$dbconn->Execute($sql);
			 
        } elseif ($file_ext == 'ogg') {
				
				   $comments = array ('TITLE' => $dbrs->fields[0], 
					 										'ARTIST' => $dbrs->fields[1], 
															'ALBUM' => $dbrs->fields[2], 
															'TRACKNUMBER' => $dbrs->fields[3],
															'GENRE' => $dbrs->fields[4],
															'DATE' => $dbrs->fields[5],
															'COMMENTS' => $dbrs->fields[6],
															'LYRICS' => $dbrs->fields[7]);
					 
					 if (OggWrite (MUSIC_DIR . '/' . $location, $comments)) {
					 
					 	$sql = "update netjuke_track set size = ".filesize (MUSIC_DIR . '/' . $location)
								 . " where id = " . $this_id;
						$dbconn->Execute($sql);
						
				 	 } else {
					 
					 	return (2);
						
					 }
				
				}
	  
      } else {
	   
          return (1);
		
      }

    }

  }

	return (0);

}

function ReadFileID3 ($location, $path) {
	
  require_once(FS_PATH."/lib/getid3/getid3.php");
	
	// These are assumptions getid3() can utilize
  $types = array ('zip', 'ogg', 'riff', 'mpeg', 'midi', 'mp3');
	$assume = '';
	
	// Attempt to scan the file aggressively
	$ext = substr ($path, strrpos ($path, '.') + 1);
	
	if (in_array ($ext, $types)) {
	
		$assume = $ext;
		
	}

	if ( $AudioFileInfo = @GetAllFileInfo($path, $assume) ) {    

      // prepare default values
      $temp_id3 = array( 'name' => "",
                         'artist' => "",
                         'album' => "",
                         'genre' => "",
                         'size' => filesize($path),
                         'time' => 0,
                         'tr_num' => 0,
                         'tr_cnt' => 0,
                         'year' => 0,
                         'date' => date("Y-m-d H:i:s"),
                         'date_added' => date("Y-m-d H:i:s"),
                         'bit_rate' => 0,
                         'sample_rate' => 0,
                         'volume_adj' => 0,
                         'kind' => "",
                         'comments' => "",
                         'location' => $location,
                         'tr_img' => "",
                         'ar_img' => "",
                         'al_img' => "",
                         'lyrics' => "" );
      // get track name
      if (isset($AudioFileInfo["comments"]["title"][0])) {
        $temp_id3["name"] = trim($AudioFileInfo["comments"]["title"][0]);
      } else {
        $temp_id3["name"] = "";
      }
      
      // get artists name
      if (isset($AudioFileInfo["comments"]["artist"][0])) {
        $temp_id3["artist"] = trim($AudioFileInfo["comments"]["artist"][0]);
      } else {
        $temp_id3["artist"] = "";
      }
      
      // get album name
      if (isset($AudioFileInfo["comments"]["album"][0])) {
        $temp_id3["album"] = trim($AudioFileInfo["comments"]["album"][0]);
      } else {
        $temp_id3["album"] = "";
      }
      
      // get genre name
      if (isset($AudioFileInfo["comments"]["genre"][0])) {
        $temp_id3["genre"] = trim($AudioFileInfo["comments"]["genre"][0]);
      } else {
        $temp_id3["genre"] = "";
      }
      
      // get time in seconds
      if (isset($AudioFileInfo["playtime_seconds"])) {
        $temp_id3["time"] = floor($AudioFileInfo["playtime_seconds"]);
      } else {
        $temp_id3["time"] = 0;
      }
      
      // get track number
      if (isset($AudioFileInfo["comments"]["track"][0])) {
        $temp_id3["tr_num"] = trim($AudioFileInfo["comments"]["track"][0]);
      } else {
        $temp_id3["tr_num"] = 0;
      }
        
      // get year
      if (isset($AudioFileInfo["comments"]["year"][0])) {
        $temp_id3["year"] = abs($AudioFileInfo["comments"]["year"][0]);
      } else {
        $temp_id3["year"] = 1900;
      }
        
      // get bit rate
      if (isset($AudioFileInfo["bitrate"])) {
        $temp_id3["bit_rate"] = floor($AudioFileInfo["bitrate"] / 1000);
      } else {
        $temp_id3["bit_rate"] = 0;
      }
      
      // get sample rate
      if (isset($AudioFileInfo["audio"]["sample_rate"])) {
        $temp_id3["sample_rate"] = abs($AudioFileInfo["audio"]["sample_rate"]);
      } else {
        $temp_id3["sample_rate"] = 0;
      }
        
      // get comments
      if (isset($AudioFileInfo["comments"]["comment"])) {
        $temp_id3["comments"] = $AudioFileInfo["comments"]["comment"][0];
      } else {
        $temp_id3["comments"] = "";
      }
		  
	  $temp_vals = explode('.',$location);
      $file_ext = strtolower(array_pop($temp_vals));
  
      if (    ($file_ext == 'mp3')
           || ($file_ext == 'mp2') ) {
     
      // START MP3/MP2 SPECIFIC
        
        $temp_id3["kind"] = "MPEG AUDIO FILE";
        
        // get lyrics
        if (isset($AudioFileInfo["lyrics3"]["LYR"])) {
          $temp_id3["lyrics"] = $AudioFileInfo["lyrics3"]["LYR"];
        } elseif (isset($AudioFileInfo["id3v2"]["ULT"][0]["data"])) {
          $temp_id3["lyrics"] = $AudioFileInfo["id3v2"]["ULT"][0]["data"];
        } elseif (isset($AudioFileInfo["id3v2"]["USLT"][0]["data"])) {
          $temp_id3["lyrics"] = $AudioFileInfo["id3v2"]["USLT"][0]["data"];
        } else {
          $temp_id3["lyrics"] = "";
        }
           
        // rawurlencode lyrics if we output to a text file
        // to cope w/ potential tabs and new lines
        if (!isset($_REQUEST['direct_import'])) $temp_id3["lyrics"] = rawurlencode($temp_id3["lyrics"]);
        
      // END MP3/MP2 SPECIFIC
      
      } elseif ($file_ext == 'ogg') {
        
      // START OGG SPECIFIC
        
        $temp_id3["kind"] = "OGG VORBIS AUDIO FILE";
        
      // END OGG SPECIFIC
      
      } if ($file_ext == 'wma') {
     
      // START WMA SPECIFIC
        
        $temp_id3["kind"] = "WMA AUDIO FILE";
        
      // END WMA SPECIFIC
      
      } if (    ($file_ext == 'ra')
             || ($file_ext == 'rm') ) {
     
      // START REALMEDIA SPECIFIC
        
        $temp_id3["kind"] = "REAL MEDIA FILE";
        
      // END REALMEDIA SPECIFIC
      
      } else {
      
        // not supported - ignore file
      
      }
	
		return ($temp_id3);	
		
	} else {
	
		return (-1);
		
	}

}

function UpdateTrackInfo ($id, $raw_values) {

  GLOBAL $dbconn;


  $data = array();
          
  # The following fields can already be initialize
  # as they will be inserted as is in netjuke_tracks
  $data['size']           = $raw_values[4];
  $data['time']           = $raw_values[5];
  $data['track_number']   = $raw_values[6];
  $data['year']           = $raw_values[8];
  $data['date']           = $raw_values[10];
  $data['bit_rate']       = $raw_values[11];
  $data['sample_rate']    = $raw_values[12];
  $data['kind']           = $raw_values[14];

  $data['comments']       = raw_to_db(rawurldecode($raw_values[15])); // might be url encoded

  $data['img_src']        = $raw_values[17];

  $data['lyrics']         = raw_to_db(rawurldecode($raw_values[20])); // might be url encoded
          
  $data['name']           = raw_to_db($raw_values[0]);
  
  $temp_loc = $raw_values[16];
  
  $data['location']       = specialUrlEncode($temp_loc);
    
  foreach ($data as $key => $value) {
    if (strlen($value) > 0) {
			if ($values != "") $values .= ", ";
			$values .= "$key = '$value'";
    }
  }
    
  $sql = "UPDATE netjuke_tracks SET $values WHERE id = '$id'";
	$dbconn->Execute ($sql);
	
}

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

?>
