Sindbad~EG File Manager

Current Path : /home/beeson/public_html/WebMathXpert/ThreeBodyWeb/
Upload File :
Current File : //home/beeson/public_html/WebMathXpert/ThreeBodyWeb/ThreeBody.php

<?php
// ThreeBody.php
// Set HTTP header to prevent caching
header('Content-Type: text/html; charset=UTF-8');
header("Cache-Control: no-cache, must-revalidate");

// Start or resume the session
session_start();
$sessionId = session_id();  // guaranteed not to contain a tilde
ini_set('display_errors', 1);
error_reporting(E_ALL);

// echo "<pre>";  // for debugging to see what is posted
// print_r($_POST);
//  echo "</pre>";

$binarystarbodies = array(    // the default data
    'mass'  => array(5, 5),
    'color' => array('rgb(255, 0, 0)', 'rgb(0, 0, 255)'),  // red, blue
    'r'     => array(5, 5),
    'x0'    => array(0, 0),
    'y0'    => array(1, -1),
    'p0'    => array(-1, 1),
    'q0'    => array(0, 0)
);

$figureeightbodies = array(
    'mass'  => array(1, 1, 1),
    'color' => array('rgb(255, 0, 0)', 'rgb(0, 0, 255)', 'rgb(0, 128, 0)'),  // red, blue, green
    'r'     => array(5, 5, 5),
    'x0'    => array(-0.97000436, 0.97000436, 0.0),
    'y0'    => array(0.24308753, -0.24308753, 0.0),
    'p0'    => array(0.4662036852, 0.4662036852, -0.9324073704),
    'q0'    => array(0.4323657307, 0.4323657307, -0.8647314615)
);

// If simulation data is submitted via POST (for example, from BrowseThreeBody.php)
// store it in the session so it can be used to prepopulate the form.  Thus new POSTed data
// will replace data stored in $_SESSION.  


if ($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['nbodies']) || isset($_POST['mass']))) {
    $caption = $_SESSION['caption'] = $_POST['caption']; 
    $integrationMethod = $_SESSION['integrationMethod'] = isset($_POST['integrationMethod']) ? $_POST['integrationMethod'] : "rk4"; 
    $tmax = $_SESSION['tmax'] = isset($_POST['tmax']) ? $_POST['tmax'] : "1000";
}
else if (!isset($_SESSION['saved_bodies'])){  
	$_SESSION['saved_bodies'] = $figureeightbodies;   // the default, to fill the form initially 
	$_SESSION['nbodies'] = $nbodies = 3;
	$_SESSION['caption'] = $caption = "figure eight"; 
	$_SESSION['background'] = $background = "rgb(255,255,255)"; 
	$_SESSION['integrationMethod'] = $integrationMethod = "leapfrog";  // that goes with figure eight 
	$_SESSION['tmax'] = $tmax = "100";   // about 7  per loop, so this is many loops 
}
else{ 
	$integrationMethod = $_SESSION['integrationMethod']; 
	$tmax = $_SESSION['tmax'];
}

if ($_SERVER['SERVER_NAME'] == 'localhost') {
    $nextpagegraph = "https://localhost:8443/GraphSolution.php"; 
    $serverAddress = 'localhost';  
    $username = $password = null;
} else {
    $nextpagegraph = "https://mathxpert.org/GraphSolution.php"; 
    $serverAddress = 'mathxpert.org';  
    $username = 'beeson'; 
    $password = 'Turing2024';
}
$serverPort = 12350; // Ending in 5'caption'ody, 49 for MathXpert
$timeout = 3600; // Connection timeout in seconds.
$startupDelay = 5; // Delay for server startup if needed

// Clear saved session data if requested
if (isset($_GET['clear']) && $_GET['clear'] == '1') {
    $_SESSION['saved_bodies'] = [
        'mass'  => ['', ''],
        'color' => ['', ''],
        'r'     => ['', ''],
        'x0'    => ['', ''],
        'y0'    => ['', ''],
        'p0'    => ['', ''],
        'q0'    => ['', '']
    ];
    $_SESSION['nbodies'] = 2;
    $_SESSION['caption'] = "";
    $_SESSION['background'] = "rgb(255,255,255)";
    $_SESSION['integrationMethod'] = "rk4";
    $_SESSION['tmax'] = "1000";

    header("Location: ThreeBody.php");
    exit();
}

