<?php
header
("Content-type: text/html; charset=iso-8859-1");
?>

<?php
  
/*
    WITM is a web-based front end for the
    mathematical software 'Mathematica'
    from Wolfram Research.

    WITM is mainly of use to those with small
    handheld computers, such as PDA and
    smartphones. The program is optimised
    for such devices by use of cascading style
    sheets. Some aspects of the layout are
    changed when the device is a mobile one -
    this happens automatically. The graphs
    drawn in WITM will be 1 of two sizes
    depending on whether the device is a
    mobile or not. Smaller graphs are
    displayed on mobile devices to suite
    the smaller screens the devices have.

    Written by Dr. David Kirkby, under the
    GNU General Public License, version 2
    Copyright (C) 2006  Dr. David Kirkby
    This program is free software; you can
    redistribute it and/or modify it under the
    terms of the GNU General Public
    License as published by the Free
    Software Foundation; either version
    2 of the License, or (at your option) any
    later version.

    This program is distributed in the hope
    that it will be useful, but WITHOUT ANY
    WARRANTY; without even the implied
    warranty of MERCHANTABILITY or FITNESS
    FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for
    more details.

    You should have received a copy of the
    GNU General Public License along with
    this program; if not, write to the Free
    Software Foundation, Inc., 51 Franklin
    Street, Fifth Floor, Boston,
    MA  02110-1301, USA.

    The license is written in full in
    the file 'licensing.php'
  */

  
$WITMversion="0.76";
  
$WITMdate="8/7/06";
  
$WITMlongdate="8th July 2006";

  
/*
    Give the path to the command line front
    end for Mathematica. This is called 'math'
    and *not* 'mathematica'. Two options
    (batchinput and batchoutput) are needed
    too.
  */

  
$math="/usr/local/bin/math -batchinput -batchoutput";

  
/*  
    Since Mathematica commands can be time
    and memory intensive, we put some limits
    here to protect our server from slowing
    too much.

    $maxmemory is the maximum memory that may
    be used in Mb. An attept to use more will
    result in Mathematica aborting and giving
    and error message.

    $maxtime is the maximum time in seconds
    the Mathematica kernel will run for.
    Mathematica will abort if it has used this
    much time and has still not finished.

  */

  
$maxmemory=200;       // Max memory in Mb.
  
$maxtime=500;         // Max time in s.

  /*
    To make best use of the displays on
    typical modern computers, graphs are
    drawn reasonably large. The width is
    set by $WidthOfGraphic

    On mobile devices, which have screens with
    less resolution, the images are drawn
    smaller. This is set by
    $WidthOfGraphicMobile.
  */

  
$WidthOfGraphic=600;      
  
$WidthOfGraphicMobile=220;

  
/*
    Set the type of images created. This can
    be "gif", "jpg", "bmp" and perhaps others
    too. Basically anything that Export[]
    can produce is OK.

    But for all the examples I tried, gif
    produces the smallest files, next
    jpg and bmp produces huge files. So there
    is not a lot of point in using anything
    other than gif. It also has the advantage
    that it is possible to animage gif files,
    so potentially we could create
    animations.
  */
  
$ImageFormat="gif";

  
/*
    When using Mathematica, the first line
    must be stripped from the output, as that
    contains information about the version of
    Mathematica, and is not the result of the
    calculation.

    sed '1d'

    will strip the first line, but it might be
    necessary to change this if your
    Mathematica version outputs data in a
    slightly different format to the Solaris
    (SPARC) version 5.2 tested.
  */

  
$sedcommand="sed '1d'";

  
/*
    The names of files used for images
    created on both fixed and handheld
    devices. NOTE - THESE ARE STILL
    HARDCODED IN A COUPLE OF PLACES.
    There is not much point in changing
    these.
  */


  
$fixed="\"graph.$ImageFormat\"";        
  
$handheld="\"handheld.$ImageFormat\"";

  
/*
    On a public access site, such as
    Sourceforge, a working copy of Mathematica
    can not be installed without breaching
    the Mathematica license conditions.

    WITM will print appropriate messages in
    that case on the public access web
    server.

    We can set the demo site's name and URL.
  */

  
$demoURL="witm.sourceforge.net";
  
$demoSite="Sourceforge";

  
/*
    To print the appropiate messages on
    the public access web server, we need
    to test what server is being used.

    If $webserver is $demoURL then we print
    appropriate messages.
  */

  
