<?php

// Try to turn off the gz handler
if (ini_get("safe_mode") == 0) {
  ini_set ("zlib.output_compression", "0");
}

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

# CALL COMMON LIBRARIES

require_once('./lib/inc-common.php');
require_once(FS_PATH."/etc/locale/".LANG_PACK."/inc-batch.php");
require_once(FS_PATH."/lib/zipfile/zipfile.php");

// Don't try to subvert me!
if (BATCH_DOWNLOAD == 'f') {

  header ("Location: index.php\n\n");

}

set_time_limit (BATCH_TIME_LIMIT);

if (strtolower($_REQUEST['do']) == 'download') {
	bundleMe ($_REQUEST['val']);
} else {
	header ("Location: index.php\n\n");
}

function bundleMe ($val) {

  GLOBAL $dbconn, $NETJUKE_SESSION_VARS;

  $total_size = 0;
  $files = "";
	
  $zipfile = new zipfile(); 

  if ($val != '') {

    ignore_user_abort (false);
    header("Content-type: application/octet-stream");
    header("Content-Disposition: attachment; filename=netjuke-".substr(time(),-7).".zip" );

    $id = split(",",$val);

    $trans = get_html_translation_table (HTML_ENTITIES);
    $trans = array_flip ($trans);

    foreach ($id as $this_id) {

      $sql = "SELECT tr.location, tr.time, tr.name, ar.name, al.name  "
        . " from netjuke_tracks tr, netjuke_artists ar, netjuke_albums al "
        . " where tr.id = $this_id and ar.id = tr.ar_id and al.id = tr.al_id ";

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

      $tr_location  = rawurldecode(separatorCleanup($dbrs->fields[0]));
      $tr_time      = floor($dbrs->fields[1]);
      $tr_name      = strtr(format_for_display($dbrs->fields[2]),$trans);
      $ar_name      = strtr(format_for_display($dbrs->fields[3]),$trans);
      $al_name      = strtr(format_for_display($dbrs->fields[4]),$trans);

      # Append web path value if location still doesn't contain ://
      # Copes with the fact that the streaming server could be a relative path (eg: music/)
      # instead of a protocol+hostname combination (http://streaming.host.dom)
      #if (!strstr($tr_location,"://")) $tr_location  = WEB_PATH."/".$tr_location;

      // adding file to zip archiv, compression level 0
      $zipfile->add_file(MUSIC_DIR.'/'.$tr_location, basename($tr_location), 0);
      $zipfile->echo_data();

      // update the track's download count.
      // Is normally done accurately in the dispatcher, but it is now optional...
      $dbconn->Execute( "update netjuke_tracks set dl_cnt = dl_cnt + 1 where id = ".$this_id." " );

      $dbrs->Close();

      if (BATCH_SIZE_LIMIT != '0') {

        $total_size += filesize (MUSIC_DIR . '/' . rawurldecode($tr_location));
        if (($total_size / (1024 * 1024)) >= intval (BATCH_SIZE_LIMIT)) {

            break;

        }

      } // if BATCH_SIZE_LIMIT

    } // foreach $id

    $zipfile->echo_footer();
  } 

  // else $val == ""
  else {
    alert (PLAYER_NOID);
  }

  exit;

} // function bundleMe()

?>