if (!(isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1)
   || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) {
    $redirect = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: ' . $redirect);
    exit();
}

?>
<script>

// This function updates the hidden input fields with the actual viewport dimensions.
function updateFields() {
    // Update viewport dimensions using client window size
    var w = window.innerWidth;
    var h = window.innerHeight;
    document.getElementById("pxminField").value = 0;
    document.getElementById("pxmaxField").value = w;
    document.getElementById("pyminField").value = 0;
    document.getElementById("pymaxField").value = h;
    console.log("Updated viewport dimensions: " + w + " x " + h);  
    // alert("Updating viewport dimensions: " + w + " x " + h);
} 
</script>
<?php 

require("SendMessage.php");
$clientSocket = createClientSocket($serverAddress, $serverPort, $timeout);

// Helper function: Convert a color string "rgb(R, G, B)" to "R,G,B"
function convertColor($colorStr) {
    $colorStr = trim($colorStr);
    if (strpos($colorStr, "rgb(") === 0) {
        $inside = substr($colorStr, 4, -1); // Remove "rgb(" and ")"
        return str_replace(' ', '', $inside); // Remove spaces to get "R,G,B"
    }
    return $colorStr;
}

if(isset($_GET['indatabase'])){ 
	$indatabase = true;
}
else
	$indatabase = false;

	if ($_SERVER['REQUEST_METHOD'] === 'POST') {

	    // Store exact user input for repopulating the form later
	    $_SESSION['saved_bodies'] = $_POST;

	    // Also prepare a processed version for computation if needed
	    $bodies = [];
	    if (isset($_POST['mass']) && is_array($_POST['mass'])) {
	        $nbodies = count($_POST['mass']);
	        for ($i = 0; $i < $nbodies; $i++) {
	            $bodies[] = array(
	                'mass'  => floatval($_POST['mass'][$i]),
	                'color' => $_POST['color'][$i],  // expected in "rgb(R, G, B)" format
	                'r'     => floatval($_POST['r'][$i]),
	                'x0'    => floatval($_POST['x0'][$i]),
	                'y0'    => floatval($_POST['y0'][$i]),
	                'p0'    => floatval($_POST['p0'][$i]),
	                'q0'    => floatval($_POST['q0'][$i])
	            );
	        }
	    }

	    // Background and border
	    $background = $_POST['background'] ?? "rgb(255,255,255)";
	    $border = $_POST['border'] ?? "rgb(255,255,0)";
	}
?>
   
