<?php

$helpstyle	= '<div style="font-size:10pt;font-weight:normal;margin-top:5px; margin-left:0px;background-color:#A5FF89">';

$hr			= '<hr noshade width="100%" size="1" align="left">';

$desc_maxsize = $hr . $helpstyle . 
		'Maximum size, this profile may grow. ' . 
		'Any number is taken as <b>MB</b>, unless another scale is specified ' .
		'such as <b>K, M, G, T</b> or <b>KB, MB, GB, TB</b>. ' .
		'If set to <b>0</b>, no size limit applies.<br>Ex. 300, 300M, 2G etc.' .
	"</div>\n";
$desc_expire = $hr . $helpstyle . 
		'Expire time. This specifies the maximum lifetime for this profile. ' . 
		'Data files older than this, will be deleted. ' .
		'Any number is taken as <b>hours</b> unless another scale is specified ' .
		'such as <b>d, day, days</b> and/or <b>h, hour, hours</b>. ' .
		'If set to <b>0</b> or <b>never</b>, no time limit applies.<br>Ex. 72, 72h, 4d 12h, 14days etc.' .
	"</div>\n";

function ExpireString($hours) {

	$expire = '';
	if ( $hours == 0 ) {
		$expire = "never";
	} else {
		if ( $hours > 24 ) {
			$days  = (int)($hours/24);
			$hours = $hours % 24;
	
			$expire = "$days Day";
			$expire .= $days > 1 ? "s ": " ";
		} 
		if ( $hours > 0 ) {
			$expire .= "$hours  Hour";
			if ( $hours > 1 ) 
				$expire .= "s";
		}
	}

	return $expire;

} // End of ExpireString

function ProgressBar ( $state ) {

?>
	<tr>
    <th class="STATTABLE" colspan="2">
	<table style='width: 100%; text-align: left; background-color: rgb(220, 220, 220);' cellpadding='2' cellspacing='2'>
		<tbody>
			<tr>
<?php if ( $state > 1 ) { ?>
				<td style='text-align:left;font-size:10pt;width:<?echo $state;?>%;'><?echo $state;?>%</td>
				<td bgcolor=#FFFFFF></td>
<?php } else { ?>
				<td colspan='2' bgcolor=#FFFFFF style='font-size:10pt;text-align:left;width:100%'><?echo $state;?>%</td>
<?php } ?>
			</tr>
		</tbody>
	</table>
	</th>
	</tr>
<?php

} # End of ProgressBar

