<?php

// Lower error output
// We don't want anything upsetting our XML stream
#error_reporting(0);

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

# CALL COMMON LIBRARIES

require_once('./lib/inc-common.php');
require_once(FS_PATH.'/lib/cc_license/cc_license.php');
require_once(FS_PATH."/etc/locale/".LANG_PACK."/inc-index.php");
require_once(FS_PATH."/lib/rsswriter/rsswriter.php");

if (ENABLE_XML == 'f')
  header( 'Location: '.WEB_PATH.'/index.php');

# MAKE SURE EVERYTHING IS DEFINED
ensure_defined_REQUEST('do');
ensure_defined_REQUEST('val');
ensure_defined_REQUEST('type');
ensure_defined_REQUEST('id');
ensure_defined_REQUEST('count');

# BUILD THE RSS OBJECT AND ADD NAMESPACES
$rss = new RSSWriter (WEB_PATH,
                      "Netjuke @ ".$_SERVER['SERVER_NAME'],
                      "Netjuke Streaming Media Jukebox",
                      array (),
                      LANG_PACK);
$rss->useModule ('cc', "http://web.resource.org/cc/");
$rss->useModule ('authena', "http://authena.org/rss/1.0/");
$rss->useModule ('audio', "http://media.tangent.org/rss/1.0/");

# THESE ARE THE VALID SEARCH METHODS

switch ($_REQUEST['do']) {

  // Show a rundown of all of a group (genre/artist/album)
  case 'show.all':
    show_all ($_REQUEST['type']);
    break;

  // Show the latest of a particular set
  case 'show.latest':
    show_latest ($_REQUEST['type'], $_REQUEST['count']);
    break;

  // Show the artists Netjuke knows about, optionally limited by an id, or a val
  case 'show.artists':
    show_group ('artists', $_REQUEST['id'], $_REQUEST['val'], $_REQUEST['type']);
    break;

  // Show albums Netjuke knows about, optionally limited by an id or a val
  case 'show.albums':
    show_group ('albums', $_REQUEST['id'], $_REQUEST['val'], $_REQUEST['type']);
    break;

  // Show information about a particular track or group of tracks
  case 'show.tracks':
    show_tracks ($_REQUEST['id']);
    break;

  // Show all subgenres of a given genre
  case 'show.subs':
    break;

  // Show information about a playlist and the tracks it contains
  case 'show.playlist':
    show_playlist ($_REQUEST['id']);
    break;

  // Show a list of playlists in a given group
  case 'show.playlists':
    show_playlist_group ($_REQUEST['type']);
    break;

  default:
    header( 'Location: '.WEB_PATH.'/index.php');
    break;

}

// WRITE THE XML OUT TO THE USER AGENT
$rss->serialize ();

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

function show_latest ($type, $count) {

  global $rss;

  if ($type == 'al') {
    $table = 'netjuke_albums';
    $action = 'albums';
  } else {
    $table = 'netjuke_artists';
    $action = 'artists';
  }

  $items = GetLatest($table, $count);

  foreach ($items as $item) {
    $rss->addItem (WEB_PATH.'/search.php?do=list.'.$action.'&col='.$type.'_id&val='.$item[0].'&sort='.$type,
                   $item[1]);
  }

}

// Show all of a particular type of metadata (genre/artist/album)
function show_all ($type, $include_tracks=false) {

  global $dbconn;
  global $rss;

  $sql = "select id, name, img_src, track_cnt, comments, license";

  switch ($type) {

    case 'ge':
      if ($type == 'ge') $sql .= ", parent_id";
      $sql .= " from netjuke_genres ";
      break;

    case 'ar':
      $sql .= " from netjuke_artists ";
      break;

    case 'al':
      $sql .= " from netjuke_albums ";
      break;

    default:
      return (false);
      break;

  }

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

  while (! $dbrs->EOF) {

    $rss->addItem (WEB_PATH.'/explore.php?do=list.artists&'.$type.'_id='.$dbrs->fields[0],
                   $dbrs->fields[1]);
    $dbrs->MoveNext ();

  }

  $dbrs->Close();

}

