<?php
/* $Id$ */
/*
	freeswitch_recordings.php
	Copyright (C) 2008 Mark J Crane
	All rights reserved.

	FreeSWITCH (TM)
	http://www.freeswitch.org/

	Redistribution and use in source and binary forms, with or without
	modification, are permitted provided that the following conditions are met:

	1. Redistributions of source code must retain the above copyright notice,
	   this list of conditions and the following disclaimer.

	2. Redistributions in binary form must reproduce the above copyright
	   notice, this list of conditions and the following disclaimer in the
	   documentation and/or other materials provided with the distribution.

	THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
	INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
	AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
	AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
	OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
	SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
	INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
	CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
	POSSIBILITY OF SUCH DAMAGE.
*/

require("guiconfig.inc");
require("/usr/local/pkg/freeswitch.inc");

$a_recordings 	   = &$config['installedpackages']['freeswitchrecordings']['config'];
$dir_recordings = '/usr/local/freeswitch/recordings/';
$dir_music_on_hold_8000 = '/usr/local/freeswitch/sounds/music/8000/';

if ($_GET['a'] == "download") {

	session_cache_limiter('public');
	
  if ($_GET['type'] = "rec") {
    if  (file_exists($dir_recordings.$_GET['filename'])) {
      	$fd = fopen($dir_recordings.$_GET['filename'], "rb");
      	if ($_GET['t'] == "bin") {
            header("Content-Type: application/force-download");
            header("Content-Type: application/octet-stream");
            header("Content-Type: application/download");
            header("Content-Description: File Transfer");
            header('Content-Disposition: attachment; filename="'.$_GET['filename'].'"');
      	}
        else {
      	    $file_ext = substr($_GET['filename'], -3);
      	    if ($file_ext == "wav") {
              header("Content-Type: audio/x-wav");
            }
      	    if ($file_ext == "mp3") {
              header("Content-Type: audio/mp3");
            }
        }
        header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
        header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past	
        header("Content-Length: " . filesize($dir_recordings.$_GET['filename']));
        fpassthru($fd);
    }
  }

  if ($_GET['type'] = "moh") {
    if  (file_exists($dir_music_on_hold_8000.$_GET['filename'])) {
      	$fd = fopen($dir_music_on_hold_8000.$_GET['filename'], "rb");
      	if ($_GET['t'] == "bin") {
            header("Content-Type: application/force-download");
            header("Content-Type: application/octet-stream");
            header("Content-Type: application/download");
            header("Content-Description: File Transfer");
            header('Content-Disposition: attachment; filename="'.$_GET['filename'].'"');
      	}
        else {
      	    $file_ext = substr($_GET['filename'], -3);
      	    if ($file_ext == "wav") {
              header("Content-Type: audio/x-wav");
            }
      	    if ($file_ext == "mp3") {
              header("Content-Type: audio/mp3");
            }
        }
        header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
        header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past	
        header("Content-Length: " . filesize($dir_music_on_hold_8000.$_GET['filename']));
        fpassthru($fd);
    }
  }

  exit;
}
else {
  //echo $dir_recordings.$_GET['filename'];
}

if (($_POST['submit'] == "Upload") && is_uploaded_file($_FILES['ulfile']['tmp_name'])) {

	if ($_POST['type'] == 'moh') {
		move_uploaded_file($_FILES['ulfile']['tmp_name'], $dir_music_on_hold_8000 . $_FILES['ulfile']['name']);
		$savemsg = "Uploaded file to $dir_music_on_hold_8000" . htmlentities($_FILES['ulfile']['name']);
		//system('chmod -R 744 $dir_music_on_hold_8000*');
		unset($_POST['txtCommand']);
	}
	if ($_POST['type'] == 'rec') {
		move_uploaded_file($_FILES['ulfile']['tmp_name'], $dir_recordings . $_FILES['ulfile']['name']);
		$savemsg = "Uploaded file to $dir_recordings" . htmlentities($_FILES['ulfile']['name']);
		//system('chmod -R 744 $dir_recordings*');
		unset($_POST['txtCommand']);
	}
}




if ($_GET['act'] == "del") {
    if ($_GET['type'] == 'rec') {
        if ($a_recordings[$_GET['id']]) {
            unlink_if_exists('/usr/local/freeswitch/recordings/'.$a_recordings[$_GET['id']]['filename']);
            unset($a_recordings[$_GET['id']]);
            write_config();
            header("Location: freeswitch_recordings.php");
            exit;
        }
    }

    if ($_GET['type'] == 'moh') {
        unlink_if_exists($dir_music_on_hold_8000.$_GET['filename']);
        header("Location: freeswitch_recordings.php");
        exit;
    }

}



include("head.inc");

?>

<script>
function EvalSound(soundobj) {
  var thissound= eval("document."+soundobj);
  thissound.Play();
}
</script>

<body link="#0000CC" vlink="#0000CC" alink="#0000CC">
<?php include("fbegin.inc"); ?>
<p class="pgtitle">FreeSWITCH: Recordings</p>

<div id="mainlevel">
<table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr><td class="tabnavtbl">
<?php

display_top_tabs(build_menu());
 	
?>
</td></tr>
</table>

<table width="100%" border="0" cellpadding="0" cellspacing="0">
   <tr>
     <td class="tabcont" >

<?php


//build a list of recordings from the config.xml
$config_recording_list = '';
$i = 0;
if (count($a_recordings) > 0) {
  foreach ($a_recordings as $recordingent) {
    $config_recording_list .= $recordingent['filename']."|";
    $i++;
  }
}



$config_change = 0; 	
if (is_dir($dir_recordings)) {
    if ($dh = opendir($dir_recordings)) {
        while (($file = readdir($dh)) !== false) {
            if (filetype($dir_recordings . $file) == "file") {

                if (strpos($config_recording_list, $file) === false) {

                    //$handle = fopen($dir_recordings.$file,'rb');
                    //$file_content = fread($handle,filesize($dir_recordings.$file));
                    //fclose($handle);

                    $a_file = split("\.", $file);

                    $recordingent = array();
                    $recordingent['filename'] = $file;
                    $recordingent['recordingname'] = $a_file[0];
                    $recordingent['recordingid'] = guid();
                    //$recordingent['filecontent'] = base64_encode($file_content);
                    $recordingent['descr'] = 'Auto';

                    $a_recordings[] = $recordingent;
                    write_config();

                    unset($file_content);

                }
                else {
                    //echo "The file was found.<br/>";
                }

            }
        }
        closedir($dh);
    }
}



//saved for future use if and when config.xml scales well
	//enough to save the files inside it
//$i = 0;
//if (count($a_recordings) > 0) {
//	foreach ($a_recordings as $recordingent) {
	
//	  if (!is_file($dir_recordings.$recordingent['filename'])) {
	      //echo "not found: ".$recordingent['filename']."<br />";
	
	      //recording not found restore the file from the config.xml
	          //$file_content = $recordingent['filecontent'];
	          //$handle = fopen($dir_recordings.$recordingent['filename'],'w');
	          //fwrite ($handle, base64_decode($file_content));
	          //unset($file_content);
	          //fclose($handle);
	          //$recordingent['filecontent'] = base64_encode($file_content);
	
	      // loop through recordings in the config.xml
	      //  if the file does not exist remove it from the file system.
	      //unset($a_recordings[$i]);
	
//	      $config_change = 1;
//	  }
//	  else {
	      //echo "found: ".$recordingent['filename']."<br />";
//	  }
	
//	$i++;
//	}
//}

if ($config_change == 1) {
    write_config();
    $config_change = 0;
}

//if ($savemsg) print_info_box($savemsg);
//if (file_exists($d_hostsdirty_path)): echo"<p>";
//print_info_box_np("The FreeSWITCH recordings have been changed.<br>You must apply the changes in order for them to take effect.");
//echo"<br />";
//endif;