function ProfileDialog ($edit_expire, $edit_maxsize ) {

	global $PROFILEDATADIR;
	global $self;
	global $desc_maxsize;
	global $desc_expire;

	if ( !isset($_SESSION['channels'])  ) {
		$_SESSION['channels'] = array();
	}
	$channels = $_SESSION['channels'];

	$ro_flag_expire = $edit_expire ? '' : 'readonly';
	$ro_flag_size   = $edit_maxsize ? '' : 'readonly';

	$type 	 = $_SESSION['refresh'] ? 'Continuous' : 'History';
	$tstart  = UNIX2ISO($_SESSION['profileinfo']['tstart']);
	$tend 	 = UNIX2ISO($_SESSION['profileinfo']['tend']);
	$tupdate = UNIX2ISO($_SESSION['profileinfo']['updated']);
	$pattern = "/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/";
	$replacement = "$1-$2-$3-$4-$5";
	$tstart  = preg_replace($pattern, $replacement, $tstart);
	$tend	 = preg_replace($pattern, $replacement, $tend);
	$tupdate = preg_replace($pattern, $replacement, $tupdate);
	$size	 = ScaleBytes($_SESSION['profileinfo']['size'], 1);
	$maxsize = $_SESSION['profileinfo']['maxsize'] ? ScaleBytes($_SESSION['profileinfo']['maxsize'], 1) : 'unlimited';
	$description = implode("\n", $_SESSION['profileinfo']['comment']);
	$status	= $_SESSION['profileinfo']['status'];
	$locked	= $_SESSION['profileinfo']['locked'] == 1 ? " - locked" : "";
	$colortag = "style='color:red'";
	// $EnterButton = "<span style='color:red'>&lt;- Enter new value</span>";
	$EnterButton = "<span style='color:red'><input name='edit' value='Enter new value' type='submit'></span>";
	$opt_delete = $status == 'OK' && ( $_SESSION['profile'] != 'live' );

	if ( preg_match("/built (\d+\.{0,1}\d*)/", $status, $matches) ) {
		$progress = $matches[1];
	} else 
		$progress = -1;

	if ( $_SESSION['profile'] == 'live' ) 
		$filter = '';
	else
		$filter = file_get_contents("$PROFILEDATADIR/" . $_SESSION['profile'] . "/" . $_SESSION['profileinfo']['filter']);

	$expire = ExpireString($_SESSION['profileinfo']['expire']);

?>
<div style='margin-top:20px; margin-left:20px;'>
<form action="<? echo $self;?>" method="POST">
<input type="image" border="0" name="EnterKey" src="invisible.gif">
<table class="STATTABLE" cellspacing="4"  cellpadding="4">
<tr class="STATTABLE">
    <th class="STATTABLE" colspan='2'>
<?php 
	if ( $opt_delete ) 
    	print "<input type='image' name='deleteprofile' title='Delete this profile' src='trash.png' align='right'>\n";
	if ( $progress >= 0 ) 
		print "Building ";
?>
		Profile: <?echo $_SESSION['profile'];?>
	</th>
</tr>
<?php if ( $progress >= 0 ) 
	ProgressBar($progress);
?>
<tr class="STATTABLE">
    <td class="STATTABLE">Description:</td> 
    <td class="MYVALUE">
    	<textarea name="description" cols="25" rows="3" style="width:100%" readonly><? echo $description; ?></textarea>
    </td>
</tr>
<tr class="STATTABLE">
    <td class="STATTABLE" >Type:</td> 
    <td class="MYVALUE"><?echo $type; ?></td>
</tr>
<tr class="STATTABLE">
    <td class="STATTABLE">Start:</td> 
    <td class="MYVALUE">
		<input type="text" name="ro_tstart" value="<?echo $tstart; ?>" SIZE="17" MAXLENGTH="16" 
			style=font-size:12px; readonly>
	</td>
</tr>
<tr class="STATTABLE">
    <td class="STATTABLE">End:</td> 
    <td class="MYVALUE">
		<input type="text" name="ro_tend" value="<?echo $tend; ?>" SIZE="17" MAXLENGTH="16" 
			style=font-size:12px; readonly>
	</td>
</tr>
<tr class="STATTABLE">
    <td class="STATTABLE">Last Update:</td> 
    <td class="MYVALUE">
		<input type="text" name="ro_tupdate" value="<?echo $tupdate; ?>" SIZE="17" MAXLENGTH="16" 
			style=font-size:12px; readonly>
	</td>
</tr>
<tr class="STATTABLE">
    <td class="STATTABLE">Sources:</td> 
    <td class="MYVALUE">
    <select name="ro_sources" size="4" style="width:100%" disabled multiple>
<?php
	$profilesources = explode(':', $_SESSION['profileinfo']['sourcelist']);
	for( $i=0; $i<count($channels); $i++ ) {
		$selected = '';
		for ( $j=0; $j<count($profilesources); $j++ ) {
			if ( $channels[$i] == $profilesources[$j] ) 
				$selected = 'selected';
		}
		print "<option $selected>" . $channels[$i] . "</option>\n";
	}
?>
    </select>
    </td>
</tr>
<tr class="STATTABLE">
    <td class="STATTABLE">Filter:</td> 
    <td class="MYVALUE">
    	<textarea name="ro_filter" cols="25" rows="3" style="width:100%" readonly><? echo $filter; ?></textarea>
    </td>
</tr>
<tr class="STATTABLE">
    <td class="STATTABLE">Size:</td> 
    <td class="MYVALUE"> <? echo $size; ?> </td>
</tr>
<tr class="STATTABLE">
    <td class="STATTABLE" <? if ( $edit_maxsize ) echo $colortag; ?>>Max. Size:</td> 
    <td class="MYVALUE">
<?php if ( $type == 'Continuous' ) { ?>
    	<input type="image" name="edit_maxsize" title="Change max. size" src="edit.png" align='right'>
<?php } ?>
		<input type='text' name='profile_maxsize' value='<?echo $maxsize; ?>' SIZE='16' MAXLENGTH='16' 
			style=font-size:12px; <? echo $ro_flag_size; ?> >
<?php 		If ( $edit_maxsize ) {
			print "$EnterButton\n";
			print "<br>$desc_maxsize\n";
		}
?>
    </td>
</tr>
<tr class="STATTABLE">
    <td class="STATTABLE" <? if ( $edit_expire ) echo $colortag; ?>>Expire:</td> 
    <td class="MYVALUE">
<?php if ( $type == 'Continuous' ) { ?>
    	<input type="image" name="edit_expire" title="Change expire value" src="edit.png" align='right'>
<?php } ?>
		<input type='text' name='profile_expire' value='<? echo $expire; ?>' SIZE='16' MAXLENGTH='16' 
			style=font-size:12px; <? echo $ro_flag_expire; ?> >
<?php 		If ( $edit_expire ) {
			print "$EnterButton\n";
			print "<br>$desc_expire\n";
		}
?>
    </td>
</tr>
<tr class="STATTABLE">
    <td class="STATTABLE">Status:</td> 
    <td class="MYVALUE"><? echo "$status $locked"; ?></td>
</tr>
</table>
</form>
</div>
<?php
} // End of ProfileDialog

function NewProfileDialog ( ) {

	global $self;
	global $helpstyle;
	global $hr;
	global $desc_maxsize;
	global $desc_expire;

	$liveprofile = ReadProfile('live');
	$channels = explode(':', $liveprofile['sourcelist']);

	$live_start  = UNIX2DISPLAY($liveprofile['tstart']);
	$tnow		 = time();
	$tnow		-= $tnow % 300;
	$tnow		 = UNIX2DISPLAY($tnow);

	$colortag = "style='color:red'";

	$desc_profilename = $hr . $helpstyle . 
		'Name of new profile.<br>' . 
		'The naming follows the directory naming definition.' .
	"</div>\n";

	$desc_tstart = $hr . $helpstyle . 
		'Start time of new profile.<br>' . 
		"Any time is accepted from <b>$live_start</b> ( Start of the <b>live</b> profile ) up to <b>$tnow</b>. ". 
		"If left empty, the profile starts from now: <b>$tnow</b> (continuous profile)." .
	"</div>\n";

	$desc_tend = $hr . $helpstyle . 
		'End time of new profile.<br>' . 
		'Must be later than start of the profile. Leave empty for a continuous profile.' .
	"</div>\n";
	
	// global defined: $desc_maxsize
	// global defined: $desc_expire
	
	if ( array_key_exists('new_profile', $_SESSION ) )
		$new_profile = $_SESSION['new_profile'];
	else {
		// Initialize the default values
		$new_profile = array();
		$new_profile['profilename'] = '';
		$new_profile['description'] = '';
		$new_profile['tstart'] 		= '';
		$new_profile['tend'] 		= '';
		$new_profile['sources']		= array();
		$new_profile['filter']		= '';
		$new_profile['maxsize']		= '0';
		$new_profile['expire']		= '0';
		$_SESSION['new_profile'] 	= $new_profile;
	}

?>
<div style='margin-top:20px; margin-left:20px;'>
<form action="<? echo $self;?>" method="POST">
<input type="image" border="0" name="new_create" src="invisible.gif">
<table class="STATTABLE" cellspacing="4"  cellpadding="4">
<tr class="STATTABLE">
    <td class="STATTABLE"> Profile: </td>
    <td class="MYVALUE">
		<input type="text" name="new_profilename" value="<?echo $new_profile['profilename']; ?>"
			SIZE="32" MAXLENGTH="32" style="width:100%"><br><? echo $desc_profilename;?>
	</td>
</tr>
<tr class="STATTABLE">
    <td class="STATTABLE">Description:</td> 
    <td class="MYVALUE">
    	<textarea name="new_description" cols="25" rows="3" 
			style="width:100%" ><? echo $new_profile['description']; ?></textarea>
    </td>
</tr>
<tr class="STATTABLE">
    <td class="STATTABLE">Start:</td> 
    <td class="MYVALUE">
		<input type="text" name="new_tstart" value="<?echo $new_profile['tstart']; ?>"
			SIZE="17" MAXLENGTH="16" style=font-size:12px;>&nbsp;<b>Format: yyyy-mm-dd-HH-MM</b>
		<br><? echo $desc_tstart;?>
	</td>
</tr>
<tr class="STATTABLE">
    <td class="STATTABLE">End:</td> 
    <td class="MYVALUE">
		<input type="text" name="new_tend" value="<?echo $new_profile['tend']; ?>"
			SIZE="17" MAXLENGTH="16" style=font-size:12px;>&nbsp;<b>Format: yyyy-mm-dd-HH-MM</b>
		<br><? echo $desc_tend;?>
	</td>

<tr class="STATTABLE">
    <td class="STATTABLE">Sources:</td> 
    <td class="MYVALUE">
    <select name="new_sources[]" size="4" style="width:100%" multiple>
<?php
	for( $i=0; $i<count($channels); $i++ ) {
		$selected = '';
		for ( $j=0; $j<count($new_profile['sources']); $j++ ) {
			if ( $i == $new_profile['sources'][$j] ) 
				$selected = 'selected';
		}
		print "<option value='$i' $selected>" . $channels[$i] . "</option>\n";
	}
?>
    </select>
    </td>
</tr>
<tr class="STATTABLE">
    <td class="STATTABLE">Filter:</td> 
    <td class="MYVALUE">
    	<textarea name="new_filter" cols="25" rows="3" style="width:100%" ><? echo $new_profile['filter']; ?></textarea>
    </td>
</tr>
<tr class="STATTABLE">
    <td class="STATTABLE">Max. Size:</td> 
    <td class="MYVALUE">
		<input type='text' name='new_maxsize' value="<?echo $new_profile['maxsize']; ?>" SIZE='16' MAXLENGTH='16' 
			style=font-size:12px; ><br><? echo $desc_maxsize;?>

    </td>
</tr>
<tr class="STATTABLE">
    <td class="STATTABLE">Expire:</td> 
    <td class="MYVALUE">
	<? $_tmp = ExpireString($new_profile['expire']); ?>
		<input type='text' name='new_expire' value="<? echo $_tmp; ?>" SIZE='16' MAXLENGTH='16' 
			style=font-size:12px; ><br><? echo $desc_expire;?>
    </td>
</tr>
<tr class="STATTABLE">
    <td class="STATTABLE" colspan="2">
		<input name='new_cancel' value='Cancel' type='submit'>
		<input name='new_create' value='Create Profile' type='submit'>
	</td>
</tr>
</table>
</form>
</div>
<?php
} // End of NewProfileDialog