$webserver=$_SERVER['SERVER_NAME'];

  
/*
    We now process data from the form which
    is shown further down this page. There
    are 3 buttons from this form, so all
    3 need processing. Actually 4 are
    processed, since one of them is
    different on mobile devices.

    WITM displays graphical output on the web
    browser. But unless the computations
    are producing graphics there is no
    point in displaying such an image, as it
    uses bandwidth, which is expensive on
    mobile devices where one often pays a lot
    for bandwidth.

    For this reason the user can delete any
    graphs not needed. So that a semi-decent
    demo can be provided on Sourceforge,
    (or wherever you choose), the PHP
    code will not allow one to delete the
    graphics on that site.

  */

  
if (isset($_POST['RemoveGraphic'])) {
    if (
$webserver === $demoURL)
      
$data="Sorry, this demo on $demoSite  will not allow you to delete the graphic, but normally it would  be deleted from the server, to save you downloading an old graph each time. So you would delete it once you are finished with it.";
    else
      
system("rm $fixed $handheld");
  }

  
/*
    Again, like the above where a graphic is
    removed if 'Delete Image', is depressed,
    so WITM does things if the 'Evaluate'
    button is depressed.
  */

  
if (isset($_POST['EvaluateFullSize'])) {
    
/*
      On sourceforge we can't use Mathematica
      due to License restrictions,
      so just print a message instead.
    */
    
if ($webserver === $demoURL)
      
$data="Sorry, due to the license restrictions on Mathematica, I can't install a copy of that product here for all to use. So this demo of WITM on $demoSite does not function. If you installed WITM yourself, you would get text results like:\n\n5 x^3 - 10 x^2 -9\n\nin this text box and graphical ones, like the 3D graph, in the box below.\n\nI would appreciate feedback on WITM, even if you can only provide it from this demo.";
    else {
      
$cmd=$_POST['input_data'];
      
/*
        Undo the effect of the magic
        quote abomination
      */
      
if (get_magic_quotes_gpc()) {
        
$cmd=stripslashes($cmd);
      }
      
/*
        The command that will be sent
        to Mathematica is not the same
        as the user types in, but is more
        complex, to add code for checking
        memory usage, checking CPU time
        and testing if the result is
        graphical.
   
        This looks complex (and it is).
        1) If the expression is Graphics,
           then it is exported, but if
           not it is returned.
        2) If the computation takes too
          much memory, it gets aborted.
        3) If the computation takes too
          long, it gets exported.

        The following line adds all the bits
        necessary for these tests.
      */
      
$fullcmd=escapeshellarg("TimeConstrained[MemoryConstrained[expr=$cmd;head=ToString[Head[expr]];If[head==ToString[Graphics] || head==ToString[SurfaceGraphics] || head==ToString[ContourGraphics] || head ==ToString[DensityGraphics] || head==ToString[GraphicsArray] || head==ToString[Graphics3D] ,Export[$fixed,expr,ImageSize->$WidthOfGraphic],expr],$maxmemory*1024*1024,\"Too Much RAM has been used so we are Aborting. This is currently limited to $maxmemory Mb in witm.php, but can be changed on the web server.\"],$maxtime,\"This is taking too long, so is being aborted. There is a limit of $maxtime seconds, which can only be changed by editing the PHP script on the web server - a user can't override this from their browser.\"]");

      
$handle = popen("echo $fullcmd | tee stdin.txt | $math | $sedcommand | tee stdout.txt", "r");
      
$data=fread($handle,10000);
      
pclose($handle);
    }
  }

  
/*
    The following is almost the same as the
    command above, but is modified a little
    for the mobile device. It prints smaller
    graphics and saves them to a different
    file name on mobile devices.
  */
  
