<?php
//  modify instrument files
// todo value refer to the following
// 2: instrument descirptor
// 21: session descriptor
// 56: list of customJoin files
// 6: session allowed user file
// 60: instrument allowed user file
// 61: instrument reference
// 62: session reference
// 71: instrument general
// 72: session general
// 721: session scenario
// 81: delete instrument dir
// 91:  modify instrument specific documentaiton text file
// 923:  delete instrument scneario files
// 9231:  delete instrument scneario file
// 925:  restore inst file
// 1011 : save modules file

// note: the following are used in createWizard.htm
//var postReferenceData='todo=61';
//var postGeneralData='todo=71';
//var postDescText='todo=91';
// todo=2 : modify instrument descriptor
header("Content-Type: text/plain");

require("../phpVars.php");

 $svydir='';
 $rootdir=$_SERVER['DOCUMENT_ROOT'];
 $dsvydir=$rootdir.'dSurvey/';
 $admins_dir=$dsvydir.'admins/';
 $instruments_dir=$dsvydir.'instruments/';
 $instruments_dir0=$dsvydir.'instruments';

 $break = Explode('/',$_SERVER['SCRIPT_NAME']);
 $myScriptName = $break[count($break) - 1];

 $todo=extractRequestVar('TODO','','No TODO in doModify');


 if ($todo=='2') {                             // modify descriptor file
   $aname=extractRequestVar('FILE','','No FILE in doModify');
   $newfile=$instruments_dir.$aname;
   $overwrite=extractRequestVar('OVERWRITE','0','');
    if ($overwrite!=='1') {
       if (file_exists($newfile)) {
         print "Sorry. $newfile already exists " ;
         return 0;
    }
   }
    $content=extractRequestVar('CONTENT','0','');

    $fnum=fopen($newfile,'w');
    if (!$fnum) {
      print "- Error Unable to open (for writing) file: $newfile ";
      return 0 ;
    }
    if (!fwrite($fnum,$content)) {
         print "- Error  Unable to write to file: $newfile ";
          return 0 ;
     }
     print 'ok. File created: ' . $newfile ;
     fclose($fnum);
     return 0 ;
 }

 if ($todo=='21') {                             // modify descriptor file(session)
   $aname=extractRequestVar('FILE','','No FILE in doModify');
   $newfile=$sessions_dir.$aname;
   $overwrite=extractRequestVar('OVERWRITE','0','');
    if ($overwrite!=='1') {
       if (file_exists($newfile)) {
         print "Sorry. $newfile already exists " ;
         return 0;
    }
   }
    $content=extractRequestVar('CONTENT','0','');

    $fnum=fopen($newfile,'w');
    if (!$fnum) {
      print "- Error Unable to open (for writing) file: $newfile ";
      return 0 ;
    }
    if (!fwrite($fnum,$content)) {
         print "- Error  Unable to write to file: $newfile ";
          return 0 ;
     }
     print 'ok. session descriptor file created: ' . $newfile ;
     fclose($fnum);
     return 0 ;
 }

   if ($todo=='56') {                             //   list of customJoin
       $getem=$admins_dir.'customJoin' ;
       $dir=opendir($getem);
       $dlist='';
       while (!($filename= readdir($dir)) === FALSE) {
          if (!is_dir($admins_dir.'/customJoin/'. $filename)) {
                   $apath=pathinfo($filename);
                   $aext2=strtoupper($apath['extension']);
                   if ($aext2=='XML') {
                         $dlist=$dlist.' '.$filename;
                   }
          }
        }
        print $dlist ;
        return 0 ;
   }

  if ($todo=='6') {                             //   session allowedUsers file
    $aname=extractRequestVar('NAME','','No NAME in doModify');
    $content=extractRequestVar('CONTENT','','NO CONTENT in doModify');
    $newfile=$sessions_dir.$aname.'/allowedUsers.xml'     ;
    $fnum=fopen($newfile,'w');
    if (!$fnum) {
      print "- Error Unable to open (for writing) file: $newfile ";
      return 0 ;
    }
    if (!fwrite($fnum,$content)) {
         print "- Error  Unable to write to file: $newfile ";
          return 0 ;
     }
     print 'ok. a session allowedUsers file created: ' . $newfile ;
     fclose($fnum);
     return 0 ;
  }

  if ($todo=='60') {                             //   instrument allowedUsers file
    $aname=extractRequestVar('NAME','','No NAME in doModify');
    $content=extractRequestVar('CONTENT','','NO CONTENT in doModify');
    $newfile=$instruments_dir.$aname.'/allowedUsers.xml'     ;
    $fnum=fopen($newfile,'w');
    if (!$fnum) {
      print "- Error Unable to open (for writing) file: $newfile ";
      return 0 ;
    }
    if (!fwrite($fnum,$content)) {
         print "- Error  Unable to write to file: $newfile ";
          return 0 ;
     }
     print 'ok. an instruments allowedUsers file created: ' . $newfile ;
     fclose($fnum);
     return 0 ;
  }



  if ($todo=='61') {                             //   reference data (instrument specific

     $aname=extractRequestVar('NAME','','No NAME in doModify');
     $newfile=$instruments_dir.$aname.'\reference.xml' ;
     $stuff=extractRequestVar('CONTENT','','No CONTENT in doModify');   // will be return unescaped
    $fnum=fopen($newfile,'w');
     if (!$fnum) {
        print "- Error Unable to open (for writing) file: $newfile ";
        return 0 ;
     }
     if (!fwrite($fnum,$stuff)) {
         print "- Error  Unable to write to file: $newfile ";
         return 0 ;
     }
     print 'ok. File created: ' . $newfile ;
     fclose($fnum);
     return 0 ;
  }


  if ($todo=='62') {                             //   reference data (session specific
    $aname=extractRequestVar('NAME','','No NAME in doModify');
    $content=extractRequestVar('CONTENT','','NO CONTENT in doModify');
    $newfile=$sessions_dir.$aname.'/reference.xml'     ;
    $fnum=fopen($newfile,'w');
    if (!$fnum) {
      print "- Error Unable to open (for writing) file: $newfile ";
      return 0 ;
    }
    if (!fwrite($fnum,$content)) {
         print "- Error  Unable to write to file: $newfile ";
          return 0 ;
     }
     print 'ok. a session reference file created: ' . $newfile ;
     fclose($fnum);
     return 0 ;
  }


   if ($todo=='71' ) {                   /* modify instrument specific general data file */
      $aname=extractRequestVar('NAME','','No NAME in doModify');
      $newfile=$instruments_dir.$aname.'/params.xml' ;
      $stuff=extractRequestVar('CONTENT','','No CONTENT in doModify');   // will be return unescaped

      $fnum=fopen($newfile,'w');
      if (!$fnum) {
        print "- Error Unable to open (for writing) file: $newfile ";
        return 0 ;
      }
      if (!fwrite($fnum,$stuff)) {
         print "- Error  Unable to write to file: $newfile ";
         return 0 ;
      }
      print 'ok. File created: ' . $newfile ;
      fclose($fnum);
      return 0 ;
  }

  if ($todo=='72') {                             //   general data (session specific
    $aname=extractRequestVar('NAME','','No NAME in doModify');
    $content=extractRequestVar('CONTENT','','NO CONTENT in doModify');
    $newfile=$sessions_dir.$aname.'/params.xml'     ;
    $fnum=fopen($newfile,'w');
    if (!$fnum) {
      print "- Error Unable to open (for writing) file: $newfile ";
      return 0 ;
    }
    if (!fwrite($fnum,$content)) {
         print "- Error  Unable to write to file: $newfile ";
          return 0 ;
     }
     print 'ok. a session params file created: ' . $newfile ;
     fclose($fnum);
     return 0 ;
  }

 if ($todo=='721') {                             //   scenaril file (session specific
    $aname=extractRequestVar('NAME','','No NAME in doModify');
    $scname=extractRequestVar('SCNAME','','No SCNAME in doModify');
    $content=extractRequestVar('CONTENT','','NO CONTENT in doModify');
    $newfile=$sessions_dir.$aname.'/'.$scname.'.xml';
    $fnum=fopen($newfile,'w');
    if (!$fnum) {
      print "- Error Unable to open (for writing) file: $newfile ";
      return 0 ;
    }
    if (!fwrite($fnum,$content)) {
         print "- Error  Unable to write to file: $newfile ";
          return 0 ;
     }
     print 'ok. a session scenario file created: ' . $newfile ;
     fclose($fnum);
     return 0 ;
  }

  if ($todo=='81'){              /* delete instrument directory */

    $aname=extractRequestVar('NAME','','No NAME in doModify');
    $astat='Deleted files: ' ;

    $instFile=$instruments_dir.$aname.'.xml' ;
    if (!file_exists($instFile)) {
       $astat=$astat. " Note: No such descriptor file:  $instFile";
    } else {
       $astat=$astat.' '.$instFile ;
       $bstat=unlink($instFile);
       if (!$bstat) {
             print "Sorry. Unable to delete file: $instFile ";
            exit ;
       }
    }

    $aa=$instruments_dir.$aname.'/' ;
    if (!file_exists($aa)) {
       print "Sorry. No such  directory: $aa  ";
       exit ;
    }
    $stuff= killDir($aa,0) ;
    print  "OK  : $astat  <br /> \n $stuff ";
    return 0 ;
  }

  if ($todo=='91'){              /* modify instrument specific documentaiton text file */
      $aname=extractRequestVar('NAME','','No NAME in doModify');
      $newfile=$instruments_dir.$aname.'/describe.txt' ;

      $stuff=extractRequestVar('CONTENT','','No CONTENT in doModify');   // will be return unescaped
      $fnum=fopen($newfile,'w');
      if (!$fnum) {
        print "- Error Unable to open (for writing) file: $newfile ";
        return 0 ;
      }
      if (!fwrite($fnum,$stuff)) {
         print "- Error  Unable to write to file: $newfile ";
         return 0 ;
      }
      print 'ok. File created: ' . $newfile ;
      fclose($fnum);
      return 0 ;
  }

  if ($todo=='923'){              /* delete instrument scneario files */
      $stuff='';
      $aname=extractRequestVar('NAME','','No NAME in doModify');
      $flist=extractRequestVar('FILE','','No FILE in doModify');
      $flist2=explode(' ',$flist);
      for ($i=0 ; $i<count($flist2) ; $i++) {
          $afile=trim($flist2[$i]);
          if ($afile=='')   continue ;
          $afile=$instruments_dir.$aname.'/'.$afile   ;
          IF(UNLINK($afile)) {
               $stuff .= $afile . ' ' ;
          }  else {
               $stuff = 'Problem: ' . $stuff . ' <br /> unable to delete ' . $afile    ;
               return $amess ;
          }
     }

      print $stuff;
      return 0;
 }

 if ($todo=='921'){              /*  return list of files in specs and modules directories of  instrument */
      $aname=extractRequestVar('NAME','','No NAME in doModify');
      $aext=extractRequestVar('EXT','','');
      $aext=strtoupper($aext);
      $dlist=''   ;
      $igot=0 ;

// instname/specs/
      $getem=$instruments_dir.$aname.'/specs'  ;
      $dir=opendir($getem);
      while (!($filename= readdir($dir)) === FALSE) {
          if (!is_dir($instruments_dir.$aname.'/specs/'. $filename)) {
               if ($aext!=='') {
                   $apath=pathinfo($filename);
                   $aext2=$apath['extension'];
                   if (strtoupper($aext2)==$aext)  {
                      $dlist=$dlist.' specs/'.$filename;
                      $igot++ ;
                   }
                } else {
                    $dlist=$dlist.' specs/'.$filename;
                    $igot++ ;
                }
          }
      }
      closedir($dir);

// instname/modules/
      $getem=$instruments_dir.$aname.'/modules'  ;
      $dir=opendir($getem);
      while (!($filename= readdir($dir)) === FALSE) {
          if (!is_dir($instruments_dir.$aname.'/modules/'. $filename)) {
               if ($aext!=='') {
                   $apath=pathinfo($filename);
                   $aext2=$apath['extension'];
                   if (strtoupper($aext2)==$aext)  {
                      $dlist=$dlist.' modules/'.$filename;
                      $igot++ ;
                   }
                } else {
                    $dlist=$dlist.' modules/'.$filename;
                    $igot++ ;
                }
          }
      }
      closedir($dir);

// instname/aname/*.xml
      $getem=$instruments_dir.$aname.'/'  ;
      $dir=opendir($getem);
      while (!($filename= readdir($dir)) === FALSE) {
          if (!is_dir($instruments_dir.$aname.'/'. $filename)) {
               if ($aext!=='') {
                   $apath=pathinfo($filename);
                   $aext2=$apath['extension'];
                   if (strtoupper($aext2)==$aext)  {
                      $dlist=$dlist.' ./'. $filename;
                      $igot++ ;
                   }
                } else {
                    $dlist=$dlist.' ./'. $filename;
                    $igot++ ;
                }
          }
      }
      closedir($dir);


// instname/lib/*.js
      $aext='JS';
      $getem=$instruments_dir.$aname.'/lib'  ;
      $dir=opendir($getem);
      while (!($filename= readdir($dir)) === FALSE) {
          if (!is_dir($instruments_dir.$aname.'/lib/'. $filename)) {
               if ($aext!=='') {
                   $apath=pathinfo($filename);
                   $aext2=$apath['extension'];
                   if (strtoupper($aext2)==$aext)  {
                      $dlist=$dlist.' lib/'.$filename;
                      $igot++ ;
                   }
                } else {
                    $dlist=$dlist.' lib/'.$filename;
                    $igot++ ;
                }
          }
      }
      closedir($dir);

// instname/lib/*.css
      $aext='CSS';
      $getem=$instruments_dir.$aname.'/lib'  ;
      $dir=opendir($getem);
      while (!($filename= readdir($dir)) === FALSE) {
          if (!is_dir($instruments_dir.$aname.'/lib/'. $filename)) {
               if ($aext!=='') {
                   $apath=pathinfo($filename);
                   $aext2=$apath['extension'];
                   if (strtoupper($aext2)==$aext)  {
                      $dlist=$dlist.' lib/'.$filename;
                      $igot++ ;
                   }
                } else {
                    $dlist=$dlist.' lib/'.$filename;
                    $igot++ ;
                }
          }
      }
      closedir($dir);




      print $igot.' '.$dlist;
      return 0;

  }

  if ($todo=='9231'){              /* delete inst file*/
       $aname=extractRequestVar('NAME','','No NAME in doModify');
      $afile=extractRequestVar('FILE','','No FILE in doModify');
      $fromfile=$instruments_dir.$aname.'/'.$afile   ;
      $qq=unlihnk($fromfile);
      if ($qq) {
        print "ok. $fromfile deleted ";
      } else {
        print "-Error. Unable to delete $fromfile ";
      }
      return 0 ;
  }

  if ($todo=='925'){              /* restore inst file*/
      $aname=extractRequestVar('NAME','','No NAME in doModify');
      $afile=extractRequestVar('FILE','','No FILE in doModify');
      $adest=extractRequestVar('DEST','','No DESTin doModify');
      $fromfile=$instruments_dir.$aname.'/'.$afile   ;
      $tofile=$instruments_dir.$aname.'/'.$adest   ;
      $qq=copy($fromfile,$tofile);
      if ($qq) {
        print "ok. $fromfile copied to $tofile ";
      } else {
        print "-Error. Unable to copy $fromfile to $tofile ";
      }
      return 0 ;
  }

  if ($todo=='1011'){              /* save modules file */
    $aname=extractRequestVar('NAME','','No NAME in doModify');
    $content=extractRequestVar('CONTENT','','NO CONTENT in doModify');
    $newfile=$instruments_dir.$aname.'/modules/modules1.xml';
    $fnum=fopen($newfile,'w');
    if (!$fnum) {
      print "- Error Unable to open (for writing) file: $newfile ";
      return 0 ;
    }
    if (!fwrite($fnum,$content)) {
         print "- Error  Unable to write to file: $newfile ";
          return 0 ;
     }
     print 'ok. modules file file created: ' . $newfile ;
     fclose($fnum);
     return 0 ;
  }

  if ($todo=='1022'){              /* save temp file for verification testing */
      $aname=extractRequestVar('NAME','','No NAME in doModify');
      $newfile=$instruments_dir.$aname.'/specs/$verify.xml' ;
      $stuff=extractRequestVar('CONTENT','','No CONTENT in doModify');   // will be return unescaped
      $fnum=fopen($newfile,'w');
      if (!$fnum) {
        print "- Error Unable to open (for writing) file: $newfile ";
        return 0 ;
      }
      if (!fwrite($fnum,$stuff)) {
         print "- Error  Unable to write to file: $newfile ";
         return 0 ;
      }
      print 'ok. Verification file created: ' . $newfile ;
      fclose($fnum);
      return 0 ;

 }

  print '-error: no such todo ' . $todo ;
  return 0;