function ConfirmDelete () {

	global $self;

	print "<h3 class='warnstring'>Delete profile '" . $_SESSION['profile'] .
		"' and all its data?</h3>\n";
	print "<div style='margin-left:20px;'>\n";
	print "<form action='$self' method='POST'>\n";
	print "<input name='confirmdelete' value='Delete Profile' type='submit'>\n";
	print "<input name='cancel' value='Cancel' type='submit'>\n";
	print "</form>\n";
	print "</div>\n";
	$_SESSION['delete_profile'] 	  = $_SESSION['profile'];
	$_SESSION['delete_requested'] = time();

} // End of ConfirmDelete

function DoReload ($message) {

	global $self;
?>
	<div style='margin-top:20px; margin-left:20px;'>
	<form action="<? echo $self;?>" method="POST">
		<?echo $message; ?>&nbsp;
		<input name"Continue" value="Continue" type="submit" >
	</form>
	</div>

<?php
} // End of DoReload

function DisplayAdminPage() {

	if ( !isset($_SESSION['channels'])  ) {
		$_SESSION['channels'] = array();
	}
	$channels = $_SESSION['channels'];

	$edit_expire  = 0;
	$edit_maxsize = 0;
	$quiet		  = 0;	// flag, if we display the Profile Record
	if ( array_key_exists('edit_expire', $_SESSION ) ) {
		$edit_expire = 1;
		unset($_SESSION['edit_expire']);
	}
	if ( array_key_exists('edit_maxsize', $_SESSION ) ) {
		$edit_maxsize = 1;
		unset($_SESSION['edit_maxsize']);
	}
	if ( array_key_exists('admin', $_SESSION ) ) {
		$action  = $_SESSION['admin'];
		switch ($action) {
			case "change":
				$args = "modify profile=" . $_SESSION['profile'] . 
					";expire=" . $_SESSION['new_expire'] .  ";maxsize=" . $_SESSION['new_maxsize'];
				$result = nfsend_query($args, 0);
				if ( is_array($result) ) {
					$profileinfo = ReadProfile($_SESSION['profile']);
					$_SESSION['profileinfo'] = $profileinfo;
					unset($_SESSION['admin']);
				} else {
					ShowMessages();
				}
				break;
			case "delete":
				if ( array_key_exists('delete_profile', $_SESSION ) &&
					array_key_exists('delete_requested', $_SESSION )) {
					$profile = $_SESSION['delete_profile'];
					$when = $_SESSION['delete_requested'];
					// Don't allow more than 30s between request for delete and confirmation
					if ( (time() - $when) < 30 ) {
						$args = "delete profile=$profile";
			
						$result = nfsend_query($args, 0);
						if ( is_array($result) ) {
							unset($_SESSION['ProfileList']);
							$profiles = GetProfiles();
							// as current profile no longer exists, switch to 'live'
							$_SESSION['profile'] = 'live';
							$profileinfo = ReadProfile($_SESSION['profile']);
							$_SESSION['profileinfo'] = $profileinfo;

							DoReload("Profile deleted.");
							$quiet = 1;
						} else {
							ShowMessages();
						}
					} else {
						SetMessage('error', "Timeout for confirmation to delete profile!");
						ShowMessages();
					}
					unset($_SESSION['delete_profile']);
					unset($_SESSION['delete_requested']);
					unset($_SESSION['admin']);
		
				} else 
					ConfirmDelete();
				break;
			case "new":
				NewProfileDialog();
				unset($_SESSION['admin']);
				$quiet = 1;
				break;
			case "execnew":
				$args = array();
				$args[] = "add profile=" . $_SESSION['new_profile']['profilename'];
				if ( strlen($_SESSION['new_profile']['tstart']) ) 
					$args[] = "tstart=" . $_SESSION['new_profile']['tstart'];
				if ( strlen($_SESSION['new_profile']['tend']) ) 
					$args[] = "tend=" . $_SESSION['new_profile']['tend'];

				// turn a multiline string into a single line argument -c 'description'
				if ( strlen($_SESSION['new_profile']['description']) ) {
					$_tmp = $_SESSION['new_profile']['description'];
					$_tmp = preg_replace("/\\\r/", "", $_tmp);
					$_tmp = preg_replace("/\\\/", "\\\\134", $_tmp);
					$_tmp = preg_replace("/'/",  "\\\\047", $_tmp);
					$_tmp = preg_replace("/\\\n/", "\\\\012", $_tmp);
					$_tmp = preg_replace("/;/",  "\\\\073", $_tmp);
					$args[] = "description=$_tmp";
				}
				$args[] = "expire=" . $_SESSION['new_profile']['expire'];
				$args[] = "maxsize=" . $_SESSION['new_profile']['maxsize'];
				$src = array();
				foreach ( $_SESSION['new_profile']['sources'] as $i ) {
					$src[] = $channels[$i];
				}
				$args[] = "sources=" . implode(':', $src);
				$filter = $_SESSION['new_profile']['filter'];
				$filter = preg_replace("/\r/", '', $filter);

				$runarg = implode(';', $args) . ";filter=$filter";

				$result = nfsend_query($runarg, 0);
				if ( is_array($result) ) {
					unset($_SESSION['ProfileList']);
					$profiles = GetProfiles();

					// switch to new profile
					$_SESSION['profile'] = $_SESSION['new_profile']['profilename'];
					$profileinfo = ReadProfile($_SESSION['profile']);
					$_SESSION['profileinfo'] = $profileinfo;
					DoReload("Profile created.");
					unset($_SESSION['new_profile']);
					unset($_SESSION['admin']);
					$quiet = 1;
				} else {
					ShowMessages();
					NewProfileDialog();
					unset($_SESSION['admin']);
					$quiet = 1;
				}

				break;
			default:
				// this should never happen

		} // End of switch($action)
	}

	if ( !$quiet )
		ProfileDialog($edit_expire, $edit_maxsize);
/*
print "<pre>";
print_r($_SESSION);
print_r($_POST);
print "</pre>";
*/

} // End of DisplayAdminPage
?>