if (isset($_POST['EvaluateMobile'])) {
    if (
$webserver === $demoURL)
    
$data="Sorry, due to the license restrictions on Mathematica, I can't install a copy of that product here for all to use. So this demo of WITM on $demoSite does not function. If you installed WITM yourself, you would get text results in this text box and graphical ones, like the 3D graph, in the box below. I would appreciate feedback on WITM, even if you can only provide it from this demo.";
    else {
      
$cmd=$_POST['input_data'];
      
/*
        Undo the effect of the magic
        quote abomination
      */
      
if (get_magic_quotes_gpc()) {
        
$cmd=stripslashes($cmd);
      }
      
$fullcmd=escapeshellarg("TimeConstrained[MemoryConstrained[expr=$cmd;head=ToString[Head[expr]];If[head==ToString[Graphics] || head==ToString[SurfaceGraphics] || head==ToString[ContourGraphics] || head ==ToString[DensityGraphics] || head==ToString[GraphicsArray] || head==ToString[Graphics3D] ,Export[$handheld,expr,ImageSize->$WidthOfGraphicMobile],expr],$maxmemory*1024*1024,\"Too Much RAM has been used so we are Aborting. This is currently limited to $maxmemory Mb in witm.php, but can be changed on the web server.\"],$maxtime,\"This is taking too long, so is being aborted. There is a limit of $maxtime seconds, which can only be changed by editing the PHP script on the web server - a user can't override this from their browser.\"]");
      
$handle = popen("echo $fullcmd | tee stdin.txt | $math | $sedcommand | tee stdout.txt", "r");
      
$data=fread($handle,10000);
      
pclose($handle);
    }
  }
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta name="DESCRIPTION" content="Source code for WITM which allows Mathematica to be used on a browser.">
    <meta name="KEYWORDS" content="Mathematica, PHP, source code, webMathematica, web, front end, internet,browser, internet explorer">
    <title>PHP script for WITM - the Web Interface to Mathematica</title>
    <link rel="stylesheet" type="text/css" media="all"      href="styles/all.css">
    <link rel="stylesheet" type="text/css" media="screen"   href="styles/screen.css">
    <link rel="stylesheet" type="text/css" media="print"    href="styles/print.css">
    <link rel="stylesheet" type="text/css" media="handheld" href="styles/handheld.css">
    <link rel="shortcut icon" href="images/favicon.ico">
  </head>
  <body>
    <h1>PHP script for WITM (Web
        Interface to Mathematica)</h1>
    <!--
      The classes 'nohandheld' and 'handheld'
      are used to conditionally display
      things on handheld devices
    -->

    <!--
      Print longish versions of WITM's
      date and Mathematica version on
      largeish computers.
    -->
   
    <div class="nonhandheld">
      <img src="images/witm-icon.gif" width="94" height="100"  ALT="WITM icon">
<br class="clearit">
      <?php
        
echo "<a href=\"http://witm.sourceforge.net/\">WITM</a> version $WITMversion, dated $WITMlongdate.";
      
?>
      <br>
      Copyright(C) 2006 <a href="&#109;&#097;&#105;&#108;&#116;&#111;:&#100;&#097;&#118;&#105;&#100;&#046;&#107;&#105;&#114;&#107;&#098;&#121;&#064;&#111;&#110;&#101;&#116;&#101;&#108;&#046;&#110;&#101;&#116;">Dr. David Kirkby</a> PhD.
      Licensed under the <a href="http://www.gnu.org/copyleft/gpl.html">GNU General Public License</a>
    </div> <!-- end of "nonhandheld class -->

    <!--
      Print shorter versions of WITM's
      date and Mathematica version on
      handheld computers.
    -->
    <div class="handheld">
      <?php
        
/*
          On this handheld device, we attempt
          to read only the Mathematica
          version number (4.0, 4.1, 4.2, 5.1
          5.2 etc) whereas on a larger
          computer, the exact type is
          displayed, such as:

          5.2 for Sun Solaris (UltraSPARC) (June 21, 2005).

          This is done by sending Mathematica
          either $VersionNumber (on a handheld
          computer) or $Version (on a larger
          computer).
        */
        
$handle = popen("echo '\$VersionNumber' | $math | $sedcommand 2>&1", "r");
        
$str=fread($handle,200);
        
$len=strlen($str);
        
/*
          Test if we can read the version
          number (4.0, 4.1, 4.2, 5.0, 5.1,
          5.2 or later)
        */
        
if($len === 0) // can't read version.
          
echo "<a href=\"index.php\">WITM</a> ver $WITMversion. <div class=\"warning\">WARNING: It would appear that WITM has not connected to Mathematica - this will <b>always</b> happen on <a href=\"http://witm.sourceforge.net/\">http://witm.sourceforge.net/</a> since Mathematica is not installed on Sourceforge. But if this message appears when you expect WITM to connect to Mathematica, then there is a problem.</div>";
        else
// print version
          
echo "<div class=\"good\"><a href=\"http://witm.sourceforge.net/\">WITM</a> ver $WITMversion. <a href=\"http://www.wolfram.com/products/mathematica/index.html\">Mathematica</a> ver $str</div>";  
      
