Sindbad~EG File Manager

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

<?php
// Set HTTP header to prevent caching
header("Cache-Control: no-cache, must-revalidate");

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

$serverPort = 12349; // Adjust the server port. Ending in 9 for the Engine;  in 7 for Polygon
$timeout = 3600; // Connection timeout in seconds. If the server does not respond by then, close the socket.
$startupDelay = 5; // Delay for server startup in seconds if the server is not already running

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();
}
if ($_SERVER['SERVER_NAME'] == 'localhost') {
    $nextpagegraph = "https://localhost:8443/GraphDoc.php"; 
    $nextpagesymbol = "https://localhost:8443/SymbolicDoc.php"; 
    $serverAddress = 'localhost';  
} else {
    $nextpagegraph = "https://mathxpert.org/GraphDoc.php"; 
    $nextpagesymbol = "https://mathxpert.org/SymbolicDoc.php"; 
    $serverAddress = 'mathxpert.org'; 
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, maximum-scale=1.0, user-scalable=0">
    <title>Select a Problem</title>
    <style>
        /* Set a global font-family rule for all text elements. Only Times New Roman actually works well. */
        text {
            font-family: 'Times New Roman', 'STIX Two Math', 'Cambria Math', 'Latin Modern Math', 'TeX Gyre Termes Math';
        }
	    svg text {
	          font-family: 'Times New Roman';
	    }
    </style>
    <script src="spinner_picker.js"></script>
    <style>
        /* Some basic style for this demo 
         * To prevent overscrolling on mobile use this css:
         * body { overscroll-behavior: contain; }
         */
        body { overscroll-behavior: contain; margin: 0; }
        h1 { font-size: 24px; margin: 0 0 5px 0; font-weight: bold; }
        h2 { font-size: 16px; margin: 0 0 5px 0; font-weight: normal; }
        .demo-sample { float: left; text-align: center; width: 200px; margin: 10px 0 0 10px; padding: 5px 7px 2px 5px; border: 1px solid #333333; box-shadow: 1.5px 1.5px 2.5px 3px #ccc; }
        .demo-sample canvas { width: 100%; height: 200px; border: solid black 1px; }
        table, td, tr { border: none; border-collapse: collapse; }
    </style>
</head>


<?php

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();
}
?>
<html>
 
<?php  
	if(empty($_GET))
	   $language = "english";
	else
	   $language = $_GET["language"]; 
	if (isset($_SESSION['languagenumber']))
	   $languagenumber = $_SESSION['languagenumber']; 

	ob_start();
	include 'toolbar.php';
	$toolbarContent = ob_get_clean();
?> 
<style>
	.hidden {
				visibility: hidden;
				position: absolute;
				}
</style>
<body onload="init()">
	<button onclick="LargerType()">Larger Type</button>
	<button onclick="SmallerType()">Smaller Type</button>
	<button onclick="Accept()">Accept Selected Problem</button> 
<script src="ProblemPicker.js"></script>
  
     <!--   <ul style="list-style-type: none;">
            <li style="font-weight: bold;">Choose a problem from the MathXpert Problem Library:</li>
            <li>1. Hover and scroll with the mouse wheel or with the mousepad</li>
            <li>2. Hover and use the arrow-up- or w- and arrow-down- or s-key</li>
            <li>3. Click on the upper or lower half</li>
            <li>4. On mobile use the scroll gesture</li>
        </ul>
	 -->
      
        <table class="demo-sample" style="width:calc(100% - 40px); max-width: 800px; padding:0;">
            <tr>
                <th width="30%">Subject</th>
                <th width="60%">Topic</th>
                <th width="10%">Problem Number</th>
            </tr>
            <tr>
                <td><canvas id="subject"></canvas></td>
                <td><canvas id="topic"></canvas></td>
                <td><canvas id="problemnumber"></canvas></td>
            </tr>
        </table>
		<svg id="mySVG" viewBox = "0 0 500 80" xmlns="http://www3.org/2000/svg">
		<div id="hiddenToolbar" class="hidden">
			<?php echo $toolbarContent; ?>
		</div>
<?php  
require("SendMessage.php");
$clientSocket = createClientSocket($serverAddress, $serverPort, $timeout);

// we are going to download the "topic strings" needed to set up the problem-picker control 
// using the correct natural language
if(isset($_SESSION['languagenumber']))
  { $response = sendMessage($clientSocket,"askTopicStrings", $languagenumber);
	$response2 = sendMessage($clientSocket,"askSubjectStrings", $languagenumber);
  }
else
  { $response = sendMessage($clientSocket,"askTopicStrings", $language);
	$response2 = sendMessage($clientSocket,"askSubjectStrings", $language);
  }
$topicStrings = explode("\n", " \n" . $response);   // now it's an array, with " " as 0-th element
$subjectStrings = explode("\n",  $response2);  // an array of subject strings,  but no " " tacked on the front 
// Before downloading all the problems,  find out how many there are for each topic.
$problemNumbersAsString = sendMessage($clientSocket,"asknProblems","dummy");  
// param is not used for this message but an empty string is dropped in sendMessage so C receives NULL; hence "dummy" is sent.
$problemNumbers = explode( "\n",$problemNumbersAsString);
?>
<script>
    // convert those arrays to Javascript
    var topics = <?php echo json_encode($topicStrings,JSON_UNESCAPED_UNICODE); ?>;
    var subjects = <?php echo json_encode($subjectStrings,JSON_UNESCAPED_UNICODE); ?>;
  	var jProblemNumbers = <?php echo json_encode($problemNumbers,JSON_UNESCAPED_UNICODE); ?>;
</script>
<?php	
// Now fetch from the server the entire contents of the MathXpert Problem Library in SVG form
$AllProblems = array(200); // enough to index the problems by topic
$maxtopic =  179;
foreach(range(1,$maxtopic) as $topic)
	{ if ( 40 <= $topic && $topic <= 43)
		 continue;
	  $problemsAsString = sendMessage($clientSocket,"askProblemsSVG", strval($topic));
		  // Each problem is a single string with newlines; they are separated by double newlines.
	  if($problemsAsString===false)
		{ echo "\nGoodbye, cruel world! My server left me just standing here!\n";
		  die();
		}
	  $problems = explode("\n\n", $problemsAsString);  
	  	  // now $problems is an array of the problems for $topic; each entry is a string giving SVG for one problem.
	  $AllProblems[$topic] = $problems;  // we use key-value form, since some topics are not used
	}
	// The next <br> serves to put the <svg> element below the spinner controls.
	// Without <br> it is not visible
?>
<br>   
<script>
	// Now write a Javascript function to deliver the problems on demand in the browser:
	// Generate the JavaScript function with parsed JSON
	
    var problems = <?php echo json_encode($AllProblems, JSON_UNESCAPED_UNICODE); ?>;

    function getProblem(topic, problemnumber) {
        if (problems[topic] && problems[topic][problemnumber-1]) {
            return problems[topic][problemnumber-1];
        } else {
		    console.error("Invalid topic or problem number. Topic: " + topic + ", Problem Number: " + problemnumber);
		    return "";
        }
    }
</script>

<?php 

/*
// Function to clean invalid UTF-8 characters recursively
// This was used for debugging.  If there are any characters
// that are not legal UTF-8, the "die()"  line will be executed.
function cleanInvalidUtf8Characters($data) {
    if (is_array($data)) {
        foreach ($data as $key => $value) {
            $data[$key] = cleanInvalidUtf8Characters($value);
			echo("key is $key<br>");
        }
    } elseif (is_string($data)) {
        $newdata = mb_convert_encoding($data, 'UTF-8', 'UTF-8');
		if( !($newdata == $data))
		    { echo("$newdata not equal $data<br>$");
			  die();
			}
    }
    return $data;
}
*/

?>

<?php
//  Following code processes
//  the commented-out data entry form at the top of this file.
//  For simplicity that is omitted from this demo.
    if ($_SERVER["REQUEST_METHOD"] === "POST") 
    {
      $data = $_POST["data"];
	    // Check if the "data" field is empty
	  if (empty($data)) 
			{
	          // Display an alert using JavaScript
	          echo '<script>alert("You must enter a formula to be displayed");</script>';
			  // This saves having to restart the server. 
	     	} 
	  else 
	  {
        $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

        if ($socket === false) 
        {
            echo "Socket creation failed: " . socket_strerror(socket_last_error()) . "<br>";
        } 
		else 
        {   
            socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => $timeout, "usec" => 0));
            $result = socket_connect($socket, $serverAddress, $serverPort);

            if ($result) 
            {
                $response = sendMessage($clientSocket,"parseAndDisplay",$data);
                if ($response === false)
                {
                    $errcode = socket_last_error($socket);
                    $message = socket_strerror($errcode);
                    echo "Socket_read error: $message<br>";
                } else 
                {   
					//  we want to write the SVG code in $response into the web page.  We first 
					//  include a grid for debugging purposes (so we exit php temporarily)
                   ?>
					<svg id="mySvg2" viewBox = "0 0 500 100" xmlns="http://www3.org/2000/svg">
					    <defs>
					    <pattern id="smallGrid" width="16" height="16" patternUnits="userSpaceOnUse">
					      <path d="M 8 0 L 0 0 0 8" fill="none" stroke="gray" stroke-width="0.5"/>
					    </pattern>
					    <pattern id="grid" width="16" height="16" patternUnits="userSpaceOnUse">
					      <rect width="160" height="160" fill="url(#smallGrid)"/>
					      <path d="M 80 0 L 0 0 0 80" fill="none" stroke="gray" stroke-width="1"/>
					    </pattern>
					  </defs>    
					  <rect width="100%" height="100%" fill="url(#grid)" />
					  <?php  // and now add the dynamically generated SVG 
					    echo ($response);
					  ?>
					</svg>
					<?php 
                }
                socket_close($socket);  // because server has already closed it
            } 
            else 
            {
                echo "Failed to connect to the C program: " . socket_strerror(socket_last_error()) . "<br>";
            }
        }
	  }
    }

    ?>
	<div style="clear: both;"></div>
	<div id="chosenValues"></div>
			