<!DOCTYPE html>
<html>
<head>
    <title>Enter a Problem</title>
    <style>
        body { font-family: Arial, sans-serif; }
        table, th, td {
            border: 1px solid #444;
            border-collapse: collapse;
            padding: 5px;
        }
        input[type="text"] {
            width: 70%;
            background-color: #e0f8e0;  /* Light-green background */
        }
        .error {
            border: 2px solid red;
        }
        .button-group button,
        .button-group input[type="submit"] {
            padding: 10px 20px;
            font-size: 16px;
            background-color: rgb(0,0,128);
            color: white;
            border: none;
            cursor: pointer;
            margin-right: 5px;
        }
        .button-group button:hover,
        .button-group input[type="submit"]:hover {
            background-color: rgb(0,0,150);
        }
        thead tr {
            background-color: #cce6ff; /* Light-blue header row */
        }
    </style>
    <script>
        function parseColor(colorStr) {
            colorStr = colorStr.trim().toLowerCase();
            if (colorStr.charAt(0) === '#') {
                colorStr = colorStr.substring(1);
            }
            if (colorStr.length === 6) {
                var r = parseInt(colorStr.substring(0,2), 16);
                var g = parseInt(colorStr.substring(2,4), 16);
                var b = parseInt(colorStr.substring(4,6), 16);
                if (isNaN(r) || isNaN(g) || isNaN(b)) return null;
                return "rgb(" + r + ", " + g + ", " + b + ")";
            } else {
                var temp = document.createElement("div");
                temp.style.color = colorStr;
                if (temp.style.color === "") return null;
                document.body.appendChild(temp);
                var computed = window.getComputedStyle(temp).color;
                document.body.removeChild(temp);
                return computed;
            }
        }
        function validateForm(event) {
            var inputs = document.querySelectorAll("input[type='text']");
            inputs.forEach(function(input) {
                input.classList.remove("error");
            });
            var valid = true;
            var rows = document.getElementById("bodiesTable").getElementsByTagName("tbody")[0].rows;
            for (var i = 0; i < rows.length; i++) {
                var cells = rows[i].cells;
                var massInput = cells[0].querySelector("input");
                var colorInput = cells[1].querySelector("input");
                var rInput = cells[2].querySelector("input");
                var x0Input = cells[3].querySelector("input");
                var y0Input = cells[4].querySelector("input");
                var p0Input = cells[5].querySelector("input");
                var q0Input = cells[6].querySelector("input");
                var mass = parseFloat(massInput.value);
                if (isNaN(mass) || mass <= 0) {
                    massInput.classList.add("error");
                    valid = false;
                }
                var rVal = parseFloat(rInput.value);
                if (isNaN(rVal) || rVal <= 0) {
                    rInput.classList.add("error");
                    valid = false;
                }
                var x0 = parseFloat(x0Input.value);
                if (isNaN(x0)) {
                    x0Input.classList.add("error");
                    valid = false;
                }
                var y0 = parseFloat(y0Input.value);
                if (isNaN(y0)) {
                    y0Input.classList.add("error");
                    valid = false;
                }
                var p0 = parseFloat(p0Input.value);
                if (isNaN(p0)) {
                    p0Input.classList.add("error");
                    valid = false;
                }
                var q0 = parseFloat(q0Input.value);
                if (isNaN(q0)) {
                    q0Input.classList.add("error");
                    valid = false;
                }
                var rgbColor = parseColor(colorInput.value);
                if (rgbColor === null) {
                    colorInput.classList.add("error");
                    valid = false;
                } else {
                    colorInput.value = rgbColor;
                }
            }
            if (!valid) {
                event.preventDefault();
                alert("Please fix the highlighted errors.");
            }
        }
        function addBodyRow() {
            var tbody = document.getElementById("bodiesTable").getElementsByTagName('tbody')[0];
            var rowCount = tbody.rows.length;
            if (rowCount >= 12) {
                alert("Maximum of 12 bodies reached.");
                return;
            }
            var row = tbody.insertRow(-1);
            row.innerHTML = `
                <td><input type='text' name='mass[]' placeholder='mass' required></td>
                <td><input type='text' name='color[]' placeholder='color' required></td>
                <td><input type='text' name='r[]' placeholder='radius' required></td>
                <td><input type='text' name='x0[]' placeholder='x0' required></td>
                <td><input type='text' name='y0[]' placeholder='y0' required></td>
                <td><input type='text' name='p0[]' placeholder='p0' required></td>
                <td><input type='text' name='q0[]' placeholder='q0' required></td>
            `;
        }
        window.addEventListener("DOMContentLoaded", function() {
            document.getElementById("bodyForm").addEventListener("submit", validateForm);
            var savedDataElem = document.getElementById("savedData");
            if (savedDataElem) {
                try {
                    var savedData = JSON.parse(savedDataElem.textContent);
                    var tbody = document.getElementById("bodiesTable").getElementsByTagName("tbody")[0];
                    tbody.innerHTML = "";
                    var count = savedData.mass ? savedData.mass.length : 0;
                    for (var i = 0; i < count; i++) {
                        var row = tbody.insertRow(-1);
                        row.innerHTML = `
                            <td><input type='text' name='mass[]' placeholder='mass' required value='${savedData.mass[i]}'></td>
                            <td><input type='text' name='color[]' placeholder='color' required value='${savedData.color[i]}'></td>
                            <td><input type='text' name='r[]' placeholder='radius' required value='${savedData.r[i]}'></td>
                            <td><input type='text' name='x0[]' placeholder='x0' required value='${savedData.x0[i]}'></td>
                            <td><input type='text' name='y0[]' placeholder='y0' required value='${savedData.y0[i]}'></td>
                            <td><input type='text' name='p0[]' placeholder='p0' required value='${savedData.p0[i]}'></td>
                            <td><input type='text' name='q0[]' placeholder='q0' required value='${savedData.q0[i]}'></td>
                        `;
                    }
                } catch (e) {
                    console.error("Error parsing saved data:", e);
                }
            }
        });
    </script>
