<?php
// Xinfeng Chen, 2002.07.08, 2002.10.29
class CBaseArrayFile {
 var $_rawlist=array(), $_iptr=0, $_size=0;

 function _explodeRecord($a_line){}
 // Implemeted by descendant, Return: NONE
 function _composeRecord($a_line){}
 // Implemeted by descendant, Return composed line as $a_line
 function _compareRecord($a_key){die("NOT IMPLEMENTED");}
 // Implemeted by descendant, Return: true/false

 function reset(){
  $this->_rawlist=array();
  $this->_iptr=$this->_size=0;
  $this->_explodeRecord('');
 }

 function readFile($a_filename){
  if(file_exists($a_filename)){
   $this->_rawlist=@file($a_filename);
   foreach($this->_rawlist as $key=>$value){$this->_rawlist[$key]=chop($value);}
  }else{
   $this->_rawlist=array();
  }
  $this->_size=count($this->_rawlist);
  return $this->moveto(0);
 }

 function writeFile($a_filename){
  $this->update();

  if(!($TMP=fopen($a_filename,"w"))){return false;}
  foreach($this->_rawlist as $item){fwrite($TMP,"$item\n");}
  fclose($TMP);
  chmod($a_filename, 0660);
  return true;
 }

 function createFile($a_filename){ $this->reset(); return true; }

 function destroyFile($a_filename){
  if(!is_file($a_filename)){return false;}
  return unlink($a_filename);
 }

 function itemCount() {return $this->_size;}

 function moveTo($a_idx) {
  if($a_idx >= $this->_size || $a_idx <0) return false;

  $this->_iptr = $a_idx;
  $line=$this->_rawlist[$a_idx];
  $this->_explodeRecord(&$line);
  return ($line != "");
 }

 function moveNext() {
  return $this->moveTo($this->_iptr+1);
 }

 function appendNew() {
  $this->_rawlist[]=""; $this->_size++;
  $this->moveTo($this->_size-1);
 }

 function insertNew() {
  array_unshift($this->_rawlist, ""); $this->_size++;
  $this->moveTo(0);
 }

 function update() {
  if($this->_iptr>=0 && $this->_iptr < $this->_size) {
   $this->_composeRecord(&$this->_rawlist[$this->_iptr]);
  }
 }

 function find($a_key) {
  for($i=0; $i<$this->_size; $i++) {
   $this->moveto($i);
   if($this->_compareRecord($a_key)) {return true;}
  }
  return false;
 }

 function delete() {
  $ptr=$this->_iptr;
  if($ptr >=0 && $ptr < $this->_size) {
   array_splice($this->_rawlist, $ptr, 1); $this->_size--;
   $this->moveTo($ptr);
   return true;
  }
  return false;
 }
}

?>