<?php

$monitor_count=0;
$monitor_op = -1;
$header_sent=false;
function monitor($op,$message) {
  global $monitor_count, $monitor_op, $header_sent, $header;
  if (!($monitor_count>80)&& ($monitor_op == $op||$monitor_op==0))  {
    if (!$header_sent) {
      echo $header;
      $header_sent=true;
    }
    $monitor_count++;
    echo $message.'<br />';
  }
}

$header0=
'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=windows-1250">
  <meta name="generator" content="PSPad editor, www.pspad.com">';
$header1=
'
  <link href="scispirit.css" rel="stylesheet" type="text/css">
  <title>Scispirit</title>
  </head>
  <body style="margin: 20px;">
';
$header=$header0.$header1;

// script for displaying a page via the url
// http://www.scispirit.com/display.php?filename.htm

//first get the file name

$sought0=$_SERVER['QUERY_STRING'];
monitor(0,"examining $sought0");
// rough validity checks
$valid = (
  (strpos($sought0,"=")===false) && // rule out normal GET format
  !(strpos($sought0,".")==false)  // zero stil no good, so == is OK
);

if ($valid) { // analyse url: first cut domain part, if any
  $sought=$sought0;
  monitor(0,"File is valid");
  
  if (strpos($sought,"http://")===0) $sought=substr($sought,7);
  if (strpos($sought,"www.scispirit.com")===0) $sought=substr($sought,17);
  if ($sought=="/" || $sought=="") $sought="intro.htm";
  else if (substr($sought,0,1)=="/") $sought = substr($sought,1);
  $valid= (strlen($sought)<50) && (strlen($sought)>3);
} 

