<?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.ogginfo.php");
require_once(FS_PATH."/lib/getid3/getid3.id3v1.php");
require_once(FS_PATH."/lib/getid3/getid3.id3v2.php");
require_once(FS_PATH."/lib/getid3/getid3.functions.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')
     || (substr($_SERVER['SCRIPT_NAME'],-13) == 'text-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_ICON_SET' => ''
                      , 'DEFAULT_THEME' => ''
                      , 'EDIT_MEDIA' => ''
                      , 'BATCH_DOWNLOAD' =>''
                      , 'BATCH_TIME_LIMIT' => ''
                      , 'BATCH_SIZE_LIMIT' => ''
                      , 'DATA_DIR_TRASH' => ''
                      , 'ORGANIZE_FORMAT' => ''
                      , 'JUKEBOX_URL' => ''
                      , 'JUKEBOX_PASS' => ''
		      , 'ENABLE_XML' => '');

  $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 (isset($data['USER_THEMES']) && $data['USER_THEMES'] == 'f') {

        $NETJUKE_SESSION_VARS["inv_icn"] = $data['INV_ICN'];
        $NETJUKE_SESSION_VARS["icon_set"] = $data['DEFAULT_ICON_SET'];
        $NETJUKE_SESSION_VARS["theme"] = $data['DEFAULT_THEME'];

        netjuke_session('update');

      } else {

        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;
    case 'ge':
      $table = 'netjuke_genres';
      break;
    default:
      $table = FALSE;

  }

  if ( ($table) && (abs($id) != 0) ) {

    $sql = "update ".$table." set img_src = '".$img."' where id = ".abs($id);
    $dbconn->Execute( $sql );

  }

  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();
  $status = '';

  # 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['mtime']          = getmtime ($temp_loc);

  $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 {
      if (!isset($track_cache['netjuke_artists'][$data['ar_id']]))
	$track_cache['netjuke_artists'][$data['ar_id']] = 0;

      $track_cache['netjuke_artists'][$data['ar_id']]++;

      if (!isset($track_cache['netjuke_albums'][$data['al_id']]))
	$track_cache['netjuke_albums'][$data['al_id']] = 0;

      $track_cache['netjuke_albums'][$data['al_id']]++;

      if (!isset($track_cache['netjuke_genres'][$data['ge_id']]))
	$track_cache['netjuke_genres'][$data['ge_id']] = 0;

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

    if (is_array ($ids)) {
      foreach ($ids as $id => $val) {

        track_cache($do, $table, $id, $val);

      }
    }

    track_cache('reset', $table);

  }

}

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

function CacheCleanUp($thorough=0) {

  GLOBAL $dbconn;

  $statements = array();

  # Perform basic cleanup
  $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');

  if ($thorough == 0)
    return;

  # Perform a more thorough check...

  # GENRES
  $sql = "select id from netjuke_genres where track_cnt <= 1 and id != 1";
  $dbrs = $dbconn->Execute ($sql);

  if ($dbrs->RecordCount() > 0) {
    while (!$dbrs->EOF) {
      $sql = "select id from netjuke_tracks where ge_id = ".$dbrs->fields[0];
      $ge_rs = $dbconn->Execute ($sql);
      if ($ge_rs->RecordCount() == 0)
        $statements[] = "delete from netjuke_genres where id = ".$dbrs->fields[0];
      $ge_rs->Close ();
      $dbrs->MoveNext ();
    }
  }

  $dbrs->Close ();

  # ALBUMS
  $sql = "select id from netjuke_albums where track_cnt <= 1 and id != 1";
  $dbrs = $dbconn->Execute ($sql);

  if ($dbrs->RecordCount() > 0) {
    while (!$dbrs->EOF) {
      $sql = "select id from netjuke_tracks where al_id = ".$dbrs->fields[0];
      $al_rs = $dbconn->Execute ($sql);
      if ($al_rs->RecordCount() == 0)
        $statements[] = "delete from netjuke_albums where id = ".$dbrs->fields[0];
      $al_rs->Close ();
      $dbrs->MoveNext ();
    }
  }

  $dbrs->Close ();

  # ARTISTS
  $sql = "select id from netjuke_artists where track_cnt <= 1 and id != 1";
  $dbrs = $dbconn->Execute ($sql);

  if ($dbrs->RecordCount() > 0) {
    while (!$dbrs->EOF) {
      $sql = "select id from netjuke_tracks where ar_id = ".$dbrs->fields[0];
      $ar_rs = $dbconn->Execute ($sql);
      if ($ar_rs->RecordCount() == 0)
        $statements[] = "delete from netjuke_artists where id = ".$dbrs->fields[0];
      $ar_rs->Close ();
      $dbrs->MoveNext ();
    }
  }

  $dbrs->Close ();

  foreach ($statements as $sql) {
    $dbconn->Execute ($sql);
  }

}

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

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 FindGenreID ($genre) {

    $genres = array_map ('strtolower', ArrayOfGenres());
    $val = array_search (strtolower ($genre), $genres);
    if ($val === false) $val = 255;

    return ($val);

}