?>
	<table width="100%" border="0" cellpadding="6" cellspacing="0">
    <tr>
      <td><p><span class="vexpl"><span class="red"><strong>Recordings:<br>
          </strong></span>
          To make a recording dial *732673 (record) or you can make a
          16bit 8khz/16khz Mono WAV file then copy it to the
          following directory then refresh the page to play it back.
          Click on the 'Filename' to download it or the 'Recording Name' to
          play the audio.
          </span></p></td>
    </tr>
  </table>

  <br />

	<div id="niftyOutter">
	<form action="" method="POST" enctype="multipart/form-data" name="frmUpload" onSubmit="">
	  <table border='0'>
	    <tr>
	      <td width='50%'><b>location:</b> <?php echo $dir_recordings; ?></td>
	      <td valign="top" class="label">
	        <input name="type" type="hidden" value="rec">     	
        </td>
	      <td align="right">File to upload:</td>
	      <td valign="top" class="label">
			     <input name="ulfile" type="file" class="button" id="ulfile">
			     <input name="submit" type="submit"  class="button" id="upload" value="Upload">
	      </td>
	    </tr>	
	  </table>
	</div>
	</form>

    <table width="100%" border="0" cellpadding="0" cellspacing="0">
    <tr>
      <td width="30%" class="listhdrr">Filename (download)</td>
      <td width="30%" class="listhdrr">Recording Name (play)</td>
      <td width="30%" class="listhdr">Description</td>
      <td width="10%" class="list">
        <!--
        <table border="0" cellspacing="0" cellpadding="1">
          <tr>
            <td width="17"></td>
            <td valign="middle"><a href="freeswitch_recordings_edit.php"><img src="/themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" width="17" height="17" border="0"></a></td>
          </tr>
        </table>
        -->
      </td>
		</tr>

      <?php
      $i = 0;
      if (count($a_recordings) > 0) {
      	foreach ($a_recordings as $recordingent) {
			if (strlen($recordingent['filename']) > 0) {
      ?>
      <tr>
      <td class="listlr" ondblclick="document.location='freeswitch_recordings_edit.php?id=<?=$i;?>'">
          <a href="freeswitch_recordings.php?a=download&type=rec&t=bin&filename=<?=$recordingent['filename'];?>">
            <?=$recordingent['filename']?>
          </a>
      </td>
      <td class="listr" ondblclick="document.location='freeswitch_recordings_edit.php?id=<?=$i;?>';">
          <a href="javascript:void(0);" onclick="window.open('freeswitch_recordings_play.php?a=download&type=rec&filename=<?=$recordingent['filename'];?>', 'play',' width=420,height=40,menubar=no,status=no,toolbar=no')">
            <?=$recordingent['recordingname'];?>&nbsp;
          </a>
      </td>
      <td class="listbg" ondblclick="document.location='freeswitch_recordings_edit.php?id=<?=$i;?>';">
        <font color="#FFFFFF"><?=htmlspecialchars($recordingent['descr']);?>&nbsp;
      </td>
      <td valign="middle" nowrap class="list">
        <table border="0" cellspacing="0" cellpadding="1">
          <tr>
            <td valign="middle"><a href="freeswitch_recordings_edit.php?id=<?=$i;?>"><img src="/themes/<?= $g['theme']; ?>/images/icons/icon_e.gif" width="17" height="17" border="0"></a></td>
            <td><a href="freeswitch_recordings.php?type=rec&act=del&id=<?=$i;?>" onclick="return confirm('Do you really want to delete this?')"><img src="/themes/<?= $g['theme']; ?>/images/icons/icon_x.gif" width="17" height="17" border="0"></a></td>
          </tr>
       </table>
      </td>
      </tr>
      <?php
			}
			else {
				//clean up blank entries
				unset($a_recordings[$i]);
				write_config();
			}
      	
		$i++;
      	} //end for each
      } //end count
      ?>

      <!--
      <tr>
      <td class="list" colspan="3"></td>
      <td class="list">
        <table border="0" cellspacing="0" cellpadding="1">
          <tr>
            <td width="17"></td>
            <td valign="middle"><a href="freeswitch_recordings_edit.php"><img src="/themes/<?= $g['theme']; ?>/images/icons/icon_plus.gif" width="17" height="17" border="0"></a></td>
          </tr>
        </table>
		  </td>
     </tr>
     -->

     <tr>
       <td class="list" colspan="3"></td>
       <td class="list"></td>
     </tr>
     </table>



    <br />
    <br />
    <br />

  	<table width="100%" border="0" cellpadding="6" cellspacing="0">
      <tr>
        <td><p><span class="vexpl"><span class="red"><strong>Music on Hold:<br>
            </strong></span>
            Music on hold can be in WAV or MP3 format. To play an MP3 file you must have
            mod_shout enabled on the 'Modules' tab. You can adjust the volume of the MP3 
            audio from the 'Settings' tab. For best performance upload 16bit 8khz/16khz Mono WAV files.
            <!--Click on the 'Filename' to download it or the 'Recording Name' to
            play the audio.-->
            </span></p></td>
      </tr>
    </table>

    <br />

  	<div id="niftyOutter">
  	<form action="" method="POST" enctype="multipart/form-data" name="frmUpload" onSubmit="">
  	  <table border='0'>
  	    <tr>
  	      <td width='50%'><b>location:</b> <?php echo $dir_music_on_hold_8000; ?></td>
  	      <td valign="top" class="label">
  	        <input name="type" type="hidden" value="moh">     	
          </td>
  	      <td align="right">File to upload:</td>
  	      <td valign="top" class="label">
  			     <input name="ulfile" type="file" class="button" id="ulfile">
  			     <input name="submit" type="submit"  class="button" id="upload" value="Upload">
  	      </td>
  	    </tr>	
  	  </table>
  	</div>
  	</form>


    <table width="100%" border="0" cellpadding="0" cellspacing="0">
    <tr>
		<td width="28%" class="listhdrr">File Name (download)</td>
		<td width="28%" class="listhdrr">Name (play)</td>
		<td width="25%" class="listhdr">Last Modified</td>
		<td width="10%" class="listhdr" nowrap>Size</td>		
		</tr>
		
    <?php
		
    if ($handle = opendir($dir_music_on_hold_8000)) {
        while (false !== ($file = readdir($handle))) {
            if ($file != "." && $file != ".." && is_file($dir_music_on_hold_8000.$file)) {

                $tmp_filesize = filesize($dir_music_on_hold_8000.$file);
                $tmp_filesize = byte_convert($tmp_filesize);

                echo "<tr>\n";
                echo "  <td class=\"listlr\" ondblclick=\"\">\n";
                echo "	  <a href=\"freeswitch_recordings.php?a=download&type=moh&t=bin&filename=".$file."\">\n";
                echo "    	$file";
                echo "	  </a>";
                echo "  </td>\n";
                echo "  <td class=\"listlr\" ondblclick=\"\">\n";
                echo "	  <a href=\"javascript:void(0);\" onclick=\"window.open('freeswitch_recordings_play.php?a=download&type=moh&filename=".$file."', 'play',' width=420,height=40,menubar=no,status=no,toolbar=no')\">\n";
                $tmp_file_array = split("\.",$file);
                echo "    	".$tmp_file_array[0];
                echo "	  </a>";
                echo "  </td>\n";
                echo "  <td class=\"listlr\" ondblclick=\"\">\n";
                echo 		date ("F d Y H:i:s", filemtime($dir_music_on_hold_8000.$file));
                echo "  </td>\n";
                echo "  <td class=\"listlr\" ondblclick=\"\">\n";
                echo "	".$tmp_filesize;
                echo "  </td>\n";
                echo "  <td valign=\"middle\" nowrap class=\"list\">\n";
                echo "    <table border=\"0\" cellspacing=\"0\" cellpadding=\"1\">\n";
                echo "      <tr>\n";
                //echo "        <td valign=\"middle\"><a href=\"freeswitch_recordings.php?id=$i\"><img src=\"/themes/".$g['theme']."/images/icons/icon_e.gif\" width=\"17\" height=\"17\" border=\"0\"></a></td>\n";
                echo "        <td><a href=\"freeswitch_recordings.php?type=moh&act=del&filename=".$file."\" onclick=\"return confirm('Do you really want to delete this file?')\"><img src=\"/themes/". $g['theme']."/images/icons/icon_x.gif\" width=\"17\" height=\"17\" border=\"0\"></a></td>\n";
                echo "      </tr>\n";
                echo "   </table>\n";
                echo "  </td>\n";
                echo "</tr>\n";

            }
        }
        closedir($handle);
    }
    ?>

     <tr>
       <td class="list" colspan="3"></td>
       <td class="list"></td>
     </tr>
     </table>

<br>
<br>
<br>
<br>
<br>
<br>

</td>
</tr>
</table>

</div>


<?php include("fend.inc"); ?>
</body>
</html>