<?php

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

// UTILITY CODE - file, encoding, and query functions

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

function GetLatest ($table, $limit) {
  global $dbconn;

  $dbrs = $dbconn->SelectLimit(  " SELECT id, name, img_src, track_cnt "
                               . " from " . $table . " "
                               . " where track_cnt > 0 "
                               . " order by id desc "
                               , $limit );

  $latest = array ();
  while (!$dbrs->EOF) {

    $latest[] = $dbrs->fields;
    $dbrs->MoveNext();

  }

  $dbrs->Close();

  return ($latest);

}

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

function GetLatestArtists ($limit) {
  return (GetLatest ('netjuke_artists', $limit));
}

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

function GetLatestAlbums ($limit) {
  return (GetLatest ('netjuke_albums', $limit));
}

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

// Please see http://www.w3.org/WAI/ER/IG/ert/iso639.htm for additional language definitions
// Failure to add new languages to this function will break ID3 write-back (among other things)
function get_lang_in_639 () {

  if (isset ($NETJUKE_SESSION_VARS['language']))
    $lang = $NETJUKE_SESSION_VARS['language'];
  else
    $lang = LANG_PACK;

  switch ($lang) {

    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;

    case 'ru':
      $lang = 'rus';
      break;

    case 'it':
      $lang = 'ita';
      break;

    case 'no':
      $lang = 'nor';
      break;

    default:
      $lang = 'XXX';
      break;

    }

  return ($lang);

}

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

function MoveToTrash ($location) {

  $location = rawurldecode ($location);
  $dirs = explode ('/', dirname ($location));

  if (is_writable (FS_PATH . '/' . DATA_DIR_TRASH)) {

    $path = FS_PATH . '/' . DATA_DIR_TRASH;

    foreach ($dirs as $dir) {

      $path .= '/' . $dir;
      $path = separatorCleanup ($path);
      if (! file_exists ($path)) {

        @mkdir ($path, 0755);

      }

    }

    $dest = separatorCleanup ($path . '/' . basename ($location));
    $src = separatorCleanup (MUSIC_DIR . '/' . $location);

    if (! @copy ($src, $dest)) {

      return (false);

    } else {

      @unlink ($src);
      return (true);

    }

  } else {

    return (false);

  }

}

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

// Defines a field in $_REQUEST with a default-value

function ensure_defined_REQUEST($key, $defaultvalue='') {
  if (!isset($_REQUEST[$key])) $_REQUEST[$key]=$defaultvalue;
}

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

function SetErrorLevel () {

    global $dbconn;

    $mypath = DefineRootPath ();
    $vstr = join(file($mypath."/VERSION.txt"), '');

    if (strstr($vstr, 'dev') == true) {

        // Reporting E_NOTICE can be good too (to report uninitialized
        // variables or catch variable name misspellings ...)
        // Turn on adodb's debug mode...
        error_reporting (E_ALL);
        $dbconn->debug = 1;

    } else {

        // Report simple running errors
        error_reporting  (E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR);

    }

}

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

function load_themes () {
  GLOBAL $NETJUKE_THEME_LIST;

  // Load all currently installed themes into an array

  if ($dir = @opendir (FS_PATH . "/var/html/themes/")) {

    while (($file = readdir ($dir)) !== false) {

      if ($file != "CVS" && $file != "." && $file != ".."
          && is_file (FS_PATH . "/var/html/themes/" . $file)
          && strtolower (substr ($file, -4)) == '.php') {

          if ((!isset($NETJUKE_THEME_LIST)) || (! array_key_exists ($file, $NETJUKE_THEME_LIST))) {
            $theme = include_once (FS_PATH."/var/html/themes/".$file);

            if (isset($theme) && is_subclass_of($theme, 'Theme')) {
              $file = substr ($file, 0, strlen($file)-4);
              $NETJUKE_THEME_LIST[$file] = $theme;
            }
          }

      }

    }

    closedir ($dir);

  }

  return ($NETJUKE_THEME_LIST);

}


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