function show_tracks ($ids, $as_playlist = 0) {

  global $dbconn, $NETJUKE_LICENSES;
  global $rss;

  if (is_string ($ids))
    $id_list = explode (',', $ids);
  elseif (is_array ($ids))
    $id_list = $ids;

  foreach ($id_list as $id) {

    $sql = "select tr.name, tr.year, tr.comments, tr.bit_rate, tr.time"
         . ", al.name, ge.name, ar.name, tr.license, tr.kind, us.email, tr.date"
         . " from netjuke_tracks tr, netjuke_albums al, netjuke_genres ge, netjuke_artists ar, netjuke_users us"
         . " where tr.id = ".$id." and al.id = tr.al_id and ge.id = tr.ge_id and ar.id = tr.ar_id and us.gr_id = 1 limit 1";
    $tr_rs = $dbconn->Execute ($sql);

    while (! $tr_rs->EOF) {

      $license_uri = '';

      // Attempt to locate the license
      $license = find_license_by_uri (rawurldecode ($tr_rs->fields[8]), $NETJUKE_LICENSES);
      if (is_object ($license)) {
        $license_uri = $license->uri;
        $rss->setExtra ($license->get_rdf());
      }

      $meta = array ('audio:songname' => $tr_rs->fields[0],
                     'audio:year' => $tr_rs->fields[1],
                     'audio:comment' => $tr_rs->fields[2],
                     'audio:bitrate' => $tr_rs->fields[3],
                     'audio:recording_time' => $tr_rs->fields[4],
                     'audio:album' => $tr_rs->fields[5],
                     'audio:genre' => $tr_rs->fields[6],
                     'audio:artist' => $tr_rs->fields[7],
                     'authena:pristine' => WEB_PATH."/play.php?do=play&val=".$id,
                     'authena:watermarked' => WEB_PATH."/play.php?do=play_resample&quality=3&val=".$id,
                     'authena:thumbnail' => WEB_PATH."/play.php?do=play_clip&duration=5&val=".$id,
                     'authena:price' => "$1.99",
                     'authena:license' => $license_uri,
                     'dc:title' => $tr_rs->fields[0],
                     'dc:creator' => '<cc:Agent><dc:title>'.$tr_rs->fields[7].'</dc:title></cc:Agent>',
                     'dc:format' => "audio/mpeg",
                     'dc:description' => $tr_rs->fields[9],
                     'dc:publisher' => '<cc:Agent><dc:title>'.$tr_rs->fields[10].'</dc:title></cc:Agent>',
                     'dc:date' => date("Y-m-d", strtotime ($tr_rs->fields[11])),
                     'dc:type' => "http://purl.org/dc/dcmitype/Sound",
                     'dc:subject' => "Audio Resource",
                     'dc:source' => WEB_PATH,
                     'cc:license' => $license_uri);

      $rss->addItem (WEB_PATH."/play.php?do=play&val=".$id, $tr_rs->fields[0], $meta);

      $tr_rs->MoveNext ();

    }

    $tr_rs->Close ();

  }

}

// Show a group Netjuke knows about (genre/album/artist), optionally limited by an id or a val
function show_group ($type, $id, $val, $limit_by) {

  global $dbconn, $NETJUKE_SESSION_VARS;
  global $rss;

  switch ($type) {
    # Show all artists
    case 'artists':
      $col = 'ar';
      break;

    # Show albums
    case 'albums':
      $col = 'al';
      break;

    case 'genres':
      $col = 'ge';
      break;

    default:
      return;
      break;
  }

  $sql = "select distinct $col.id, $col.name from netjuke_genres ge, netjuke_albums al, netjuke_artists ar"
       . ", netjuke_tracks tr where ar.id = tr.ar_id and al.id = tr.al_id and ge.id = tr.ge_id";

  if ($limit_by != '') {
    $sql .= " and tr.".$limit_by."_id = $id";
  }

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

  while (! $dbrs->EOF) {

    switch ($type) {
      case 'artists':
        $rss->addItem (WEB_PATH.'/explore.php?do=list.albums&'.$limit_by.'_id='.$id.'&'.$col.'_id='.$dbrs->fields[0],
                    $dbrs->fields[1]);
        break;

      case 'albums':
        $rss->addItem (WEB_PATH.'/search.php?do=list.tracks&col=al_id&val='.$dbrs->fields[0],
                    $dbrs->fields[1]);
        break;
    }

    $dbrs->MoveNext ();
  }
}

// Show information about a playlist and the tracks it contains
function show_playlist ($id) {

  global $dbconn;
  global $rss, $NETJUKE_SESSION_VARS;

  $sql = "
      SELECT tr.id, ar.id, al.id,
             ge.id, tr.time, tr.track_number, pt.sequence, pt.id,
             tr.img_src, ar.img_src, al.img_src, tr.size
      from netjuke_tracks tr, netjuke_artists ar, netjuke_albums al,
           netjuke_genres ge, netjuke_plists pl, netjuke_plists_tracks pt
      where pt.pl_id = ".$id."
        and pt.us_email = '".$NETJUKE_SESSION_VARS["email"]."'
        and pt.pl_id = pl.id
        and pt.us_email = pl.us_email
        and tr.id = pt.tr_id
        and ar.id = tr.ar_id
        and al.id = tr.al_id
        and ge.id = tr.ge_id
        order by pt.sequence,tr.track_number,tr.location asc
   ";

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

   $rows = $dbrs->RecordCount();

   if ($rows < 1) {
     exit;
   }

   $ids = array ();

   while (! $dbrs->EOF) {
     $ids[] = $dbrs->fields[0];
     $dbrs->MoveNext ();
   }

  if (count ($ids))
    show_tracks ($ids);
}

// Show a list of playlists in a given group
function show_playlist_group ($type) {

  global $dbconn, $NETJUKE_SESSION_VARS;
  global $rss;

  if ($type == 'private') {
    if (ENABLE_COMMUNITY != 't') {

      $sql = " SELECT id, title, comment, shared_list, sequence ".
             " from netjuke_plists ".
             " where us_email = '".$NETJUKE_SESSION_VARS["email"]."' ".
             " order by sequence asc ";

    } else {

      $sql = " SELECT id, title, comment, shared_list, sequence ".
             " from netjuke_plists ".
             " where us_email = '".$NETJUKE_SESSION_VARS["email"]."' ".
             " and shared_list = 'f' ".
             " order by sequence asc ";

    }

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

    while (! $dbrs->EOF) {

      $rss->addItem (WEB_PATH.'/pl-edit.php.php?do=edit&pl_id='.$dbrs->fields[0],
                      $dbrs->fields[1]);

      $dbrs->MoveNext ();
    }

  } elseif ($type == 'shared' && ENABLE_COMMUNITY == 't') {

    $dbrs = $dbconn->Execute( " SELECT id, title, comment, shared_list, sequence ".
                              " from netjuke_plists ".
                              " where us_email = '".$NETJUKE_SESSION_VARS["email"]."' ".
                              " and shared_list = 't' ".
                              " order by sequence asc " );

    while (! $dbrs->EOF) {

      $rss->addItem (WEB_PATH.'/pl-edit.php.php?do=edit&pl_id='.$dbrs->fields[0],
                      $dbrs->fields[1]);

      $dbrs->MoveNext ();
    }

  } elseif ($type == 'community' && ENABLE_COMMUNITY == 't') {

    $dbrs = $dbconn->Execute( " SELECT pf.pl_id, pl.title, pl.comment, pf.sequence "
                            . " from netjuke_plists_fav pf, netjuke_plists pl "
                            . " where pf.us_email = '".$NETJUKE_SESSION_VARS["email"]."' "
                            . " and pl.id = pf.pl_id "
                            . " and pl.shared_list = 't' "
                            . " order by pf.sequence asc " );

    while (! $dbrs->EOF) {

      $rss->addItem (WEB_PATH.'/pl-shrd-view.php?do=view&pl_id='.$dbrs->fields[0],
                      $dbrs->fields[1]);

      $dbrs->MoveNext ();
    }
  }

}

?>