</head>
<body>
    <h1>Enter a Problem</h1>
    <form id="bodyForm" method="post" action="ThreeBody.php">
	    <input type="hidden" name="sessionId" value="<?php echo htmlspecialchars($sessionId); ?>">
	    <input type="hidden" name="pxmin" id="pxminField" value="0">
	    <input type="hidden" name="pxmax" id="pxmaxField" value="800">
	    <input type="hidden" name="pymin" id="pyminField" value="0">
	    <input type="hidden" name="pymax" id="pymaxField" value="600">
	    <input type="hidden" name="border" value="rgb(255,255,0)"> <!-- yellow -->
	    <input type="hidden" name="background" value="<?php echo $background; ?>">     
	    <input type="hidden" name="nbodies" id="nbodiesField" value="<?php echo $nbodies; ?>">
	 
        <table id="bodiesTable">
            <thead>
                <tr>
                    <th>Mass</th>
                    <th>Color</th>
                    <th>Radius</th>
                    <th colspan="2">Initial Position</th>
                    <th colspan="2">Initial Velocity</th>
                </tr>
            </thead>
				<tbody>
                <?php
                $savedData = array();
					 // if data was POSTed, it was put in $_SESSION so it will be there now
                if (isset($_SESSION['saved_bodies'])) { 
                    $savedData = $_SESSION['saved_bodies']; 
                    // $integrationMethod = $_SESSION['integrationMethod']; 
                    // $tmax = $_SESSION['tmax'];
					}
                // Determine the current number of bodies; if none saved, default to 2.
                $bodyCount = (isset($savedData['mass']) && is_array($savedData['mass'])) ? count($savedData['mass']) : 2;
                if (!empty($savedData) && isset($savedData['mass'])) {   
                    // which MUST be the case, because we used some default data if there was none already and none POSTed
                    $count = count($savedData['mass']);
                    for ($i = 0; $i < $count; $i++) {
                        ?>
								<tr>
								    <td><input type="text" name="mass[]" placeholder="mass" required value="<?php printf('%.15g', $savedData['mass'][$i]); ?>"></td>
								    <td><input type="text" name="color[]" placeholder="color" required value="<?php echo htmlspecialchars($savedData['color'][$i]); ?>"></td>
								    <td><input type="text" name="r[]" placeholder="radius" required value="<?php printf('%.15g', $savedData['r'][$i]); ?>"></td>
								    <td><input type="text" name="x0[]" placeholder="x0" required value="<?php printf('%.15g', $savedData['x0'][$i]); ?>"></td>
								    <td><input type="text" name="y0[]" placeholder="y0" required value="<?php printf('%.15g', $savedData['y0'][$i]); ?>"></td>
								    <td><input type="text" name="p0[]" placeholder="p0" required value="<?php printf('%.15g', $savedData['p0'][$i]); ?>"></td>
								    <td><input type="text" name="q0[]" placeholder="q0" required value="<?php printf('%.15g', $savedData['q0'][$i]); ?>"></td>
								</tr>
                        <?php
                    }
                } 
                ?>
            </tbody>
        </table>
        <br>
		  <div class="button-group">
				<?php if ($bodyCount < 12): ?>
					<button type="button" onclick="addBodyRow()">Add Another Body</button>
				<?php endif; ?>
				<input type="submit" id="solve" value="Solve and Draw" formaction="DrawSolution.php?indatabase=<?php echo $indatabase ? 'true' : 'false'; ?>">
				<input type="submit" id="review" value="Review Entries" formaction="Review.php">
				<button type="button" id="clear" onclick="window.location.href='ThreeBody.php?clear=1'">Clear the Form</button>
			</div
			<div style="margin-top: 12px; display: flex; flex-direction: row; gap: 24px; flex-wrap: nowrap; align-items: flex-start;">
			  <!-- Integration Method Fieldset -->
			  <div style="margin-top: 12px; display: flex; flex-direction: row; gap: 24px; flex-wrap: nowrap; align-items: flex-start;">
			    <!-- Integration Method Fieldset -->
			    <fieldset style="display: inline-flex; flex-direction: column; border: 2px solid #007BFF; background-color: #cce6ff; padding: 10px;">
			      <legend style="font-weight: bold; padding: 0 6px;">Integration by</legend>
			      <div style="display: flex; flex-direction: column; gap: 6px;">
					<label>
					  <input type="radio" name="integrationMethod" value="rk4"
					    <?php if ($integrationMethod == 'rk4') echo 'checked'; ?>>
					  Runge-Kutta
					</label>
					<label>
					  <input type="radio" name="integrationMethod" value="leapfrog"
					    <?php if ($integrationMethod == 'leapfrog') echo 'checked'; ?>>
					  Leapfrog
					</label>
			      </div>
			    </fieldset>

			    <!-- End Time Fieldset -->
			    <fieldset style="display: inline-flex; flex-direction: column; border: 2px solid #007BFF; background-color: #cce6ff; padding: 10px; position: relative; top: 1px;">
			      <legend style="font-weight: bold; padding: 0 6px;">End Time</legend>
			      <input type="text" name="tmax" value= <?php echo($tmax)?>
			             style="background-color: #ccffcc; padding: 4px 6px; width: 80px;">
			    </fieldset>
			  </div>
    </form>
	 <?php
	 if (isset($_POST['solveNow'])) {
	     echo '<script>
	         window.addEventListener("DOMContentLoaded", function(){
	             var btn = document.getElementById("solve");
	             if (btn) { btn.click(); }
	         });
	     </script>';
	 }
	 ?>