?>
    </div> <!-- end of handheld class -->

    <div class="nonhandheld">
      <?php
        $handle
= popen("echo '\$Version' | $math | $sedcommand | sed  's/\"//g'  2>&1", "r");
        
$str=fread($handle,200);
        
/*
          Test if we can read the version
          number (4.0, 4.1, 4.2, 5.0, 5.1,
          5.2 or later)
        */
        
$len=strlen($str);
        if(
$len === 0) // Can't read version
          
echo "<div class=\"warning\">WARNING: It would appear that WITM has not connected to Mathematica - this will <b>always</b> happen on <a href=\"http://witm.sourceforge.net/\">http://witm.sourceforge.net/</a> since Mathematica is not installed on Sourceforge. But if this message appears when you expect WITM to connect to Mathematica, then there is a problem.</div>";
        else
          echo
"<div class=\"good\"><b>Mathematica: $str</b></div>";  
       
?>
      </div> <!-- end of handheld class -->
      <div class="nonhandheld">
      <br>
      Enter your
      <a href="http://www.wolfram.com/products/mathematica/index.html">Mathematica</a>
      commands in the text box below.
      If you are not sure of the command, or
      a command's syntax, take a look at
      one of the following 4 links on the
      <a href="http://www.wolfram.com/">Wolfram Research</a>
      web site:
      <ul>
        <li>
          <a href="http://documents.wolfram.com/">Documentation centre</a>
        </li>
        <li>
          <a href="http://documents.wolfram.com/v5/">Mathematica version 5 Documentation</a>
        </li>
        <li>
          <a href="http://documents.wolfram.com/mathematica/book/">The Mathematica book (5th edition)</a>
        </li>
        <li>
          <a href="http://library.wolfram.com/conferences/devconf99/withoff/index2.html">Various tutorials</a>
        </li>
      </ul>
      <!--
        display form for Mathematica input  
      -->  
      <Form action="witm.php" method="post" >
       <p>
        <TEXTAREA name="input_data" rows="6" cols="80">
          <?php
            
echo htmlspecialchars("$data");
          
?>
        </TEXTAREA>
<br class="clearit">
        <input type=submit name="EvaluateFullSize" value="Evaluate">
        <input type=submit name="reset" value="Clear">
        <input type=submit name="RemoveGraphic" value="Delete image"><br>
        <?php
          
/*
            The browser would often load a
            cached copy of an image, rather
            than the new image that was
            created. This bit of code, based
            on a method suggested by Krustov
            on uk.net.web.authoring,
            gives a random file name for
            the browser to load - such as:

            graph.jpg?124393732

            where the numeric part is random.
            The browser ignores the numeric
            part but it forces it to reload
            the new image.
          */
          
$rnd=rand();
          if (
file_exists("graph.$ImageFormat"))
            echo
"<img src=\"graph.$ImageFormat?$rnd\" width=\"$WidthOfGraphic\"  ALT=\"-Graphics-\">";
          
?>
       </p>
        </form>
      </div> <!-- end of nonhandheld class -->
      <div class="handheld">
      <Form action="witm.php" method="post" >
       <p>
        <TEXTAREA name="input_data" rows="3" cols="80" >
        <?php
          
echo htmlspecialchars("$data");
          
?>
        </TEXTAREA>
        <br>
        <input type=submit name="EvaluateMobile" value="Evaluate">
        <input type=submit name="reset" value="Clear">
        <input type=submit name="RemoveGraphic" value="Delete Graphic"><br>
        <?php
          $rnd
=rand();
          if (
file_exists("handheld.$ImageFormat"))
          echo
"<img src=\"handheld.$ImageFormat?$rnd\"  width=\"$WidthOfGraphicMobile\"  ALT=\"-Graphics-\">";
        
?>
       <p>
      </form>
    </div> <!-- end of 'handheld' class -->
    <div class="nonhandheld">
      <h2>Documentation</h2>
      <a href="http://witm.sourceforge.net/">WITM's
      documentation</a> can be read on the
      Sourceforge web site. The documentation
      should have also been
      <a href="index.php">installed locally</a>.
      You really need to read the
      documentation, as some things behave
      differently from when using
      Mathematica's notebook interface.

      <!-- Include Sourceforge, W3C 4.01
      and WC3 CSS loos on large computers
      but not on handhelds.  -->

      <?php
        
include ("footer.php");
      
?>
    </div> <!-- end of 'nonhandheld' class -->
  </body>
</html>