<?php

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

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

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

ensure_defined_REQUEST('do');
ensure_defined_REQUEST('dir');

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

if ($_REQUEST['do'] == 'import') {
  header('Location: '.WEB_PATH.'/admin/tabfile-recursive.php?do=process&scan_dir='.rawurlencode(MUSIC_DIR.rawurldecode($_REQUEST['dir'])).'&recursive_scan=1&auto_queue=1&direct_import=1');
  exit;
}

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

$onload = "document.pathForm.dir.focus();";

$section = "sysadmin";
include (INTERFACE_HEADER);

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

?>

<script type="text/javascript" language="Javascript">
<!--

function LocalSelectAll() {
   for (var i=0;i< document.importForm.elements.length;i++) {
      if (    (document.importForm.elements[i].name == 'import_dirs[]')
           || (document.importForm.elements[i].name == 'import_files[]') ) {
         document.importForm.elements[i].checked = true;
      }
   }
}

function LocalResetAll() {
   for (var i=0;i< document.importForm.elements.length;i++) {
      if (    (document.importForm.elements[i].name == 'import_dirs[]')
           || (document.importForm.elements[i].name == 'import_files[]') ) {
         document.importForm.elements[i].checked = false;
      }
   }
}

function OrganizeDirs() {
   var str='';

   for (var i=0;i < document.importForm.elements.length;i++) {
      if (document.importForm.elements[i].checked == true
	  && document.importForm.elements[i].name == 'import_dirs[]') {
	  	if (str != '') {
				str = str + ',' + document.importForm.elements[i].value;
			} else {
				str = document.importForm.elements[i].value;
			}
      }
   }

   if (str != '') {
   	top.location.href = './organize.php?do=organize&val=' + str;
   } else {
   	alert("<?php echo  COMMON_NOTRACK ?>");
   }
}

//-->
</script>

<?php

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

DirBrowser($_REQUEST['dir']);

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

include (INTERFACE_FOOTER);

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