<script>
document.addEventListener("DOMContentLoaded", function () {
	const form = document.getElementById("bodyForm");
	const solveButton = document.getElementById("solve");

	// Listen for any changes in text fields inside the form
	form.querySelectorAll("input[type='text']").forEach(input => {
		input.addEventListener("input", () => {
			if (solveButton) {
				// Update the formaction to force indatabase=false
				const base = "DrawSolution.php";
				solveButton.setAttribute("formaction", base + "?indatabase=false");
			}
		}); 
		 
	const pxmaxField = document.getElementById("pxmaxField");
	const pymaxField = document.getElementById("pymaxField");

	// Get the visible window size
	const width = window.innerWidth;
	const height = window.innerHeight;
	pxmaxField.value = width;
	pymaxField.value = height;
	}); 
});
</script>
<script>
document.addEventListener("DOMContentLoaded", function () {
  const tmaxInput = document.querySelector('input[name="tmax"]');

  if (tmaxInput) {
    tmaxInput.addEventListener("input", function (e) {
      // Keep only digits
      const digitsOnly = this.value.replace(/\D/g, '');
      if (this.value !== digitsOnly) {
        this.value = digitsOnly;
      }
    });

    // Optional: prevent pasting non-digits
    tmaxInput.addEventListener("paste", function (e) {
      e.preventDefault();
      const pasted = (e.clipboardData || window.clipboardData).getData('text');
      const digits = pasted.replace(/\D/g, '');
      document.execCommand("insertText", false, digits);
    }); 
  }
});
</script>
</body>
</html>

Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists