Location: PHPKode > scripts > Legacy Files > legacy-files/LegacyFiles.php
<?php
// Author: Mario Haza hide@address.com
// Date: 2004-08-25
// Version: 0.06
// License: Freely Distributable

// Changelog:
// 0.01 initial version
// 0.02 obtain more than 9 fields using ereg
//      obtain the record fields by name or index
// 0.03 validate internal name
// 0.04 validate record count if it's on the header or footer
//      space function
// 0.05 write files
//      trailers
// 0.06 float < 0 bug 

define(FieldName,0);
define(FieldType,1);
define(FieldLength,2);
define(FieldDec,3);

define(ERR_NCI,"Incorrect field name: ");
define(ERR_TCI,"Incorrect field type: ");
define(ERR_LI,"Incorrect lenght: ");
define(ERR_DI,"Incorrect decimal places: ");
define(ERR_AA,"Error trying to open the file: ");
define(ERR_CFE,"Without data on the header");
define(ERR_CFP,"Without data on the footer");
define(ERR_CFC,"Without data on the fields");
define(ERR_DFE,"You have not defined the header format");
define(ERR_DFP,"You have not defined the footer format");
define(ERR_DFC,"You have not defined the fields");
define(ERR_F,"Format error: ");
define(ERR_NOMI,"Error on internal name");
define(ERR_NUMR,"Error on record count");

class LegacyFiles {
var $ExternalName;
var $InternalName;
var $ValidateInternalName;
var $Mode;
var $HasHeader;
var $HasFooter;
var $HeaderDelim;
var $FieldsDelim;
var $FooterDelim;

var $HeaderFormat;
var $FieldsFormat;
var $FooterFormat;

var $HeaderTrailer;
var $FieldsTrailer;
var $FooterTrailer;

var $_rec;
var $_header;
var $_records;
var $_record;
var $_posrec = 0;
var $_numrec = 0;
var $_footer;
var $_errors = array();
var $_file;
var $_content;

// Formats
// Array(field,type,length,decimals)
// field: field name (must begin with a letter, could have numbers)
// type:
//   Y: internal name
//   Z: record count
//   T: trailer
//   A: character (decimals must be zero)
//   N: numeric (decimals must be >= 0)
// length: obligatory, put -1 if it's variable length

function LegacyFiles($External,
                 $Internal="", 
                 $Mode='L', 
                 $Header=true,
                 $Footer=true,
                 $HeaderDelim="",
                 $FieldsDelim=";",
                 $FooterDelim="",
                 $HeaderTrailer=".",
                 $FieldsTrailer=".",
                 $FooterTrailer=".") {
  $this->ExternalName     = $External;
  $this->InternalName     = $Internal;
  $this->Mode             = $Mode;
  $this->HasHeader        = $Header;
  $this->HasFooter        = $Footer;
  $this->HeaderDelim      = $HeaderDelim;
  $this->FieldsDelim      = $FieldsDelim;
  $this->FooterDelim      = $FooterDelim;
  $this->HeaderTrailer    = $HeaderTrailer;
  $this->FieldsTrailer    = $FieldsTrailer;
  $this->FooterTrailer    = $FooterTrailer;
}

function FormatVerify($Format="") {
  if(is_array($Format)) {
    $FtoOK = true;
    for($i=0;$i<count($Format) && $FtoOK;$i++) {
      if(!ereg("^[A-Za-z][A-Za-z0-9]{2,}$",$Format[$i][FieldName])) {
        $FtoOK = false;
        $this->_errors[] = ERR_NCI.$Format[$i][FieldName];
      }
      if(!ereg("^[YZTAN]$",$Format[$i][FieldType])) {
        $FtoOK = false;
        $this->_errors[] = ERR_TCI.$Format[$i][FieldName]." ".$Format[$i][FieldType];
      }
      if(!is_int($Format[$i][FieldLength])) {
        $FtoOK = false;
        $this->_errors[] = ERR_LI.$Format[$i][FieldName]." ".$Format[$i][FieldLength];
      }
      if($Format[$i][FieldType]=="N" && !is_int($Format[$i][FieldDec])) {
        $FtoOK = false;
        $this->_errors[] = ERR_DI.$Format[$i][FieldName]." ".$Format[$i][FieldDec];
      }
    }
    if($FtoOK) {
      return $Format;
    } else {
      return "";
    }
  } else {
    return "";
  }
}

function DefineHeaderFormat($Format="") {
  $Fto = $this->FormatVerify($Format);
  if(is_array($Fto)) {
    $this->HeaderFormat = $Format;
  } else {
    $this->HeaderFormat = "";
    $this->HasHeader = false;
  }
}

function DefineFooterFormat($Format="") {
  $Fto = $this->FormatVerify($Format);
  if(is_array($Fto)) {
    $this->FooterFormat = $Format;
  } else {
    $this->FooterFormat = "";
    $this->HasFooter = false;
  }
}

function DefineFieldsFormat($Format="") {
  $Fto = $this->FormatVerify($Format);
  if(is_array($Fto)) {
    $this->FieldsFormat = $Format;
  } else {
    $this->FieldsFormat = "";
  }
}

function CreateFile() {
  $this->_content = "";
  $this->_header = "";
  $this->_records = "";
  $this->_record = "";
  $this->_footer = "";
  $this->_numrec = 0;
  if($this->HasHeader && !is_array($this->HeaderFormat)) {
    $this->_errors[] = ERR_DFE;
    return false;
  }
  if($this->HasFooter && !is_array($this->FooterFormat)) {
    $this->_errors[] = ERR_DFP;
    return false;
  }
  if(!is_array($this->FieldsFormat)) {
    $this->_errors[] = ERR_DFC;
    return false;
  }
  $this->OpenFile();
  return true;
}

function OpenFile() {
  switch($this->Mode) {
    case 'L': //Lectura
    case 'R': //Read
      $this->_file = fopen($this->ExternalName, 'r');
      break;
    case 'E': //Escritura
    case 'W': //Write
      $this->_file = fopen($this->ExternalName, 'w');
      break;
  }
  if(!$this->_file) {
    $this->_errors[] = ERR_AA.$this->ExternalName;
  }
}

function CloseFile() {
  if($this->_file) {
    fclose($this->_file);
    $this->_file = false;
  }
}

function FormatExpression($Fto,$Delim,$Inicio=0) {
  $expr = "^";
  $cFto = count($Fto);
  for($ci=0;$ci<$cFto;$ci++) {
    if($ci>=$Inicio) $expr .= "(";
    if($Fto[$ci][FieldLength]>0) {
      switch($Fto[$ci][FieldType]) {
        case 'Y':
        case 'A':
        case 'T':
          $expr .= ".{".$Fto[$ci][FieldLength]."}";
          break;
        case 'N':
        case 'Z':
          $enteros=$Fto[$ci][FieldLength];
          $decimales=$Fto[$ci][FieldDec];
          if($decimales>0) {
            $expr .= "[0-9-]{".($enteros -$decimales -1)."}\.[0-9]{".$decimales."}";
          } else {
            $expr .= "[0-9-]{".$enteros."}";
          }
          break;
      }
    } else {
      $expr .= ".*";
    }
    if($ci>=$Inicio) $expr .= ")";
    $c2 = $ci +1;
    if($c2<$cFto && $Fto[$c2][FieldType]!='T')
      $expr .= $Delim;
  }
  $expr .= "$";
  return $expr;
}

function ReadFile() {
  $this->_content = "";
  $this->_header = "";
  $this->_records = "";
  $this->_record = "";
  $this->_footer = "";
  if($this->HasHeader && !is_array($this->HeaderFormat)) {
    $this->_errors[] = ERR_DFE;
    return false;
  }
  if($this->HasFooter && !is_array($this->FooterFormat)) {
    $this->_errors[] = ERR_DFP;
    return false;
  }
  if(!is_array($this->FieldsFormat)) {
    $this->_errors[] = ERR_DFC;
    return false;
  }
  $this->OpenFile();
  if($this->_file) {
    $this->_content = fread($this->_file, filesize($this->ExternalName));
    //echo $this->_content; //debug
  }
  $this->CloseFile();
  if(strlen($this->_content)>0) {
    $this->_content=str_replace("\r","\n",$this->_content);
    $this->_content=ereg_replace("\n{2,}","\n",$this->_content);
    $this->_content=ereg_replace("\n$","",$this->_content);
    $registros = explode("\n",$this->_content);
    $num_records=count($registros);

    $cHeaderFormat=count($this->HeaderFormat);
    $cFooterFormat=count($this->FooterFormat);
    $cFieldsFormat=count($this->FieldsFormat);

    if($num_records>0) {
      $ri=0;
      $this->_header = array();
      if($this->HasHeader) {
        if($cHeaderFormat<=9) {
          $expr = $this->FormatExpression($this->HeaderFormat,$this->HeaderDelim);
          if(ereg($expr,$registros[$ri],$campos)) {
            for($ci=0;$ci<$cHeaderFormat;$ci++) {
              $this->_header[$ci] = $campos[($ci +1)];
            }
          } else {
            $this->_errors[] = ERR_F.$registros[$ri];
          }
        } else {
          $exi=0;
          $encontrado=true;
          $this->_record = array();
          while($exi<$cHeaderFormat && $encontrado) {
            $expr = $this->FormatExpression($this->HeaderFormat,$this->HeaderDelim,$exi);
            $encontrado=ereg($expr,$registros[$ri],$campos);
            if($encontrado)
              for($ci=$exi;$ci<$cHeaderFormat;$ci++) {
                $this->_record[$ci] = $campos[($ci -$exi +1)];
              }
            $exi += 9;
          }
          if($encontrado) {
            for($ci=0;$ci<$cHeaderFormat;$ci++) {
              $this->_header[$ci] = $this->_record[$ci];
            }
          } else {
            $this->_errors[] = ERR_F.$registros[$ri];
          }
        }
        $ri=1;

        if($this->InternalName!="") {
          for($ky=0;$ky<count($this->HeaderFormat);$ky++) {
            if($this->HeaderFormat[$ky][FieldType]=="Y" &&
               $this->HeaderFields($ky)!=$this->InternalName) {
                $this->_errors[] = ERR_NOMI;
                break;
            }
          }
        }

        if(count($this->_errors))
          return false;
      }
      $fin=$num_records;
      $this->_footer = array();

      if($this->HasFooter) {
        $fin--;
        if($cFooterFormat<=9) {
          $expr = $this->FormatExpression($this->FooterFormat,$this->FooterDelim);
          if(ereg($expr,$registros[$fin],$campos)) {
            for($ci=0;$ci<$cFooterFormat;$ci++) {
              $this->_footer[$ci] = $campos[($ci +1)];
            }
          } else {
            $this->_errors[] = ERR_F.$registros[$fin];
          }
        } else {
          $exi = 0;
          $encontrado=true;
          while($exi<$cFooterFormat && $encontrado) {
            $expr = $this->FormatExpression($this->FooterFormat,$this->FooterDelim,$exi);
            $encontrado=ereg($expr,$registros[$fin],$campos);
            if($encontrado)
              for($ci=$exi;$ci<$cFooterFormat;$ci++) {
                $this->_record[$ci] = $campos[($ci -$exi +1)];
              }
            $exi += 9;
          }
          if($encontrado) {
            for($ci=0;$ci<$cFooterFormat;$ci++) {
              $this->_footer[$ci] = $this->_record[$ci];
            }
          } else {
            $this->_errors[] = ERR_F.$registros[$fin];
          }
        }

        if($this->InternalName!="") {
          for($ky=0;$ky<count($this->FooterFormat);$ky++) {
            if($this->FooterFormat[$ky][FieldType]=="Y" &&
               $this->FooterFields($ky)!=$this->InternalName) {
                $this->_errors[] = ERR_NOMI;
                break;
            }
          }
        }

        if(count($this->_errors))
          return false;
      }

      $this->_records = array();
      $ei=0;
      while($ri<$fin) {
        if($cFieldsFormat<=9) {
          $expr = $this->FormatExpression($this->FieldsFormat,$this->FieldsDelim);
          if(ereg($expr,$registros[$ri],$campos)) {
            for($ci=0;$ci<count($this->FieldsFormat);$ci++) {
              $this->_records[$ei][$ci] = $campos[($ci +1)];
            }
            $ei++;
          } else {
            $this->_errors[] = ERR_F.$registros[$ri];
          }
        } else {
          $exi = 0;
          $encontrado=true;
          while($exi<$cFieldsFormat && $encontrado) {
            $expr = $this->FormatExpression($this->FieldsFormat,$this->FieldsDelim,$exi);
            $encontrado=ereg($expr,$registros[$ri],$campos);
            if($encontrado)
              for($ci=$exi;$ci<$cFieldsFormat;$ci++) {
                $this->_record[$ci] = $campos[($ci -$exi +1)];
              }
            $exi += 9;
          }
          if($encontrado) {
            for($ci=0;$ci<$cFieldsFormat;$ci++) {
              $this->_records[$ei][$ci] = $this->_record[$ci];
            }
            $ei++;
          } else {
            $this->_errors[] = ERR_F.$registros[$ri];
          }
        }

        $ri++;
      }
      $this->_numrec=$ei;

      if($this->HasHeader) {
        for($ky=0;$ky<count($this->HeaderFormat);$ky++) {
          if($this->HeaderFormat[$ky][FieldType]=="Z" &&
             intval($this->HeaderFields($ky))!=intval($this->_numrec)) {
              $this->_errors[] = ERR_NOMI;
              break;
          }
        }
      }

      if($this->HasFooter) {
        for($ky=0;$ky<count($this->FooterFormat);$ky++) {
          if($this->FooterFormat[$ky][FieldType]=="Z" &&
             intval($this->FooterFields($ky))!=intval($this->_numrec)) {
              $this->_errors[] = ERR_NOMI;
              break;
          }
        }
      }

    }
    //print_r($this->_header);
    //print_r($this->_records);
    //print_r($this->_footer);
    return true;
  } else {
    $this->_errors[] = ERR_AA.$this->ExternalName;
    return false;
  }
}

function GoNext() {
  $ret = true;
  if($this->_numrec > 0) {
    $this->_posrec++;
    if($this->_posrec >= $this->_numrec) {
      $this->_posrec = $this->_numrec;
      $ret = false;
    }
  } else {
    $ret = false;
  }
  return $ret;
}

function GoPrevious() {
  $ret = true;
  if($this->_numrec > 0) {
    $this->_posrec--;
    if($this->_posrec < 0) {
      $this->_posrec = -1;
      $ret = false;
    }
  } else {
    $ret = false;
  }
  return $ret;
}

function GoTo($pos) {
  $ret = true;
  if($this->_numrec > 0) {
    $this->_posrec = $pos -1;
    if($this->_posrec > $this->_numrec) {
      $this->_posrec = $this->_numrec -1;
      $ret = false;
    }
    if($this->_posrec < 0) {
      $this->_posrec = 0;
      $ret = false;
    }
  } else {
    $ret = false;
  }
  return $ret;
}

function BOF() {
  if($this->_posrec == 0)
    return true;
  else
    return false;
}

function EOF() {
  if($this->_posrec >= $this->_numrec)
    return true;
  else
    return false;
}

function RecNum() {
  if($this->_numrec > 0)
    return $this->_posrec +1;
  else
    return 0;
}

function HeaderFields($col) {
  if(is_string($col)) {
    for($ci=0;$ci<count($this->HeaderFormat);$ci++) {
      if($this->HeaderFormat[$ci][0]==$col) {
        $colx=$ci;
        break;
      }
    }
  } else
    $colx=$col;
  return $this->_header[$colx];
}

function FooterFields($col) {
  if(is_string($col)) {
    for($ci=0;$ci<count($this->FooterFormat);$ci++) {
      if($this->FooterFormat[$ci][0]==$col) {
        $colx=$ci;
        break;
      }
    }
  } else
    $colx=$col;
  return $this->_footer[$colx];
}

function RecordFields($col) {
  if(is_string($col)) {
    for($ci=0;$ci<count($this->FieldsFormat);$ci++) {
      if($this->FieldsFormat[$ci][0]==$col) {
        $colx=$ci;
        break;
      }
    }
  } else
    $colx=$col;
  return $this->_records[$this->_posrec][$colx];
}

function Spaces($num,$sep='') {
  if($sep=='')
    return sprintf("%".$num."s"," ");
  else
    return sprintf("%'".$sep.$num."s",$sep);
}

function ConvertToFormat($Fto,$Datos) {
  $reg = array();
  for($ci=0;$ci<count($Fto);$ci++) {
    if($Fto[$ci][FieldLength]>0) {
      switch($Fto[$ci][FieldType]) {
        case 'Y':
        case 'T':
        case 'A':
          $reg[$ci] = sprintf("%-".$Fto[$ci][FieldLength].".".$Fto[$ci][FieldLength]."s",$Datos[$ci]);
          break;
        case 'Z':
          $reg[$ci] = sprintf("%0".$Fto[$ci][FieldLength]."d",$Datos[$ci]);
          if(strlen($reg[$ci])>$Fto[$ci][FieldLength]) {
            $reg[$ci] = substr($registro[$ci], -1, $Fto[$ci][FieldLength]);
          }
          break;
        case 'N':
          $enteros=$Fto[$ci][FieldLength];
          $decimales=$Fto[$ci][FieldDec];
          if($decimales>0) {
            $reg[$ci] = sprintf("%0".$enteros.".".$decimales."f",$Datos[$ci]);
            if(floatval($Datos[$ci])<1.00)
              $reg[$ci] = substr($reg[$ci], - $Fto[$ci][FieldLength]);
          } else {
            $reg[$ci] = sprintf("%0".$enteros."d",$Datos[$ci]);
          }
          if(strlen($reg[$ci])>$Fto[$ci][FieldLength]) {
            //$reg[$ci] = substr($reg[$ci], - $Fto[$ci][FieldLength]);
            $reg[$ci] = $this->Spaces($Fto[$ci][FieldLength],'#');
          }
          break;
      }
    } else {
      switch($Fto[$ci][FieldType]) {
        case 'Y':
        case 'T':
        case 'A':
          $reg[$ci] = sprintf("%s",$Datos[$ci]);
          break;
        case 'Z':
          $reg[$ci] = sprintf("%d",$Datos[$ci]);
          break;
        case 'N':
          $decimales=$Fto[$ci][FieldDec];
          if($decimales>0) {
            $reg[$ci] = sprintf("%.".$decimales."f",$Datos[$ci]);
          } else {
            $reg[$ci] = sprintf("%d",$Datos[$ci]);
          }
          break;
      }

    }
  }
  return $reg;
}

function AddHeader($encabezado='') {
  if($this->HasHeader) {
    if(!is_array($encabezado)) {
      $this->_errors[] = ERR_CFE;
      $this->CloseFile();
      return false;
    }
    $cHeaderFormat=count($this->HeaderFormat);
    for($ci=0;$ci<$cHeaderFormat;$ci++) {
      if($this->HeaderFormat[$ci][FieldType]=="Z")
        $encabezado[$ci] = $this->_numrec;
      else if($this->HeaderFormat[$ci][FieldType]=="Y" && $this->InternalName!="")
        $encabezado[$ci] = $this->InternalName;
      else if($this->HeaderFormat[$ci][FieldType]=="T")
        $encabezado[$ci] = $this->Spaces($this->HeaderFormat[$ci][FieldLength],$this->HeaderTrailer);
    }
    //print_r($encabezado);

    $this->_header = $this->ConvertToFormat($this->HeaderFormat,$encabezado);
    //print_r($this->_header);
    $contenido_header = "";
    for($ci=0;$ci<$cHeaderFormat;$ci++) {
      $contenido_header .= $this->_header[$ci];
      $c2 = $ci +1;
      if($c2<$cHeaderFormat && $this->HeaderFormat[$c2][FieldType]!='T')
        $contenido_header .= $this->HeaderDelim;
    }
    $contenido_header .= "\n";
    $this->_content = $contenido_header . $this->_content;
  }
  return true;
}

function AddFooter($pie='') {
  if($this->HasFooter) {
    if(!is_array($pie)) {
      $this->_errors[] = ERR_CFP;
      $this->CloseFile();
      return false;
    }
    $cFooterFormat=count($this->FooterFormat);
    for($ci=0;$ci<$cFooterFormat;$ci++) {
      if($this->FooterFormat[$ci][FieldType]=="Z")
        $pie[$ci] = $this->_numrec;
      else if($this->FooterFormat[$ci][FieldType]=="Y" && $this->InternalName!="")
        $pie[$ci] = $this->InternalName;
      else if($this->FooterFormat[$ci][FieldType]=="T")
        $pie[$ci] = $this->Spaces($this->FooterFormat[$ci][FieldLength],$this->FooterTrailer);
    }

    $this->_footer = $this->ConvertToFormat($this->FooterFormat,$pie);
    for($ci=0;$ci<$cFooterFormat;$ci++) {
      $this->_content .= $this->_footer[$ci];
      $c2 = $ci +1;
      if($c2<$cFooterFormat && $this->FooterFormat[$c2][FieldType]!='T')
        $this->_content .= $this->FooterDelim;
    }
    $this->_content .= "\n";
  }
  return true;
}

function AddRecord(& $datos) {
  if(!is_array($datos)) {
    $this->_errors[] = ERR_CFC;
    $this->CloseFile();
    return false;
  }

  $cFieldsFormat=count($this->FieldsFormat);
  for($ci=0;$ci<$cFieldsFormat;$ci++) {
    if($this->FieldsFormat[$ci][FieldType]=="T")
      $datos[$ci] = $this->Spaces($this->FieldsFormat[$ci][FieldLength],$this->FieldsTrailer);
  }

  $this->_record = $this->ConvertToFormat($this->FieldsFormat,$datos);
  $this->_records[] = $this->_record;
  $this->_numrec += 1;

  for($ci=0;$ci<$cFieldsFormat;$ci++) {
    $this->_content .= $this->_record[$ci];
    $c2 = $ci +1;
    if($c2<$cFieldsFormat && $this->FieldsFormat[$c2][FieldType]!='T')
      $this->_content .= $this->FieldsDelim;
  }
  $this->_content .= "\n";

  return true;
}

function WriteFile($datos,$encabezado='',$pie='') {
  $this->_records = '';
  $this->_numrec = 0;
  $this->_posrec = -1;

  if(!is_array($datos)) {
    $this->_errors[] = ERR_CFC;
    $this->CloseFile();
    return false;
  } else {
    $this->_records = array();

    $cregistros = count($datos);
    $this->_posrec = 0;
 
    for($ri=0;$ri<$cregistros;$ri++) {
      if(!$this->AddRecord($datos[$ri])) {
        $this->CloseFile();
        return false;
      }
    }

    if(!$this->AddHeader($encabezado)) {
      $this->CloseFile();
      return false;
    }

    if(!$this->AddFooter($pie)) {
      $this->CloseFile();
      return false;
    }
  }

  fwrite($this->_file, $this->_content);
  $this->CloseFile();
  return true;
}

}
?>
Return current item: Legacy Files