Subversion Repositories computer_asset_manager_v2

Rev

Rev 70 | Rev 77 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed

<?php

   class Camp {
      protected static $dbStructure;
      
      /**
       * Builds an instance and loads data from database
       * 
       * #parameter int $id The id of the record to load
       */
      public function __construct( $id = 0 ) {
         if ( $id ) {
            $this->loadFromDB( $id );
            $_SESSION['workingon'][get_called_class()] = $id;
         }
      } // __construct
      
      public function loadFromDB( $id ) {
         //print "<pre>Loading from DB\nClass = " . get_called_class() . "\nID = $id\n</pre>";
         global $dbConnection;

         $this->data = array();
         $fields = array();
         $calculatedFields = array();
         foreach ( static::$dbStructure['table']['fields'] as $key => $data ) {
            switch ( $data['type'] ) {
               case '1:1H' : // one to one with history
                  $calculatedFields[$key] = $data;
                  break;
               case '1:M' : // one to many
                  $calculatedFields[$key] = $data;
                  break;
               default: // standard
                  $fields[] = $data['fieldname'];
            }
         }
         $query = sprintf( "select %s from %s where %s = %s",
            implode( ',', $fields ),
            static::$dbStructure['table']['tableName'],
            static::$dbStructure['table']['primaryKey'],
            $id
         );
         //print "<pre> Constructor using query\n$query</pre>";
         //print "<pre>Constructor finding dbstructure of\n" . print_r( static::$dbStructure, true) . '</pre>';
         if ( ( $this->data = $dbConnection->getOneRow( $query ) ) === false )
            print DBQuery::error2String();
         
         // note, we had to wait to do the calculated fields since they needed the primary key from this record
         foreach ( $calculatedFields as $key => $data ) {
            switch ( $data['type'] ) {
               case '1:1H' : // one to one with history
                  $this->data[$key] = $this->oneToOneHistoryLoad( $data );
                  break;
               case '1:M' : // one to many
                  $this->data[$key] = $this->oneToManyLoad( $data );
                  break;
               default:
                  print "<pre>Error, I do not know how to load calculated field type $data[type]</pre>";
            } // switch
         } // foreach
         //print "<pre>Data after loadFromDB\n" . print_r($this->data, true) . "</pre>"; die;
      } // loadFromDB
      
      /**
       * gets the contents of $fieldname
       * 
       * @parameter string $fieldname name of the database field to retrieve
       * 
       * @return string The value of $fieldname stored in structure
       */
      public function __get( $fieldname ) {
         if ( empty( $this->data ) )
            $this->data = array();
         return 
            isset( $this->data[static::$dbStructure['table']['fields'][$fieldname]['fieldname']] ) ?
               $this->data[static::$dbStructure['table']['fields'][$fieldname]['fieldname']] :
               null;
      } // __get
      

      /**
       * Gets stats for an extended class.
       * 
       * Gets number of active and inactive rows for a class, using the
       * view ($viewName)
       * 
       * @return int[] array of integers which is a count
       */
      public static function getStats () {
         global $dbConnection;
         global $activeOnly;
         
         $return = array();
         $restrictions = array();
         $trueClass = get_called_class();
         $saveActive = $activeOnly;
         $activeOnly = false;
/*         
         $query = sprintf( 
            'select count(*) num,isnull(removed) active from %s %s group by isnull(removed) order by isnull(removed) desc',
            static::$dbStructure['table']['tableName'],  
            self::makeWhereClause()
         );
         $result = $dbConnection->doSQL( $query );
         foreach ( $result['returnData'] as $row ) {
            if ( $row['active'] == 1 ) {
               $return['active'] = $row['num'];
            } elseif ( $row['active'] == 0 ) {
               $return['inactive'] = $row['num'];
            }
         }
*/
         if ( isset( static::$dbStructure['table']['inactiveField'] ) ) {
            $return['active'] = 0;
            $return['inactive'] = 0;
            $query = sprintf(
               'select count(*) num, isnull(%s) active from %s %s group by isnull(%s) order by isnull(%s) desc',
               static::$dbStructure['table']['inactiveField'],
               static::$dbStructure['table']['tableName'],
               self::makeWhereClause(),
               static::$dbStructure['table']['inactiveField'],
               static::$dbStructure['table']['inactiveField']
               );
            //print "<pre>Getting Active\n$query</pre>"; die;
            $activeOnly = $saveActive;
            $result = $dbConnection->doSQL( $query );
            foreach ( $result['returnData'] as $row ) {
               if ( $row['active'] == 1 ) {
                  $return['active'] = $row['num'];
               } elseif ( $row['active'] == 0 ) {
                  $return['inactive'] = $row['num'];
               }
            }
         } else {
            $query = sprintf(
               'select count(*) num from %s %s',
               static::$dbStructure['table']['tableName'],
               self::makeWhereClause()
               );
            $return['total'] = $dbConnection->getOneDBValue( $query );
         }


         /*
         $active = sprintf( 
            'select count(%s) from %s %s', 
            static::$dbStructure['table']['primaryKey'],  
            static::$dbStructure['table']['tableName'], 
            self::makeWhereClause() 
         );
         
         $activeOnly = false;
         $inactive = sprintf( 
            'select count(%s) from %s  %s', 
            static::$dbStructure['table']['primaryKey'],  
            static::$dbStructure['table']['tableName'], 
            self::makeWhereClause( "removed is not null" ) )
         );
         
         //print "<pre>Active\n$active</pre><pre>Inactive\n$inactive</pre>"; die;
         
         $return['active'] = $dbConnection->getOneDBValue( $active );
         $return['inactive'] = $dbConnection->getOneDBValue( $inactive );
         */

         $activeOnly = $saveActive;
         return $return;
      }
      
      /**
       * Creates a where clause
       * 
       * Merges $restrictions with any restrictions which may be in place
       * for the current user. Also sets 'class_removed is null' if
       * $activeOnly (global) is set
       * 
       * @parameter string[] $restrictions array of conditionals
       * 
       * @return string all restricions ANDED together
       */
      public static function makeWhereClause( $restrictions = array(), $restrictGlobals = array(), $tablename = null ) {
         global $activeOnly;
         
         //print "<pre>" . print_r( $restrictions, true ) . "</pre>";

         $trueClass = get_called_class();
         foreach ( $_SESSION['restrictions'][$trueClass] as $restriction ) {
            $restrictions[] = $restriction;
         }
         if ( $activeOnly && isset( $trueClass::$dbStructure['table']['inactiveField'] ) ) {
            $restrictions[] = $trueClass::$dbStructure['table']['inactiveField'] .  ' is null';
         }
         /*
         if ( isset( $restrictGlobals['workingon'] ) && isset( $_SESSION['workingon'] ) ) {
            foreach ( $_SESSION['workingon'] as $class => $id ) {
               $restrictions[] = strtolower( $class ) . "_id = $id";
            }
         }
         */
         return count( $restrictions ) ? 'where ' . implode( ' and ', $restrictions ) : '';
      } //
      
      /**
       * Creates a list of all records for a particular class and returns
       * a UL with all LI's set as links (A's) to displaying a record.
       * 
       * @parameter string[] $filter array of conditionals to limit if $list not set
       * @parameter string[] $list An optional list of data to be displayed
       * 
       * @return string A UL with each LI containing a link to an entry
       */
      public static function showSelectionList( $filter = array(), $list = array(), $noAdd = false ) {
         global $url;
         $return = array();
         $module = get_called_class();
         unset ( $_SESSION['workingon'][$module] );
         if ( empty( $list ) ) {
            $list = self::getAll( $filter );
         }
         //print "<pre>showSelectionList\n" . print_r( $list, true ) . "</pre>"; die;
         foreach ( $list as $id => $name ) {
            if ( $id )
               $return[] = "<a href='$url?module=$module&id=$id'>$name</a>";
         }
         //print "<pre>noadd is $noAdd</pre>"; die;
         if ( ! $noAdd && $_SESSION['user']->isAuthorized( strtolower($module) . '_add') )
            $return[] = "<br /><a href='$url?module=$module&action=add'>Add New</a>";
         return count($return) ? "<ul>\n<li>" . implode( "</li>\n<li>", $return ) . "</li>\n</ul>" : '';
      }
      
      /**
       * Gets all matching rows
       * 
       * Does an SQL call to retrieve ID and Name for all rows matching
       * $filter and $_REQUEST['to_find'].
       * 
       * @parameter string[] $filter Optional list of conditionals for where clause
       * 
       * @return array[] An array of indexes and names matching query
       */
      public static function getAll( $filter = array(), $restrictGlobals = array() ) {
         global $activeOnly;
         global $dbConnection;
         
         //print "<pre>" . print_r( $filter, true ) . "</pre>";
         if ( isset( $_REQUEST['to_find'] ) ) {
            $filter[] = sprintf( " %s like '%%%s%%'", static::$dbStructure['table']['selectionDisplay'],  $_REQUEST['to_find']) ;
         }
         $return = array();
         $query = sprintf( 'select %s id, %s name from %s %s', 
               static::$dbStructure['table']['primaryKey'],
               static::$dbStructure['table']['selectionDisplay'],
               static::$dbStructure['table']['tableName'],
               self::makeWhereClause( $filter, $restrictGlobals )
               );
         $query .= " order by " . static::$dbStructure['table']['selectionDisplay'];
         //print "<pre>$query</pre>\n";
         $return = $dbConnection->queryToKeyedArray( $query );
         return $return;
      }
      
      /**
       * Returns the "name" of an instance
       * 
       * Normally, this is $this->name, but some classes may want to put
       * in additional data
       * 
       * @return string Display name of this instance
       */
      public function __toString() {
         return $this->name;
      }
      
      /**
       * Returns an HTML structure which can display a record
       * 
       * Note that if the instance has children, they will be displayed 
       * also. Additionally, if it has fields marked as type 'calculated'
       * it will perform the limited calculations.
       * 
       * @return string HTML to display record
       */
      public function display() {
         //print "<pre>In Display\n" . print_r( $this->data, true) . '</pre>'; die;
         global $dbConnection;
         global $url;
         $return = array();
         $save = '';
         
         /* get the records for this, including from other tables */
         foreach ( static::$dbStructure['table']['fields'] as $key => $record ) {
            if ( isset( $record['display'] ) && $record['display'] === false ) // we don't try to show links
               continue;
            if ( $record['type'] == '1:1H' ) { // this one is supposed to be set up as a link
                  $return[] = sprintf( 
                     "<td>%s</td><td><a href='$url?module=%s&id=%s'>%s</a></td>",
                     $record['displayName'],
                     $record['class'],
                     $this->data[$key]['id'],
                     $this->data[$key]['display']
                  );
            } elseif ( $record['type'] == '1:M' ) { // this is an array in data, so we just grab the values
               $return[] = '<td>' . $record['displayName'] . "</td>\n<td>" . implode( ',', array_values( $this->data[$key] ) ) . '</td>';
            } else { // just pulling data from the table itself
               $return[] = '<td>' . $record['displayName'] . "</td>\n<td>" . $this->data[$record['fieldname']] . '</td>';
            }
         }
         if ( $_SESSION['user']->isAuthorized( strtolower(get_called_class()) . '_edit') )
            $return[] = sprintf( "<td colspan='2'><a href='$url?module=%s&id=%s&action=edit'>Edit</a></td>",
                        get_called_class(),
                        $this->data[static::$dbStructure['table']['primaryKey']]
                     );
         
         $return = "<div class='show_record'>\n<table class='show_record'>\n<tr>" . implode("</tr>\n<tr>", $return ) . "</tr>\n</table>\n</div>";
         
         /* Now, get the children records */
         if ( isset( $_REQUEST['to_find'] ) ) {
            $save = $_REQUEST['to_find'];
            unset( $_REQUEST['to_find'] );
         }
         foreach ( static::$dbStructure['children'] as $name => $record) {
            $class = isset( $record['class'] ) ? $record['class'] : $name;
            //print "<pre>Working on child $name with class $class\n</pre>";
            if ( isset( $record['filter'] ) ) { // we'll parse it against $this->data to fill in any variables
               $record['filter'] = $dbConnection->templateReplace( $record['filter'], $this->data );
               //print "<pre>$filter\n" . print_r( $this->data, true) . "</pre>"; die;
            } elseif ( isset( $record['query'] ) ) {
               $record['query'] = $dbConnection->templateReplace( $record['query'], $this->data );
            } else {
               if ( isset( $record['intermediateTable'] ) ) {
                  // they have defined an intermediate table, so we need to use that
                  $record['filter'] = sprintf(
                     '%s in (select %s from %s where %s = %s and removed is null)',
                     $record['remoteID'],
                     $record['remoteID'],
                     $record['intermediateTable'],
                     $record['myID'],
                     $this->id
                     );
               } else {
                  $record['filter'] = static::$dbStructure['table']['primaryKey'] . ' = ' . $this->data[static::$dbStructure['table']['primaryKey']];
               }
            }
            if ( ! isset( $record['name'] ) )
               $record['name'] = $class;
            //print "<pre>record\n" . print_r( $record, true) . "</pre>"; die;
            
            if ( isset( $record['query'] ) ) {
               // print "<pre>\tRunning query $record[query]\n</pre>";
               // they just gave us a query, so run it. Must return only two columns, id and name
               $data = $dbConnection->queryToKeyedArray( $record['query'] );
               // pass the result to showSelectionList
               $found = count( $data ) ? $class::showSelectionList( array( ), $data, isset( $record['noAdd'] )  ) : array();
            } else {
               $found = $class::showSelectionList( array( $record['filter'] ), array(), isset( $record['noAdd'] )  );
            }
            //print "<pre>[$found]</pre>"; die;
            if ( $found )
               $return .= "<div class='show_record'>\n<h3>$record[name]</h3>\n" . $found  . '</div>';
         }
         if ( $save !== null ) {
            $_REQUEST['to_find'] = $save;
         }
         return $return;
      } // display
      
      /**
       * Function is basically a placeholder in case a extended class
       * needs to do some additional processing when editing
       * 
       * In some cases, the edit function can not handle additional fields.
       * See the Device class, where device_type is a table with many-to-many
       * linkages to device. Since this type of thing is very rare, I decided
       * to just allow edit and post to call an additional function in
       * those cases.
       * 
       * Based on the action requested, will either return an HTML string
       * which will be placed in the edit screen (for edit), or an array
       * of SQL to be executed to update/add rows (for post).
       * 
       * If the action is edit, there should be a <td></td> around the 
       * whole thing
       */
      
      protected function editAdditionalFields() {
         if ( $_REQUEST['action'] == 'edit' ) {
            return '';
         } elseif ($_REQUEST['action'] == 'post' ) {
            return array();
         }
      }
      
      protected function oneToOneHistoryLoad( $field ) {
         //print "<pre>In oneToOneHistoryLoad, field is\n" . print_r( $field, true ) . '</pre>'; die;
         global $dbConnection;
         if ( isset( $field['displayQuery'] ) ) { // They want us to run a query
            // 
            $return = $dbConnection->getOneRow(
               $dbConnection->templateReplace( $field['displayQuery'], 
                  array( 'id' => $this->data[static::$dbStructure['table']['primaryKey']] ) 
                  )
               ); 
         } elseif ( isset( $field['linkageTable'] ) ) { // we have to come up with the query ourselves
            /* Since we have a linkage table, we assume the column name in the linkage table is the
             * same as the primary key in the remote table (see the using).
             * Everything else is chosen from the definition
             * 
             * Note, on 1:1H, assume the linkage table has a full history with a null removed
             * date for the current value
             */
            $query = sprintf( 
               'select a.%s id,a.%s display from %s b join %s a using (%s) where b.%s = %s and b.removed is null',
               $field['fieldname'],
               $field['displayColumn'],
               $field['linkageTable'],
               $field['foreignTable'],
               $field['foreignColumn'],
               $field['linkageColumn'],
               $this->data[static::$dbStructure['table']['primaryKey']],
               $field['linkageTable']
               );
            //print "<pre>oneToOneHistory Query is \n$query</pre>"; die;
            $return = $dbConnection->getOneRow( $query );
         } // if..else
         //print "<pre>return from oneToOneHistory is\n$return</pre>"; die;
         return $return;
      }
      
      /**
       * Gets all rows in a one to many relationship and returns it as an array
       * 
       * If 'displayQuery' is defined, it should return one row for each match, with two columns
       * 'id' is a unique ID, and 'display' is a textual display of the value. An
       * order by clause can be used to determine the display order of the values 
       * returned.
       * 
       * If 'displayQuery' is not defined, will build a query based on the definition.
       * 
       * The returned array uses the 'id' field for the index and the 'display' field
       * for the value
       * 
       * @parameter array[] $field A Field Definition from $dbStructure
       * 
       * @returns array[] where the the key is the id and the value is the display field
       */
      public function oneToManyLoad ( $field ) {
         global $dbConnection;
         $query = '';
         if ( isset( $field['displayQuery'] ) ) { // They want us to run a query
            $query = $dbConnection->templateReplace( 
               $field['displayQuery'], 
               array( 'id' => $this->data[static::$dbStructure['table']['primaryKey']] ) 
            );
         } else {
            $query = sprintf(
               'select %s id, %s display from %s a join %s b using ( %s ) where a.%s = %s order by %s',
               $field['foreignColumn'],
               $field['foreignDisplayColumn'],
               $field['linkageTable'],
               $field['foreignTable'],
               $field['foreignColumn'],
               $field['linkageColumn'],
               $this->data[static::$dbStructure['table']['primaryKey']],
               $field['foreignDisplayColumn']
               );
         } // else
         $return = $dbConnection->doSQL( $query, array( 'returnType' => 'associative' ) );
         $returnArray = array();
         foreach ( $return['returnData'] as $row => $data ) {
            $returnArray[$data['id']] = $data['display'];
         }
         return $returnArray;
      } // oneToManyLoad
      
      
      /**
       * Allow one to many types to be edited also
       */
      protected function oneToManyEdit( $key, $record ) {
         global $dbConnection;
         
         $id = $this->__get('id') === null ? 0 : $this->__get('id');
         $query = $dbConnection->templateReplace (
            sprintf(
           "select 
               ~~foreignTable~~.~~foreignColumn~~ id,
               ~~foreignTable~~.~~foreignDisplayColumn~~ name,
               not isnull(~~linkageColumn~~) checked
            from
               ~~foreignTable~~ ~~foreignTable~~
               left outer join (
                     select
                        ~~linkageColumn~~,
                        ~~foreignColumn~~
                     from
                        ~~linkageTable~~
                     where
                        ~~linkageColumn~~ = %s
                  ) current using ( ~~foreignColumn~~ )
                  order by ~~foreignDisplayColumn~~
            ", $id
            ),
            $record
            );
         //print "<pre>$query</pre>"; die;
         $data = $dbConnection->doSQL( $query );
         $data = $data['returnData'];
         // save current state in data
         $this->data[$key] = array();
         foreach ( $data as $row ) {
            if ( count( $row ) > 1 ) 
               $this->data[$key][$row['id']] = $row['checked'];
         }
         //print "<pre>" . print_r($this->data, true) . "</pre>"; die;
         //print "<pre>" . print_r($query, true) . "</pre>"; die;
         $html = $dbConnection->htmlCheckBoxes( array( 'data' => $data, 'arrayName' => $key ) );
         //print "<pre>" . print_r($html, true) . "</pre>"; die;
         return $html;
      } // oneToManyEdit
      
      
      protected function edit() {
         global $dbConnection;
         
         // save everything we have right now
         //$this->beforeEdit = $this->data;
         $return = array();
         //print "<pre>In Edit\n" . print_r( $this->data, true ) . "</pre>"; die;
         foreach ( static::$dbStructure['table']['fields'] as $key => $record ) {
            //print "<pre>Processing $record[displayName]\n</pre>";
            if ( isset( $record['display'] ) && $record['display'] === false ) // we don't do things which aren't supposed to be shown
               continue;
            switch ( $record['type'] ) {
               case '1:1H':
                  //print "<pre>Doing 1:1H\n</pre>";
                  // get a list of all options
                  $list = $record['class']::getAll( array(), array( 'workingon' => true ));
                  //print "<pre> list is\n" . print_r( $list, true ) . "</pre>";
                  $selectedRow = isset( $this->data[$key]['id'] ) ? $this->data[$key]['id'] : null;
                  //print "<pre>Selected value is $selectedRow</pre>";
                  $select = $dbConnection->htmlSelect( array (
                              'data'      => $list,
                              'name'      => $key, //$record['foreignColumn'],
                              'nullok'    => true,
                              'selected'  => isset( $selectedRow ) ? $selectedRow : -1,
                              //'class'     => 
                           )
                  );
                  $return[] = sprintf( 
                     "<td>%s</td><td>%s</td>",
                     $record['displayName'],
                     $select
                  );
                  break;
               case '1:M' :
                  //print "<pre>Doing 1:M\n</pre>";
                  $checkBoxes = $this->oneToManyEdit( $key, $record );
                  $return[] = "<td>$record[displayName]</td>\n<td>$checkBoxes</td>";
                  break;
               default: 
                  //print "<pre>Adding $record[displayName]\n</pre>";
                  if ( isset( $record['canEdit'] ) && $record['canEdit'] == false ) {
                     $return[] = sprintf( 
                              "<td>%s</td><td>%s</td>",
                              $record['displayName'],
                              isset( $this->data[$record['fieldname']] ) ? $this->data[$record['fieldname']] : ''
                           );
                  } else {
                     $return[] = sprintf( 
                              "<td>%s</td><td><input type='text' name='%s' value='%s'></td>",
                              $record['displayName'],
                              $record['fieldname'],
                              $this->data[$record['fieldname']]
                              );
                  } // if..else
            } // switch
         } // foreach
         //$return[] = $this->editAdditionalFields();
         //print "<pre>In Edit, return is\n" . print_r( $return, true ) . "</pre>";
         $return[] = "<td colspan='2'><input type='submit' name='Save' value='Save'></td>";
         $hiddens = sprintf( "<input type='hidden' name='module' value='%s'>\n", get_called_class() ) .
                     sprintf( "<input type='hidden' name='id' value='%s'>\n", isset( $this->data[static::$dbStructure['table']['primaryKey']] ) ? $this->data[static::$dbStructure['table']['primaryKey']] : 0 ) .
                     "<input type='hidden' name='action' value='post'>\n";
         return "<div class='show_record'>\n<form><table class='show_record'>\n<tr>" . implode("</tr>\n<tr>", $return ) . "</tr>\n</table>\n$hiddens</form></div>";
      } // edit
      

      /**
       * Adds new row in linkage table after marking old row as inactive
       * 
       * Returns two queries which should be executed to update a linkage table
       * 
       * The "History" part of this is that the old rows are not removed.
       * Instead, they are marked as removed and this new row is added.
       * 
       * This function assumes the table has two date columns, created and removed
       * created should be default current_timestamp so we do not manually update
       * it here.
       */
      public function post1to1History( $linkageTable, $myColumn, $linkedToColumn, $newValue ) {
         $queries = array();
         if ( $newValue != -1 ) {
            $queries[] = sprintf( 
               "update %s set removed = date(now()) where %s = %s and removed is null",
               $linkageTable,
               $myColumn,
               $this->__get('id')
               );
            $queries[] = sprintf(
               "insert into %s ( %s, %s ) values ( %s, %s )",
               $linkageTable,
               $myColumn, 
               $linkedToColumn,
               $this->__get('id'),
               $newValue
               );
         }
         return $queries;
      }
      
      protected function oneToManyPost( $key, $record ) {
         global $dbConnection;
         
         $request = $_REQUEST[$key];
         $queries = array();
         foreach ( $this->data[$key] as $index => $checked ) {
            if ( $checked && empty( $request[$index] ) ) { // we unchecked something
               $queries[] = $dbConnection->templateReplace( 
                  sprintf(
                     'delete from ~~linkageTable~~ where ~~linkageColumn~~ = %s and ~~foreignColumn~~ = %s',
                     $this->__get('id'),
                     $index
                     ),
                  $record
               );
            } elseif ( ! $checked && isset( $request[$index] ) ) { // we checked something
               $queries[] = $dbConnection->templateReplace( 
                  sprintf(
                     'insert into ~~linkageTable~~ (~~linkageColumn~~, ~~foreignColumn~~ ) values (%s, %s)',
                     $this->__get('id'),
                     $index
                     ),
                  $record
               );
            } // if..elseif
         } // foreach
         return $queries;
      }
      
      /**
       * Posts the results of a previous form
       * 
       * After a form is filled in, will search for any values which have
       * changed. It will generate a separate SQL statement for each of them
       * and execute the queries in in batch
       * 
       * Once this is done, will reload the values from the database, so
       * we immediately know if there was a problem.
       */
      protected function post() {
         global $dbConnection;

         //print "<pre>Function Post\n" .  print_r($_REQUEST, true) . '</pre>'; die;
         
         // first, if this is a new record, just insert a blank one and get the ID.
         // A little bit of overhead, but it allows us
         if ( empty( $this->data[static::$dbStructure['table']['primaryKey']] ) ) {
            // by default, we pre-populate some fields and that means they won't get updated, so init structure
            foreach ( $this->data as $key => $record ) {
               if ( ! is_array( $this->data[$key] ) && $this->data[$key] )
                  $this->data[$key] = '';
            }
            $insertQuery = $dbConnection->insertQuery(
                  static::$dbStructure['table']['tableName'],
                  array( static::$dbStructure['table']['selectionDisplay'] => 'Blank Record' ) );
            $this->data[static::$dbStructure['table']['primaryKey']] = $dbConnection->insert( $insertQuery );
            
            print "<pre>\n" . print_r( $this->data , true ) . "</pre>"; die;
         }
         
         $queries = array();
         $fields = array();
         foreach ( static::$dbStructure['table']['fields'] as $key => $record ) {
            if ( isset( $record['display'] ) && $record['display'] === false ) // we don't try to show links
               continue;
            if ( isset( $record['canEdit'] ) && ! $record['canEdit'] )
               continue;
            switch ( $record['type'] ) {
               case '1:1H' :
                  if ( $_REQUEST[$key] != $this->data[$key]['id'] ) { // they have changed a value
                     //print "<pre>Doing 1:1H\nRequest\n" . $_REQUEST[$record['fieldname']] . "\nData" . $this->data[$record['fieldname']]['id'] . "</pre>"; die;
                     $queries = array_merge( $queries, 
                                 $this->post1to1History( 
                                    $record['linkageTable'], 
                                    $record['linkageColumn'], 
                                    $record['foreignColumn'], 
                                    $_REQUEST[$key]
                                 )
                              );
                  } // if
                  break;
               case '1:M' :
                  $queries = array_merge( $queries, $this->oneToManyPost( $key, $record ) );
                  break;
               default:
                  if ( $_REQUEST[$record['fieldname']] != $this->data[$record['fieldname']] ) { // they have changed a value
                     $fields[$record['fieldname']] = $_REQUEST[$record['fieldname']];
                  }
            } // switch
         } // foreach
         //print "<pre>posting fields in data\n" . print_r( $this->data, true ) . "</pre>"; die;
         if ( count( $fields ) ) {
            $queries[] = $dbConnection->updateQuery( 
                  static::$dbStructure['table']['tableName'],
                  array( static::$dbStructure['table']['primaryKey'] => $this->data[static::$dbStructure['table']['primaryKey']] ),
                  $fields );
         } // if there are fields
         /*
         print "<pre>Request" . print_r( $_REQUEST, true ) . "</pre>";
         print "<pre>Data" . print_r( $this->data, true ) . "</pre>";
         print "<pre>Queries" . print_r( $queries, true ) . "</pre>"; die;
         */
         $dbConnection->runSQLScript( $queries );
         $this->loadFromDB( $this->data[static::$dbStructure['table']['primaryKey']] );
      } // post
      
      /**
       * Simple controller. Will determine what action is going on, then
       * call the correct method, returning the HTML required
       */
      public function run() {
         if ( isset( $_REQUEST['action'] ) ) {
            switch ( $_REQUEST['action'] ) {
               case 'add':
                  // prepopulate some fields with what we've been working on
                  $this->data = array();
                  foreach ( static::$dbStructure['table']['fields'] as $fieldname => $record ) {
                     if ( isset( $record['class'] ) && isset( $_SESSION['workingon'][$record['class']] ) ) {
                        $this->data[$record['fieldname']] = $_SESSION['workingon'][$record['class']];
                     } else {
                        $this->data[$fieldname] = '';
                     } // if..else
                  } // foreach
                  $this->data['id'] = 0;
                  //print '<pre>' . print_r( $this->data, true ) . '</pre>'; die;
                  // now, fall through and do the edit
               case 'edit':
                  $return = $this->edit();
                  break;
               case 'post':
                  $this->post();
                  // fall through and display the record
               default:
                  $return =  $this->display();
            } // switch
         } else {
            $return =  $this->display();
         }
         return $return;
      }
   } // abstract class Camp

?>