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

  include_once "$LIBRARYPATH/fnStartHtml.php";
  include_once "$LIBRARYPATH/fnRetrovoxStartHtml.php";
  include_once "$LIBRARYPATH/fnJournalToHtml.php";
  include_once "$LIBRARYPATH/fnHyperlinkPlainText.php";
  include_once "$LIBRARYPATH/fnHtmlAsciiMenuItems.php";

  include_once "$LIBRARYPATH/fnSpecialLinkPlainText.php";
  include_once "$LIBRARYPATH/fnDocumentToHtml.php";

  include_once "$LIBRARYPATH/fnSwitchFileSelect.php";
  include_once "$LIBRARYPATH/fnFillWebTemplate.php";

  include_once "$LIBRARYPATH/fnMessageToHtml.php";
  include_once "$LIBRARYPATH/fnListBlockToHtml.php";
  include_once "$LIBRARYPATH/fnCodeBlockToHtml.php";
  include_once "$LIBRARYPATH/fnCodeBlockFromHtml.php";
  include_once "$LIBRARYPATH/fnFaqToHtml.php";
  

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


  $sSelfEditUrl = 
     "/refurb/manage/notepad/retrovox-notepad.php?file=%2Fhome%2Fwaggacwc%2Fpublic_html%2Frefurb%2Fmanage%2Fnotepad%2Fretrovox-notepad-save.php";

  //-- Get the Web-page templates for displaying error messages and 
  //-- result pages.
  $aaTextLines = file($ERRORTEMPLATE);
  $sErrorTemplateContents = implode('', $aaTextLines);

  $aaTextLines = file($ADMINTEMPLATE);
  $sAdminTemplateContents = implode('', $aaTextLines);

  //-- 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);

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

  $sCurrentDirectory = dirname($sFilePath);
  $sCurrentWebDirectory =   
    str_replace("$WEBROOT", '', $sCurrentDirectory);

  $sFileContents = $_POST['fileContents'];

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

  //-- 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));

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


 
  if ($sFilePath == '')
  {

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

      You did not specify any file to be saved.

      This may indicate that the script retrovox-notepad.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 retrovox-notepad.php

      No changes to any text file have been saved.

      'Choose a file to edit' link://retrovox-notepad-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 = "Web Notepad Save: the file doesn't exist";
      $sPageContent = "
          = Web Notepad 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://retrovox-notepad-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 = "Web Notepad Save: the file is not writable";
      $sPageContent = "
          = Web Notepad 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 is probably not your idea
      of recreation to fiddle around with file permissions. 
      In fact you may well not 
      even know what a permission is or how to change it. 
      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 cryptic explanations
      that the post-graduate students at universities like Berkeley 
      have decided 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.
      You may have better luck if you can telnet or ssh into the 
      Web-server.

       
      'Re-enter the file name'
         link://retrovox-notepad-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 = "Web Notepad: the path is a directory";
    $sPageContent = "
          = Web Notepad Save: 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 retrovox-notepad.php or retrovox-notepad-new.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

  //$sBackupFileDirectory =
  //  'c:/apache2/htdocs/ideas/manage/old-data';

  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
  $fileHandler = fopen($sFilePath, "w");
  fwrite($fileHandler, stripslashes($sFileContents));
  fclose($fileHandler);

  $sCleanFileContents = stripslashes($sFileContents);

  $sPageTitle = "$sFileName saved (Notepad)";
  $sPageContent = $sPageContent. "
         = $sFileName saved (Notepad)


      [ascii-menu-item:admin]
      [ascii-menu-item:browse-folders]
      [ascii-menu-item:search]
      [ascii-menu-item:copy-file]
      [ascii-menu-item:view-file-lines]
      [ascii-menu-item:web-edit]
      [ascii-menu-item:file-edit]
      text-icon:web-view 
      link://$sFileWebPath?".rand(1,999)." 



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

    Further actions:

    u--
      [ascii-menu-item:admin]
      Administration Home
     -
      [ascii-menu-item:browse-folders]
      Jump to a different folder
     -
      [ascii-menu-item:search]
      Find a file on the server
     -
      [ascii-menu-item:copy-file]
      Copy or rename this file
     -
      [ascii-menu-item:view-file-lines]
      View this file with line numbers
     - 
      [ascii-menu-item:file-edit]
      Continue editing the same file
      ( 'In a new window' 
        !link://retrovox-notepad.php?file=$sFilePathEncoded )
     -
      [ascii-menu-item:web-edit]
      Edit file with the WEBPAD editor
     -
      'Edit a different or new file'
        link://retrovox-notepad-choose-file.php?file=$sFilePathUrlEncoded
     -
      text-icon:web-view
      link://$sFileWebPath?".rand(1,999)."
      View the file as a web-page
      ( 'In a new window' !link://$sFileWebPath?".rand(1,999)." )
     -
      'Undo last file change'
     link://$MANAGEMENTWEBFOLDER/undo-file-change.php?file=$sFilePathUrlEncoded
     -
      'View File Source'
      link:///get-source.php?file=$sFilePathUrlEncoded
     

     The following backup files for this text file currently exist


     1-";

    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://$NOTEPADWEBFOLDER/retrovox-notepad.php?file=$sCurrentPath
             )";
       } //-- if
    } //-- for


    $sPageContent = $sPageContent."
          
    '(!)' link:///refurb/manage/notepad/retrovox-notepad.php?file=/home/waggacwc/public_html/refurb/manage/notepad/retrovox-notepad-save.php      

           ";



   $sPageContent = fnMessageToHtml($sPageContent);
 
   $sCurrentDirectory = dirname($sFilePath);
   $sPageContent = $sPageContent.fnSwitchFileSelect($sCurrentDirectory, "$NOTEPADWEBFOLDER/retrovox-notepad.php"); 

   $sOutputPage = fnFillWebTemplate(
      $sAdminTemplateContents, $sPageContent, $sPageTitle);   

   $sOutputPage = fnHtmlAsciiMenuItems(
     $sOutputPage, $sFilePath, 
     $MANAGEMENTWEBFOLDER,
     $WEBPADWEBFOLDER);

   echo $sOutputPage;

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