function DirBrowser($req_path) {

  global $dbconn, $ICONS;

  $html = '';
  $supported_formats = explode(',',SUPPORTED_FORMATS);

  $req_path = stripslashes(rawurldecode($req_path));

  $fs_path = MUSIC_DIR.'/'.str_replace('../','',$req_path);

  if (substr($fs_path,-1,1) == '/') $fs_path = rtrim($fs_path,'/');

  if ( ! ( preg_match("/^[A-Z]:/",$fs_path) ) ) {
  	#if (substr($fs_path,0,1) != '/')  $fs_path = '/'.$fs_path;
  } elseif ( preg_match("/^\/[A-Z]:/",$fs_path) ) {
  	$fs_path = substr($fs_path,1);
  }

  $web_path = str_replace('../','',$req_path);
  if (substr($web_path,-1,1) == '/') $web_path = rtrim($web_path,'/');
  if (substr($web_path,0,1) != '/') $web_path = '/'.$web_path;

  $bc_nav_html = '';

  $bc_nav_arr = BreadCrumNav($web_path);

  $total = count($bc_nav_arr);
  $cnt = 1;

  foreach ($bc_nav_arr as $link => $caption) {

    if ($cnt < $total) {
      $bc_nav_html .= '&nbsp;<b>&raquo;</b>&nbsp;<a href="'.$_SERVER['PHP_SELF']."?dir=".rawurlencode($link).'">'.$caption.'</a>';
    } else {
      $bc_nav_html .= '&nbsp;<b>&raquo;</b>&nbsp;'.$caption.'</a>';
    }

    $cnt++;

  }

  echo "
    <table width='100%' border='0' cellspacing='1' cellpadding='3' class='border'>
      <tr>
  	    <td class='header'><b>".FBROWS_HEADER_1." (".FBROWS_ROOT." = ".MUSIC_DIR.")</b></td>
  	  </tr>
      <tr>
        <td class='content'>
          <b>".$bc_nav_html."</b>
        </td>
      </tr>
          <form action=\"".$_SERVER['PHP_SELF']."\" method=\"post\" name=\"pathForm\">
      <tr>
        <td class='content' nowrap>
          <input type=\"text\" name=\"dir\" value=\"".$web_path."\" size=\"60\">
          <select name=\"do\">
            <option value=\"list\">".FBROWS_SELECT_LIST."</option>
            <option value=\"import\">".FBROWS_SELECT_IMPORT."</option>
          </select>
          <input type=\"submit\" value=\" ".FBROWS_BTN_GO." \" class=\"btn_content\">
        </td>
      </tr>
          </form>
    </table>
    <br>
    <table width='100%' border='0' cellspacing='1' cellpadding='3' class='border'>
      <tr>
  	    <td class='header' nowrap colspan='5'><b>".FBROWS_HEADER_2."</b></td>
  	  </tr>
      <form action=\"./tabfile-recursive.php\" method=\"post\" name=\"importForm\">
      <input type=\"hidden\" name=\"interactive\" value=\"1\">
      <tr>
        <td class='content' nowrap align='center'>
          <b><a href=\"Javascript:LocalSelectAll();\">".FBROWS_SELECT_ALL."</a></b>
        </td>
        <td class='content' nowrap align='center'>
          <b><a href=\"Javascript:LocalResetAll();\">".FBROWS_RELEASE_ALL."</a></b>
        </td>
        <td class='content' nowrap align='center' colspan=\"2\">
          <b><a href=\"Javascript:document.importForm.submit();\">".FBROWS_IMPORT_SEL."</a></b>
        </td>
		<td class='content' nowrap align='center' colspan=\"2\">
          <b><a href=\"Javascript:OrganizeDirs();\">".FBROWS_ORGANIZE_SEL."</a></b>
        </td>
      </tr>
      <tr>
        <td class='content' nowrap align='center' colspan='2'>
          <input type=\"checkbox\" name=\"recursive_scan\" value=\"1\" checked> ".FBROWS_RECURSIVE."
        </td>
        <td class='content' nowrap align='center'>
          <input type=\"checkbox\" name=\"auto_queue\" value=\"1\" checked> ".FBROWS_FNAME_PARS."
        </td>
        <td class='content' nowrap align='center'>
          <input type=\"checkbox\" name=\"verbose_scan\" value=\"1\"> ".FBROWS_VERBOSE."
        </td>
        <td class='content' nowrap align='center'>
          <input type=\"checkbox\" name=\"direct_import\" value=\"1\" checked> ".FBROWS_DIRECT_IMP."
        </td>
  	  </tr>
    </table>
    <br>
  ";

  $retval = array();

  if ( !( $handle = @opendir($fs_path) ) ) {

    echo '<B>'.FBROWS_NOT_FOUND_1.' '.$fs_path
        .'.<br />'.FBROWS_NOT_FOUND_2.'.';

  } else {

	while ($this = readdir($handle)) {
	  if (substr($this, 0, 1) != '.') $retVal[] = $this;
	}

    closedir($handle);

  }

  if (count($retVal) > 0) {

    sort($retVal);

    echo "
      <table width='100%' border='0' cellspacing='1' cellpadding='3' class='border'>
      <tr>
        <td class=\"header\" width=\"2%\" align=\"center\" valign=\"top\" nowrap>".FBROWS_TH_OPT."</td>
        <td class=\"header\" width=\"3%\" align=\"center\" valign=\"top\" nowrap>".FBROWS_TH_TYP."</td>
        <td class=\"header\" width=\"63%\" align=\"left\" valign=\"top\">".FBROWS_TH_NAM."</td>
        <td class=\"header\" width=\"20%\" align=\"center\" valign=\"top\" nowrap>".FBROWS_TH_MOD."</td>
        <td class=\"header\" width=\"7%\" align=\"center\" valign=\"top\" nowrap>".FBROWS_TH_SIZ."</td>
      </tr>
    ";

    foreach ($retVal as $filename) {

      $checkbox = $href = $caption = $filestype =  $filesize =  '';

      $cur_dir = str_replace('./','',$fs_path.'/');

      if (is_dir($fs_path.'/'.$filename)) {

        $checkbox = "<input type=\"checkbox\" name=\"import_dirs[]\" value=\"".specialUrlEncode(str_replace('//','/',$web_path.'/'.$filename))."\" title=\"".FBROWS_CHECK_1."\">";

        $href_path = $web_path.'/'.$filename;

        if (substr($href_path,0,2) == '//') $href_path = str_replace('//','/',$href_path);

        $href = str_replace('//','/',$_SERVER['PHP_SELF'].'?dir='.rawurlencode($href_path));

        $caption = "<a href=\"".$href."\">".$filename."</a>";

        $filestype =  '<IMG SRC="'.$ICONS['dir']['url'].'" ALT="'.FBROWS_ALT_DIR.'" WIDTH="'.$ICONS['dir']['x'].'" HEIGHT="'.$ICONS['dir']['y'].'" HSPACE="0" VSPACE="0" BORDER="0" ALIGN="absmiddle">';

        $filesize =  '&nbsp;';

      } elseif (is_file($fs_path.'/'.$filename)) {

        $temp_vals = explode('.',$filename);

        $file_ext = strtolower(rtrim(array_pop($temp_vals)));

        if (strlen($file_ext) == 0) $file_ext = '|||'; // makes sure file_ext str is never empty

        if (in_array($file_ext, $supported_formats)) {

          $db_path = specialUrlEncode($req_path.'/'.$filename);

          if (substr($db_path,0,1) == '/')  $db_path = substr($db_path,1);

					$sql = "select id from netjuke_tracks where location = '".$db_path."'";
          $dbrs = $dbconn->Execute($sql);

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

            $checkbox = "<input type=\"checkbox\" name=\"import_files[]\" value=\"".specialUrlEncode(str_replace('//','/',$web_path.'/'.$filename))."\" title=\"".FBROWS_CHECK_2."\">";

          } else {

            $checkbox = '<a href="'.WEB_PATH.'/search.php?do=search.adv&tr_location='.$db_path.'"><IMG SRC="'.$ICONS['check']['url'].'" ALT="!" WIDTH="'.$ICONS['check']['x'].'" HEIGHT="'.$ICONS['check']['y'].'" HSPACE="0" VSPACE="4" BORDER="0"></a>';

          }

          $dbrs->close();

          $href = STREAM_SRVR.'/'.str_replace('//','/',$web_path.'/'.$filename);

          if (!strstr($href,'://')) $href  = WEB_PATH.'/'.$href;

          $href = separatorCleanup($href);

          // $caption = "<a href=\"".$href."\">".$filename."</a>";
          $caption = $filename;

          $filestype = '<IMG SRC="'.$ICONS['file']['url'].'" ALT="'.FBROWS_ALT_FILE.'" WIDTH="'.$ICONS['file']['x'].'" HEIGHT="'.$ICONS['file']['y'].'" HSPACE="0" VSPACE="0" BORDER="0" ALIGN="absmiddle">';

          $filesize = myFilesizeFormat(filesize($fs_path."/".$filename));

        } else {

          $href = '';

          $checkbox = "&nbsp;";

        }

      }

  	  if ($href != '') {

  	    echo "
  	      <tr>
            <td class=\"content\" align=\"center\" valign=\"top\" nowrap>".$checkbox."</td>
            <td class=\"content\" align=\"center\" valign=\"top\" nowrap>".$filestype."</td>
            <td class=\"content\" align=\"left\" valign=\"top\">".$caption."</td>
            <td class=\"content\" align=\"center\" valign=\"top\" nowrap>".date("Y-m-d H:i:s",filemtime($fs_path."/".$filename))."</td>
            <td class=\"content\" align=\"right\" valign=\"top\" nowrap>".$filesize."</td>
          </tr>
        \n";

      }

    }

    echo "</form>\n";
    echo "</table>\n";

  }

  return ($html);

}

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

function BreadCrumNav($web_path) {

  $items = array();

  $dirs = explode('/',$web_path);

  while ($this_dir = array_pop($dirs)) {

    $items[implode('/', $dirs).'/'.$this_dir] = $this_dir;

  }

  ksort($items);

  $navbar = array('/' => FBROWS_ROOT);

  $navbar = array_merge($navbar,$items);

  return $navbar;

}

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

?>