//==========================================
// (this is adapated from http://psoug.org/snippet/Delete_all_files_in_directory_34.htm
// kill a directory (first delete files, and subdirectories
// note: will NOT delete subdirectoreis of subdirecotires

FUNCTION killDir($path,$afake) {

  $debugStr = '';                 // init the debug string
   if ($afake==1) {
       $debugStr .= "  File/directories that WOULD BE deleted from $path = ";
   } else {
        $debugStr .= "  File/directories deleted from $path = ";
   }

  $handle = OPENDIR($path) ;
  if (!$handle) {
     $amess='Problem: ' . $debugStr . ' <br /> unable to  open ' . $path    ;
     return $amess ;
  }

// parse through all files/dirs ....
  WHILE (FALSE !== ($file = READDIR($handle))) {
     IF ($file == "." || $file == "..") continue ;              //  skip?

     IF(IS_FILE($path."/".$file)) {
             if ($afake==1) {
                 $debugStr .= $file . ' ' ;
             } else {
                 IF(UNLINK($path."/".$file)) {
                      $debugStr .= $file . ' ' ;
                 }  else {
                   $amess='Problem: ' . $debugStr . ' <br /> unable to delete ' . $file    ;
                   return $amess ;
                 }
             }

     } ELSE {                    // It's a directory...crawl through the directory and delete the contents

         $handle2 = OPENDIR($path."/".$file) ;
         if (!$handle2) {
                $amess="Problem:  $debugStr  <br /> Unable to  open  $path  \/  $file "   ;
                return $amess ;
         }
         WHILE (FALSE !== ($file2 = READDIR($handle2))) {
              IF ($file2 == "." || $file2 == "..") continue ;
              if ($afake==1) {
                               $debugStr .=  $file.'/'.$file2 . ' ' ;
               } else {
                       IF(UNLINK($path."/".$file."/".$file2)) {
                              $debugStr .=  $file.'/'.$file2 . ' ' ;
                       }  else {
                              return 'Problem: ' . $debugStr . '  <br /> Could not delete '. $path.'/'.$file.'/'.$file2 ;
                      }
               }               // afake unlink
         }                             // all $file2 in $handle2
         closedir($handle2) ;

         if ($afake==1) {
                 $debugStr .= ' [dir : '.$file. ' ]';
         } else {
                 IF(RMDIR($path."/".$file)) {
                    $debugStr .= ' [dir : ' .$file. ' ]' ;
                 }  else {
                    return 'Problem: ' . $debugStr . '  <br />Could not rmDir '. $path.'/'.$file.'/' ;
                }
         }             // remove subdirectory
      }                          // a subdir of $path

  }                       // $file in $handle

 closedir($handle) ;

 if ($afake==1) {
          $debugStr .= " :: NOT ACTUALLY removed  ".$path  ;
 } else {
       IF(RMDIR($path)) {                       // and remove the actual directory
             $debugStr .= " :: <br /> Sucesss: removed  ".$path  ;
      }  else {
          return $debugStr . ' :: <br /> Problem: could not remove session directory: ' . $path ;
      }
 }
 RETURN $debugStr;

}


?>