// Delete aging random playlists, etc.
function PerformHousekeeping () {

    GLOBAL $dbconn;

    // Get a list of playlists to be deleted (greater than 5 days old and still named Random )
    $time = mktime (adodb_date("H"),adodb_date("i"),adodb_date("s"),adodb_date("m")-1,adodb_date("d"),  adodb_date("Y"));
    $ts = adodb_date("Y-m-d H:i:s", $time);
    $sql = "delete from netjuke_plists where title like 'Random %' and created <= '".$ts."' and shared_list = 'f'";
    $dbconn->Execute($sql);

}

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

function get_pl_tracks($pl_id = 0) {

  GLOBAL $dbconn, $NETJUKE_SESSION_VARS;

  $dbrs = $dbconn->Execute(" SELECT pt.tr_id
                             from netjuke_plists_tracks pt, netjuke_plists pl
                             where pt.pl_id = $pl_id
                             and pt.pl_id = pl.id
                             and (    pl.us_email = '".$NETJUKE_SESSION_VARS['email']."'
                                   or pl.shared_list = 't' )
                             order by pt.sequence ");

  $cnt = 0;

  $str = '';

  while (!$dbrs->EOF) {

    if ($cnt != 0) $str .= ",";

    $str .= abs($dbrs->fields[0]);

    $dbrs->MoveNext();

    $cnt++;

  }

  $dbrs->Close();

  return $str;

}

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

function specialUrlEncode ($str = "") {

   $str = rawurlencode($str);
   $str = ereg_replace ('%2F','/',$str);
   $str = ereg_replace ('%3A',':',$str);
   $str = ereg_replace ('%40','@',$str);
   $str = ereg_replace ('%7E','~',$str);
   // the following is to eliminate any potential leftover php \
   $str = ereg_replace ('%5C','',$str);

   return $str;

}

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

function raw_to_db($str = "") {

   $str = str_replace("'","\\'",$str);
   return str_replace("\\\\","\\",$str);

}

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

function db_to_raw($str = "") {

   return str_replace("\\'","'",$str);

}

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

function obfuscate_apply($str = "") {

   # nothing much given we're in an open-source environment anyway...
   # Just enough to keep honest people honest. ;o)
   return rawurlencode(base64_encode($str));

}

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

function obfuscate_undo($str = "") {

   # nothing much given we're in an open-source environment anyway...
   # Just enough to keep honest people honest. ;o)
   return base64_decode(rawurldecode($str));

}

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

function format_for_display($str = "") {

   return htmlspecialchars($str);

}

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

function check_image($file = "") {

  if (    ( strlen($file) > 0 )
       && (    (substr(strtolower($file),-4,4) == ".gif")
            || (substr(strtolower($file),-4,4) == ".jpg") )  )  {

    $fs_path = str_replace("//","/",FS_PATH."/".ARTWORK_DIR."/".$file);
    $web_path = str_replace(":/","://", str_replace("//","/",WEB_PATH."/".ARTWORK_DIR."/".$file) );

    if (@file_exists($fs_path)) {
      $file = $web_path;
    } else {
      $file = "";
    }

  } else {

    $file = "";

  }

  return $file;

}

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

function get_display_name($email) {

  GLOBAL $dbconn;

  $dbrs = $dbconn->SelectLimit(  " SELECT name, nickname "
                               . " from netjuke_users"
                               . " where email = '$email' "
                               , 1 );

  if ($dbrs->fields[1] != '') {

    $display_name = $dbrs->fields[1];

  } elseif ($dbrs->fields[0] != '') {

    $display_name = $dbrs->fields[0];

  } else {

    $display_name = str_replace("@","-at-",$email);

  }

  return $display_name;

}

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

function getTimeSize() {

  GLOBAL $dbconn;

  $dbrs = $dbconn->Execute("select sum(time), sum(size) from netjuke_tracks");

  $time = myTimeFormat( $dbrs->fields[0] );
  $size = myFilesizeFormat( $dbrs->fields[1] );

  return array($time,$size);

}

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

function getCount( $type = 'tr', $extra_clause = '' ) {

  GLOBAL $dbconn;

  switch($type) {
    case 'ar':
      $table = 'netjuke_artists';
      break;
    case 'al':
      $table = 'netjuke_albums';
      break;
    case 'ge':
      $table = 'netjuke_genres';
      break;
    default:
      $table = 'netjuke_tracks';
      $type = 'tr';
  }

  $dbrs = $dbconn->Execute("select count(id) from ".$table." ".$extra_clause);
  $cnt = (int) $dbrs->fields[0];
  $dbrs->Close();

  return $cnt;

}

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

function myTimeFormat($numofsec = 0) {

  if ($numofsec > 0) {
    $min = (int) ($numofsec / 60);
    if ($min > 59) {
      $hr = (int) ($min / 60);
      $min = ( $min - ($hr * 60) );
      $hr_str = $hr . ":";
      $sec = ( $numofsec - ( ($hr * 3600) + ($min * 60) ) );
      if (strlen($min) == 1) $min = '0' . $min;
    } else {
      $hr_str = "";
      $sec = ( $numofsec - ($min * 60) );
    }
    if (strlen($sec) == 1) $sec = '0' . $sec;
    $time = $hr_str . $min . ':' . $sec;
  } else {
    $time = 'N/A';
  }

  return $time;

}

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

function myFilesizeFormat($sizeinbytes = 0) {

  if ($sizeinbytes >= 1073741824) {
    $file_size = round($sizeinbytes / 1073741824 * 100) / 100 . " GB";
  } elseif ($sizeinbytes >= 1048576) {
    $file_size = round($sizeinbytes / 1048576 * 100) / 100 . " MB";
  } elseif ($sizeinbytes >= 1024) {
    $file_size = round($sizeinbytes / 1024 * 100) / 100 . " KB";
  } else {
    $file_size = $sizeinbytes . "B";
  }

  return $file_size;

}

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

function cust_str_shuffle($str) {

  $cnt = strlen($str);

  $pos = 0;

  $arr = array();

  while ($pos < $cnt) {

    $arr[] = substr($str,$pos,1);

    $pos++;

  }

  shuffle($arr);

  $newstr = implode('',$arr);

  return $newstr;

}

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

function encode_security_key($str) {

  $str = cust_str_shuffle(obfuscate_apply($str));

  // make sure the key is at least 256 chars long
  if (strlen($str) < 256) $str = encode_security_key($str);

  // make sure the key is at max 512 chars long
  if (strlen($str) > 512)  {
    $pos = floor( ( (strlen($str) - 512) / 2 ) );
    $str = substr($str,$pos,512);
  }

  return $str;

}

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

// File must be relative to netjuke root, name must be unique
// Calls to this function should be placed in configuration file
// Errors : -1 File Not Found, -2 Permission denied, -3 module name already exists
// else returns numeric index for this module
function register_module ($file, $name) {

    GLOBAL $NETJUKE_MODULES;

    // Do some sanity checking

    if (! @file_exists (FS_PATH . '/' . $file)) {

        return (-1);

    }

    if (! @is_readable (FS_PATH . '/' . $file)) {

        return (-2);

    }

    if (array_key_exists ($name, $NETJUKE_MODULES)) {

        return (-3);

    }

    // Everything looks good, lets register it
    $NETJUKE_MODULES[$name] = $file;

    // Initialize the module (if necessary)
    netjuke_module_init ($name, 'netjuke_module_init');

    return ($index);

}

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

// Module may be numeric or textual, function is valid function name in module file
// additional arguments will be passed to specified function
function call_module ($module, $function) {

    GLOBAL $NETJUKE_MODULES;

    // Attempt to find the module
    if (! array_key_exists ($module, $NETJUKE_MODULES)) {

        return (-1);

    }

    // Split off our arguments
    $args = func_get_args ();
    $args = array_slice ($args, 2);

    $file = $NETJUKE_MODULES[$module];
    if (@require_once (FS_PATH.'/'.$file)) {

        if (@function_exists ($function)) {

            @call_user_func_array ($function, $args);

        }

    }

}

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

function httpQ($command, $arg = '') {

  $pass = JUKEBOX_PASS;
  list ($host, $port) = split (":", JUKEBOX_URL, 2);
  $fp = pfsockopen($host, $port, $errno, $errstr);

  if(!$fp)
  {
    echo "$errstr ($errno)\n";
  }
  else
  {
    if($arg == "")
    {
      $msg = "GET /$command?p=$pass HTTP/1.0\r\n\r\n";
    }
    else
    {
      $msg = "GET /$command?p=$pass&a=$arg HTTP/1.0\r\n\r\n";
    }

    fputs($fp, $msg);
    while(!feof($fp))
    {
      echo fgets($fp,128);
    }
  }

  fclose($fp);
}

?>