<script>
  // Initialize the default scale factor
  var scaleFactor = 1;

  function LargerType() {
    // Check if it's already at the maximum size
    if (scaleFactor > 0.5) {
      // Decrease the scale factor by 20%
      scaleFactor -= 0.2;

      // Get the SVG element
      var svg = document.getElementById('mySVG');
	
      // Dynamically change the viewBox based on the scale factor
      var newWidth = 500 * scaleFactor;
      var newHeight = 80 * scaleFactor;
      svg.setAttribute('viewBox', '0 0 ' + newWidth + ' ' + newHeight);
    }
  }

  function SmallerType() {
    // Check if it's already at the minimum size
    if (scaleFactor  <  2) {
      // Increase the scale factor by 20%
      scaleFactor += 0.2;

      // Get the SVG element
      var svg = document.getElementById('mySVG');

      // Dynamically change the viewBox based on the scale factor
      var newWidth = 500 * scaleFactor;
      var newHeight = 80 * scaleFactor;
      svg.setAttribute('viewBox', '0 0 ' + newWidth + ' ' + newHeight);
    }
  }
   
  function getToolbarWidth() {
      const buttonSVGElements = document.querySelectorAll('.buttonsvg');
      let maxWidth = 0;

      buttonSVGElements.forEach(element => {
          // Try direct width attribute access
          let elementWidth = element.getAttribute('width');
          //console.log('Element:', element, 'Width:', elementWidth);

          if (elementWidth > maxWidth) {
              maxWidth = elementWidth;
          }
      });

      return maxWidth;
  }


  
  function Accept() {
	  subject = subjectPicker.getIndex();
	  topicnumber = topics33[subject][topicPicker.getIndex()];
      //var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
	  // var height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
	  var windowwidth =   document.body.clientWidth;
      // var height =   document.body.clientHeight;  // wrong as it includes the favorites bar and the url field
	  var height = window.innerHeight;   //  technically this is the "viewport height"
	  const hiddenToolbar = document.getElementById('toolbar'); 
	  console.log(hiddenToolbar);
	  const toolbarwidth = parseInt(getToolbarWidth()); 
	  console.log("toolbarwidth = ",toolbarwidth);    // correctly logs 62
	  var graphwidth = windowwidth-toolbarwidth; 
	  console.log("graphwidth = ", graphwidth); 
	  var nextpage;
	  var language = <?php echo ("\"$language\"")?>;
	  // is it a graph topic or a symbolic topic?  We can't use C macros here so I just hard-coded it:
	  if(topicnumber < 44)
	     nextpage = <?php echo ("\"$nextpagegraph\"")?>;
	  else
	     nextpage = <?php echo ("\"$nextpagesymbol\"")?>;
      var myform = document.createElement('form');
      myform.setAttribute('method', 'post');
      myform.setAttribute('action', nextpage);
      myform.style.display = 'hidden';
	  var topicinput = document.createElement("input");
	  topicinput.setAttribute("type", "hidden");
	  topicinput.setAttribute("name", "topicField");
	  topicinput.setAttribute("value", topicnumber);
	  myform.appendChild(topicinput);
	  var widthinput = document.createElement("input");  
	  widthinput.setAttribute("type", "hidden");
	  widthinput.setAttribute("name", "widthField"); 
	  if(topicnumber < 44)
		  widthinput.setAttribute("value", graphwidth);  
	  else 
	     widthinput.setAttribute("value", windowwidth);
	  myform.appendChild(widthinput);  
	  var toolbarwidthinput = document.createElement("input");
	  toolbarwidthinput.setAttribute("type", "hidden"); 
	  toolbarwidthinput.setAttribute("name", "toolbarwidthField"); 
	  toolbarwidthinput.setAttribute("value", toolbarwidth);
	  myform.appendChild(toolbarwidthinput);
	  var heightinput = document.createElement("input");
	  heightinput.setAttribute("type", "hidden");
	  heightinput.setAttribute("name", "heightField");
	  heightinput.setAttribute("value", height);
	  myform.appendChild(heightinput);
	  var problemnumberinput = document.createElement("input");
	  problemnumberinput.setAttribute("type", "hidden");
      problemnumberinput.setAttribute("name", "problemnumberField");
	  problemnumberinput.setAttribute("value", problemnumberPicker.getIndex()+1);
	  myform.appendChild(problemnumberinput);
	  var languageinput = document.createElement("input");
	  languageinput.setAttribute("type", "hidden");
	  languageinput.setAttribute("name", "language");
	  languageinput.setAttribute("value", language);
	  myform.appendChild(languageinput);
	  document.body.appendChild(myform);
	  myform.submit();
  }
</script>
</body>
</html>


 

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