// 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, ar.img_src,"
	 . " al.img_src, tr.img_src, ge.img_src, al.comments, ar.comments,"
	 . " tr.license, al.license, ar.license 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) {

      // Track name
      $data['TIT2']['encodingid'] = 0;
      $data['TIT2']['data'] = $dbrs->fields[0];

      // Artist name
      $data['TPE1']['encodingid'] = 0;
      $data['TPE1']['data'] = $dbrs->fields[1];

      // Album name
      $data['TALB']['encodingid'] = 0;
      $data['TALB']['data'] = $dbrs->fields[2];

      // Track number
      $data['TRCK']['encodingid'] = 0;
      $data['TRCK']['data'] = $dbrs->fields[3];

      // Genre name
      $data['TCON']['encodingid'] = 0;
      $data['TCON']['data'] = $dbrs->fields[4];

      // Comments
      $data['COMM'][0]['encodingid'] = 0;
      $data['COMM'][0]['data'] = $dbrs->fields[6];
      $data['COMM'][0]['language'] = $lang;
      $data['COMM'][0]['description'] = 'Track Comments';
      $data['COMM'][1]['encodingid'] = 0;
      $data['COMM'][1]['data'] = $dbrs->fields[15];
      $data['COMM'][1]['language'] = $lang;
      $data['COMM'][1]['description'] = 'Album Comments';
      $data['COMM'][2]['encodingid'] = 0;
      $data['COMM'][2]['data'] = $dbrs->fields[16];
      $data['COMM'][2]['language'] = $lang;
      $data['COMM'][2]['description'] = 'Artist Comments';

      // Year
      $data['TYER']['encodingid'] = 0;
      $data['TYER']['data'] = $dbrs->fields[5];

      // License
      $data['TCOP']['encodingid'] = 0;
      $data['TCOP']['data'] = $dbrs->fields[5]." ".$dbrs->fields[1].". Licensed to the public under ".$dbrs->fields[17];

      // Lyrics
      $data['USLT'][0]['encodingid'] = 0;
      $data['USLT'][0]['data'] = $dbrs->fields[7];
      $data['USLT'][0]['language'] = $lang;
      $data['USLT'][0]['description'] = 'Lyrics';

      // Netjuke tagging signature :)
      $data['TXXX'][0]['encodingid']  = 0;
      $data['TXXX'][0]['description'] = 'ID3v2-tagged by';
      $data['TXXX'][0]['data']        = 'Netjuke w/ getID3() v'.GETID3VERSION.' (www.silisoftware.com)';

      // Attach any associated images
      for ($i = 10; $i < 14; $i++) {
        if ($fd = @fopen($dbrs->fields[10], 'rb')) {
            $data['APIC'][$i - 10]['data']          = fread($fd, filesize($dbrs->fields[10]));
            fclose ($fd);

	    $data['APIC'][$i - 10]['encodingid']    = (isset($EditorAPICencodingID)  ? $EditorAPICencodingID : 0);
	    $data['APIC'][$i - 10]['picturetypeid'] = (isset($EditorAPICpictypeID)   ? $EditorAPICpictypeID  : 0);
            $data['APIC'][$i - 10]['description']   = (isset($EditorAPICdescription) ? $EditorAPICdescription : '');

	    require_once(GETID3_INCLUDEPATH.'getid3.getimagesize.php');
            $imageinfo = GetDataImageSize($data['APIC'][$i - 10]['data']);
	    $imagetypes = array(1=>'gif', 2=>'jpeg', 3=>'png');
            if (isset($imageinfo[2]) && ($imageinfo[2] >= 1) && ($imageinfo[2] <= 3)) {
		$data['APIC'][0]['mime']      = 'image/'.$imagetypes[$imageinfo[2]];
	    }
	}
      }

      $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 (! WriteID3v1 (MUSIC_DIR . '/' . $location, $dbrs->fields[0], $dbrs->fields[1],
              $dbrs->fields[2], $dbrs->fields[5], $dbrs->fields[7], FindGenreID($dbrs->fields[4]), $dbrs->fields[3], TRUE)) {

                return (2);

            }

            if (! WriteID3v2 (MUSIC_DIR . '/' . $location, $data, 3, 0, true, 0, true)) {

                return (2);

            }


	    $sql = "update netjuke_tracks set size = '".@filesize (MUSIC_DIR . '/' . $location). "', mtime = '"
                 . getmtime($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_tracks set size = '".@filesize (MUSIC_DIR . '/' . $location). "', mtime = '"
                    . getmtime ($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");

  clearstatcache();

  // These are assumptions getid3() can utilize
  $types = array ('zip', 'ogg', 'riff', 'mpeg', 'midi', 'mp3', 'aac');
  $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(MUSIC_DIR.'/'.$location),
                       '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 {
        // fix for oggenc - uses identifier "tracknumber"
        if (isset($AudioFileInfo["comments"]["tracknumber"][0])) {
          $temp_id3["tr_num"] = trim($AudioFileInfo["comments"]["tracknumber"][0]);
        } else {
          $temp_id3["tr_num"] = 0;
        }
    }

    // get year
    if (isset($AudioFileInfo["comments"]["year"][0])) {
      $temp_id3["year"] = abs($AudioFileInfo["comments"]["year"][0]);
    } else {
      // fix for oggenc - uses identifier "date"
      if (isset($AudioFileInfo["comments"]["date"][0])) {
        $temp_id3["year"] = abs($AudioFileInfo["comments"]["date"][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

      } elseif ($file_ext == 'aac' || $file_ext == 'm4p' || $file_ext == 'm4a') {

      // START AAC SPECIFIC

        $temp_id3["kind"] = "AAC AUDIO FILE";

      // END AAC SPECIFIC

      } elseif ($file_ext == 'shn') {

      // START SHORTEN SPECIFIC

        $temp_id3["kind"] = "SHORTEN AUDIO FILE";

      // END SHORTEN SPECIFIC

      } else if ($file_ext == 'mpc') {

      // START MUSEPACK SPECIFIC

        $temp_id3["kind"] == "MUSEPACK AUDIO FILE";

      // END MUSEPACK SPECIFIC

      } else {

        // not supported - ignore file

      }

      return ($temp_id3);

	} else {

		return (-1);

	}

}

function UpdateOtherTable ($table, $key, $previous="") {

    GLOBAL $dbconn;

    $sql = "SELECT id from $table WHERE name = '".$key."'";
    $dbset = $dbconn->Execute ($sql);
    #print_r ($dbset);
    if (! $dbset->_numOfRows) {

        // This field does not yet exist in the database, add them
        $sql = "INSERT INTO $table (`name` , `track_cnt`) VALUES ( '".$key."', '1')";
        $dbconn->Execute ($sql);

        $retval = $dbconn->Insert_ID();

    } else {

        // already exists, increment track counter
        $sql = "UPDATE $table SET `track_cnt` = `track_cnt` + 1 WHERE id = '".$dbset->fields[0]."'";
        $dbconn->Execute ($sql);

        $retval = $dbset->fields[0];
    }

    // Now decrement the track counter for previous id if necessary
    if ($previous != "") {

        $sql = "UPDATE $table SET `track_cnt` = `track_cnt` - 1 WHERE  id = '$previous'";
        $dbconn->Execute ($sql);

    }

    return ($retval);

}

function UpdateTrackInfo ($id, $raw_values) {

  GLOBAL $dbconn;

  $data = array();
  $values = '';

  // Check if there has been a change to the artist, album, or genre
  $artist                 = $raw_values['artist'];
  $album                  = $raw_values['album'];
  $genre                  = $raw_values['genre'];

  // No blank records stored in db
  if ($artist == "")
    $artist = "N/A";
  if ($album == "")
    $album = "N/A";
  if ($genre == "")
    $genre = "N/A";

  $sql = "SELECT tr.ar_id, tr.al_id, tr.ge_id, ar.name, al.name, ge.name, tr.location FROM"
       . " netjuke_tracks tr, netjuke_artists ar, netjuke_albums al, netjuke_genres ge WHERE"
       . " ar.id = tr.ar_id AND al.id = tr.al_id AND ge.id = tr.ge_id AND tr.id = $id";
  $dbrs = $dbconn->Execute ($sql);

  if ($dbrs !== false) {

    if (strtolower($artist) != strtolower($dbrs->fields[3])) {

        $data['ar_id'] = UpdateOtherTable ('netjuke_artists', $artist, $dbrs->fields[0]);

    }

    if (strtolower($album) != strtolower($dbrs->fields[4])) {

        $data['al_id'] = UpdateOtherTable ('netjuke_albums', $album, $dbrs->fields[1]);

    }

    if (strtolower($genre) != strtolower($dbrs->fields[5])) {

        $data['ge_id'] = UpdateOtherTable ('netjuke_genres', $genre, $dbrs->fields[2]);

    }

  }


  # The following fields can already be initialize
  # as they will be inserted as is in netjuke_tracks
  $data['size']           = $raw_values['size'];
  $data['time']           = $raw_values['time'];
  $data['track_number']   = $raw_values['tr_num'];
  $data['year']           = $raw_values['year'];
  $data['date']           = $raw_values['date'];
  $data['bit_rate']       = $raw_values['bit_rate'];
  $data['sample_rate']    = $raw_values['sample_rate'];
  $data['kind']           = $raw_values['kind'];

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

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

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

  $data['name']           = raw_to_db($raw_values['name']);

  $temp_loc               = urldecode($dbrs->fields[6]);

  $data['mtime']          = getmtime($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);

}

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

function PrefsTabs ($selected = "") {

	require_once(FS_PATH."/etc/locale/".LANG_PACK."/inc-admin_index.php");

  $html = "<center><table width='550' border=0 cellspacing=1 cellpadding=3 class='border'>"
        . "<tr>";

  if ($selected == "system") {
    $html .= "<td align='center' class='headeractive' nowrap><b><a ";
  } else {
    $html .= "<td align='center' class='header' nowrap><b><a ";
  }
  $html .= "href = \"".WEB_PATH."/admin/prefs-edit-system.php\" title=\"".ADMNDX_EDIT_HELP."\">".ADMPREF_HEADER_1."</a></b></td>";

  if ($selected == "content") {
    $html .= "<td align='center' class='headeractive' nowrap><b><a ";
  } else {
    $html .= "<td align='center' class='header' nowrap><b><a ";
  }
  $html .=  "href = \"".WEB_PATH."/admin/prefs-edit-content.php\" title=\"".ADMNDX_EDIT_HELP."\">".ADMPREF_HEADER_2."</a></b></td>";

  if ($selected == "appearance") {
    $html .= "<td align='center' class='headeractive' nowrap><b><a ";
  } else {
    $html .= "<td align='center' class='header' nowrap><b><a ";
  }
  $html .=  "href = \"".WEB_PATH."/admin/prefs-edit-appearance.php\" title=\"".ADMNDX_EDIT_HELP."\">".ADMPREF_HEADER_4."</a></b></td>";

  $html .= "</td></tr></table></center><br>";

  echo $html;
}

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

function lang_pack_menu($name, $selected_val="", $onchange="") {

  $html = "<select name=\"$name\" onchange=\"$onchange\" class=input_content>";

  $values = array( "en"=>ADMPREF_FORMS_LANGPACK_CAPTION_1
                 , "fr"=>ADMPREF_FORMS_LANGPACK_CAPTION_2
                 , "de"=>ADMPREF_FORMS_LANGPACK_CAPTION_3
                 , "ca"=>ADMPREF_FORMS_LANGPACK_CAPTION_4
                 , "es"=>ADMPREF_FORMS_LANGPACK_CAPTION_5
		 , "ru"=>ADMPREF_FORMS_LANGPACK_CAPTION_6
                 , "no"=>ADMPREF_FORMS_LANGPACK_CAPTION_7);

  asort($values);

  foreach ($values as $key => $value) {

    if ($key == $selected_val) {
      $selected = "selected";
    } else {
      $selected = "";
    }

    $html .= "<option value=\"$key\" $selected>$value </option>";

  }

  $html .= "</select>";

  return $html;

}

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

function Find_Id_TrBatchEdit($table,$value) {

   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) VALUES ('$value')";

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

     if ($dbrs->RecordCount() < 1) {
       if ($dbconn->Execute($insert_sql) === false) {
	     $errors .= "- ".TRBEDIT_ERROR_INSERT." $table ($value): ".$dbconn->ErrorMsg()."\\n";
       } else {
         $dbrs = $dbconn->Execute($select_sql);
       }
     }

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

   } else {

     return array(0,$errors);

   }

}

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

function getmtime ($location) {

  $location = rawurldecode ($location);
  $time = @filemtime (MUSIC_DIR.'/'.$location);

  if ($time != false)
    return (date("Y-m-d H:i:s", $time));
  else
    return (false);

}

?>
