<?php
//-->-->-->-->-->-->-->-->-->-->-->-->-->-->  
  include "/home/waggacwc/public_html/refurb/RETRO-GLOBALS.php";

  include "$LIBRARYPATH/fnStartHtml.php";
  include "$LIBRARYPATH/fnRetrovoxStartHtml.php";
  include "$LIBRARYPATH/fnJournalToHtml.php";
  include "$LIBRARYPATH/fnFaqToHtml.php";
  include "$LIBRARYPATH/fnDocumentToHtml.php";

  include_once "$LIBRARYPATH/fnHyperlinkPlainText.php";
  include_once "$LIBRARYPATH/fnSpecialLinkPlainText.php";
  include_once "$LIBRARYPATH/fnHtmlAsciiMenuItems.php";
  include "$LIBRARYPATH/fnMessageToHtml.php";
  //include "$LIBRARYPATH/fnDebugArray.php";
  include_once "$LIBRARYPATH/fnFillWebTemplate.php";
  include_once "$LIBRARYPATH/fnWebTemplateInsertSelfEdit.php";
  include_once "$LIBRARYPATH/fnWebTemplateInsertTemplateEdit.php";


  include "$LIBRARYPATH/fnCodeBlockToHtml.php";
  include "$LIBRARYPATH/fnCodeBlockFromHtml.php";
  include "$LIBRARYPATH/fnListBlockToHtml.php";
 
  include "$LIBRARYPATH/fnSwitchFileSelect.php";

  $bNewFile = false;     //-- 
  $sFilePath = '';       //-- the name and full path to the text file
  $sFileContents = '';   //-- the contents of the text file
  $aaTextLines = '';     //--
  $iBackups = 4;         //-- the number of backup files to create
  $EDITOR = "WebPad";

  //-- Convert all file-path specifications to forward-slashes since this avoids
  //-- all the 'escaping' nightmare of back-slashes
  $sFilePath = stripslashes($_POST['saveFilePath']);
  $sFilePath = str_replace('\\', '/', $sFilePath);
  $sFilePath = preg_replace('#[/]+#', '/', $sFilePath);

  $sWikiFolder = "/home/waggacwc/public_html/refurb/docs";
  $sCwcFolder = "/home/waggacwc/public_html";
  $sRefurbFolder = "/home/waggacwc/public_html/refurb";
  $sTemplateFolder = "/home/waggacwc/public_html/refurb/html-templates";


  $sFilePathEncoded = htmlspecialchars($sFilePath);
  $sFilePathUrlEncoded = htmlspecialchars(urlencode($sFilePath));

  $sCurrentDirectory = dirname($sFilePath);
  $sCurrentWebDirectory =   
    str_replace('c:/apache2/htdocs', '', $sCurrentDirectory);

  $sFileContents = $_POST['fileContents'];

  $sFileName = str_replace("$sCurrentDirectory/", '', $sFilePath);
  $sFileNameUrlEncoded = htmlspecialchars(urlencode($sFileName));

  $sDefaultPageTemplate = "<html><body></body></html>";

  //-- Get the contents of the relevant templates
  $aaTextLines = file($ERRORTEMPLATE);
  $sErrorTemplateContents = implode('', $aaTextLines);

  $aaTextLines = file($WEBPADTEMPLATE);
  $sWebpadTemplateContents = implode('', $aaTextLines);

  if (file_exists($DOCUMENTTEMPLATE))
  {
    $aaTextLines = file($DOCUMENTTEMPLATE);
    $sDocumentTemplateContents = implode('', $aaTextLines);
  }
  else
  {
    $sDocumentTemplateContents = $sDefaultPageTemplate;
  }

  if (file_exists($CWCTEMPLATE))
  {
    $aaTextLines = file($CWCTEMPLATE);
    $sCwcTemplateContents = implode('', $aaTextLines);
  }
  else
  {
    $sCwcTemplateContents = $sDefaultPageTemplate;
  }

  if (file_exists($WEBEDITFOLDERFILE))
  {
    $aaWebEditFolderList = file($WEBEDITFOLDERFILE);
  }

  //-- This needs to be fixed and generalized
  if (!array_search($sFilePath, $aaWebEditFolderList))
  {
    echo 'off';
  }

  if (!strstr($sFilePath, $sWikiFolder) 
   && (dirname($sFilePath) != $sCwcFolder)
   && (dirname($sFilePath) != $sRefurbFolder)
   && (dirname($sFilePath) != $sTemplateFolder))
  {
      $sPageTitle = "$EDITOR, (File not editable)";
      $sPageContent = "
          = $EDITOR, (File not editable)

      The file which you selected to edit with the $EDITOR is not 
      registered as being editable. You may edit it with the management
      web editor but you will need a password in order to access that editor. 
      The current editor is for maintaining documents which can then be 
      published either on the Internet as web pages or in another format.

      Currently (feb 2004) only documents in the 
      '/refurb/docs/' link://webpad.php?file=/refurb/docs/
      directory are editable using this interface.

      It is true that, this being the case I really shouldnt allow you to choose
      a file in a different directory, since that can only cause frustration
      when you receive this error message. To do.

      'Choose another file to edit' link://webpad-choose-file.php

 
       ";

      $sPageContent = fnMessageToHtml($sPageContent);
      $sOutputPage = fnFillWebTemplate(
        $sWebpadTemplateContents, $sPageContent, $sPageTitle);   
      echo $sOutputPage;
      exit;
  }





  //-- This is the base-name for the backup files
  $sBackupFileBaseName = preg_replace("/$/", ".old", $sFileName);

  if (preg_match("/\./", $sFilePath))
  {
    $sHtmlFilePath = preg_replace("/\.[^\.]*$/", ".html", $sFilePath);
  }
  else
  {
    $sHtmlFilePath = preg_replace("/$/", ".html", $sFilePath);
  }

  $sFileWebPath = htmlspecialchars(str_replace(
      $WEBDOCUMENTROOT, '', $sFilePath));

  $sHtmlFileWebPath = htmlspecialchars(str_replace(
      $WEBDOCUMENTROOT, '', $sHtmlFilePath));

  //$sHtmlFileNameUrlEncoded = htmlspecialchars(urlencode($sFileName));
  

  $debug = "";
  if ($debug == "true")
  {
    echo "
      <pre>
      sFilePath=$sFilePath
      sFileName=$sFileName
      sCurrentDirectory=$sCurrentDirectory
      sFileWebPath=$sFileWebPath
      sCurrrentWebDirectory=$sCurrentWebDirectory
      sHtmlFilePath=$sHtmlFilePath
      </pre>";
    //exit;
  } //--if

 
  if ($sFilePath == '')
  {

      $sPageTitle = "$EDITOR, (No file name specified)";
      $sPageContent = "
          = $EDITOR, (No file name specified)

      You did not specify any file to be saved.

      This may indicate that the script webpad.php
      is not working correctly

      Or it may indicate that you have typed the address of this 
      page directly in your web-browser rather than arriving here after
      submiting the form in the script webpad.php

      No changes to any text file have been saved.

      'Choose a file to edit' link://webpad-choose-file.php
      'Copy a file' link://move-file-form.php

 
       ";

      $sPageContent = fnMessageToHtml($sPageContent);
      $sOutputPage = fnFillWebTemplate(
        $sAdminTemplateContents, $sPageContent, $sPageTitle);   
      echo $sOutputPage;
      exit;


  } //-- if no file specified


  if (!file_exists($sFilePath))
  {

      $sPageTitle = "$EDITOR Save: the file doesn't exist";
      $sPageContent = "
          = $EDITOR Save: the file doesn't exist

       The file-name $sFilePathEncoded which you are trying to save doesn't 
       exist. This probably means that either one of these scripts is not
       working properly, or else somebody deleted the file while you were  
       editing it. This situation needs to be fixed. For now, all I can say is
       sorry about that, and I hope that you didnt waste too much time on 
       editing a non existant file. Have you considered taking up carpentry
       instead of text-editing? Generally speaking it is quite rare for a piece
       of wood to just disappear and therefore you probably wont experience the
       sort of frustration which you are now feeling. 

       But dont despair, just click the 'Back' button on your browser, as soon as
       you have finished reading these messages, and then cut an paste all the 
       text which is in the text area and then save the file on your local computer,
       or else create a new file on the server using the 'copy' function and cut
       and paste the text in there. 

       'Re-enter the file name'
         link://webpad-choose-file.php?file=$sFilePathUrlEncoded
 
       ";

      $sPageContent = fnMessageToHtml($sPageContent);
      $sOutputPage = fnFillWebTemplate(
        $sAdminTemplateContents, $sPageContent, $sPageTitle);   
      echo $sOutputPage;
      exit;
  } //-- if file doesn't exist

  if (!is_writable($sFilePath))
  {
    //$bChmodSucceeded = chmod($sFilePath, 0407);
    copy($sFilePath, "$sFilePath-temp");
    rename("$sFilePath-temp", $sFilePath);

    if (!is_writable($sFilePath))
    {

      $sPageTitle = "$EDITOR Save: the file is not writable";
      $sPageContent = "
          = $EDITOR Save: the file is not writable

      
      The file-name [$sFilePathEncoded] which you just specified has its permissions
      set so that is cannot be edited (updated or modified in any way). This 
      situation really shouldn't occur since the editing script (notepad.php) 
      should pick up this situation and stop you from editing the file and wasting
      your time, since you cant save the changes. Sadly, however, if you are reading
      this message, and you are not looking at the source of the PHP script, then
      the situation has occurred and its not much good for me to tell you that
      the situation shouldnt occur. Thats one of those very annoying things that
      programmers tend to often say; 'that shouldnt happen'. Well it has happened
      now what can you do about it? Thats what really matters.

      Firstly, let me say that the current script has attempted to help you out
      by automatically making the file you were trying to edit, editable. But it
      failed badly. The script tried to copy the file to a temporary file name
      and then copy it back again. This trick sometimes works. But this time it
      didnt work at all. So its no help to you. 

      The best thing that you can do is to log into your web-server and try to
      fiddle around with the permissions on the files there. I know that this 
      was not how you were envisioning spending your day, that it not you idea
      of recreation to fiddle around with permissions. In fact you may well not 
      even know what a permission is or how to change it or anything like that. 
      If you are a determined sort of person you can find out all you need to 
      know from the Internet. If your web-server is running Unix or Linux or 
      a variant of one of these, then do a search at the http://www.google.com
      site for the text 'man chmod' and read the ridiculously cryptic explanation
      that the post-graduate student at Berkeley have deemed to complicate your
      life with. 

      I am getting tired of this long-winded error message so I am just going to
      leave you with a few hints.
 
      You may be able to overcome the problem by typing. 
          
            chmod a+w $sFilePath
          
      if you can log into the web-server (assuming that it is a Unix variant 
      server). This sometimes works. Another trick is to rename or copy the 
      file to a different name and then rename it back again to its original name.
      The purpose of this is to make you, or the web-server the owner of the file,
      however, the current script has just attempted that trick and it FAILED.
      Nevertheless, you may have better luck if you can telnet or ssh into the 
      Web-server.

      'Re-enter the file name'
         link://webpad-choose-file.php?file=$sFilePathUrlEncoded
 
      'Copy the file (to try to make it editable)'
         link://$MANAGEMENTWEBFOLDER/move-file-form.php?file=$sFilePathUrlEncoded
       ";

      $sPageContent = fnMessageToHtml($sPageContent);
      $sOutputPage = fnFillWebTemplate(
        $sAdminTemplateContents, $sPageContent, $sPageTitle);   
      echo $sOutputPage;
      exit;

    } //-- file still not writeable
  } 
  //-- if file not writeable

  if (is_dir($sFilePath))
  {

    $sPageTitle = "$EDITOR: the path is a directory";
    $sPageContent = "
          = $EDITOR: the path is a directory

       The file-name $sFilePathEncoded which you just tried to save is a 
       'directory' or 'folder' on the web-server.

       The file-name $sFilePathEncoded for the file which you
       have been editing is a directory (folder). This indicates 
       that the script webpad.php is not working properly.

       I do not have any idea why this situation would occur and I cant really
       offer you any help. You could try sending me an email at 
       matth3wbishop@yahoo.com  

       You could also try using the 'SAFE' scripts for editing files which are
       located on the server. These are called SAFE-notepad.php or 
       SAFE-webpad.php and they have been written to remove some of the things
       that could go wrong with the more fully featured normal notepad browser
       editing scripts. 


 
       ";

      $sPageContent = fnMessageToHtml($sPageContent);
      $sOutputPage = fnFillWebTemplate(
        $sAdminTemplateContents, $sPageContent, $sPageTitle);   
      echo $sOutputPage;
      exit;

  } //-- if file is a directory


  //-- We need to locate and extract the data from the 
  //-- document configuration file path.
  $sDocumentConfigFilePath = "";
  $sDocumentTemplatePath = "";

  if (preg_match("/\./", $sFilePath))
  {
    $sDocumentConfigFilePath = preg_replace("/\.[^\.]*$/", ".conf", $sFilePath);
  }
  else
  {
    $sDocumentConfigFilePath = preg_replace("/$/", ".conf", $sFilePath);
  }

  if (file_exists($sDocumentConfigFilePath))
  {
    $aaDocumentSettings = parse_ini_file($sDocumentConfigFilePath);
    $sDocumentTemplatePath = $aaDocumentSettings['document-template-path'];
    $sDocumentTocLocation = $aaDocumentSettings['table-of-contents-location'];
    //fnDebugArray($aaDocumentSettings);
    //echo "sDocumentTemplatePath=$sDocumentTemplatePath";
    //exit;
  }

  if (file_exists($sDocumentTemplatePath))
  {
    $aaTextLines = file($sDocumentTemplatePath);
    $sDocumentTemplateContents = implode('', $aaTextLines);
  }
  else
  {
    $sDocumentTemplatePath = 
      "/home/waggacwc/public_html/refurb/html-templates/sam-tregar-2.html";
    $aaTextLines = file($sDocumentTemplatePath);
    $sDocumentTemplateContents = implode('', $aaTextLines);
  }




  if (file_exists($sFilePath))
  {
    for ($ii = $iBackups; $ii > 0; $ii--)
    {
       $sNewName = "$BACKUPFILEDIRECTORY/$sBackupFileBaseName$ii.txt";
       $sOldName = "$BACKUPFILEDIRECTORY/$sBackupFileBaseName".($ii-1).".txt";
       if (file_exists($sOldName))
       {
          if (file_exists($sNewName))
          {
             unlink($sNewName);
          }
          copy($sOldName, $sNewName);
       } //-- if
    } //-- for

    copy($sFilePath, $BACKUPFILEDIRECTORY.'/'.$sBackupFileBaseName."1.txt");
    //unlink($sFilePath);
  } //-- if file exists


  //-- save the changes to the text document
  $fileHandler = fopen($sFilePath, "w");
  fwrite($fileHandler, stripslashes($sFileContents));
  fclose($fileHandler);

  $sCleanFileContents = stripslashes($sFileContents);

  $bGenerateHtml = false;

  if (preg_match("/\[\*journal\*\]/i", $sCleanFileContents)) 
  {
    $bGenerateHtml = true;
    $sHtmlFileContents = fnJournalToHtml($sCleanFileContents);
  } 
  elseif (preg_match("/\[\*document\*\]/i", $sCleanFileContents)) 
  {
    $bGenerateHtml = true;
    $sHtmlFileContents = fnDocumentToHtml($sCleanFileContents);
  } 
  elseif (preg_match("/\[\*faq\*\]/i", $sCleanFileContents)) 
  {
    $bGenerateHtml = true;
    $sHtmlFileContents = fnFaqToHtml($sCleanFileContents);
  } 
  elseif (preg_match("/\[\*cwc\*\]/i", $sCleanFileContents)) 
  {
    $bGenerateHtml = true;
    $sHtmlFileContents = fnDocumentToHtml($sCleanFileContents);
  } 

  if ($bGenerateHtml)
  {
    //-- The functions fnSpecialLinkPlainText and 
    //-- fnWebTemplateInsertSelfEdit should and could be combined
    //-- since they do very similar jobs.

    $sHtmlFileContents = fnHtmlAsciiMenuItems($sHtmlFileContents);

    $sHtmlFileContents = 
       fnSpecialLinkPlainText(
         $sHtmlFileContents, $sFilePath, $WEBPADWEBFOLDER);
    $sHtmlFileContents = fnFillWebTemplate(
       $sDocumentTemplateContents, $sHtmlFileContents);   

    $sHtmlFileContents = fnWebTemplateInsertSelfEdit(
      $sHtmlFileContents, $sFilePath, 
      "$WEBPADWEBFOLDER/webpad.php?file=");   
    $sHtmlFileContents = fnWebTemplateInsertTemplateEdit(
      $sHtmlFileContents, $sDocumentTemplatePath, 
      "$WEBPADWEBFOLDER/webpad.php?file=");   

    //-- Save the generated HTML document
    $fileHandler = fopen($sHtmlFilePath, "w");
    fwrite($fileHandler, $sHtmlFileContents);
    fclose($fileHandler);
  }


  $sPageTitle = "$sFileName saved: $EDITOR ";
  $sPageContent = "
        = $sFileName saved: $EDITOR 

    text-icon:para link://$sFileWebPath 
    text-icon:Xi 
    link://$MANAGEMENTWEBFOLDER/view-file-lines.php?file=$sFilePathUrlEncoded 
    text-icon:epsilon link://webpad.php?file=$sFilePathUrlEncoded 
    text-icon:harr
    link://$MANAGEMENTWEBFOLDER/move-file-form.php?file=$sFilePath 
    text-icon:clubs
    link://webpad-choose-file.php?file=$sFilePathUrlEncoded 
    text-icon:sect
    link://$MANAGEMENTWEBFOLDER/find-file-form.php?file=$sFileNameUrlEncoded 
   ";

    if (file_exists($sHtmlFilePath))
    {
      $sPageContent = $sPageContent.
        " text-icon:omega link://$sHtmlFileWebPath?".rand(1,999)."
         ";
    } //-- if

   $sPageContent = $sPageContent."

    The changes which you made to the text file $sFilePathEncoded
    have been saved.

    ";


    $sPageContent = $sPageContent."

   u--
    link://webpad-choose-file.php 
    Choose a file to edit
    - 
    text-icon:para link://$sFileWebPath 
    View the file ('In a new window' !link://$sFileWebPath )
    - 
    text-icon:Xi 
    link://$MANAGEMENTWEBFOLDER/view-file-lines.php?file=$sFilePathUrlEncoded
    View this file with line numbers
    - 
    text-icon:epsilon 
    link://webpad.php?file=$sFilePathUrlEncoded
    Continue editing the same file 
    ('In a new window' link://webpad.php?file=$sFilePathUrlEncoded )
    - 
    text-icon:harr
    link://$MANAGEMENTWEBFOLDER/move-file-form.php?file=$sFilePath
    Copy or rename this file
    -
    text-icon:clubs
    link://webpad-choose-file.php?file=$sFilePathUrlEncoded
    Edit a different or new file
    -
    text-icon:sect
    link://$MANAGEMENTWEBFOLDER/find-file-form.php?file=$sFileNameUrlEncoded
    Find a file on the server";

    if (file_exists($sHtmlFilePath))
    {
      $sPageContent = $sPageContent."
         - text-icon:omega link://$sHtmlFileWebPath?".rand(1,999)."
           View the Web Page of the Document (!)

         ";
    } //-- if

   $sPageContent = $sPageContent."

    The following backup files for this text file currently exist:


    a-";
    for ($ii = $iBackups; $ii > 0; $ii--)
    {
       $sBackupFileName = "$BACKUPFILEDIRECTORY/$sBackupFileBaseName$ii.txt";
       $sMisplacedBackupFileName = 
         "$sCurrentDirectory/$sBackupFileBaseName$ii.txt";

       $sCurrentPath = htmlspecialchars(urlencode(
            $sBackupFileName));

       $sCurrentWebPath = htmlspecialchars(str_replace(
              $WEBDOCUMENTROOT, '', $sBackupFileName));

       if (file_exists($sBackupFileName))
       {
          $sPageContent = $sPageContent."
            - $sBackupFileName (
             'view' link://$sCurrentWebPath |
             'edit' link://$WEBPADWEBFOLDER/webpad.php?file=$sCurrentPath
                  )";
       } //-- if
    } //-- for

   $sPageContent = $sPageContent."

       ";


   $sPageContent = fnMessageToHtml($sPageContent);

   $sCurrentDirectory = dirname($sFilePath);
   $sPageContent = $sPageContent.
     fnSwitchFileSelect 
       ($sCurrentDirectory, "$WEBPADWEBFOLDER/webpad.php"); 

   $sOutputPage = fnFillWebTemplate(
        $sWebpadTemplateContents, $sPageContent, $sPageTitle);   
   echo $sOutputPage;

//--<--<--<--<--<--<--<--<--<--<--<--<--<--<
?>