if ($valid) { // match with file table

  // fast-track intro_b
  if ($sought=='intro_b.htm') {
    $identified=true;
    $set_ext='htm';
    $set_url='intro_b';
    $full_url='intro_b.htm';
  } else {
  
    include 'file_list.inc';
    // process the data from file_list
    $scan=true;
    reset($names);
    reset($url);
    reset($indents);
    $indentified=false;
    
    while ($scan) {
    //read the next set of data from $names
      $key_temp = key($names);
      $name_temp = current($names); // temp vars to avoid overwriting previous                          
  
      if ($name_temp) { // not yet reached the end of data   
        $name=$name_temp;
        $key=$key_temp;
        $urldata = $url[$key];
        if ($dotpos=strpos($urldata,'.')) { // there is a dot, not at the start
          $set_url=substr($urldata,0,$dotpos);
          $set_ext= substr($urldata,$dotpos+1);
        }
        else {
          $set_url=$urldata;
          $set_ext='htm';
        }
        $full_url= $set_url.'.'.$set_ext;
        monitor(0,"comparing with $full_url");
        
        if ($indents[$key]===0) {
          $level=0;  
          $name0 = $name;  // name of upper level
        }
        
        if ($sought==$full_url) { // url identified
          $scan=false;
          $identified=true;
          $side_file = str_replace('/','_',"$name0");
          $side_file = str_replace('?','_',$side_file);
          $side_file = str_replace(' ','_',$side_file);      
          $base_include = 'base_'.$side_file.'.inc';
          $insertion = file_get_contents($base_include);
        }
        else next($names); // try the next one
      } else $scan=false;
    } // end of scan
  
    /*
    output is $set_ext, $full_url, $set_url, $identified
    */
  } // end of fast track
  
  
  if ($identified) { // 
    monitor (1,"match found: insertion is $base_include");
    if (($set_ext=='html')||($set_ext=='htm')||($set_ext=='shtml')) { // standard file so add the 
                                                // insertion and display
      
      if ($set_url=='intro') $full_url = 'intro_b'.".$set_ext";
      monitor(1,"starting file construction of $full_url");
                        // first check for saved version 
      $saved_file = 'base_'.$full_url;
      if (file_exists($saved_file)) echo file_get_contents($saved_file);

      else {
              
        $source = file_get_contents($full_url);
        
        // now hack $source to alter relative urls to include display
        
        function getto (&$srce,$target) { // outputs text up to next occurrence of target
          $pt = strpos($srce,$target);
          if (!($pt===false)) {
            $val = substr($srce,0,$pt);
            $srce = substr($srce,$pt);
            return $val;
          } else return false;        
        }
        
        function get (&$srce,$n) { // outputs next n characters
          $val = substr($srce,0,$n);          
          $trunc = substr($srce,$n); // false if $n longer than length of source
          if ($trunc) $srce=$trunc;
          else $srce = '';
          return $val;
        }
   
   // get the body tag and save it
        $head = getto($source,'<body');
        $head .= getto($source,'>');
        $head .= get($source,1);
        
        $hacking=true;
        $hacked = '';
        
        while ($hacking) {
          monitor(1,"hacking file");
          $next_bit = getto($source,'<a'); // find next start link tag
          if (!($next_bit===false)) {// there is a next link or bookmark tag
            $hacked .= $next_bit;
            $tag = getto($source,'>');
            if ($tag) { 
              $tag .= get($source,2);
            } else { // so there is no closing '>' and $tag === false  
              $remainder = substr($source,2); // get bit after the '<a'
              if ($remainder) $source .= $remainder; // skip the offending '<a'
              break;           
            }
            // so we now have a well-defined tag
            if ($p = strpos($tag,'href')) { // there's a url here
              $hacked .= substr($tag,0,$p+4); // output to the end of the 'href'
              $hacked .= getto($tag,'"');
              $hacked .= get($tag,1); // the '"'
              $url = getto($tag,'"'); // got it! (OK so there might be a missing '"' ??)
              if ((strpos($url,'http//')===false)&&
                  (strpos($url,'?')===false)) // it's a relative url and not already a query
                $url = "display.php?$url";
              $hacked .= ($url.$tag);
            } else { // it isn't a link
              $hacked .= $tag;         
            }
       
          } else {
            $hacking = false;
            $hacked.= $source;
          }
        }
        
        $contents = $head."\n".$insertion.$hacked; 
        file_put_contents ($saved_file,$contents);      
        echo $contents;   
        
      } // end of case where need to hack file
    }  // end of case where identified file is HTML
    
    
    else { // not an html file
      if (!$header_sent) {echo $header; $header_sent=true;}
      // do stuff about telling what to do next
      $ext_type = array (
      'doc' => 'Microsoft Word 1997-2003 document',
      'docx' => 'Microsoft Word Open XML Document',
      'rtf' => 'Rich Text Format File',
      'txt' => 'Plain Text File',
      'pps' => 'PowerPoint Slide Show',
      'ppt' => 'PowerPoint Presentation',
      'pptx' => 'Microsoft PowerPoint Open XML Document',
      'bmp' => 'Bitmap Image File',
      'gif' => 'Graphical Interchange Format File',
      'jpg' => 'JPEG Image File',
      'tif' => 'Tagged Image File',
      'pdf' => 'Portable Document Format File (Adobe reader required)'
       );
      if (isset($ext_type[$set_ext]))
      {
        $type_name = $ext_type[$set_ext];
        $message =  "<p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;
        The file <a href=\"$sought\">$sought</a> is of type 
           \"$type_name\".<br />" ;
      }
      else $message =  "<p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;
        The file <a href=\"$sought\">$sought</a> is of an unrecognised 
             type. <br />";
      $message .= "If it does not open or save on clicking the
           link above, try saving the file by right-clicking the link
          (Windows) and selecting 'save'<br />";
      // the head has been sent so need to do the navbar and the message
      echo $insertion.$message;  
    } // end of non-HTML case
  } // end of handling identified file
  else
  {
    // handle unlisted file
    if (!$header_sent) {
      echo $header0; 
    // check sought is full url ...
      echo "<meta http-equiv=\"Refresh\"
         content=\"0;url=$sought0\">\n";
      echo $header1;
      $header_sent=true;
      echo "<p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;
    The file <a href=\"$sought0\">$sought0</a> is not part of the main 
  scispirit site. <br /> If you are not automatically redirected to this iste 
    in a few seconds, please click on the link  just given. <br />";
    }
    else {
    echo "The file <a href=\"$sought0\">$sought0</a> is not part of the main 
  scispirit site. <br /> If it does not open on clicking the
           link above, try saving the file by right-clicking this link
          (Windows) and selecting 'save'<br />";
    }
  }
} // 


echo '</body></html>';

?>

